text stringlengths 14 6.51M |
|---|
{ *************************************************************************** }
{ }
{ Audio Tools Library (Freeware) }
{ Class TMonkey - for manipulating with Monkey's Audio file information }
{ }
{ Uses: }
{ - Class TID3v1 }
{ - Class TID3v2 }
{ - Class TAPEtag }
{ }
{ Copyright (c) 2001,2002 by Jurgen Faul }
{ E-mail: jfaul@gmx.de }
{ http://jfaul.de/atl }
{ }
{ Version 1.2 (21 April 2002) }
{ - Class TID3v2: support for ID3v2 tags }
{ - Class TAPEtag: support for APE tags }
{ }
{ Version 1.1 (11 September 2001) }
{ - Added property Samples }
{ - Removed WAV header information }
{ }
{ Version 1.0 (7 September 2001) }
{ - Support for Monkey's Audio files }
{ - Class TID3v1: reading & writing support for ID3v1.x tags }
{ }
{ *************************************************************************** }
unit Monkey;
interface
uses
Classes, SysUtils, ID3v1, ID3v2, APEtag;
const
{ Compression level codes }
MONKEY_COMPRESSION_FAST = 1000; { Fast (poor) }
MONKEY_COMPRESSION_NORMAL = 2000; { Normal (good) }
MONKEY_COMPRESSION_HIGH = 3000; { High (very good) }
MONKEY_COMPRESSION_EXTRA_HIGH = 4000; { Extra high (best) }
{ Compression level names }
MONKEY_COMPRESSION: array [0..4] of string =
('Unknown', 'Fast', 'Normal', 'High', 'Extra High');
{ Format flags }
MONKEY_FLAG_8_BIT = 1; { Audio 8-bit }
MONKEY_FLAG_CRC = 2; { New CRC32 error detection }
MONKEY_FLAG_PEAK_LEVEL = 4; { Peak level stored }
MONKEY_FLAG_24_BIT = 8; { Audio 24-bit }
MONKEY_FLAG_SEEK_ELEMENTS = 16; { Number of seek elements stored }
MONKEY_FLAG_WAV_NOT_STORED = 32; { WAV header not stored }
{ Channel mode names }
MONKEY_MODE: array [0..2] of string =
('Unknown', 'Mono', 'Stereo');
type
{ Real structure of Monkey's Audio header }
MonkeyHeader = record
ID: array [1..4] of Char; { Always "MAC " }
VersionID: Word; { Version number * 1000 (3.91 = 3910) }
CompressionID: Word; { Compression level code }
Flags: Word; { Any format flags }
Channels: Word; { Number of channels }
SampleRate: Integer; { Sample rate (hz) }
HeaderBytes: Integer; { Header length (without header ID) }
TerminatingBytes: Integer; { Extended data }
Frames: Integer; { Number of frames in the file }
FinalSamples: Integer; { Number of samples in the final frame }
PeakLevel: Integer; { Peak level (if stored) }
SeekElements: Integer; { Number of seek elements (if stored) }
end;
{ Class TMonkey }
TMonkey = class(TObject)
private
{ Private declarations }
FFileLength: Integer;
FHeader: MonkeyHeader;
FID3v1: TID3v1;
FID3v2: TID3v2;
FAPEtag: TAPEtag;
procedure FResetData;
function FGetValid: Boolean;
function FGetVersion: string;
function FGetCompression: string;
function FGetBits: Byte;
function FGetChannelMode: string;
function FGetPeak: Double;
function FGetSamplesPerFrame: Integer;
function FGetSamples: Integer;
function FGetDuration: Double;
function FGetRatio: Double;
public
{ Public declarations }
constructor Create; { Create object }
destructor Destroy; override; { Destroy object }
function ReadFromFile(const FileName: string): Boolean; { Load header }
property FileLength: Integer read FFileLength; { File length (bytes) }
property Header: MonkeyHeader read FHeader; { Monkey's Audio header }
property ID3v1: TID3v1 read FID3v1; { ID3v1 tag data }
property ID3v2: TID3v2 read FID3v2; { ID3v2 tag data }
property APEtag: TAPEtag read FAPEtag; { APE tag data }
property Valid: Boolean read FGetValid; { True if header valid }
property Version: string read FGetVersion; { Encoder version }
property Compression: string read FGetCompression; { Compression level }
property Bits: Byte read FGetBits; { Bits per sample }
property ChannelMode: string read FGetChannelMode; { Channel mode }
property Peak: Double read FGetPeak; { Peak level ratio (%) }
property Samples: Integer read FGetSamples; { Number of samples }
property Duration: Double read FGetDuration; { Duration (seconds) }
property Ratio: Double read FGetRatio; { Compression ratio (%) }
end;
implementation
{ ********************** Private functions & procedures ********************* }
procedure TMonkey.FResetData;
begin
{ Reset data }
FFileLength := 0;
FillChar(FHeader, SizeOf(FHeader), 0);
FID3v1.ResetData;
FID3v2.ResetData;
FAPEtag.ResetData;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetValid: Boolean;
begin
{ Check for right Monkey's Audio file data }
Result :=
(FHeader.ID = 'MAC ') and
(FHeader.SampleRate > 0) and
(FHeader.Channels > 0);
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetVersion: string;
begin
{ Get encoder version }
if FHeader.VersionID = 0 then Result := ''
else Str(FHeader.VersionID / 1000 : 4 : 2, Result);
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetCompression: string;
begin
{ Get compression level }
Result := MONKEY_COMPRESSION[FHeader.CompressionID div 1000];
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetBits: Byte;
begin
{ Get number of bits per sample }
if FGetValid then
begin
Result := 16;
if FHeader.Flags and MONKEY_FLAG_8_BIT > 0 then Result := 8;
if FHeader.Flags and MONKEY_FLAG_24_BIT > 0 then Result := 24;
end
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetChannelMode: string;
begin
{ Get channel mode }
Result := MONKEY_MODE[FHeader.Channels];
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetPeak: Double;
begin
{ Get peak level ratio }
if (FGetValid) and (FHeader.Flags and MONKEY_FLAG_PEAK_LEVEL > 0) then
case FGetBits of
16: Result := FHeader.PeakLevel / 32768 * 100;
24: Result := FHeader.PeakLevel / 8388608 * 100;
else Result := FHeader.PeakLevel / 128 * 100;
end
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetSamplesPerFrame: Integer;
begin
{ Get number of samples in a frame }
if FGetValid then
if (FHeader.VersionID >= 3900) or
((FHeader.VersionID >= 3800) and
(FHeader.CompressionID = MONKEY_COMPRESSION_EXTRA_HIGH)) then
Result := 73728
else
Result := 9216
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetSamples: Integer;
begin
{ Get number of samples }
if FGetValid then
Result := (FHeader.Frames - 1) * FGetSamplesPerFrame + FHeader.FinalSamples
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetDuration: Double;
begin
{ Get song duration }
if FGetValid then Result := FGetSamples / FHeader.SampleRate
else Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.FGetRatio: Double;
begin
{ Get compression ratio }
if FGetValid then
Result := FFileLength /
(FGetSamples * FHeader.Channels * FGetBits / 8 + 44) * 100
else
Result := 0;
end;
{ ********************** Public functions & procedures ********************** }
constructor TMonkey.Create;
begin
{ Create object }
inherited;
FID3v1 := TID3v1.Create;
FID3v2 := TID3v2.Create;
FAPEtag := TAPEtag.Create;
FResetData;
end;
{ --------------------------------------------------------------------------- }
destructor TMonkey.Destroy;
begin
{ Destroy object }
FID3v1.Free;
FID3v2.Free;
FAPEtag.Free;
inherited;
end;
{ --------------------------------------------------------------------------- }
function TMonkey.ReadFromFile(const FileName: string): Boolean;
var
SourceFile: file;
begin
try
{ Reset data and search for file tag }
FResetData;
if (not FID3v1.ReadFromFile(FileName)) or
(not FID3v2.ReadFromFile(FileName)) or
(not FAPEtag.ReadFromFile(FileName)) then raise Exception.Create('');
{ Set read-access, open file and get file length }
AssignFile(SourceFile, FileName);
FileMode := 0;
Reset(SourceFile, 1);
FFileLength := FileSize(SourceFile);
{ Read Monkey's Audio header data }
Seek(SourceFile, ID3v2.Size);
BlockRead(SourceFile, FHeader, SizeOf(FHeader));
if FHeader.Flags and MONKEY_FLAG_PEAK_LEVEL = 0 then
FHeader.PeakLevel := 0;
if FHeader.Flags and MONKEY_FLAG_SEEK_ELEMENTS = 0 then
FHeader.SeekElements := 0;
CloseFile(SourceFile);
Result := true;
except
FResetData;
Result := false;
end;
end;
end.
|
unit Turtle;
interface
uses
FMX.Graphics, FMX.Dialogs, System.Types, Math, Classes, StrUtils, SysUtils;
type
TTurtle = Class(TObject)
private
currentPosition: TPointF;
currentAngle: Integer;
displayCanvas: FMX.Graphics.TCanvas;
moveDist: Integer;
public
constructor Create(position: TPointF; moveDist: Integer);
procedure DrawLine();
procedure Rotate(angle: Integer; direction: String);
procedure InterpretMoves(moves: TStringList);
End;
implementation
// Uses display to easily access canvas
uses Display;
// Create a basic turtle
constructor TTurtle.Create(position: TPointF; moveDist: Integer);
begin
self.currentPosition := position;
self.currentAngle := 90;
self.displayCanvas := Form1.Image1.Bitmap.Canvas;
self.moveDist := moveDist;
end;
// Draw a line, moveDist up from turtle
procedure TTurtle.DrawLine;
var
p1, p2: TPointF;
x2, y2: Single;
begin
// Start position
p1 := currentPosition;
// End position calculations
x2 := p1.X + moveDist * Sin(DegToRad(currentAngle));
y2 := p1.Y - moveDist * Cos(DegToRad(currentAngle));
p2 := TPointF.Create(x2, y2);
// Begin drawing
displayCanvas.BeginScene;
displayCanvas.DrawLine(p1, p2, 100);
displayCanvas.EndScene;
// Update current location
currentPosition := p2;
end;
// Rotate the turtle
procedure TTurtle.Rotate(angle: Integer; direction: String);
begin
if (direction = 'L') or (direction = 'l') then
currentAngle := (currentAngle - angle) mod 360
else if (direction = 'R') or (direction = 'r') then
currentAngle := (currentAngle + angle) mod 360
else
// Display message if incorrect direction used
// TODO: Raise exception instead
ShowMessage('Invalid direction!');
end;
procedure TTurtle.InterpretMoves(moves: TStringList);
var
move: String;
moveArray: TStringDynArray;
begin
for move in moves do
begin
moveArray := SplitString(move, '\ ');
if moveArray[0] = 'draw' then
self.DrawLine
else if moveArray[0] = 'turn' then
self.Rotate(StrToInt(moveArray[1]), moveArray[2]);
end;
end;
end.
|
unit ltr114api;
interface
uses SysUtils, ltrapi, ltrapitypes;
const
LTR114_CLOCK = 15000; // тактовая частота модуля в кГц
LTR114_ADC_DIVIDER = 1875; //делитель частоты для АЦП
LTR114_MAX_CHANNEL = 16; // Максимальное число физических каналов
LTR114_MAX_R_CHANNEL = 8; //Максимальное число физических каналов для измерения сопротивлений
LTR114_MAX_LCHANNEL = 128; // Максимальное число логических каналов
LTR114_MID = $7272; ////id модуля LTR114
LTR114_ADC_RANGEQNT = 3; // количество диапазонов измерения напряжений
LTR114_R_RANGEQNT = 3; // количество диапазонов измерения сопротивлений
LTR114_SCALE_INTERVALS = 3;
LTR114_MAX_SCALE_VALUE = 8000000; //код шкалы, соответствующий максимальному значению диапазона измерения
//флаги для функции LTR114_ProcessData
LTR114_PROCF_NONE = $00;
LTR114_PROCF_VALUE = $01; //признак необходимисти перевода кода в физические величины
LTR114_PROCF_AVGR = $02; //признак необходимости осреднения двух измерений - +I и -I
//коды диапазонов напряжений
LTR114_URANGE_10 = 0;
LTR114_URANGE_2 = 1;
LTR114_URANGE_04 = 2;
//коды диапазонов сопротивлений
LTR114_RRANGE_400 = 0;
LTR114_RRANGE_1200 = 1;
LTR114_RRANGE_4000 = 2;
//режимы коррекции данных
LTR114_CORRECTION_MODE_NONE = 0;
LTR114_CORRECTION_MODE_INIT = 1;
LTR114_CORRECTION_MODE_AUTO = 2;
//режимы синхронизации
LTR114_SYNCMODE_NONE = 0;
LTR114_SYNCMODE_INTERNAL = 1;
LTR114_SYNCMODE_MASTER = 2;
LTR114_SYNCMODE_EXTERNAL = 4;
//режимы проверки входов
LTR114_CHECKMODE_X0Y0 = 1;
LTR114_CHECKMODE_X5Y0 = 2;
LTR114_CHECKMODE_X0Y5 = 4;
LTR114_CHECKMODE_ALL = 7;
//коды стандартных режимов измерения
LTR114_MEASMODE_U = $00;
LTR114_MEASMODE_R = $20;
LTR114_MEASMODE_NR = $28;
//коды специальных режимов коммутации
LTR114_MEASMODE_NULL = $10; //измерение собственного нуля
LTR114_MEASMODE_DAC12 = $11; //измерение DAC1 - DAC2
LTR114_MEASMODE_NDAC12 = $12;
LTR114_MEASMODE_NDAC12_CBR = $38;
LTR114_MEASMODE_DAC12_CBR = $30;
LTR114_MEASMODE_DAC12_INTR = $91; //измерение DAC1 - DAC2 посередине интервала
LTR114_MEASMODE_NDAC12_INTR = $92;
LTR114_MEASMODE_DAC12_INTR_CBR = $B8; //измерение DAC1 - DAC2 посередине интервала
LTR114_MEASMODE_NDAC12_INTR_CBR = $B0;
LTR114_MEASMODE_X0Y0 = $40;
LTR114_MEASMODE_X5Y0 = $50;
LTR114_MEASMODE_X0Y5 = $70;
//коды дополнительных возможностей
LTR114_FEATURES_STOPSW = 1; //использовать режим автокалибровки
LTR114_FEATURES_THERM = 2; //термометр
LTR114_FEATURES_CBR_DIS = 4; //запрет начальной калибровки
LTR114_MANUAL_OSR = 8; //ручная установка OSR
//настройки модуля по-умолчанию
LTR114_DEF_DIVIDER = 2;
LTR114_DEF_INTERVAL = 0;
LTR114_DEF_OSR = 0;
LTR114_DEF_SYNC_MODE =LTR114_SYNCMODE_INTERNAL;
//коды тестов модуля LTR114
LTR114_TEST_INTERFACE = 1; //проверка интерфейса PC-LTR114
LTR114_TEST_DAC = 2; //проверка DAC
LTR114_TEST_DAC1_VALUE = 3; //передача тестового значения для DAC1
LTR114_TEST_DAC2_VALUE = 4; //передача тестового значения для DAC2
LTR114_TEST_SELF_CALIBR = 5; //проведение измерения модулем себя для калибровки
//параметры подтверждения проверки интерфейса PC-LTR114
LTR114_TEST_INTERFACE_DATA_L = $55;
LTR114_TEST_INTERFACE_DATA_H = $AA;
// Коды ошибок, возвращаемые функциями библиотеки */
LTR114_ERR_INVALID_DESCR = -10000; // указатель на описатель модуля равен NULL
LTR114_ERR_INVALID_SYNCMODE = -10001; // недопустимый режим синхронизации модуля АЦП
LTR114_ERR_INVALID_ADCLCHQNT = -10002; // недопустимое количество логических каналов
LTR114_ERR_INVALID_ADCRATE = -10003; // недопустимое значение частоты дискретизации АЦП модуля
LTR114_ERR_GETFRAME = -10004; // ошибка получения кадра данных с АЦП
LTR114_ERR_GETCFG = -10005; // ошибка чтения конфигурации
LTR114_ERR_CFGDATA = -10006; // ошибка при получении конфигурации модуля
LTR114_ERR_CFGSIGNATURE = -10007; // неверное значение первого байта конфигурационной записи модуля
LTR114_ERR_CFGCRC = -10008; // неверная контрольная сумма конфигурационной записи
LTR114_ERR_INVALID_ARRPOINTER = -10009; // указатель на массив равен NULL
LTR114_ERR_ADCDATA_CHNUM = -10010; // неверный номер канала в массиве данных от АЦП
LTR114_ERR_INVALID_CRATESN = -10011; // указатель на строку с серийным номером крейта равен NULL
LTR114_ERR_INVALID_SLOTNUM = -10012; // недопустимый номер слота в крейте
LTR114_ERR_NOACK = -10013; // нет подтверждения от модуля
LTR114_ERR_MODULEID = -10014; // попытка открытия модуля, отличного от LTR114
LTR114_ERR_INVALIDACK = -10015; // неверное подтверждение от модуля
LTR114_ERR_ADCDATA_SLOTNUM = -10016; // неверный номер слота в данных от АЦП
LTR114_ERR_ADCDATA_CNT = -10017; // неверный счетчик пакетов в данных от АЦП
LTR114_ERR_INVALID_LCH = -10018; // неверный режим лог. канала
LTR114_ERR_CORRECTION_MODE = -10019; // неверный режим коррекции данных
LTR114_ERR_GET_PLD_VER = -10020; // ошибка при чтении версии ПЛИСа
LTR114_ERR_ALREADY_RUN = -10021; // ошибка при попытке запуска сбора данных когда он уже запущен
LTR114_ERR_MODULE_CLOSED = -10022; //
//================================================================================================*/
type
{$A4}
LTR114_GainSet = record
Offset:double; // смещение нуля */
Gain :double; // масштабный коэффициент */
end;
LTR114_CbrCoef = record
U: array[0..LTR114_ADC_RANGEQNT-1] of single; //значения ИОН для диапазонов измерения напряжений
I: array[0..LTR114_R_RANGEQNT-1] of single; //значения токов для диапазонов измерения сопротивлений
UIntr: array[0..LTR114_ADC_RANGEQNT-1] of single; //значение промежуточных напряжений
end;
TINFO_LTR114 = record
Name : array [0..7] of AnsiChar; // название модуля (строка)
Serial : array [0..15] of AnsiChar; // серийный номер модуля (строка)
VerMCU : word; // версия ПО модуля (младший байт - минорная, старший - мажорная
Date : array [0..13] of AnsiChar; // дата создания ПО (строка) */
VerPLD : byte; //версия прошивки ПЛИС
CbrCoef : LTR114_CbrCoef; // заводские калибровочные коэффициенты */
end;
//
TSCALE_LTR114 = record
Null : integer; //значение нуля
Ref : integer; //значение +шкала
NRef : integer; //значение -шкала
Interm : integer;
NInterm : integer;
end;
//информация о модуле
TCBRINFO = record
Coef : array [0..LTR114_SCALE_INTERVALS-1] of LTR114_GainSet; //вычисленные на этапе автокалибровки значения Gain и Offset
TempScale : ^TSCALE_LTR114; //массив временных измерений шкалы/нуля
Index : TSCALE_LTR114; //количество измерений в TempScale
LastVals : TSCALE_LTR114; //последнее измерение
HVal : integer;
LVal : integer;
end;
//описатель логического канала
LTR114_LCHANNEL = record
MeasMode : byte; //режим измерения
Channel : byte; //физический канал
Range : byte; //диапазон измерения*/
end;
//опистаель модуля LTR114
TLTR114= record // информация о модуле LTR114
size:integer; // размер структуры в байтах
Channel:TLTR; // описатель канала связи с модулем
AutoCalibrInfo: array[0..LTR114_ADC_RANGEQNT-1] of TCBRINFO; // данные для вычисления калибровочных коэф. для каждого диапазона
LChQnt : integer; // количество активных логических каналов
LChTbl : array[0..LTR114_MAX_LCHANNEL-1] of LTR114_LCHANNEL; // управляющая таблица с настройками логических каналов
Interval : word; //длина межкадрового интервала
SpecialFeatures : byte; //дополнительные возможности модуля (подключение термометра, блокировка коммутации)
AdcOsr : byte; //значение передискр. АЦП - вычисляется в соответствии с частотой дискретизации
SyncMode : byte; //режим синхронизации
FreqDivider : integer; // делитель частоты АЦП (2..8000)
// частота дискретизации равна F = LTR114_CLOCK/(LTR114_ADC_DIVIDER*FreqDivider)
FrameLength : integer; //размер данных, передаваемых модулем за один кадр
//устанавливается после вызова LTR114_SetADC
Active : boolean; //находится ли модуль в режиме сбора данных
Reserve : integer;
ModuleInfo : TINFO_LTR114; // информация о модуле LTR114
end;
//================================================================================================*/
pTLTR114=^TLTR114;
//================================================================================================*/
{$A+}
Function LTR114_Init(hnd : pTLTR114) : integer; {$I ltrapi_callconvention};
Function LTR114_Open(hnd: pTLTR114; net_addr : LongWord; net_port: word; crate_snChar : Pointer; slot_num : integer) : integer; {$I ltrapi_callconvention};
Function LTR114_Close(hnd: pTLTR114) : integer; {$I ltrapi_callconvention};
Function LTR114_GetConfig(hnd: pTLTR114): integer; {$I ltrapi_callconvention};
Function LTR114_Calibrate(hnd: pTLTR114): integer; {$I ltrapi_callconvention};
Function LTR114_SetADC(hnd: pTLTR114): integer; {$I ltrapi_callconvention};
Function LTR114_Start(hnd: pTLTR114): integer; {$I ltrapi_callconvention};
Function LTR114_Stop(hnd: pTLTR114): integer; {$I ltrapi_callconvention};
Function LTR114_GetErrorString(err: Integer) : string; {$I ltrapi_callconvention};
Function LTR114_GetFrame(hnd: pTLTR114; bufDWORD : Pointer):integer; {$I ltrapi_callconvention};
Function LTR114_Recv(hnd: pTLTR114; dataDWORD : Pointer; tmarkDWORD : Pointer; size : LongWord; timeout : LongWord):integer; {$I ltrapi_callconvention};
Function LTR114_ProcessData(hnd: pTLTR114; srcDWORD: Pointer; destDOUBLE: Pointer; sizeINT : Pointer; correction_mode : integer; flags : integer):integer; {$I ltrapi_callconvention};
Function LTR114_ProcessDataTherm(hnd: pTLTR114; srcDWORD: Pointer; destDOUBLE: Pointer; thermDOUBLE : Pointer; sizeINT : Pointer; tcntINT : Pointer; correction_mode : integer; flags : integer):integer; {$I ltrapi_callconvention};
Function LTR114_CheckInputs(hnd: pTLTR114; ChannelsMask : integer; CheckMode : integer; res_dataDOUBLE : Pointer; sizeINT : Pointer):integer; {$I ltrapi_callconvention};
Function LTR114_SetRef(hnd: pTLTR114; range : integer; middle:boolean) :integer; {$I ltrapi_callconvention};
Function LTR114_GetDllVer() : word; {$I ltrapi_callconvention};
Function LTR114_CreateLChannel(MeasMode : integer; Channel : integer; Range: integer) : LTR114_LCHANNEL; {$I ltrapi_callconvention};
//================================================================================================*/
implementation
Function LTR114_Init(hnd : pTLTR114) : integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Open(hnd: pTLTR114; net_addr : LongWord; net_port: word; crate_snChar : Pointer; slot_num : integer) : integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Close(hnd: pTLTR114) : integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_GetConfig(hnd: pTLTR114): integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Calibrate(hnd: pTLTR114): integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_SetADC(hnd: pTLTR114): integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Start(hnd: pTLTR114): integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Stop(hnd: pTLTR114): integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr114api' name 'LTR114_GetErrorString';
Function LTR114_GetFrame(hnd: pTLTR114; bufDWORD : Pointer):integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_Recv(hnd: pTLTR114; dataDWORD : Pointer; tmarkDWORD : Pointer; size : LongWord; timeout : LongWord):integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_ProcessData(hnd: pTLTR114; srcDWORD: Pointer; destDOUBLE: Pointer; sizeINT : Pointer; correction_mode : integer; flags : integer):integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_ProcessDataTherm(hnd: pTLTR114; srcDWORD: Pointer; destDOUBLE: Pointer; thermDOUBLE : Pointer; sizeINT : Pointer; tcntINT : Pointer; correction_mode : integer; flags : integer):integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_CheckInputs(hnd: pTLTR114; ChannelsMask : integer; CheckMode : integer; res_dataDOUBLE : Pointer; sizeINT : Pointer):integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_SetRef(hnd: pTLTR114; range : integer; middle:boolean) :integer; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_GetDllVer() : word; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_CreateLChannel(MeasMode : integer; Channel : integer; Range: integer) : LTR114_LCHANNEL; {$I ltrapi_callconvention}; external 'ltr114api';
Function LTR114_GetErrorString(err: Integer) : string; {$I ltrapi_callconvention};
begin
LTR114_GetErrorString:=string(_get_err_str(err));
end;
end.
|
//////////////////////////////////////////
// Процедуры для работы с приборами Тэкон через модем К-105
//////////////////////////////////////////
unit Threads.K105;
interface
uses Windows, Classes, SysUtils, GMConst, GMGlobals, IdSocketHandle,
Threads.ReqSpecDevTemplate, GM485, GMGenerics, UDPBindingStorage,
Connection.UDP, Connection.Base;
type
TConnectionObjectK105 = class(TConnectionObjectIncomingUDP)
end;
TRequestK105Devices = class(TRequestSpecDevices)
private
lst485IDs: array [0..$F] of TRequestDetails;
FReplyList: TGMCollection<TSpecDevReqListItem>;
nFirstPacket: int;
FUDPBindingsAndThreads: TUDPBindingsAndThreads;
function GetEmptyID: int;
function GetSocket(): TIdSocketHandle;
procedure CheckReplyList;
protected
procedure BackGroungProc; override;
procedure DoOneRequest(ri: TSpecDevReqListItem); override;
public
constructor Create(id_obj: int; AUDPBindingsAndThreads: TUDPBindingsAndThreads);
procedure AddReplyBlock(buf: array of Byte; Len: int);
procedure BeforeDestruction(); override;
end;
implementation
{ TRequestK105Devices }
uses ProgramLogFile, Devices.Tecon.Common;
function TRequestK105Devices.GetEmptyID(): int;
var i: int;
begin
Result := -1;
try
for i := nFirstPacket to High(lst485IDs) do
if lst485IDs[i].rqtp = rqtNone then
begin
Result := i;
Exit;
end;
// не нашли или перешли через 0
for i := 0 to High(lst485IDs) do
if lst485IDs[i].rqtp = rqtNone then
begin
Result := i;
Exit;
end;
finally
if Result >= 0 then
nFirstPacket := Result + 1;
end;
end;
procedure TRequestK105Devices.CheckReplyList();
var i, nReq: int;
ri: TSpecDevReqListItem;
begin
// зачистим неотвеченные
for i := 0 to High(lst485IDs) do
if Abs(lst485IDs[i].TimeTick - GetTickCount()) > 20000 then
lst485IDs[i].rqtp := rqtNone;
while FReplyList.Count > 0 do
begin
ri := FReplyList.Items[0];
ConnectionObject.buffers.NumberOfBytesRead := ri.ReqDetails.BufCnt;
WriteBuf(ConnectionObject.buffers.BufRec, 0, ri.ReqDetails.buf, ConnectionObject.buffers.NumberOfBytesRead);
TConnectionObjectK105(ConnectionObject).LogBufRec();
if Tecon_CheckPrmReply(ri.ReqDetails.buf, ri.ReqDetails.BufCnt) then
begin
nReq := ri.ReqDetails.buf[4] and $0F;
if lst485IDs[nReq].rqtp <> rqtNone then
begin
PostGBV(lst485IDs[nReq], ri.ReqDetails.buf, ri.ReqDetails.BufCnt);
lst485IDs[nReq].rqtp := rqtNone;
end;
end;
FReplyList.Delete(0);
end;
end;
procedure TRequestK105Devices.BackGroungProc();
begin
inherited BackGroungProc();
CheckReplyList();
end;
function TRequestK105Devices.GetSocket: TIdSocketHandle;
begin
Result := FUDPBindingsAndThreads.ByThread(self);
end;
procedure TRequestK105Devices.DoOneRequest(ri: TSpecDevReqListItem);
var n: int;
sckt: TIdSocketHandle;
ext: TPrepareRequestBufferInfo;
begin
// Сначала ищем пустой номер, а потом сокет.
// Иначе, пока ждем этот самый пустой номер, сокет уже может отвалиться
repeat
if Terminated then Exit;
n := GetEmptyID();
if n < 0 then
begin
SleepThread(100);
CheckReplyList();
end;
until n >= 0;
sckt := GetSocket();
if sckt = nil then
begin
Terminate;
Exit;
end;
ext.ReqID := n;
ri.PrepareBuffer(ext);
lst485IDs[n] := ri.ReqDetails;
lst485IDs[n].TimeTick := GetTickCount();
WriteBuf(ConnectionObject.buffers.BufSend, 0, lst485IDs[n].buf, lst485IDs[n].BufCnt);
ConnectionObject.buffers.LengthSend := lst485IDs[n].BufCnt;
// раньше отправка была через message в главную форму.
// не знаю, зачем так было, сделал напрямки
try
TConnectionObjectK105(ConnectionObject).Socket := sckt;
ConnectionObject.ExchangeBlockData(etSend);
except
on e: Exception do
ProgramLog.AddException('TConnectionObjectK105.ExchangeBlockData ' + e.Message);
end;
SleepThread(200);
end;
procedure TRequestK105Devices.BeforeDestruction;
begin
FUDPBindingsAndThreads.RemoveThread(self);
FReplyList.Free();
inherited;
end;
constructor TRequestK105Devices.Create(id_obj: int; AUDPBindingsAndThreads: TUDPBindingsAndThreads);
begin
inherited Create(OBJ_TYPE_K105, id_obj);
FReplyList := TGMCollection<TSpecDevReqListItem>.Create();
nFirstPacket := 0;
FreeOnTerminate := true;
FUDPBindingsAndThreads := AUDPBindingsAndThreads;
CreateConnectionObject(TConnectionObjectK105);
ConnectionObject.LogPrefix := 'K105_ObjId=' + IntToStr(ID_Obj);
end;
procedure TRequestK105Devices.AddReplyBlock(buf: array of Byte; Len: int);
var rd: TRequestDetails;
begin
rd.Init();
if Len < Length(rd.buf) then
begin
WriteBuf(rd.buf, 0, buf, Len);
rd.BufCnt := Len;
FReplyList.Add().ReqDetails := rd;
end;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program C11ID;
Const
maxN =100000;
Var
n :LongInt;
ans :Int64;
A :Array[1..maxN] of LongInt;
procedure Enter;
var
i :LongInt;
begin
Read(n);
for i:=1 to n do Read(A[i]);
end;
procedure QSort(l,r :LongInt);
var
i,j,key,tmp :LongInt;
begin
if (l>=r) then Exit;
i:=l; j:=r; key:=A[(l+r) div 2];
repeat
while (A[i]<key) do Inc(i);
while (A[j]>key) do Dec(j);
if (i<=j) then
begin
if (i<j) then
begin
tmp:=A[i]; A[i]:=A[j]; A[j]:=tmp;
end;
Inc(i); Dec(j);
end;
until (i>j);
QSort(l,j); QSort(i,r);
end;
procedure Solve;
var
i :LongInt;
begin
ans:=0;
for i:=1 to n do Inc(ans,A[i]-i+1);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
QSort(1,n);
Solve;
Write(ans);
Close(Input); Close(Output);
End. |
unit SimpleDAOSQLAttribute;
interface
uses
SimpleInterface;
Type
TSimpleDAOSQLAttribute<T: class> = class(TInterfacedObject,
iSimpleDAOSQLAttribute<T>)
private
[weak]
FParent: iSimpleDAO<T>;
FFields: String;
FWhere: String;
FOrderBy: String;
FGroupBy: String;
FJoin: String;
public
constructor Create(Parent: iSimpleDAO<T>);
destructor Destroy; override;
class function New(Parent: iSimpleDAO<T>): iSimpleDAOSQLAttribute<T>;
function Fields(aSQL: String): iSimpleDAOSQLAttribute<T>; overload;
function Where(aSQL: String): iSimpleDAOSQLAttribute<T>; overload;
function OrderBy(aSQL: String): iSimpleDAOSQLAttribute<T>; overload;
function GroupBy(aSQL: String): iSimpleDAOSQLAttribute<T>; overload;
function Join(aSQL: String): iSimpleDAOSQLAttribute<T>; overload;
function Join: String; overload;
function Clear: iSimpleDAOSQLAttribute<T>;
function Fields: String; overload;
function Where: String; overload;
function OrderBy: String; overload;
function GroupBy: String; overload;
function &End: iSimpleDAO<T>;
end;
implementation
uses
System.SysUtils;
{ TSimpleDAOSQLAttribute<T> }
function TSimpleDAOSQLAttribute<T>.&End: iSimpleDAO<T>;
begin
Result := FParent;
end;
function TSimpleDAOSQLAttribute<T>.Fields: String;
begin
Result := FFields;
end;
function TSimpleDAOSQLAttribute<T>.GroupBy: String;
begin
Result := FGroupBy;
end;
function TSimpleDAOSQLAttribute<T>.Join: String;
begin
Result := FJoin;
end;
function TSimpleDAOSQLAttribute<T>.Join(aSQL: String)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FJoin := FJoin + ' ' + aSQL;
end;
function TSimpleDAOSQLAttribute<T>.GroupBy(aSQL: String)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FGroupBy := FGroupBy + ' ' + aSQL;
end;
function TSimpleDAOSQLAttribute<T>.Clear: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
FFields := '';
FWhere := '';
FOrderBy := '';
FGroupBy := '';
FJoin := '';
end;
constructor TSimpleDAOSQLAttribute<T>.Create(Parent: iSimpleDAO<T>);
begin
FParent := Parent;
end;
destructor TSimpleDAOSQLAttribute<T>.Destroy;
begin
inherited;
end;
function TSimpleDAOSQLAttribute<T>.Fields(aSQL: String)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FFields := FFields + ' ' + aSQL;
end;
class function TSimpleDAOSQLAttribute<T>.New(Parent: iSimpleDAO<T>)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self.Create(Parent);
end;
function TSimpleDAOSQLAttribute<T>.OrderBy: String;
begin
Result := FOrderBy;
end;
function TSimpleDAOSQLAttribute<T>.OrderBy(aSQL: String)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FOrderBy := FOrderBy + ' ' + aSQL;
end;
function TSimpleDAOSQLAttribute<T>.Where(aSQL: String)
: iSimpleDAOSQLAttribute<T>;
begin
Result := Self;
if Trim(aSQL) <> '' then
FWhere := FWhere + ' ' + aSQL;
end;
function TSimpleDAOSQLAttribute<T>.Where: String;
begin
Result := FWhere;
end;
end.
|
unit MediaProcessing.Definitions;
interface
uses Windows,SysUtils,Classes,SyncObjs,MMSystem, Generics.Collections;
type
TGUIDArray = array of TGUID;
TMediaType = (mtVideo,mtAudio,mtSysData);
TMediaTypeSet = set of TMediaType;
const
AllMediaTypes = [mtVideo,mtAudio,mtSysData];
type
TStreamType = DWORD;
TAllMediaStreamTypes = array [TMediaType] of TStreamType;
TAllMediaStreamBytes = array [TMediaType] of TBytes;
TAllMediaStreamGuids = array [TMediaType] of TGUIDArray;
TAllMediaStreamBools = array [TMediaType] of boolean;
const
MediaTypeNames: array [TMediaType] of string = ('Video','Audio','SysData');
stHHVI = TStreamType($49564848); //HHVI;
stHHAU = TStreamType($55414848); //HHAU;
stYUV420 = TStreamType($34565559); //YUV, 4+2+0;
stRGB = TStreamType($20424752); //RGB
stMJPEG = TStreamType($47504A4D); //MJPG
stH264 = TStreamType($34363248); //H264
stMpeg4 = TStreamType($34504D46); //FMP4
//AUDIO
stPCM =TStreamType($204D4350); //PCM
stPCMU =TStreamType($554D4350); //PCMU
stUNIV = TStreamType($554E4956); //UNIV. Universal container. Type of stream is unknown until first frame came
stCOPY = TStreamType($59504F43); //COPY
stBinary = TStreamType($53545354); //TSTS
//SYS
stPtzPosition = TStreamType($505A5450); //PTZP
stVideoAnalytics = TStreamType($53524156); //VARS
stPING = TStreamType($474E4950); //PING
stNotification = TStreamType ($4346544E); //NTFC
// stAcceptanceFilter = TStreamType($52464341); //ACFR
var
stKnownTypes: array [TMediaType] of TArray<TStreamType>;
type
TFrameFlag = (ffKeyFrame,ffInitParamsFrame,ffPrebuffer);
TFrameFlags = set of TFrameFlag;
TMediaStreamDataHeader = packed record
biMediaType: TMediaType;
biStreamType: TStreamType;
biStreamSubType: DWORD;
biFrameFlags: TFrameFlags;
Channel: integer;
TimeStamp: int64; //ms
TimeKoeff: word; //TimeStamp*TimeKoeff = ms
Tag : integer;
case TMediaType of
mtVideo: (
VideoWidth: integer;
VideoHeight: integer;
//biPlanes: Word;
VideoBitCount: Word;
VideoReversedVertical: boolean;
);
mtAudio: (
AudioChannels: DWORD;
AudioBitsPerSample: DWORD;
AudioSamplesPerSec: DWORD;
);
end;
TMediaStreamDataHeaderHelper = record helper for TMediaStreamDataHeader
procedure Assign(const aSource: TBitmapInfoHeader); overload;
procedure Assign(const aSource: TPCMWaveFormat); overload;
procedure Assign(const aSource: TWaveFormatEx); overload;
procedure AssignBitmap(aVideoWidth,aVideoHeight,aVideoBits: integer);
function ToBitmapInfoHeader(aImageSize: cardinal): TBitmapInfoHeader;
function ToPCMWaveFormat: TPCMWaveFormat;
function ToWaveFormatEx: TWaveFormatEx;
function TimeStampMs: int64;
procedure Clear;
end;
TAllMediaStreamDataHeaders = array [TMediaType] of TMediaStreamDataHeader;
//MediaType = SYSDATA, StreamType = stPing
TPingArgs = record
Reserved:byte;
end;
PPingArgs = ^TPtzPositionArgs;
//MediaType = SYSDATA, StreamType = stPtzPosition;
TPtzPositionArgs = record
Pan: double;
Tilt: double;
end;
PPtzPositionArgs = ^TPtzPositionArgs;
//MediaType = SYSDATA, StreamType = stNotification;
TNotificationArgs = record
Notification:cardinal; //TMediaStreamDataSourceNotification;
SourceId: cardinal;
end;
PNotificationArgs = ^TNotificationArgs;
//MediaType =SYSDATA, StreamType = stVideoAnalytics
TVaData = pointer;
(*
TVaEvent = record
{//// Event type. Can be SVA_EVENT_TYPE_*. }
type_: integer;
{//// Event level. Can be SVA_EVENT_LEVEL_*. }
level: integer;
{//// Object ID or SVA_UNDEFINED_ID. }
object_id: integer;
{//// ID of rule which generates this event or SVA_UNDEFINED_ID. }
rule_id: integer;
{//// Event description. It can be NULL. }
description: string;
end;
TVaEventArray = array of TVaEvent;
TVaObject = record
{//// Unique object ID }
id: integer;
{//// Object type. Can be SVA_OBJECT_TYPE_*. }
type_: integer;
{//// Object position at current time. }
position: TVaPosition;
{//// Object bounding box. }
rect: TRect;
{//// Start object position. }
start_position: TVaPosition;
{//// Object trajectory. }
trajectory: TVaPositionArray;
{//// Index of object region in mask }
mask_index: integer;
{//// Bounding box of object region in mask. }
mask_rect: TRect;
all_events: array of integer; //SVA_EVENT_TYPE_
end;
*)
//Получить человеко-читабельное имя типа потока
function GetStreamTypeName(aStreamType: TStreamType): string;
//Получить тип потока в представлении FourCC (четырехсимвольная строка)
function StreamTypeToFourccString(aStreamType: TStreamType): AnsiString;
//Получить тип потока в представлении FourCC (четырехсимвольная строка), через запятую
function StreamTypesToFourccString(const aStreamTypes: TArray<TStreamType>): AnsiString;
//Преобразовать массив типов потоков в структуру TArray<TStreamType>
function StreamTypesToArray(const aStreamTypes: array of TStreamType): TArray<TStreamType>;
//Преобразовать четырехсимвольную строку в тип потока
function FourccStringToStreamType(aFourcc: AnsiString): TStreamType;
function GetStreamTypeNames(aStreamTypes: TAllMediaStreamTypes; aLongFormat: boolean = true): string;
function FrameFlagsToString(aFlags: TFrameFlags): string;
function IsAppropriateToMediaType(aStreamType: TStreamType; aMediaType: TMediaType): boolean;
type
TConsumingLevel = 0..9;
TMediaProcessorInfo = record
TypeID: TGUID;
Name: string;
Description: string;
InputStreamTypes: TArray<TStreamType>;
InputStreamSubType: string;
OutputStreamType: TStreamType;
OutputStreamSubType: string;
ConsumingLevel:TConsumingLevel;
end;
TMediaProcessorInfoHelper = record helper for TMediaProcessorInfo
procedure Clear;
procedure SetInputStreamType(aStreamType: TStreamType);
procedure SetInputStreamTypes(const aStreamTypes: array of TStreamType);
function CanAcceptInputStreamType(aStreamType: TStreamType): boolean;
function IndexOfInputStreamType(aStreamType: TStreamType): integer;
end;
IMediaProcessor = interface
['{526EF959-157A-4767-96B7-E66012783175}']
function Info: TMediaProcessorInfo;
procedure Prepare;
function HasCustomProperties: boolean;
procedure ShowCustomProperiesDialog;
procedure SaveCustomProperties(aStream: TStream);
procedure LoadCustomProperties(aStream: TStream);
end;
TIMediaProcessorArray = array of IMediaProcessor;
IMediaProcessorImpl = interface (IMediaProcessor)
['{5543C840-A2CB-4624-8C18-83634ACB4A59}']
procedure ProcessData(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
procedure GetLastErrorInfo(out aMessage: string; out aDateTime: TDateTime);
end;
TIMediaProcessorImplArray = array of IMediaProcessorImpl;
TMediaProcessorResult = record
Data: pointer;
DataSize:cardinal;
Info: pointer;
InfoSize: cardinal;
Format: TMediaStreamDataHeader;
end;
TMediaProcessorResultList = TList<TMediaProcessorResult>;
IMediaProcessorImpl2 = interface (IMediaProcessor)
['{D8F15C33-6158-4052-8E66-63D460752418}']
procedure ProcessData2(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal;
aAuxResults: TMediaProcessorResultList);
end;
IMediaProcessor_Convertor_AvcAnyVideo_Rgb = interface
['{10A51974-972B-4768-86ED-54182222D8D3}']
end;
IMediaProcessor_Convertor_Hh_Rgb = interface
['{7738F4A5-3357-45BE-8EF5-7BE4B6B808E9}']
end;
IMediaProcessor_Convertor_H264_Rgb = interface
['{75F3FEEB-24AF-4DBC-89C6-13D986A47FA3}']
end;
IMediaProcessor_Convertor_Rgb_MJpeg = interface
['{74819984-9B95-4C88-9172-47DCBF35F28E}']
end;
IMediaProcessor_Convertor_Rgb_H264 = interface
['{7CDB426E-FC52-486E-801A-E8FBD1229F94}']
end;
IMediaProcessor_Convertor_Rgb_Vfw = interface
['{5182446E-2307-4998-8413-6BDFA8E99820}']
end;
IMediaProcessor_Transformer_Hh = interface
['{7DA18990-DE91-4377-8D95-00E1583821C7}']
end;
IMediaProcessor_Convertor_HhH264_H264 = interface
['{D350E82D-45F0-48AD-80C9-F6DBD04CC759}']
end;
IMediaProcessor_Drawer_Rgb = interface
['{BF4298D5-A15D-4AB3-8CD4-B9ECC383CD96}']
end;
IMediaProcessor_Transformer_Rgb = interface
['{69A016FC-2AAE-468E-8CA4-5CA47B8B5017}']
end;
IMediaProcessor_Panorama_Rgb = interface
['{CFA07663-940D-488D-A658-A30177E39C04}']
end;
IMediaProcessor_Stabilizer_Rgb = interface
['{4ACDA439-C84A-42B4-95B0-5C14FC4FCC97}']
end;
IMediaProcessor_Convertor_HhAu_Pcm = interface
['{B0BC9F25-D4C0-45D6-87CF-4D2314E5CD05}']
end;
IMediaProcessor_Transformer_Pcm = interface
['{1C11C7F1-4973-4C43-BFE0-FFA1814C46DA}']
end;
IMediaProcessor_Processor_Va_Any = interface
['{8234F7FE-1C23-4F20-8ED2-CAB64D3E7E3C}']
end;
const
MediaFilesOpenDialogFilter ='Файлы медиа (*.tsm;*.mp6;*.h264;*.hv;*.avi;*.mkv;*.ps;*.ts;*.mpg;*.ogg;*.asf;*.mov;*.flv;*.webm;*.wav;*.bmp;*.jpg;*.jpeg)|*.tsm;*.mp6;*.h264;*.hv;*.avi;*.mkv;*.ps;*.ts;*.mpg;*.ogg;*.asf;*.mov;*.flv;*.webm;*.wav;*.bmp;*.jpg;*.jpeg|Все файлы|*.*';
implementation
//Продублирована из VFW, чтобы не подключать целый модуль из-за одного макроса
function FOURCCTOSTR(value: cardinal): AnsiString;
var
s: AnsiString;
begin
if value=0 then
exit('NONE');
s:=AnsiChar(Value)+
AnsiChar(Value shr 8)+
AnsiChar(Value shr 16)+
AnsiChar(Value shr 24);
result:=s;
end;
{ TMediaProcessorInfoHelper }
procedure TMediaProcessorInfoHelper.Clear;
begin
FillChar(TypeID,0,sizeof(TypeID));
Name:='';
Description:='';
InputStreamTypes:=nil;
InputStreamSubType:='';
OutputStreamType:=Low(TStreamType);
OutputStreamSubType:='';
ConsumingLevel:=0;
end;
function TMediaProcessorInfoHelper.IndexOfInputStreamType(aStreamType: TStreamType): integer;
var
i: Integer;
begin
result:=-1;
for i := 0 to High(InputStreamTypes) do
begin
if (InputStreamTypes[i]=aStreamType) then
begin
result:=i;
break;
end;
end;
end;
function GetStreamTypeName(aStreamType: TStreamType): string;
begin
case aStreamType of
0: result:='None';
stHHVI: result:='Beward Video';
stHHAU: result:='Beward Audio';
stRGB: result:='RGB';
stMJPEG: result:='MJPG';
stYUV420: result:='YUV 4-2-0';
stH264: result:='H.264';
stUNIV: result:='Container (Universal)';
stMpeg4: result:='MPEG-4';
else
result:=string(FOURCCTOSTR(aStreamType));
end;
end;
function StreamTypeToFourccString(aStreamType: TStreamType): AnsiString;
var
i: Integer;
begin
if aStreamType<10 then
begin
result:='000'+IntToStr(aStreamType);
end
else begin
result:=FOURCCTOSTR(aStreamType);
for i := 1 to Length(result) do
if result[i]<=#32 then
result[i]:='_';
end;
end;
function StreamTypesToFourccString(const aStreamTypes: TArray<TStreamType>): AnsiString;
var
i: Integer;
begin
result:='';
for i := 0 to High(aStreamTypes) do
begin
if result<>'' then
result:=result+', ';
result:=result+StreamTypeToFourccString(aStreamTypes[i]);
end;
end;
function FourccStringToStreamType(aFourcc: AnsiString): TStreamType;
begin
if Length(aFourcc)<>4 then
exit(0);
if aFourcc='NONE' then
exit(0);
Result := (DWord(Ord(aFourcc[1]))) or
(DWord(Ord(aFourcc[2])) shl 8) or
(DWord(Ord(aFourcc[3])) shl 16) or
(DWord(Ord(aFourcc[4])) shl 24);
end;
function GetStreamTypeNames(aStreamTypes: TAllMediaStreamTypes; aLongFormat: boolean = true): string;
begin
if aLongFormat then
result:=Format('Video: %s; Audio: %s',[GetStreamTypeName(aStreamTypes[mtVideo]),GetStreamTypeName(aStreamTypes[mtAudio])])
else
result:=Format('V: %s; A: %s',[GetStreamTypeName(aStreamTypes[mtVideo]),GetStreamTypeName(aStreamTypes[mtAudio])]);
end;
function IsAppropriateToMediaType(aStreamType: TStreamType; aMediaType: TMediaType): boolean;
begin
if aMediaType=mtVideo then
result:=(aStreamType<>stPCM) and (aStreamType<>stPCMU) and (aStreamType<>stHHAU)
else if aMediaType=mtAudio then
result:=(aStreamType=stPCM) or (aStreamType=stHHAU) or (aStreamType=stPCMU) or (aStreamType=stUNIV)
else
result:=true;
end;
function FrameFlagsToString(aFlags: TFrameFlags): string;
begin
result:='';
if ffKeyFrame in aFlags then
result:=result+',key';
if ffInitParamsFrame in aFlags then
result:=result+',init params';
if ffPrebuffer in aFlags then
result:=result+',prebuffer';
if result<>'' then
Delete(result,1,1);
result:='['+result+']';
end;
function StreamTypesToArray(const aStreamTypes: array of TStreamType): TArray<TStreamType>;
var
i: Integer;
begin
SetLength(result,Length(aStreamTypes));
for i := 0 to High(aStreamTypes) do
result[i]:=aStreamTypes[i];
end;
function TMediaProcessorInfoHelper.CanAcceptInputStreamType(aStreamType: TStreamType): boolean;
var
i: Integer;
begin
result:=false;
for i := 0 to High(InputStreamTypes) do
begin
if (InputStreamTypes[i]=aStreamType) or (InputStreamTypes[i]=stCOPY) then
begin
result:=true;
break;
end;
end;
end;
procedure TMediaProcessorInfoHelper.SetInputStreamType(aStreamType: TStreamType);
begin
SetLength(InputStreamTypes,1);
InputStreamTypes[0]:=aStreamType;
end;
procedure TMediaProcessorInfoHelper.SetInputStreamTypes(const aStreamTypes: array of TStreamType);
begin
InputStreamTypes:=StreamTypesToArray(aStreamTypes)
end;
{ TMediaStreamDataHeaderHelper }
procedure TMediaStreamDataHeaderHelper.Assign(const aSource: TBitmapInfoHeader);
begin
self.Clear;
self.biMediaType:=mtVideo;
self.biStreamType:=aSource.biCompression;
if aSource.biCompression=0 then
Self.biStreamType:=stRGB;
self.VideoWidth:=aSource.biWidth;
self.VideoHeight:=aSource.biHeight;
self.VideoBitCount:=aSource.biBitCount;
//self.DataSize:=aSource.biSizeImage;
self.biFrameFlags:=[ffKeyFrame];
end;
procedure TMediaStreamDataHeaderHelper.Assign(const aSource: TPCMWaveFormat);
begin
self.Clear;
self.biMediaType:=mtAudio;
//0 (0x0000) Unknown
//1 (0x0001) PCM/uncompressed
//2 (0x0002) Microsoft ADPCM
//6 (0x0006) ITU G.711 a-law
//7 (0x0007) ITU G.711 Aч-law
//17 (0x0011) IMA ADPCM
//20 (0x0016) ITU G.723 ADPCM (Yamaha)
//49 (0x0031) GSM 6.10
//64 (0x0040) ITU G.721 ADPCM
//80 (0x0050) MPEG
//65,536 (0xFFFF) Experimental
case aSource.wf.wFormatTag of
WAVE_FORMAT_PCM: self.biStreamType:=stPCM;
7:self.biStreamType:=stPCMU;
else
self.biStreamType:=aSource.wf.wFormatTag; //??
end;
self.AudioChannels:=aSource.wf.nChannels;
self.AudioBitsPerSample:=aSource.wBitsPerSample;
self.AudioSamplesPerSec:=aSource.wf.nSamplesPerSec;
self.biFrameFlags:=[ffKeyFrame];
end;
procedure TMediaStreamDataHeaderHelper.Assign(const aSource: TWaveFormatEx);
var
aPCMFormat: TPCMWaveFormat;
begin
aPCMFormat.wf.wFormatTag:=aSource.wFormatTag;
aPCMFormat.wf.nChannels:=aSource.nChannels;
aPCMFormat.wf.nSamplesPerSec:=aSource.nSamplesPerSec;
aPCMFormat.wf.nAvgBytesPerSec:=aSource.nAvgBytesPerSec;
aPCMFormat.wf.nBlockAlign:=aSource.nBlockAlign;
aPCMFormat.wBitsPerSample:=aSource.wBitsPerSample;
Assign(aPCMFormat);
end;
procedure TMediaStreamDataHeaderHelper.AssignBitmap(aVideoWidth, aVideoHeight,aVideoBits: integer);
begin
self.Clear;
self.biMediaType:=mtVideo;
Self.biStreamType:=stRGB;
self.VideoWidth:=aVideoWidth;
self.VideoHeight:=aVideoHeight;
self.VideoBitCount:=aVideoBits;
self.biFrameFlags:=[ffKeyFrame];
end;
procedure TMediaStreamDataHeaderHelper.Clear;
begin
ZeroMemory(@self,sizeof(TMediaStreamDataHeader));
Self.TimeKoeff:=1;
end;
function TMediaStreamDataHeaderHelper.TimeStampMs: int64;
begin
result:=TimeStamp*TimeKoeff;
end;
function TMediaStreamDataHeaderHelper.ToBitmapInfoHeader(aImageSize: cardinal): TBitmapInfoHeader;
begin
if self.biMediaType<>mtVideo then
raise Exception.Create('Данные не являются видео');
ZeroMemory(@result,sizeof(result));
result.biSize:=SizeOf(result);
result.biWidth:=self.VideoWidth;
result.biHeight:=self.VideoHeight;
result.biBitCount:=self.VideoBitCount;
result.biPlanes:=1;
result.biCompression:=self.biStreamType;
result.biSizeImage:=aImageSize;// self.DataSize;
if result.biCompression=stRGB then
result.biCompression:=BI_RGB;
end;
function TMediaStreamDataHeaderHelper.ToPCMWaveFormat: TPCMWaveFormat;
begin
ZeroMemory(@result,sizeof(Result));
Result.wBitsPerSample:=self.AudioBitsPerSample;
Result.wf.nChannels:=self.AudioChannels;
Result.wf.nSamplesPerSec:=self.AudioSamplesPerSec;
Result.wf.nBlockAlign:=(Result.wBitsPerSample div 8) * Result.wf.nChannels;
Result.wf.nAvgBytesPerSec:=Result.wf.nBlockAlign*Result.wf.nSamplesPerSec;
if self.biStreamType=stPCM then
Result.wf.wFormatTag:=WAVE_FORMAT_PCM
else if self.biStreamType=stPCMU then
result.wf.wFormatTag:=7
else
result.wf.wFormatTag:=0;
//0 (0x0000) Unknown
//1 (0x0001) PCM/uncompressed
//2 (0x0002) Microsoft ADPCM
//6 (0x0006) ITU G.711 a-law
//7 (0x0007) ITU G.711 Aч-law
//17 (0x0011) IMA ADPCM
//20 (0x0016) ITU G.723 ADPCM (Yamaha)
//49 (0x0031) GSM 6.10
//64 (0x0040) ITU G.721 ADPCM
//80 (0x0050) MPEG
//65,536 (0xFFFF) Experimental
end;
function TMediaStreamDataHeaderHelper.ToWaveFormatEx: TWaveFormatEx;
var
aPCMFormat: TPCMWaveFormat;
begin
aPCMFormat:=self.ToPCMWaveFormat;
ZeroMemory(@result,sizeof(result));
Result.cbSize:=sizeof(result);
Result.wFormatTag:=aPCMFormat.wf.wFormatTag;
Result.nChannels:=aPCMFormat.wf.nChannels;
Result.nSamplesPerSec:=aPCMFormat.wf.nSamplesPerSec;
Result.nAvgBytesPerSec:=aPCMFormat.wf.nAvgBytesPerSec;
Result.nBlockAlign:=aPCMFormat.wf.nBlockAlign;
Result.wBitsPerSample:=aPCMFormat.wBitsPerSample;
end;
initialization
stKnownTypes[mtVideo]:=StreamTypesToArray(
[stHHVI,
stMJPEG,
stH264,
stMpeg4,
stRGB,
stYUV420,
stUNIV
]);
stKnownTypes[mtAudio]:=StreamTypesToArray(
[
stHHAU,
stPCM,
stPCMU,
stUNIV
]);
stKnownTypes[mtSysData]:=StreamTypesToArray(
[
stPtzPosition,
stVideoAnalytics,
stPING,
stNotification
]);
end.
|
unit uConsts;
interface
uses
Windows, Classes, SysUtils, Graphics, SyncObjs;
const
CST_SYSINFOFILE = 'sysinfo.CSV';
CST_CHANNELFILE = 'channels.csv';
CST_DEFJOBINFOFILE = 'defjobinfo.CSV';
CST_JOBINFOFILE = 'jobinfo.CSV';
LX_AXIS = 0;
SZ_AXIS = 1;
SY_AXIS = 2;
OZ_AXIS = 3;
{ Log On Level }
LOG_USER = 0;
LOG_ADMIN = 1;
LOG_SUPER = 2;
TCP_AUTO_LABEL = 1;
TCP_MANUAL_LABEL = 2;
ID_LOADING_2D_SCANNER_SAMSUNG = 1;
ID_LOADING_2D_SCANNER_SPECIAL = 1;
ID_OUTLET_2D_SCANNER_SAMSUNG = 2;
ID_OUTLET_2D_SCANNER_SPECIAL = 2;
{ 에러 번호 }
WARN_EMERGENCY = 1001;
WARN_NOT_MAIN_AIR = 1002;
WARN_SUB_POWER_OFF = 1003;
WARN_DC02_POWER_OFF = 1004;
WARN_HEATER_POWER_OFF = 1005;
WARN_HEATER_TEMP_ERROR = 1006;
ERR_HEATER_TEMP_OVER = 1007;
ERR_NOT_SERIAL_COMM = 1008;
ERR_NOT_PRODUCT_DATA = 1009;
WARN_HEATER_CHANGE = 1010;
WARN_FRONT_SEALING_HEATER_TEMP_ERROR = 1011;
WARN_FRONT_SEALING_HEATER_TEMP_OVER = 1012;
WARN_FRONT_DOOR_OPEN_CHECK = 1101;
WARN_LEFT_DOOR_OPEN_CHECK = 1102;
WARN_RIGHT_DOOR_OPEN_CHECK = 1103;
WARN_REAR_DOOR_OPEN_CHECK = 1104;
WARN_LABEL_PRINTER_DOOR_OPEN_CHECK = 1105;
WARN_SHIELDBAG_STACKER_DOOR_OPEN_CHECK = 1106;
WARN_VT5070_FENCE_DOOR_OPEN_CHECK = 1107;
WARN_TRAY_LOADING_DOOR_OPEN_CHECK = 1108;
WARN_SHIELDBAG_SLIDE_DOOR_OPEN_CHECK = 1109;
WARN_X080B_FRONT_BOTTOM_COVER_CHECK = 1110;
WARN_X080C_REAR_LEFT_BOTTOM_COVER_CHECK = 1111;
WARN_BUFFER_CONVEYOR_DOOR_OPEN_CHECK = 1112;
WARN_AUTO_RUNNING = 1301;
ERR_NOT_INITIALIZE_ALL = 1303;
ERR_HEATING_TIME_INSUFFICIENCY_3500 = 1400;
ERR_HEATING_TIME_INSUFFICIENCY_90P = 1401;
ERR_X011E_LOADING_CONVEYOR_RUN_CHECK = 1501;
ERR_X011E_LOADING_CONVEYOR_STOP_CHECK = 1502;
ERR_X0120_LOADING_CONVEYOR_BOX_IN_CHECK = 1503;
ERR_X0121_LOADING_CONVEYOR_BOX_1ST_CHECK = 1504;
ERR_X0122_LOADING_CONVEYOR_BOX_2ND_CHECK = 1505;
ERR_X0123_LOADING_CONVEYOR_BOX_OUT_CHECK = 1506;
ERR_X0120_NOT_LOADING_CONVEYOR_BOX_IN_CHECK = 1507;
ERR_X0121_NOT_LOADING_CONVEYOR_BOX_1ST_CHECK = 1508;
ERR_X0122_NOT_LOADING_CONVEYOR_BOX_2ND_CHECK = 1509;
ERR_X0123_NOT_LOADING_CONVEYOR_BOX_OUT_CHECK = 1510;
ERR_X0124_LOADING_1ST_STOPPER_UP_CHECK = 1511;
ERR_X0125_LOADING_1ST_STOPPER_DOWN_CHECK = 1512;
ERR_X0126_LOADING_2ND_STOPPER_UP_CHECK = 1513;
ERR_X0127_LOADING_2ND_STOPPER_DOWN_CHECK = 1514;
ERR_X0128_LOADING_SCANNER_PUSH_CHECK = 1515;
ERR_X0129_LOADING_SCANNER_BACK_CHECK = 1516;
ERR_X0600_INLET_CONVEYOR_IN_CHECK = 1601;
ERR_X0601_INLET_CONVEYOR_MIDDLE_CHECK = 1602;
ERR_X0602_INLET_CONVEYOR_OUT_CHECK = 1603;
ERR_TRAY_STOP_POSITION_ARRIVAL = 1604;
ERR_INLET_CONVEYOR_STOP_POSITION_ARRIVAL = 1608;
ERR_X0608_INLET_FRONT_FORM_PAD_CHECK = 1609;
ERR_X0609_INLET_REAR_FORM_PAD_CHECK = 1610;
ERR_LABEL_PRINTER_LABEL_ARRIVAL = 1611;
ERR_STACKER_SHIELDBAG_ARRIVAL = 1612;
ERR_STACKER_SHIELDBAG_TOP_ARRIVAL = 1613;
ERR_OUTLET_CONVEYOR_SHIELDBAG_OUT_ARRIVAL = 1615;
ERR_OUTLET_CONVEYOR_SHIELDBAG_IN_ARRIVAL = 1616;
ERR_SHIELDBAG_GRIPPER_FRONT_SHIELDBAG_ARRIVAL = 1617;
ERR_SHIELDBAG_GRIPPER_REAR_SHIELDBAG_ARRIVAL = 1618;
ERR_LABEL_HAVE_CHECK = 1619;
ERR_BUFFER_CONVEYOR_TRAY_OUT_ARRIVAL = 1620;
ERR_X011B_TRAY_FORM_PAD_REAR_CYLINDER_UP = 1624;
ERR_X011C_TRAY_FORM_PAD_REAR_CYLINDER_DOWN = 1625;
ERR_X011D_TRAY_FORM_PAD_FRONT_CYLINDER_UP = 1626;
ERR_X011E_TRAY_FORM_PAD_FRONT_CYLINDER_DOWN = 1627;
ERR_X0109_INLET_CONVEYOR_RUN_CHECK = 1649;
ERR_X0109_INLET_CONVEYOR_STOP_CHECK = 1650;
ERR_NOT_X0600_INLET_CONVEYOR_IN_CHECK = 1651;
ERR_NOT_X0601_INLET_CONVEYOR_MIDDLE_CHECK = 1652;
ERR_NOT_X0602_INLET_CONVEYOR_OUT_CHECK = 1653;
ERR_NOT_TRAY_STOP_POSITION_ARRIVAL = 1654;
ERR_NOT_INLET_CONVEYOR_STOP_POSITION_ARRIVAL = 1658;
ERR_NOT_X0608_INLET_FRONT_FORM_PAD_CHECK = 1659;
ERR_NOT_X0609_INLET_REAR_FORM_PAD_CHECK = 1660;
ERR_NOT_LABEL_PRINTER_LABEL_ARRIVAL = 1661;
ERR_NOT_STACKER_SHIELDBAG_ARRIVAL = 1662;
ERR_NOT_STACKER_SHIELDBAG_TOP_ARRIVAL = 1663;
ERR_STACKER_SHIELDBAG_OUT_POSTION_ARRIVAL = 1664;
ERR_NOT_OUTLET_CONVEYOR_SHIELDBAG_OUT_ARRIVAL = 1665;
ERR_NOT_OUTLET_CONVEYOR_SHIELDBAG_IN_ARRIVAL = 1666;
ERR_NOT_SHIELDBAG_GRIPPER_FRONT_SHIELDBAG_ARRIVAL = 1667;
ERR_NOT_SHIELDBAG_GRIPPER_REAR_SHIELDBAG_ARRIVAL = 1668;
ERR_NOT_BUFFER_CONVEYOR_TRAY_OUT_ARRIVAL = 1669;
ERR_STACKER_MOTOR_RUN_CHECK = 1701;
ERR_LOADER_CONVEYOR_RUN_CHECK = 1702;
ERR_OUTLET_CONVEYOR_MOTOR_RUN_CHECK = 1703;
ERR_INLET_CONVEYOR_RUN_CHECK = 1704;
ERR_X0316_STACKER_MOTOR_UP_LIMIT_CHECK = 1705;
ERR_X0317_STACKER_MOTOR_DOWN_LIMIT_CHECK = 1706;
ERR_X012A_LOADING_DOOR_LOCK_CHECK = 1801;
ERR_X0800_SHIELDBAG_STACKER_DOOR_LOCK_CHECK = 1802;
ERR_X0802_LABEL_PRINTER_DOOR_LOCK_CHECK = 1803;
ERR_X0803_FRONT_DOOR_UPPER_LOCK_CHECK = 1804;
ERR_X0804_FRONT_DOOR_LOWER_LOCK_CHECK = 1805;
ERR_X0805_MONITOR_DOOR_UPPER_LOCK_CHECK = 1806;
ERR_X0806_MONITOR_DOOR_LOWER_LOCK_CHECK = 1807;
ERR_X0807_LEFT_DOOR_LOCK_CHECK = 1808;
ERR_X0808_RIGHT_DOOR_LOCK_CHECK = 1809;
ERR_X0809_REAR_DOOR_LOCK_CHECK = 1810;
ERR_X080A_RIGHT_DOOR_LOCK_CHECK = 1811;
ERR_X0301_LABEL_PRINTER_SLIDE_LOCK_CHECK = 1812;
ERR_X0302_LABEL_PRINTER_SLIDE_UNLOCK_CHECK = 1813;
ERR_X0312_STACKER_LOCK_CHECK = 1814;
ERR_X0313_STACKER_UNLOCK_CHECK = 1815;
ERR_X0319_STACKER_SLIDE_LOCK_CHECK = 1816;
ERR_X031A_STACKER_SLIDE_UNLOCK_CHECK = 1817;
ERR_X063D_SEALING_TOP_SLIDE_LOCK_CHECK = 1818;
ERR_X063E_SEALING_TOP_SLIDE_UNLOCK_CHECK = 1819;
ERR_STACKER_SLIDE_CLOSE_ARRIVAL = 1820;
ERR_X063F_SEALING_TOP_SLIDE_CLOSE_ARRIVAL = 1821;
ERR_X0300_LABEL_PRINTER_SLIDE_CLOSE_CHECK = 1822;
ERR_X0117_BUFFER_CONVEYOR_DOOR_LOCK_CHECK = 1823;
ERR_X011A_FRONT_LOWER_DOOR_LOCK_CHECK = 1824;
ERR_X0911_LOADING_DOOR_LOCK_CHECK = 1825;
ERR_X0303_LABEL_PICKER_PICK_POSITION_CHECK = 2007;
ERR_X0304_LABEL_PICKER_ATTACH_POSITION_CHECK = 2008;
ERR_X0305_LABEL_PICKER_UP_CHECK = 2009;
ERR_X0306_LABEL_PICKER_DOWN_CHECK = 2010;
ERR_X0307_LABEL_PICKER_ROTATOR_TURN_CHECK = 2011;
ERR_X0308_LABEL_PICKER_ROTATOR_HOME_CHECK = 2012;
ERR_X0309_LABEL_PICKER_VACUUM_CHECK = 2013;
ERR_X0310_STACKER_OUT_CHECK = 2014;
ERR_X0311_STACKER_IN_CHECK = 2015;
ERR_X0500_SHIELDBAG_PICKER_DROP_POSITION_CHECK = 2016;
ERR_X0501_SHIELDBAG_PICKER_PICK_POSITION_CHECK = 2017;
ERR_X0502_SHIELDBAG_PICKER_SHORT_DOWN_CHECK = 2018;
ERR_X0503_SHIELDBAG_PICKER_LONG_DOWN_CHECK = 2019;
ERR_X0504_SHIELDBAG_PICKER_UP_CHECK = 2020;
ERR_X0505_SHIELDBAG_PICKER_VACUUM_CHECK = 2021;
ERR_X0604_INLET_FRONT_STOPPER_EXT_CHECK = 2022;
ERR_X0605_INLET_FRONT_STOPPER_RET_CHECK = 2023;
ERR_X0606_INLET_REAR_STOPPER_EXT_CHECK = 2024;
ERR_X0607_INLET_REAR_STOPPER_RET_CHECK = 2025;
ERR_X060A_TURN_GUIDE_FRONT_TURN_CHECK = 2026;
ERR_X060B_TURN_GUIDE_FRONT_HOME_CHECK = 2027;
ERR_X060C_TURN_GUIDE_REAR_TURN_CHECK = 2028;
ERR_X060D_TURN_GUIDE_REAR_HOME_CHECK = 2029;
ERR_X060E_TURN_GUIDE_FRONT_UP_CHECK = 2030;
ERR_X060F_TURN_GUIDE_FRONT_DOWN_CHECK = 2031;
ERR_X0610_TURN_GUIDE_REAR_UP_CHECK = 2032;
ERR_X0611_TURN_GUIDE_REAR_DOWN_CHECK = 2033;
ERR_X0612_INLET_TRAY_1ST_PUSHER_PUSH_CHECK = 2034;
ERR_X0613_INLET_TRAY_1ST_PUSHER_BACK_CHECK = 2035;
ERR_X0614_INLET_TRAY_2ND_PUSHER_PUSH_CHECK = 2036;
ERR_X0615_INLET_TRAY_2ND_PUSHER_BACK_CHECK = 2037;
ERR_X0616_INLET_TRAY_PUSHER_UP_CHECK = 2038;
ERR_X0617_INLET_TRAY_PUSHER_DOWN_CHECK = 2039;
ERR_X061A_OUTLET_CONVEYOR_BOTTOM_PUSHER_UP_CHECK = 2040;
ERR_X061B_OUTLET_CONVEYOR_BOTTOM_PUSHER_DOWN_CHECK = 2041;
ERR_X061C_OUTLET_SHIELDBAG_FRONT_GUIDE_EXT_CHECK = 2042;
ERR_X061D_OUTLET_SHIELDBAG_FRONT_GUIDE_RET_CHECK = 2043;
ERR_X061E_OUTLET_SHIELDBAG_REAR_GUIDE_EXT_CHECK = 2044;
ERR_X061F_OUTLET_SHIELDBAG_REAR_GUIDE_RET_CHECK = 2045;
ERR_X0620_NOZZLE_IN_CHECK = 2046;
ERR_X0621_NOZZLE_OUT_CHECK = 2047;
ERR_X0906_NOZZLE_VACUUM_CHECK = 2048;
ERR_X0624_SHIELDBAG_GRIPPER_FRONT_SHIELDBAG_CHECK = 2049;
ERR_X0625_SHIELDBAG_GRIPPER_REAR_SHIELDBAG_CHECK = 2050;
ERR_X0626_SHIELDBAG_FRONT_GRIPPER_OPEN_CHECK = 2051;
ERR_X0627_SHIELDBAG_FRONT_GRIPPER_CLOSE_CHECK = 2052;
ERR_X0628_SHIELDBAG_REAR_GRIPPER_OPEN_CHECK = 2053;
ERR_X0629_SHIELDBAG_REAR_GRIPPER_CLOSE_CHECK = 2054;
ERR_X062A_SHIELDBAG_GRIPPER_FRONT_1ST_UP_CHECK = 2055;
ERR_X062B_SHIELDBAG_GRIPPER_FRONT_1ST_DOWN_CHECK = 2056;
ERR_X062C_SHIELDBAG_GRIPPER_REAR_1ST_UP_CHECK = 2057;
ERR_X062D_SHIELDBAG_GRIPPER_REAR_1ST_DOWN_CHECK = 2058;
ERR_X062E_SHIELDBAG_GRIPPER_2ND_EXT_CHECK = 2059;
ERR_X062F_SHIELDBAG_GRIPPER_2ND_RET_CHECK = 2060;
ERR_X0630_SEALING_BOTTOM_FRONT_VACUUM_POS_CHECK = 2061;
ERR_X0631_SEALING_BOTTOM_FRONT_SEALING_POS_CHECK = 2062;
ERR_X0632_SEALING_BOTTOM_REAR_VACUUM_POS_CHECK = 2063;
ERR_X0633_SEALING_BOTTOM_REAR_SEALING_POS_CHECK = 2064;
ERR_X0634_SEALING_BOTTOM_PICKER_UP_CHECK = 2065;
ERR_X0635_SEALING_BOTTOM_PICKER_DOWN_CHECK = 2066;
ERR_X0636_SEALING_BOTTOM_SUPPORT_UP_CHECK = 2067;
ERR_X0637_SEALING_BOTTOM_SUPPORT_DOWN_CHECK = 2068;
ERR_X0638_SEALING_BOTTOM_VACUUM_CHECK = 2069;
ERR_X0639_SEALING_TOP_FRONT_VACUUM_POS_CHECK = 2070;
ERR_X063A_SEALING_TOP_FRONT_POS_SEALING_POS_CHECK = 2071;
ERR_X063B_SEALING_TOP_REAR_VACUUM_POS_CHECK = 2072;
ERR_X063C_SEALING_TOP_REAR_SEALING_POS_CHECK = 2073;
ERR_X1000_SEALING_TOP_PRESS_UP_CHECK = 2074;
ERR_X1001_SEALING_TOP_PRESS_DOWN_CHECK = 2075;
ERR_X1002_SEALING_TOP_HEATER_UP_CHECK = 2076;
ERR_X1003_SEALING_TOP_HEATER_DOWN_CHECK = 2077;
ERR_X1004_SEALING_TOP_PICKER_UP_CHECK = 2078;
ERR_X1005_SEALING_TOP_PICKER_MIDDLE_CHECK = 2079;
ERR_X1006_SEALING_TOP_PICKER_DOWN_CHECK = 2080;
ERR_X1007_SEALING_TOP_VACUUM_CHECK = 2081;
ERR_X012D_TRAY_LOADING_TOP_PAD_CHECK = 2082;
ERR_X030B_LABEL_PICKER_TWO_LABEL_POS = 2083;
ERR_X030C_LABEL_PICKER_ONE_LABEL_POS = 2084;
ERR_X0506_SHIELDBAG_PICKER_SHIELDBAG_CHECK = 2085;
ERR_FRONT_LOADCELL_PRESSURE_OVER = 2090;
ERR_REAR_LOADCELL_PRESSURE_OVER = 2091;
ERR_FRONT_LOADCELL_DEVICE_ERROR = 2092;
ERR_REAR_LOADCELL_DEVICE_ERROR = 2093;
ERR_LOADCELL_PRESS_BALANCE_ERROR = 2094;
ERR_FRONT_LOADCELL_PRESS_ON_TIME_SHORTAGE_ERROR = 2095;
ERR_REAR_LOADCELL_PRESS_ON_TIME_SHORTAGE_ERROR = 2096;
ERR_FRONT_LOADCELL_HUNTING_ERR = 2097;
ERR_REAR_LOADCELL_HUNTING_ERR = 2098;
ERR_X010D_TWO_STACKER_MOTOR_POWER_CHECK = 2101;
ERR_NOT_X010D_TWO_STACKER_MOTOR_POWER_CHECK = 2102;
ERR_X0810_TWO_STACKER_IN_CHECK = 2103;
ERR_X0811_TWO_STACKER_IN_SLOW_CHECK = 2104;
ERR_X0812_TWO_STACKER_MIDDLE_FRONT_SLOW_CHECK = 2105;
ERR_X0813_TWO_STACKER_MIDDLE_CHECK = 2106;
ERR_X0814_TWO_STACKER_MIDDLE_REAR_SLOW_CHECK = 2107;
ERR_X0815_TWO_STACKER_OUT_CHECK = 2108;
ERR_X0816_TWO_STACKER_OUT_SLOW_CHECK = 2109;
ERR_X031B_TWO_STACKER_2ND_LOCK_CHECK = 2110;
ERR_X031D_TWO_STACKER_1ST_LOCK_CHECK = 2111;
ERR_X031C_TWO_STACKER_2ND_UNLOCK_CHECK = 2112;
ERR_X031E_TWO_STACKER_1ST_UNLOCK_CHECK = 2113;
ERR_X0315_STACKER_SHIELDBAG_TOP_CHECK = 2114;
ERR_X0309_LABEL_SELF_CHECK = 2602; //Label Print vaccum 자가 진단 *****ljh
//ERR_X1225_DESICCANT_SELF_CHECK = 2603; //데시팩 자가 진단 Error *****ljh
//ERR_X0613_INDICATOR_SELF_CHECK = 2604; //인디게이터 자가 진단 Error *****ljh
ERR_X0505_SHIELDBAG_SELF_CHECK = 2605; //실드백 피커 자가 진단 error *****ljh
ERR_SHILD_BAG_REMOVE = 2700;
WARN_EMPTY_SHIELDBAG = 3001;
ERR_NOT_LOADING_SAMSUNG_LABEL_SCAN = 3002;
ERR_NOT_LOADING_SPECIAL_LABEL_SCAN = 3003;
ERR_NOT_SHIELDBAG_SAMSUNG_LABEL_SCAN = 3004;
ERR_NOT_SHIELDBAG_SPECIAL_LABEL_SCAN = 3005;
ERR_EC_DATA_CHECK = 3006;
ERR_EC_DATA_RECEIVE_FAIL = 3007;
ERR_EC_SERVER_COMM_FAIL = 3008;
ERR_NOT_SAME_LOADING_LOTID = 3009;
ERR_NOT_SAME_OUTLET_LOTID = 3010;
ERR_PRINT_COMM = 3011;
WARN_PRINT_PAPER_OUT = 3012;
WARN_PRINT_RIBON_OUT = 3013;
WARN_PRINT_OFF_LINE = 3014;
WARN_PRINT_HEAD_UP = 3015;
ERR_PRINT_PRINTING_FAIL = 3016;
ERR_X030A_LABEL_REMOVE = 3500;
ERR_EC_CUSTOMER_CHECK = 3017;
ERR_EC_DATA_LENGTH_FORMAT_FAIL = 3018;
ERR_EC_SERVER_RECEIVE_DATA_LENGTH_CHECK_FAIL = 3019;
ERR_PRINTER_COUNT_INIT = 3605; //라벨 프린터 수량 카운트 추가 *****LJH
ERR_PRINTER_BLACK_PAPER_EMPTY = 3606; //라벨 프린터 수량 카운트 추가 *****LJH
ERR_X0303_LABEL_SELF_CHECK = 3607;
ERR_X0603_INLET_CONVEYOR_STOP_POSITION = 3608;
ERR_PRINTER_COUNT_INIT_1 = 3616; //라벨 프린터 수량 카운트 추가 1 *****LJH
ERR_PRINTER_LABEL_EMPTY = 3617; //라벨 프린터 수량 카운트 추가 1 *****LJH
ERR_SPECIAL_LABEL_EXIT = 3621;
ERR_INLET_SPECIAL_SCAN = 3626;
ERR_OUTLET_SPECIAL_SCAN = 3627;
ERR_1ST_LABEL_FORMAT = 3718; //라벨 양식 없음 ERROR *****LJH
ERR_2ND_LABEL_FORMAT = 3719; //라벨 양식 없음 ERROR *****LJH
ERR_EC_LABEL_FORMAT = 3720; //라벨 양식 없음 ERROR *****LJH
ERR_X0104_N2_SENSOR = 3750; //N2 감지 센서 추가 *****ljh
ERR_X0529_OUTLET_CONVEYOR_SCANNER_CYLINDER_EXT = 3751;
ERR_X052A_OUTLET_CONVEYOR_SCANNER_CYLINDER_RET = 3752;
ERR_OZ_AXIS_MOVE_ENABLE = 3753;
ERR_SHIELDBAG_PICKER_MOVE_TO_PICKPOS_TIMEOUT = 3800;
ERR_SHIELDBAG_PICKER_MOVE_DOWN_TIMEOUT = 3801;
ERR_SHIELDBAG_PICKER_MOVE_UP_TIMEOUT = 3802;
ERR_SHIELDBAG_DIRECTION_SCANNER_STATUS_FAIL = 3810;
ERR_SHIELDBAG_DIRECTION_SCANNER_DIRECTION_ERR = 3811;
ERR_SHIELDBAG_DIRECTION_SCANNER_PRESCAN_FAIL = 3812;
WARN_CANT_MOVE_1ST_STOPPER = 4001;
WARN_CANT_MOVE_2ND_STOPPER = 4002;
WARN_CANT_MOVE_1ST_PUSHER = 4003;
WARN_CANT_MOVE_UPDOWN_PUSHER = 4004;
WARN_CANT_MOVE_INLET_STOPPER = 4005;
WARN_CANT_MOVE_UPDOWN_LABEL_PICKER = 4006;
WARN_CANT_MOVE_POSITIONER_LABEL_PICKER = 4007;
WARN_CANT_MOVE_TURN_LABEL_PICKER = 4008;
WARN_CANT_MOVE_BOTTOM_SEALING_PICKER = 4009;
WARN_CANT_MOVE_BOTTOM_SEALING_POSITIONER = 4010;
WARN_CANT_MOVE_BOTTOM_SEALING_SUPPORT = 4011;
WARN_CANT_MOVE_SEALING_1ST_UPDOWN_GRIPPER = 4012;
WARN_CANT_MOVE_SEALING_NOZZLE = 4013;
WARN_CANT_MOVE_TOP_SEALING_HEATER = 4014;
WARN_CANT_MOVE_TOP_SEALING_PICKER = 4015;
WARN_CANT_MOVE_TOP_SEALING_PRESS = 4016;
WARN_CANT_MOVE_TOP_SEALING_POSITIONER = 4017;
WARN_CANT_MOVE_TURN_GUIDE = 4018;
WARN_CANT_MOVE_SHIELDBAG_PICKER_POSITIONER = 4019;
WARN_CANT_MOVE_SHIELDBAG_PICKER_UPDOWN = 4020;
WARN_CANT_MOVE_TRACKER_POSITIONER = 4021;
WARN_INLET_DEVICE_TOUCH = 6001;
WARN_INLET_DEVICE_REMOVAL = 6002;
WARN_SHIELDBAG_PICKER_DEVICE_REMOVAL = 6003;
WARN_OUTLET_DEVICE_REMOVAL = 6004;
ERR_LX_AXIS_POS = 6051;
ERR_SY_AXIS_POS = 6052;
ERR_SZ_AXIS_POS = 6053;
ERR_OZ_AXIS_POS = 6054;
ERR_FRONT_SEALING_HEATER_COMMUNICATION_FAIL = 7000;
ERR_REAR_SEALING_HEATER_COMMUNICATION_FAIL = 7001;
{ 메시지 ID }
STR_OK = 1;
STR_CANCEL = 2;
STR_FINISH = 3;
STR_CLOSE = 4;
STR_READY = 5;
STR_PROJECT = 6;
STR_SYSTEM_STOP = 7;
STR_JOG = 8;
STR_UP = 9;
STR_DOWN = 10;
STR_LEFT = 11;
STR_RIGHT = 12;
STR_BACKWARD = 13;
STR_FORWARD = 14;
STR_QUERY_EXIT_PROGRAM = 15;
STR_NOT_FOUND_SYSINFOFILE = 16;
STR_NOT_FOUND_CHANNELFILE = 17;
STR_IO_SERVICE_NOT_INSTALLED = 18;
STR_AIO_SERVICE_NOT_INSTALLED = 19;
STR_CANNOT_STARTUP_AMC = 20;
STR_INIT_AXIS = 21;
STR_INVALID_KEY = 22;
STR_CURRENT_JOB = 23;
STR_INPUT_PASSWORD = 24;
STR_INPUT_NEW_PASSWORD = 25;
STR_PASSWORD_OK = 26;
STR_WRONG_PASSWORD = 27;
STR_LOGIN = 28;
STR_LOGOUT = 29;
STR_MANAUL_IO_RUNNING = 30;
STR_SELECT_OPERATOR_ID = 31;
STR_NOT_IMAGE_FILE = 32;
STR_INITIALIZE = 33;
STR_LARGE_BOX_OUTPUT = 34;
var
{ 로깅 레벨 }
VerboseMode : Integer;
{ Demo Mode ? }
StartUpWithHW : Boolean;
StartUpWithTwoShieldbag : Boolean;
LogOnLevel : Integer;
LoggedUser : String;
{ 시스템 정보 파일 }
InfoFile : string;
{ 시스템 설정 정보 파일 }
SysInfoFile : string;
{ 시스템 설정 정보 파일 }
DefSysInfoFile : string;
{ 기본 프로젝트 설정 정보 파일 }
DefJobInfoFile : string;
{ 프로젝트 설정 정보 파일 }
JobInfoFile : string;
{ 채널 설정 정보 파일 }
tmpJobInfoFile : string;
{ 채널 임시 설정 정보 파일 }
ChannelInfoFile : string;
{ 현재 프로젝트 }
CurProject : string;
{ 현재 프로젝트 정보가 있는 디렉토리 이름 }
CurProjectDir : string;
{ 마지막 작업일 }
LastWorkDate : TDateTime;
SysInfoLoaded : Boolean;
SelectGroupName : String;
tmpFolderRow : Integer;
tmpJobsRow : Integer;
FSelectedNode : Integer;
MotionCardNo : Integer;
CS_PRINTER : TCriticalSection;
CS_SOUND : TCriticalSection;
gEditName : String;
gEditValueInfo : String;
gKeyPadForm : String;
gAlphabet : Boolean;
resourcestring
SFileNotFound = 'The File %s does not exist';
implementation
initialization
CS_PRINTER := TCriticalSection.Create;
CS_SOUND := TCriticalSection.Create;
finalization
CS_PRINTER.Free;
CS_SOUND.Free;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x10;
interface
Uses SysUtils, uxPLRFXConst, u_xpl_message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
implementation
(*
Type $10 - Lighting1 - X10, ARC, ELRO, Waveman, EMW200, Impuls, RisingSun, Philips, Energenie
Buffer[0] = packetlength = $07
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = sequence number
Buffer[4] = housecode
Buffer[5] = unitcode
Buffer[6] = cmnd
Buffer[7] = filler:4/rssi:4
Test Strings :
071000B7490A0160
071000E0490C0060
0710010E430E0180
xPL Schema
x10.basic
{
device=<housecode[unitcode]
command=on|off|dim|bright|all_lights_on|all_lights_off|chime
[protocol=arc]
}
*)
const
// Packet length
PACKETLENGTH = $07;
// Type
LIGHTING1 = $10;
// Subtype
X10 = $00;
ARC = $01;
ELBRO = $02;
WAVEMAN = $03;
CHACON_EMW200 = $04;
IMPULS = $05;
RISINGSUN = $06;
PHILIPS_SBC = $07;
ENERGENIE = $08;
// Commands
COMMAND_OFF = 'off';
COMMAND_ON = 'on';
COMMAND_DIM = 'dim';
COMMAND_BRIGHT = 'bright';
COMMAND_GROUPOFF = 'group off';
COMMAND_GROUPON = 'group on';
COMMAND_CHIME = 'chime';
var
// Lookup table for commands
RFXCommandArray : array[1..7] of TRFXCommandRec =
((RFXCode : $00; xPLCommand : COMMAND_OFF),
(RFXCode : $01; xPLCommand : COMMAND_ON),
(RFXCode : $02; xPLCommand : COMMAND_DIM),
(RFXCode : $03; xPLCommand : COMMAND_BRIGHT),
(RFXCode : $05; xPLCommand : COMMAND_GROUPOFF),
(RFXCode : $06; xPLCommand : COMMAND_GROUPON),
(RFXCode : $07; xPLCommand : COMMAND_CHIME));
SubTypeArray : array[1..9] of TRFXSubTypeRec =
((SubType : X10; SubTypeString : 'x10'),
(SubType : ARC; SubTypeString : 'arc'),
(SubType : ELBRO; SubTypeString : 'elbro'),
(SubType : WAVEMAN; SubTypeString : 'waveman'),
(SubType : CHACON_EMW200; SubTypeString : 'chacon'),
(SubType : IMPULS; SubTypeString : 'impuls'),
(SubType : RISINGSUN; SubTypeString : 'risingsun'),
(SubType : PHILIPS_SBC; SubTypeString : 'philips'),
(SubType : ENERGENIE; SubTypeString : 'energenie'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
HouseCode : Byte;
UnitCode : Byte;
Command : String;
xPLMessage : TxPLMessage;
begin
HouseCode := Buffer[4];
UnitCode := Buffer[5];
Command := GetxPLCommand(Buffer[6],RFXCommandArray);
// Create x10.basic message
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'x10.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+Chr(HouseCode)+IntToStr(UnitCode));
xPLMessage.Body.AddKeyValue('command='+Command);
xPLMessage.Body.AddKeyValue('protocol='+GetSubTypeString(Buffer[2],SubTypeArray));
xPLMessages.Add(xPLMessage.RawXPL);
end;
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
// Remark : only X10 and ARC are received. The presence of protocol=arc allows
// to distinguish between them
begin
ResetBuffer(Buffer);
Buffer[0] := PACKETLENGTH;
Buffer[1] := LIGHTING1; // Type
// Subtype
Buffer[2] := GetSubTypeFromString(aMessage.Body.Strings.Values['protocol'],SubTypeArray);
// Sequence number is fixed value 2
Buffer[3] := $01;
// Split the device attribute in housecode and unitcode
Buffer[4] := Ord(aMessage.Body.Strings.Values['device'][1]);
Buffer[5] := StrToInt(Copy(aMessage.Body.Strings.Values['device'],2,Length(aMessage.Body.Strings.Values['device'])));
// Command
Buffer[6] := GetRFXCode(aMessage.Body.Strings.Values['command'],RFXCommandArray);
Buffer[7] := $0;
end;
end.
|
unit TestIfElseBreaks;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestIfElseBreaks
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess, SettingsTypes;
type
TTestIfElseBreaks = class(TBaseTestProcess)
private
leSaveIfElseStyle, leSaveBareBlockStyle: TTriOptionStyle;
leSaveCaseLabelStyle, leSaveCaseElseStyle: TTriOptionStyle;
leSaveEndElseStyle: TTriOptionStyle;
leSaveElseBeginStyle: TTriOptionStyle;
leSaveBlockBeginStyle: TTriOptionStyle;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestIfElseRemoveReturn1;
procedure TestIfElseRemoveReturn2;
procedure TestIfElseAddReturn1;
procedure TestIfElseAddReturn2;
procedure TestIfElseLeaveReturnAsIs1;
procedure TestIfElseLeaveReturnAsIs2;
procedure TestBlockStyleNever;
procedure TestBlockStyleNeverWithComment;
procedure TestIfBeginStyleNever;
procedure TestIfBeginStyleAlways;
procedure TestIfElseStyleNever;
procedure TestIfElseNeverWithComment;
procedure TestCaseStatementNever1;
procedure TestCaseStatementNever2;
procedure TestCaseStatementLeaveAsIs1;
procedure TestCaseStatementLeaveAsIs2;
procedure TestCaseStatementAlways1;
procedure TestCaseStatementAlways2;
procedure TestEndElseStyle1;
procedure TestEndElseStyle2;
procedure TestEndElseStyle3;
procedure TestEndElseStyle4;
procedure TestEndElseStyle5;
procedure TestEndElseStyle6;
procedure TestAddElseBegin1;
procedure TestAddElseBegin2;
procedure TestRemoveElseBegin1;
procedure TestRemoveElseBegin2;
end;
implementation
uses
JcfStringUtils,
BlockStyles, JcfSettings, SetReturns;
const
RETURN_ADDED_TEXT =
'unit TestIfElseBreak;' + NativeLineBreak +
NativeLineBreak +
'interface' + NativeLineBreak +
NativeLineBreak +
'implementation' + NativeLineBreak +
NativeLineBreak +
'uses Dialogs;' + NativeLineBreak +
NativeLineBreak +
'procedure TestBreaks;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'');' + NativeLineBreak +
NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else' + NativeLineBreak +
' ShowMessage(''false'');' + NativeLineBreak +
NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else' + NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else' + NativeLineBreak +
' ShowMessage(''false'');' + NativeLineBreak +
'end;' + NativeLineBreak +
NativeLineBreak +
'end.';
RETURN_REMOVED_TEXT =
'unit TestIfElseBreak;' + NativeLineBreak +
NativeLineBreak +
'interface' + NativeLineBreak +
NativeLineBreak +
'implementation' + NativeLineBreak +
NativeLineBreak +
'uses Dialogs;' + NativeLineBreak +
NativeLineBreak +
'procedure TestBreaks;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'');' + NativeLineBreak +
NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else' + NativeLineBreak +
' ShowMessage(''false'');' + NativeLineBreak +
NativeLineBreak +
'if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else if True then' + NativeLineBreak +
' ShowMessage(''twoo'')' + NativeLineBreak +
'else' + NativeLineBreak +
' ShowMessage(''false'');' + NativeLineBreak +
'end;' + NativeLineBreak +
NativeLineBreak +
'end.';
{ TTestIfElseBreaks }
procedure TTestIfElseBreaks.Setup;
begin
inherited;
leSaveIfElseStyle := JcfFormatSettings.Returns.ElseIfStyle;
leSaveBareBlockStyle := JcfFormatSettings.Returns.BlockStyle;
leSaveCaseLabelStyle := JcfFormatSettings.Returns.CaseLabelStyle;
leSaveCaseElseStyle := JcfFormatSettings.Returns.CaseElseStyle;
leSaveEndElseStyle := JcfFormatSettings.Returns.EndElseStyle;
leSaveElseBeginStyle := JcfFormatSettings.Returns.ElseBeginStyle;
leSaveBlockBeginStyle := JcfFormatSettings.Returns.BlockBeginStyle;
JcfFormatSettings.Returns.ElseBeginStyle := eLeave;
end;
procedure TTestIfElseBreaks.Teardown;
begin
inherited;
JcfFormatSettings.Returns.ElseIfStyle := leSaveIfElseStyle;
JcfFormatSettings.Returns.BlockStyle := leSaveBareBlockStyle;
JcfFormatSettings.Returns.CaseLabelStyle := leSaveCaseLabelStyle;
JcfFormatSettings.Returns.CaseElseStyle := leSaveCaseElseStyle;
JcfFormatSettings.Returns.EndElseStyle := leSaveEndElseStyle;
JcfFormatSettings.Returns.ElseBeginStyle := leSaveElseBeginStyle;
JcfFormatSettings.Returns.BlockBeginStyle := leSaveBlockBeginStyle;
end;
procedure TTestIfElseBreaks.TestBlockStyleNever;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then ' + NativeLineBreak +
' Fish();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
OUT_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then Fish();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockStyle := eNever;
TestProcessResult(TBlockStyles, IN_TEXT, OUT_TEXT);
end;
procedure TTestIfElseBreaks.TestBlockStyleNeverWithComment;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then // noremove' + NativeLineBreak +
' Fish();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockStyle := eNever;
TestProcessResult(TBlockStyles, IN_TEXT, IN_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseStyleNever;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'else if spon then' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
OUT_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then Fish()' + NativeLineBreak +
'else if spon then Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockStyle := eNever;
TestProcessResult(TBlockStyles, IN_TEXT, OUT_TEXT);
end;
procedure TTestIfElseBreaks.TestIfBeginStyleNever;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then' + NativeLineBreak +
' begin' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'end' + NativeLineBreak +
'else if spon then' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
OUT_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then begin' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'end' + NativeLineBreak +
'else if spon then' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockBeginStyle := eNever;
TestProcessResult(TBlockStyles, IN_TEXT, OUT_TEXT);
end;
procedure TTestIfElseBreaks.TestIfBeginStyleAlways;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then begin' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'end' + NativeLineBreak +
'else if spon then' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
OUT_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then' + NativeLineBreak +
'begin' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'end' + NativeLineBreak +
'else if spon then' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockBeginStyle := eAlways;
TestProcessResult(TBlockStyles, IN_TEXT, OUT_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseNeverWithComment;
const
IN_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then // comment' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'else if spon then // comment' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
OUT_TEXT = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then // comment' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'else if spon then // comment' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
begin
JcfFormatSettings.Returns.BlockStyle := eNever;
TestProcessResult(TBlockStyles, IN_TEXT, OUT_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseAddReturn1;
begin
JcfFormatSettings.Returns.ElseIfStyle := eAlways;
TestProcessResult(TBlockStyles, RETURN_REMOVED_TEXT, RETURN_ADDED_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseAddReturn2;
begin
JcfFormatSettings.Returns.ElseIfStyle := eAlways;
TestProcessResult(TBlockStyles, RETURN_ADDED_TEXT, RETURN_ADDED_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseLeaveReturnAsIs1;
begin
JcfFormatSettings.Returns.ElseIfStyle := eLeave;
TestProcessResult(TBlockStyles, RETURN_ADDED_TEXT, RETURN_ADDED_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseLeaveReturnAsIs2;
begin
JcfFormatSettings.Returns.ElseIfStyle := eLeave;
TestProcessResult(TBlockStyles, RETURN_REMOVED_TEXT, RETURN_REMOVED_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseRemoveReturn1;
begin
JcfFormatSettings.Returns.ElseIfStyle := eNever;
TestProcessResult(TBlockStyles, RETURN_ADDED_TEXT, RETURN_REMOVED_TEXT);
end;
procedure TTestIfElseBreaks.TestIfElseRemoveReturn2;
begin
JcfFormatSettings.Returns.ElseIfStyle := eNever;
TestProcessResult(TBlockStyles, RETURN_REMOVED_TEXT, RETURN_REMOVED_TEXT);
end;
const
CASE_STATEMENT_IN_TEXT_NO_BREAKS =
'unit CaseTest;' + NativeLineBreak + NativeLineBreak +
'interface ' + NativeLineBreak + NativeLineBreak +
'implementation' + NativeLineBreak + NativeLineBreak +
'uses Dialogs;' + NativeLineBreak + NativeLineBreak +
'procedure foo(i: integer);' + NativeLineBreak +
'begin' + NativeLineBreak +
' case i of' + NativeLineBreak +
' 1: ShowMessage(''1 ... OK'');' + NativeLineBreak +
' else ShowMessage(''else ... OK'');' + NativeLineBreak +
' end;' + NativeLineBreak +
' end;' + NativeLineBreak + NativeLineBreak +
'end.';
CASE_STATEMENT_IN_TEXT_BREAKS =
'unit CaseTest;' + NativeLineBreak + NativeLineBreak +
'interface ' + NativeLineBreak + NativeLineBreak +
'implementation' + NativeLineBreak + NativeLineBreak +
'uses Dialogs;' + NativeLineBreak + NativeLineBreak +
'procedure foo(i: integer);' + NativeLineBreak +
'begin' + NativeLineBreak +
' case i of' + NativeLineBreak +
' 1:' + NativeLineBreak +
'ShowMessage(''1 ... OK'');' + NativeLineBreak +
' else' + NativeLineBreak +
'ShowMessage(''else ... OK'');' + NativeLineBreak +
' end;' + NativeLineBreak +
' end;' + NativeLineBreak + NativeLineBreak +
'end.';
procedure TTestIfElseBreaks.TestCaseStatementNever1;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eNever;
JcfFormatSettings.Returns.CaseElseStyle := eNever;
// no breaks - text without breaks is left as is
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_NO_BREAKS,
CASE_STATEMENT_IN_TEXT_NO_BREAKS);
end;
procedure TTestIfElseBreaks.TestCaseStatementNever2;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eNever;
JcfFormatSettings.Returns.CaseElseStyle := eNever;
// no breaks - text with breaks is altered
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_BREAKS,
CASE_STATEMENT_IN_TEXT_NO_BREAKS);
end;
procedure TTestIfElseBreaks.TestCaseStatementLeaveAsIs1;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eLeave;
JcfFormatSettings.Returns.CaseElseStyle := eLeave;
// leave as is - text with no breaks is left as is
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_NO_BREAKS,
CASE_STATEMENT_IN_TEXT_NO_BREAKS);
end;
procedure TTestIfElseBreaks.TestCaseStatementLeaveAsIs2;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eLeave;
JcfFormatSettings.Returns.CaseElseStyle := eLeave;
// leave as is - text with breaks is left as is
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_BREAKS,
CASE_STATEMENT_IN_TEXT_BREAKS);
end;
procedure TTestIfElseBreaks.TestCaseStatementAlways1;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eAlways;
JcfFormatSettings.Returns.CaseElseStyle := eAlways;
// breaks - text without breaks has them inserted
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_NO_BREAKS,
CASE_STATEMENT_IN_TEXT_BREAKS);
end;
procedure TTestIfElseBreaks.TestCaseStatementAlways2;
begin
JcfFormatSettings.Returns.CaseLabelStyle := eAlways;
JcfFormatSettings.Returns.CaseElseStyle := eAlways;
// breaks - text with breaks is left as is
TestProcessResult(TBlockStyles, CASE_STATEMENT_IN_TEXT_BREAKS,
CASE_STATEMENT_IN_TEXT_BREAKS);
end;
const
BROKEN_END_ELSE_UNIT_TEXT =
'unit TestCase;' + NativeLineBreak +
'interface' + NativeLineBreak +
'implementation' + NativeLineBreak +
NativeLineBreak +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if (a > b) then' + NativeLineBreak +
'begin' + NativeLineBreak +
'end' + NativeLineBreak +
'else' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
'end;' + NativeLineBreak +
'end.';
UNBROKEN_END_ELSE_UNIT_TEXT =
'unit TestCase;' + NativeLineBreak +
'interface' + NativeLineBreak +
'implementation' + NativeLineBreak +
NativeLineBreak +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if (a > b) then' + NativeLineBreak +
'begin' + NativeLineBreak +
'end else' + NativeLineBreak +
'begin' + NativeLineBreak +
'end;' + NativeLineBreak +
'end;' + NativeLineBreak +
'end.';
procedure TTestIfElseBreaks.TestEndElseStyle1;
begin
JcfFormatSettings.Returns.EndElseStyle := eLeave;
TestProcessResult(TBlockStyles, BROKEN_END_ELSE_UNIT_TEXT, BROKEN_END_ELSE_UNIT_TEXT);
end;
procedure TTestIfElseBreaks.TestEndElseStyle2;
begin
JcfFormatSettings.Returns.EndElseStyle := eLeave;
TestProcessResult(TBlockStyles, UNBROKEN_END_ELSE_UNIT_TEXT, UNBROKEN_END_ELSE_UNIT_TEXT);
end;
procedure TTestIfElseBreaks.TestEndElseStyle3;
begin
JcfFormatSettings.Returns.EndElseStyle := eAlways;
// breaks - text with breaks is left as is
TestProcessResult(TBlockStyles, BROKEN_END_ELSE_UNIT_TEXT, BROKEN_END_ELSE_UNIT_TEXT);
end;
procedure TTestIfElseBreaks.TestEndElseStyle4;
begin
JcfFormatSettings.Returns.EndElseStyle := eAlways;
// without breaks -> breaks added
TestProcessResult(TBlockStyles, UNBROKEN_END_ELSE_UNIT_TEXT, BROKEN_END_ELSE_UNIT_TEXT);
end;
procedure TTestIfElseBreaks.TestEndElseStyle5;
begin
JcfFormatSettings.Returns.EndElseStyle := eNever;
TestProcessResult(TBlockStyles, BROKEN_END_ELSE_UNIT_TEXT, UNBROKEN_END_ELSE_UNIT_TEXT);
end;
procedure TTestIfElseBreaks.TestEndElseStyle6;
begin
JcfFormatSettings.Returns.EndElseStyle := eNever;
TestProcessResult(TBlockStyles, UNBROKEN_END_ELSE_UNIT_TEXT, UNBROKEN_END_ELSE_UNIT_TEXT);
end;
const
ELSE_BEGIN_TEXT_NO_RETURN = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then // comment' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'else begin ' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
' end;' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
ELSE_BEGIN_TEXT_WITH_RETURN = UNIT_HEADER +
'procedure foo;' + NativeLineBreak +
'begin' + NativeLineBreak +
'if bar then // comment' + NativeLineBreak +
' Fish()' + NativeLineBreak +
'else'+ NativeLineBreak +
'begin ' + NativeLineBreak +
' Wibble();' + NativeLineBreak +
' end;' + NativeLineBreak +
'end;' + NativeLineBreak +
UNIT_FOOTER;
procedure TTestIfElseBreaks.TestAddElseBegin1;
begin
JcfFormatSettings.Returns.ElseBeginStyle := eAlways;
TestProcessResult(TBlockStyles, ELSE_BEGIN_TEXT_WITH_RETURN, ELSE_BEGIN_TEXT_WITH_RETURN);
end;
procedure TTestIfElseBreaks.TestAddElseBegin2;
begin
JcfFormatSettings.Returns.ElseBeginStyle := eAlways;
TestProcessResult(TBlockStyles, ELSE_BEGIN_TEXT_NO_RETURN, ELSE_BEGIN_TEXT_WITH_RETURN);
end;
procedure TTestIfElseBreaks.TestRemoveElseBegin1;
begin
JcfFormatSettings.Returns.ElseBeginStyle := eNever;
TestProcessResult(TBlockStyles, ELSE_BEGIN_TEXT_WITH_RETURN, ELSE_BEGIN_TEXT_NO_RETURN);
end;
procedure TTestIfElseBreaks.TestRemoveElseBegin2;
begin
JcfFormatSettings.Returns.ElseBeginStyle := eNever;
TestProcessResult(TBlockStyles, ELSE_BEGIN_TEXT_NO_RETURN, ELSE_BEGIN_TEXT_NO_RETURN);
end;
initialization
TestFramework.RegisterTest('Processes', TTestIfElseBreaks.Suite);
end.
|
// A benchmark to measure raw performance and fragmentation resistance.
// Alternates large number of small string and small number of large string allocations.
// Pure GetMem / FreeMem benchmark without reallocations, similar to WildThreads Benchmark.
// Single-thread version.
unit RawPerformanceSingleThread;
interface
uses
Windows, BenchmarkClassUnit, Classes, Math;
type
TRawPerformanceSingleThread = class(TFastcodeMMBenchmark)
private
procedure Execute;
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses
SysUtils;
procedure TRawPerformanceSingleThread.Execute;
const
POINTERS = 16361; // take prime just below 16384
MAXCHUNK = 1024; // take power of 2
var
i, n, Size, LIndex: Cardinal;
s: array [0..POINTERS - 1] of string;
begin
n := Low(s);
for i := 1 to 8 * 1024 * 1024 do begin
if i and $FF < $F0 then // 240 times out of 256 ==> chunk < 1 kB
Size := (4 * i) and (MAXCHUNK-1) + 1
else if i and $FF <> $FF then // 15 times out of 256 ==> chunk < 32 kB
Size := 2 * n + 1
else // 1 time out of 256 ==> chunk < 256 kB
Size := 16 * n + 1;
s[n] := '';
SetLength(s[n], Size);
//start and end of string are already assigned, access every 4K page in the middle
LIndex := 1;
while LIndex <= Size do
begin
s[n][LIndex] := #1;
Inc(LIndex, 4096);
end;
Inc(n);
if n > High(s) then
n := Low(s);
if i and $FFFF = 0 then
UpdateUsageStatistics;
end;
UpdateUsageStatistics;
for n := Low(s) to High(s) do
s[n] := '';
end;
{ TRawPerformanceSingleThread }
class function TRawPerformanceSingleThread.GetBenchmarkDescription: string;
begin
Result := 'A benchmark to measure raw performance and fragmentation resistance. ' +
'Allocates large number of small strings (< 1 kB) and small number of larger ' +
'(< 32 kB) to very large (< 256 kB) strings. Single-thread version.';
end;
class function TRawPerformanceSingleThread.GetBenchmarkName: string;
begin
Result := 'Raw Performance 1 thread';
end;
class function TRawPerformanceSingleThread.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadAllocAndFree;
end;
procedure TRawPerformanceSingleThread.RunBenchmark;
begin
inherited;
Execute;
end;
end.
|
{***************************************************************
*
* Project : WSZipCodeClient
* Unit Name: ClientMain
* Purpose : Demonstrates using TCPClient to lookup ZIP codes
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:47:23
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit ClientMain;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls, extctrls,
{$ENDIF}
SysUtils, Classes, IdAntiFreezeBase,
IdAntiFreeze, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient;
type
TformMain = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
memoInput: TMemo;
lboxResults: TListBox;
Panel3: TPanel;
butnLookup: TButton;
butnClear: TButton;
Label1: TLabel;
Client: TIdTCPClient;
IdAntiFreeze1: TIdAntiFreeze;
procedure butnClearClick(Sender: TObject);
procedure butnLookupClick(Sender: TObject);
private
public
end;
var
formMain: TformMain;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TformMain.butnClearClick(Sender: TObject);
begin
memoInput.Clear;
lboxResults.Clear;
end;
procedure TformMain.butnLookupClick(Sender: TObject);
var
i: integer;
s: string;
begin
butnLookup.Enabled := true; try
lboxResults.Clear;
with Client do begin
Connect; try
lboxResults.Items.Add(ReadLn);
for i := 0 to memoInput.Lines.Count - 1 do begin
WriteLn('ZipCode ' + memoInput.Lines[i]);
lboxResults.Items.Add(memoInput.Lines[i]);
s := ReadLn;
if s = '' then begin
s := '-- No entry found for this zip code.';
end;
lboxResults.Items.Add(s);
lboxResults.Items.Add('');
end;
WriteLn('Quit');
finally Disconnect; end;
end;
finally butnLookup.Enabled := true; end;
end;
end.
|
unit Unit1;
interface
uses
DragDrop, DropSource, DropTarget, DragDropFile, ActiveX,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, DropComboTarget, Registry, Menus, JvMenus;
type
TForm1 = class(TForm)
Panel1: TPanel;
DropComboTarget1: TDropComboTarget;
Popup: TJvPopupMenu;
LoginSetup1: TMenuItem;
N2: TMenuItem;
Close1: TMenuItem;
procedure FormCreate(Sender: TObject);
{ procedure DropEmptyTarget1Drop(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer);
procedure DropEmptyTarget1Enter(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); }
procedure DropComboTarget1Drop(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer);
procedure FormDestroy(Sender: TObject);
procedure LoginSetup1Click(Sender: TObject);
procedure Close1Click(Sender: TObject);
private
{ Private declarations }
FCaption: string;
tmpdir: string;
FFileList: TStringList;
procedure DoSave;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
DragDropFormats, ComObj, LoginDetails, SaveDoc, SaveDocFunc,
SavedocDetails;
procedure TForm1.FormCreate(Sender: TObject);
var
regAxiom: TRegistry;
sRegistryRoot: string;
begin
sRegistryRoot := 'Software\Colateral\Axiom';
regAxiom := TRegistry.Create;
try
regAxiom.RootKey := HKEY_CURRENT_USER;
if regAxiom.OpenKey(sRegistryRoot+'\InsightDocSave', False) then
begin
try
if regAxiom.ReadInteger('WinTop') <> 0 then
Self.Top := regAxiom.ReadInteger('WinTop');
except
//
end;
try
if regAxiom.ReadInteger('WinLeft') <> 0 then
Self.Left := regAxiom.ReadInteger('WinLeft');
except
//
end;
end;
finally
regAxiom.Free;
end;
tmpdir := GetEnvironmentVariable('TMP')+'\';
end;
{procedure TForm1.DropEmptyTarget1Drop(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer);
type
PLargeint = ^Largeint;
var
OldCount: integer;
Buffer: AnsiString;
p: PAnsiChar;
i: integer;
Stream: IStream;
StatStg: TStatStg;
Total, BufferSize, Chunk, Size: longInt;
FirstChunk: boolean;
FileStream: TFileStream;
fName: string;
const
MaxBufferSize = 100*1024; // 32Kb
begin
// Transfer the file names and contents from the data format.
if (TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat).FileNames.Count > 0) then
begin
try
// Note: Since we can actually drag and drop from and onto ourself,
// Another, and more common, approach would be to reject or disable drops
// onto ourself while we are performing drag/drop operations.
for i := 0 to TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat).FileNames.Count-1 do
begin
FCaption := TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat).FileNames[i];
// Get data stream from source.
Stream := TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat).FileContentsClipboardFormat.GetStream(i);
if (Stream <> nil) then
begin
// Read data from stream.
Stream.Stat(StatStg, STATFLAG_NONAME);
Total := StatStg.cbSize;
// Assume that stream is at EOF, so set it to BOF.
// See comment in TCustomSimpleClipboardFormat.DoSetData (in
// DragDropFormats.pas) for an explanation of this.
Stream.Seek(0, STREAM_SEEK_SET, PLargeint(nil)^);
// If a really big hunk of data has been dropped on us we display a
// small part of it since there isn't much point in trying to display
// it all in the limited space we have available.
// Additionally, it would be *really* bad for performce if we tried to
// allocate a buffer that is too big and read sequentially into it. Tests have
// shown that allocating a 10Mb buffer and trying to read data into it
// in 1Kb chunks takes several minutes, while the same data can be
// read into a 32Kb buffer in 1Kb chunks in seconds. The Windows
// explorer uses a 1 Mb buffer, but that's too big for this demo.
BufferSize := Total;
if (BufferSize > MaxBufferSize) then
BufferSize := MaxBufferSize;
SetLength(Buffer, BufferSize);
p := PAnsiChar(Buffer);
Chunk := BufferSize;
FirstChunk := True;
while (Total > 0) do
begin
Stream.Read(p, Chunk, @Size);
if (Size = 0) then
break;
inc(p, Size);
dec(Total, Size);
dec(Chunk, Size);
if (Chunk = 0) or (Total = 0) then
begin
p := PAnsiChar(Buffer);
// Lets write the buffer to disk
fName := tmpdir + FCaption;
FileStream := TFileStream.Create(fName, fmCreate);
FileStream.WriteBuffer(p^, BufferSize-Chunk);
Chunk := BufferSize;
FirstChunk := False;
FileStream.Free;
end;
end;
end;
end;
finally
end;
end;
end; }
{procedure TForm1.DropEmptyTarget1Enter(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer);
begin
// Reject the drop unless the source supports *both* the FileContents and
// FileGroupDescriptor formats in the storage medium we require (IStream).
// Normally a drop is accepted if just one of our formats is supported.
with TVirtualFileStreamDataFormat(DataFormatAdapterTarget.DataFormat) do
begin
if not(FileContentsClipboardFormat.HasValidFormats(DropEmptyTarget1.DataObject) and
(AnsiFileGroupDescriptorClipboardFormat.HasValidFormats(DropEmptyTarget1.DataObject) or
UnicodeFileGroupDescriptorClipboardFormat.HasValidFormats(DropEmptyTarget1.DataObject))) then
Effect := DROPEFFECT_NONE;
end;
end; }
procedure TForm1.DropComboTarget1Drop(Sender: TObject;
ShiftState: TShiftState; APoint: TPoint; var Effect: Integer);
var
Stream: TStream;
i: integer;
Name: string;
begin
// Extract and display dropped data.
for i := 0 to DropComboTarget1.Data.Count-1 do
begin
Name := DropComboTarget1.Data.Names[i];
if (Name = '') then
Name := intToStr(i)+'.dat';
Stream := TFileStream.Create(tmpdir {ExtractFilePath(Application.ExeName)} + Name, fmCreate);
try
// Caption := Name;
// Copy dropped data to stream (in this case a file stream).
Stream.CopyFrom(DropComboTarget1.Data[i], DropComboTarget1.Data[i].Size);
finally
Stream.Free;
end;
end;
// Copy the rest of the dropped formats.
if DropComboTarget1.Files.Count > 0 then
begin
try
FFileList := TStringList.Create;
FFileList.Assign(DropComboTarget1.Files);
DoSave();
finally
FFileList.Free;
end;
end;
{
ListBoxFiles.Items.Assign(DropComboTarget1.Files);
ListBoxMaps.Items.Assign(DropComboTarget1.FileMaps);
EditURLURL.Text := DropComboTarget1.URL;
EditURLTitle.Text := DropComboTarget1.Title;
ImageBitmap.Picture.Assign(DropComboTarget1.Bitmap);
ImageMetaFile.Picture.Assign(DropComboTarget1.MetaFile);
MemoText.Lines.Text := DropComboTarget1.Text;
}
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
regAxiom: TRegistry;
sRegistryRoot: string;
begin
sRegistryRoot := 'Software\Colateral\Axiom';
regAxiom := TRegistry.Create;
try
regAxiom.RootKey := HKEY_CURRENT_USER;
if regAxiom.OpenKey(sRegistryRoot+'\InsightDocSave', True) then
begin
regAxiom.WriteInteger('WinTop',Self.Top);
regAxiom.WriteInteger('WinLeft',Self.Left);
regAxiom.CloseKey;
end;
finally
regAxiom.Free;
end;
end;
procedure TForm1.LoginSetup1Click(Sender: TObject);
begin
frmLoginSetup := TfrmLoginSetup.Create(Application);
frmLoginSetup.ShowModal;
frmLoginSetup.Free;
try
GetUserID;
except
Application.Terminate;
end;
end;
procedure TForm1.Close1Click(Sender: TObject);
begin
try
dmSaveDoc.orsAxiom.Disconnect;
dmSaveDoc.Free;
finally
Application.Terminate;
end;
end;
procedure TForm1.DoSave;
var
i: integer;
begin
if not FormExists(frmSaveDocDetails) then
frmSaveDocDetails := TfrmSaveDocDetails.Create(Self);
if FFileList.Count > 0 then
begin
for i := 0 to (FFileList.Count - 1) do
begin
frmSaveDocDetails.DocName := FFileList.Strings[i];
frmSaveDocDetails.Repaint;
frmSaveDocDetails.ShowModal;
end;
end;
end;
end.
|
unit gfx_pcx;
{***********************************************************************
Unit gfx_pcx.PAS v1.2 0801
(c) by Andreas Moser, amoser@amoser.de,
Delphi version : Delphi 4
gfx_pcx is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
********************************************************************************}
interface
uses SysUtils,
classes,
Windows,
JPEG,
Graphics,
io_files,
gfx_errors,
gfx_basedef;
// -----------------------------------------------------------------------------
//
// PCX Classes
//
// -----------------------------------------------------------------------------
type TPCXColorMode=(pcx16,pcx256,pcxTrue);
type TPCXTriple = packed record
r, g, b: byte;
end;
TPCXCol256 = array[0..255] of TPCXTriple;
TPcxCol16 = array[0..15] of TPCXTriple;
type TPCXHeader=packed record
pcxManufacturer:Byte;
pcxVersion :Byte; // Version information
// 0 = Version 2.5 of PC Paintbrush
// 2 = Version 2.8 w/palette information
// 3 = Version 2.8 w/o palette information
// 4 = PC Paintbrush for Windows(Plus for
// Windows uses Ver 5)
// 5 = Version 3.0 and > of PC Paintbrush
// and PC Paintbrush +, includes
// Publisher's Paintbrush . Includes
// 24-bit .PCX files
pcxEncoding :Byte; // 1 = .PCX run length encoding
pcxBitsPerPixel:Byte; // Number of bits to represent a pixel
// (per Plane) - 1, 2, 4, or 8
pcxXMin:Word;
pcxYMin:Word;
pcxXMax:Word;
pcxyMax:Word;
pcxHDpi :Word; // Horizontal Resolution of image in DPI*
pcxVDpi :Word; // Vertical Resolution of image in DPI*
pcxColormap :TPCXCol16; // Color palette setting
pcxReserved :Byte;
pcxNPlanes :Byte; // Number of color planes
pcxBytesPerLine :Word;// Number of bytes to allocate for a scanline
pcxPaletteInfo :Word;// How to interpret palette- 1 = Color/BW,
// 2 = Grayscale (ignored in PB IV/ IV +)
pcxHscreenSize :Word;
pcxVscreenSize :Word;
pcxFiller :Array[0..53] of Byte;
end;
type
TPCXBitmap = class(TBitmap)
public
procedure LoadFromStream(Stream: TStream); override;
end;
Type
TPCXFile = class(TObject)
FPCXHeader :TPCXHeader;
FPCXColorMode :TPCXColorMode;
FBitmap :TBitmap;
scan_line :array [0..65535] of byte;
Procedure ReadPCXLine(Stream:TStream);
procedure FillPCXHeader;
procedure ReadPCXHeader(Stream:TStream);
procedure ReadPCXBodyTrue(Stream:TStream);
procedure ReadPCXBody16(Stream:TStream);
procedure ReadPCXBody256(Stream:TStream);
procedure WritePCXHeader(Stream:TStream);
procedure WritePCXBodyTrue(Stream:TStream);
procedure WritePCXBody16(Stream:TStream);
procedure WritePCXBody256(Stream:TStream);
private
public
constructor Create;
destructor Destroy;override;
procedure LoadFromFile(filename: String);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(filename: String);
procedure SaveToStream(Stream: TStream);
procedure LoadBitmap(filename:String);
procedure AssignBitmap(ABitmap:TBitmap);
property Bitmap:TBitmap read FBitmap;
property SaveMode:TPCXColorMode read FPCXColorMode write FPCXColorMode;
end;
implementation
//***********************************************************
//
// TPCXFile
//
//***********************************************************
// -----------------------------------------------------------------------------
//
// LoadFromFile
//
// -----------------------------------------------------------------------------
procedure TPCXFile.LoadFromFile(FileName: String);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.LoadFromFile(Filename);
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TPCXFile.LoadFromStream(Stream: TStream);
begin
Stream.Position := 0;
ReadPCXHeader(Stream);
if FPCXHeader.pcxVersion<>5 then
begin
if GFXRaiseErrors then raise EGraphicFormat.Create('Invalid PCX Version (Ver.5 needed)');
GFXFileErrorList.Add('Invalid PCX Version (Ver.5 needed)');
end else
try
case FPCXColorMode of
pcx16: ReadPCXBody16(Stream);
pcx256: ReadPCXBody256(Stream);
pcxTrue: ReadPCXBodyTrue(Stream);
end;
except
if GFXRaiseErrors then raise EGraphicFormat.Create('PCX Error');
GFXFileErrorList.Add('PCX Error');
end;
end;
// -----------------------------------------------------------------------------
//
// SaveToFile
//
// -----------------------------------------------------------------------------
procedure TPCXFile.SaveToFile(FileName: String);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
SaveToStream(Stream);
Stream.SaveToFile(filename);
Stream.Free;
end;
// -----------------------------------------------------------------------------
//
// SaveToStream
//
// -----------------------------------------------------------------------------
procedure TPCXFile.SaveToStream(Stream: TStream);
begin
Stream.Position := 0;
WritePCXHeader(Stream);
case FBitmap.PixelFormat of
pf4Bit: WritePCXBody16(Stream);
pf8Bit: WritePCXBody256(Stream);
pf24Bit: WritePCXBodyTrue(Stream);
end;
end;
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TPCXFile.Create;
begin
FBitmap:=TBitmap.Create;
end;
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TPCXFile.Destroy;
begin
FBitmap.Free;
inherited;
end;
// -----------------------------------------------------------------------------
//
// ReadPCXHeader
//
// -----------------------------------------------------------------------------
procedure TPCXFile.ReadPCXHeader(Stream:TStream);
begin
Stream.Position:=0;
with Stream,FPCXHeader do
begin
Read(pcxManufacturer,1);
Read(pcxVersion,1);
Read(pcxEncoding,1);
Read(pcxBitsPerPixel,1);
Read(pcxXMin,2);
Read(pcxYMin,2);
Read(pcxXMax,2);
Read(pcxYMax,2);
Read(pcxHDpi,2);
Read(pcxVDpi,2);
Read(pcxColormap,48);
Read(pcxReserved,1);
Read(pcxNPlanes,1);
Read(pcxBytesPerLine,2);
Read(pcxPaletteInfo,2);
Read(pcxHscreenSize,2);
Read(pcxVscreenSize,2);
Position:=128;
end;
FBitmap.Width:=FPCXHeader.pcxXMax-FPCXHeader.pcxXMin+1;
FBitmap.Height:=FPCXHeader.pcxYmax-FPCXHeader.pcxYMin+1;
if (FPCXHeader.pcxBitsPerPixel=8) and (FPCXHeader.pcxNPlanes=3)
then begin
FPCXColorMode:=pcxTrue;
FBitmap.PixelFormat:=pf24Bit;
end else
if (FPCXHeader.pcxBitsPerPixel=1) and (FPCXHeader.pcxNPlanes=4)
then begin
FPCXColorMode:=pcx16;
FBitmap.PixelFormat:=pf4bit;
end else
if (FPCXHeader.pcxBitsPerPixel=8) and (FPCXHeader.pcxNPlanes=1)
then begin
FPCXColorMode:=pcx256;
FBitmap.PixelFormat:=pf8Bit;
end;
end;
// -----------------------------------------------------------------------------
//
// ReadPCXLine
//
// -----------------------------------------------------------------------------
Procedure TPCXFile.ReadPCXLine(Stream:TStream);
Var
databyte,db2:byte;
repeater:SmallInt;
Planes,n,p:Word;
procedure ReadLine;
Begin
n:=0;
repeat
Stream.Read(databyte,1);
If databyte >=$C0 Then
Begin
repeater:=databyte And $3F;
Stream.Read(db2,1);
while repeater>0 do
begin
scan_line[p]:=db2;
Inc(p);
dec(repeater);
Inc(n);
end;
end else
Begin
scan_line[p]:=databyte;
Inc(p);
Inc(n);
end;
until n>=FPCXHeader.pcxBytesPerLine ;
End;
begin
p:=0;
fillchar(Scan_line,FPCXHeader.pcxBytesPerLine* FPCXHeader.pcxNPlanes,0);
for Planes:=1 to FPCXHeader.pcxNPlanes do ReadLine;
end;
// -----------------------------------------------------------------------------
//
// ReadPCXBody16
//
// -----------------------------------------------------------------------------
procedure TPCXFile.ReadPCXBody16(Stream:TStream);
begin
// not implemented yet
end;
// -----------------------------------------------------------------------------
//
// ReadPCXBody256
//
// -----------------------------------------------------------------------------
procedure TPCXFile.ReadPCXBody256(Stream:TStream);
var i,j:Integer;
y: pByteArray;
palArray: TPCXCol256;
fPal:TMaxLogPalette;
databyte:Byte;
aStream:TMemoryStream;
begin
fillchar(palArray,sizeof(palArray),0);
aStream:=TMemoryStream.Create;
Stream.Position:=0;
aStream.LoadFromStream(Stream);
fPal.palVersion:=$300;
fPal.palNumEntries:=256;
aStream.Position:=Stream.Size-(256*3+1);
aStream.Read(databyte,1);
if databyte =$0c then
begin
aStream.Read(palArray,SizeOf(palArray));
for i:=0 to 255 do
begin
fPal.palPalEntry[i].peRed := palArray[i].r;
fPal.palPalEntry[i].peGreen := palArray[i].g;
fPal.palPalEntry[i].peBlue := palArray[i].b;
fPal.palPalEntry[i].peFlags:=0;
end;
FBitmap.Palette:=CreatePalette(pLogPalette(@fPal)^);
FBitMap.IgnorePalette:=False;
end;
aStream.Seek(128,soFromBeginning);
for i:=0 to FBitmap.Height-1 do
begin
ReadPCXLine(aStream);
y:=FBitmap.ScanLine[i];
for j:=0 to FBitmap.Width-1 do y[j]:=scan_line[j];
end;
aStream.Free;
End;
// -----------------------------------------------------------------------------
//
// ReadPCXBodyTrue
//
// -----------------------------------------------------------------------------
procedure TPCXFile.ReadPCXBodyTrue(Stream:TStream);
var i,j:Integer;
y:pRGBArray;
aStream:TMemoryStream;
begin
aStream:=TMemoryStream.Create;
Stream.Position:=0;
aStream.LoadFromStream(Stream);
aStream.Position:=128;
for i:=0 to FBitmap.Height-1 do
begin
ReadPCXLine(aStream);
y:=FBitmap.ScanLine[i];
for j:=0 to FPCXHeader.pcxBytesPerLine-1 do
begin
y[j].rgbtRed:=scan_line[j];
y[j].rgbtGreen:=scan_line[j+FPCXHeader.pcxBytesPerLine];
y[j].rgbtBlue:=scan_line[j+(FPCXHeader.pcxBytesPerLine*2)];
end;
end;
aStream.Free;
End;
// -----------------------------------------------------------------------------
//
// WritePCXHeader
//
// -----------------------------------------------------------------------------
procedure TPCXFile.WritePCXHeader(Stream:TStream);
begin
FillPCXHeader;
with Stream,FPCXHeader do
begin
case FBitmap.PixelFormat of
pf4Bit: begin
pcxBitsPerPixel:=4;
pcxNPlanes:=1;
end;
pf8Bit: begin
pcxBitsPerPixel:=8;
pcxNPlanes:=1;
end;
pf24Bit:begin
pcxBitsPerPixel:=8;
pcxNPlanes:=3;
end;
end;
Write(pcxManufacturer,1);
Write(pcxVersion,1);
Write(pcxEncoding,1);
Write(pcxBitsPerPixel,1);
Write(pcxXMin,2);
Write(pcxYMin,2);
Write(pcxXMax,2);
Write(pcxYMax,2);
Write(pcxHDpi,2);
Write(pcxVDpi,2);
Write(pcxColormap,48);
Write(pcxReserved,1);
Write(pcxNPlanes,1);
Write(pcxBytesPerLine,2);
Write(pcxPaletteInfo,2);
Write(pcxHscreenSize,2);
Write(pcxVscreenSize,2);
Write(pcxFiller,SizeOf(pcxFiller));
Position:=128;
end;
end;
// -----------------------------------------------------------------------------
//
// WritePCXBodyTrue
//
// -----------------------------------------------------------------------------
procedure TPCXFile.WritePCXBodyTrue(Stream:TStream);
var i,j,l:Integer;
databyte,k:byte;
dcount,nCount:Integer;
y:pRGBArray;
procedure ConvertLine(Line:Integer);
var x:Integer;
begin
y:=FBitmap.ScanLine[Line];
for x:=0 to FBitmap.Width-1 do
begin
scan_line[x]:=y[x].rgbtRed;
scan_line[x+FPCXHeader.pcxBytesPerLine]:=y[x].rgbtGreen;
scan_line[x+(2*FPCXHeader.pcxBytesPerLine)]:=y[x].rgbtBlue;
end;
end;
begin
Stream.Position:=128;
for i:=0 to FBitmap.Height-1 do
begin
ConvertLine(i);
for l:=0 to 2 do begin
j:=l*FPCXHeader.pcxBytesPerLine;
nCount:=0;
dcount:=1;
repeat
databyte:=scan_line[j];
while (databyte=scan_line[j+1]) and (dcount<63) and (nCount<FPCXHeader.pcxBytesPerLine-1)
do
begin
Inc(dcount);
Inc(j);
Inc(nCount);
end;
if (dcount>1) or (databyte>=$c0) then
begin
k:=dcount+$c0;
Stream.Write(k,1);
Stream.Write(databyte,1);
dcount:=1;
inc (ncount);
Inc(j);
end
else
begin
Stream.Write(databyte,1);
Inc (nCount);
Inc(j);
end;
until ncount>=FPCXHeader.pcxBytesPerLine;
end;
end;
databyte:=$0c;
Stream.Write(databyte,1);
End;
// -----------------------------------------------------------------------------
//
// WritePCXBody16
//
// -----------------------------------------------------------------------------
procedure TPCXFile.WritePCXBody16(Stream:TStream);
begin
// not implemented yet
end;
// -----------------------------------------------------------------------------
//
// WritePCXBody256
//
// -----------------------------------------------------------------------------
procedure TPCXFile.WritePCXBody256(Stream:TStream);
var i,j:Integer;
databyte,k:byte;
dcount,nCount:Integer;
y:pByteArray;
fPal:TPaletteEntries;
procedure ConvertLine(Line:Integer);
var x:Integer;
begin
y:=FBitmap.ScanLine[Line];
for x:=0 to FBitmap.Width-1 do
begin
scan_line[x]:=y[x];
end;
end;
begin
Stream.Position:=128;
for i:=0 to FBitmap.Height-1 do
begin
ConvertLine(i);
j:=0;
nCount:=0;
dcount:=1;
repeat
databyte:=scan_line[j];
while (databyte=scan_line[j+1]) and (dcount<63) and (nCount<FPCXHeader.pcxBytesPerLine-1)
do
begin
Inc(dcount);
Inc(j);
Inc(nCount);
end;
if (dcount>1) or (databyte>=$c0) then
begin
k:=dcount+$c0;
Stream.Write(k,1);
Stream.Write(databyte,1);
dcount:=1;
inc (ncount);
Inc(j);
end
else
begin
Stream.Write(databyte,1);
Inc (nCount);
Inc(j);
end;
until ncount>=FPCXHeader.pcxBytesPerLine;
end;
databyte:=$0c;
Stream.Write(databyte,1);
GetPaletteEntries(FBitmap.Palette,0,256,fPal);
for i:=0 to 255 do begin
Stream.Write(fPal[i].peRed,1);
Stream.Write(fPal[i].peGreen,1);
Stream.Write(fPal[i].peBlue,1);
end;
End;
// -----------------------------------------------------------------------------
//
// LoadBitmap
//
// -----------------------------------------------------------------------------
procedure TPCXFile.LoadBitmap(filename:String);
begin
try
FBitmap.LoadFromFile(filename);
except
if GFXRaiseErrors then raise EGraphicFormat.Create('Invalid bitmapfile (PCX)');
GFXFileErrorList.Add('Invalid bitmapfile (PCX)');
end;
end;
// -----------------------------------------------------------------------------
//
// AssignBitmap
//
// -----------------------------------------------------------------------------
procedure TPCXFile.AssignBitmap(ABitmap:TBitmap);
begin
FBitmap.Assign(ABitmap);
end;
// -----------------------------------------------------------------------------
//
// FillPCXHeader
//
// -----------------------------------------------------------------------------
procedure TPCXFile.FillPCXHeader;
var x:Integer;
fPalEntry:TPaletteEntries;
begin
with FPCXHeader do
begin
pcxManufacturer:=10;
pcxVersion:=5;
pcxEncoding:=1;
pcxXMin:=0;
pcxYMin:=0;
pcxXMax:=FBitmap.Width-1;
pcxyMax:=FBitmap.Height-1;
pcxHDpi:=FBitmap.Width;
pcxVDpi:=FBitmap.Height;
// if FBitmap.PixelFormat=pf4Bit then
begin
GetPaletteEntries(FBitmap.Palette,0,15,fPalEntry);
for x:=0 to 15 do
begin
pcxColormap[x].r:=fPalEntry[x].peRed;
pcxColormap[x].g:=fPalEntry[x].peGreen;
pcxColormap[x].b:=fPalEntry[x].peBlue;
end;
end;
pcxReserved:=0;
case FBitmap.PixelFormat of
pf4bit:begin
pcxNPlanes:=1;
pcxBitsPerPixel:=4;
pcxBytesPerLine:=(FBitmap.Width+7) div 8;
FPCXColorMode:=pcx16;
end;
pf8bit:begin
pcxNPlanes:=1;
pcxBitsPerPixel:=8;
pcxBytesPerLine:=FBitmap.Width;
FPCXColorMode:=pcx256;
end;
pf24bit:begin
pcxNPlanes:=3;
pcxBitsPerPixel:=8;
pcxBytesPerLine:=FBitmap.Width;
FPCXColorMode:=pcxTrue;
end;
end;
pcxPaletteInfo:=1;
pcxHscreenSize:=0;
pcxVscreenSize:=0;
for x:=0 to 53 do pcxFiller[x]:=0;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TPCXBitmap.LoadFromStream(Stream: TStream);
var
aPCX: TPCXFile;
aStream: TMemoryStream;
begin
aPCX := TPCXFile.Create;
try
aPCX.LoadFromStream(Stream);
aStream := TMemoryStream.Create;
try
aPCX.Bitmap.SaveToStream(aStream);
aStream.Position:=0;
inherited LoadFromStream(aStream);
finally
aStream.Free;
end;
finally
aPCX.Free;
end;
end;
initialization
TPicture.RegisterFileFormat('PCX','PCX-Format', TPCXBitmap);
finalization
TPicture.UnRegisterGraphicClass(TPCXBitmap);
end.
|
unit THREED;
{$I FLOAT.INC}
{$R+ Range checking }
{$S+ Stack checking }
interface
USES
CRT,
graph,
MathLib0, { Float }
Memory;
CONST
size = 2; {Max array index}
cell = 7; { smallest screen dimension / size }
TYPE
surface = array[0..size, 0..size] of longint;
OrientRec = RECORD
tilt, rota : WORD;
Xdiff, Ydiff,
Zdiff : longint;
CTilt, STilt,
CRota,SRota,
XMean,Zmean, YMean : Float;
end;
SurfaceRec = RECORD
Orient : OrientRec;
size : WORD; {max XY dimension of surface }
surfptr : ^surface;
END;
PROCEDURE mapDisp(surface : surfacerec);
PROCEDURE GetOrientation(VAR srf : SurfaceRec; Atilt, rotation : WORD);
FUNCTION GetSeaLevel( srf : SurfaceRec;
Splitpct : WORD {pct "below water" } ) : LONGINT;
PROCEDURE FlatSea(VAR srf: SurfaceRec; SeaLevel : LONGINT);
PROCEDURE project(VAR pt : PointType; srf : SurfaceRec; r,c : WORD);
PROCEDURE Animate(srf : SurfaceRec);
PROCEDURE shaded(srf : SurfaceRec; altitude, azimuth : WORD);
PROCEDURE wireframe(srf : SurfaceRec; stepsize : longint);
{=======================================================================}
implementation
CONST
grayscale : ARRAY[0..8] of FillPatternType =
(($FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF),
($FF,$77,$FF,$DD,$FF,$77,$FF,$DD),
($FF,$55,$FF,$55,$FF,$55,$FF,$55),
($BB,$55,$EE,$55,$BB,$55,$EE,$55),
($AA,$55,$AA,$55,$AA,$55,$AA,$55),
($AA,$11,$AA,$44,$AA,$11,$AA,$44),
($AA,$00,$AA,$00,$AA,$00,$AA,$00),
($88,$00,$22,$00,$88,$00,$22,$00),
($00,$00,$00,$00,$00,$00,$00,$00));
TYPE
rect = record
topleft,topright,
botright,botleft,
dummy : PointType; {always set dummy := topleft }
end;
Rhombus = ARRAY[0..4] OF PointType;
{ always set [4] := [0] to close figure }
Vector = ARRAY[1..3] OF Float;
twohts = array[1..2] of longint;
levarray = array[0..8] of longint;
VAR
DegToRad : FLOAT;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE minmax(VAR mm : twohts ; srf : SurfaceRec);
{Min surface height is minmax[1], max is minmax[2]}
var
r, c, altitude : longint;
begin
mm[1] := maxlongint;
mm[2] := -maxlongint;
for r := 0 to size do
for c := 0 to size do
begin
altitude := srf.surfptr^[r, c];
if altitude < mm[1] then
mm[1] := altitude;
if altitude > mm[2] then
mm[2] := altitude;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE MakeRect(VAR r : rect; topl, botr : PointType);
begin
r.topleft := topl;
r.botright := botr;
r.topright.X := botr.x;
r.topright.Y := topl.y;
r.botleft.X := topl.x;
r.botleft.Y := botr.y;
r.dummy := topl; { close figure }
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE paintpt (row, col : longint);
{Fill a cell x cell square with penpat}
VAR
pt , Pt2 : PointType;
rct : rect;
begin
pt.x := row * cell;
pt.y := col * cell;
pt2.x := (row + 1) * cell;
pt2.y := (col + 1) * cell;
MakeRect(rct,pt,pt2);
FillPoly(5, rct);
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
FUNCTION DTR(X:Float):Float;
begin
DTR := X / (DegToRad * 100)
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE GetOrientation(VAR srf : SurfaceRec; Atilt, rotation : WORD);
VAR
mm : twohts;
BEGIN
minmax(mm,srf);
with srf.Orient do
begin
Tilt := (ATilt + 180) mod 360;
Rota := Rotation mod 360;
CTilt := Cos(DTR(Tilt));
STilt := Sin(DTR(Tilt));
CRota := Cos(DTR(Rota));
SRota := Sin(DTR(Rota));
Zdiff := abs(mm[2] - mm[1]);
Zmean := (mm[1] + mm[2])/2;
Xmean := size / 2;
Ymean := size /2;
Xdiff := size;
Ydiff := size;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
FUNCTION GetSeaLevel( srf : SurfaceRec;
Splitpct : WORD {pct "below water" } ) : LONGINT;
BEGIN
GetSeaLevel := trunc( srf.orient.Zmean +
srf.orient.Zdiff * (splitpct/100 - 0.50) );
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE FlatSea(VAR srf: SurfaceRec; SeaLevel : LONGINT);
var
r, c : longint;
begin
for r := 0 to size do
for c := 0 to size do
if srf.surfptr^[r, c] < SeaLevel then
srf.surfptr^[r, c] := SeaLevel
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE project(VAR pt : PointType; srf : SurfaceRec; r,c : WORD);
const ZoomFactor = 1.3;
var
X2, Y2, Z2,
X3, Y3 : Float;
begin
with srf.Orient do
begin
X2 := (c-Xmean) / XDiff;
Y2 := (r-Ymean) / YDiff;
if ZDiff = 0 then Z2 := 0
else
Z2 := (srf.surfptr^[r,c] - Zmean) / ZDiff;
X3 := X2 * CRota - Y2 * SRota;
Y3 := Z2 * CTilt - (X2 * SRota + Y2 * CRota) * STilt;
pt.X := Round(GetMaxX * (DegToRad * X3 * ZoomFactor + 0.5));
pt.Y := Round(GetMaxY * (DegToRad * Y3 * ZoomFactor+ 0.5));
end; {with}
end; {proj}
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE projectXYZ( VAR pt : PointType;
Orientation : OrientRec;
X,Y,Z : FLOAT);
const ZoomFactor = 1.3;
var
X2, Y2, Z2,
X3, Y3 : Float;
begin
with Orientation do
begin
X2 := (X-Xmean) / XDiff;
Y2 := (Y-Ymean) / YDiff;
if ZDiff = 0 then Z2 := 0
else
Z2 := (Z - Zmean) / ZDiff;
X3 := X2 * CRota - Y2 * SRota;
Y3 := Z2 * CTilt - (X2 * SRota + Y2 * CRota) * STilt;
pt.X := Round(GetMaxX * (DegToRad * X3 * ZoomFactor + 0.5));
pt.Y := Round(GetMaxY * (DegToRad * Y3 * ZoomFactor+ 0.5));
end; {with}
end; {projextXYZ}
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE shade ( srf : SurfaceRec;
solar : Vector;
row, col : longint);
{Selects a gray shade for a patch}
var
i : longint;
dim, ill, normlen : Float;
normal : Vector;
begin
dim := 100 / srf.orient.Zdiff;
{Cross product of two vectors}
normal[1] := -dim * (srf.surfptr^[row, col] - srf.surfptr^[row + 1, col]);
normal[2] := -dim * (srf.surfptr^[row, col] - srf.surfptr^[row, col + 1]);
normal[3] := 1;
normlen := sqrt(sqr(normal[1]) + sqr(normal[2]) + sqr(normal[3]));
{Vector length }
for i := 1 to 3 do
normal[i] := normal[i] / normlen; {Normalize vector}
ill := 0;
for i := 1 to 3 do
ill := ill + solar[i] * normal[i]; {Dot product of normal and solar}
if ill < 0 then
setfillpattern(grayscale[0],Green)
else
setfillpattern(grayscale[round(ill * 7.9)],Green); {Set gray level}
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE shadeframe(srf : SurfaceRec; solar : Vector);
{Shades surface}
var
r, c : longint;
patch : Rhombus;
SeaLevel : LONGINT;
begin
SeaLevel := GetSeaLevel(srf,50);
{ FlatSea(srf,SeaLevel); }
SetColor(0);
for r := 0 to size - 1 do
for c := 0 to size - 1 do
begin
IF srf.surfptr^[r,c] > SeaLevel THEN BEGIN
project(patch[0], srf,r , c);
project(patch[1], srf,r,c + 1);
project(patch[2], srf,r + 1, c + 1);
project(patch[3], srf,r + 1, c);
patch[4] := patch[0]; { close polygon }
shade(srf, solar, r, c); {Get shade of patch}
FillPoly(sizeof(rhombus) div sizeof(PointType), patch);
END
ELSE BEGIN
projectXYZ(patch[0], srf.orient,c, r, SeaLevel);
projectXYZ(patch[1], srf.orient,c + 1, r, SeaLevel);
projectXYZ(patch[2], srf.orient,c + 1, r + 1, SeaLevel);
projectXYZ(patch[3], srf.orient,c, r + 1, SeaLevel);
patch[4] := patch[0]; { close polygon }
setfillpattern(grayscale[0],Blue);
FillPoly(sizeof(rhombus) div sizeof(PointType), patch);
END;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE mapDisp(surface : surfacerec);
var
i : word;
Pt, Pt2 : PointType;
rct : rect;
sum, row, col, levl, range : longint;
lev : array[0..8] of longint;
mm : twohts;
legend : string;
begin
range := surface.orient.Zdiff;
sum := trunc(surface.orient.Zmean - (surface.orient.Zdiff / 2));
levl := (range div 9) + 1; {Eight height zones, spearated by levl}
for i := 0 to 8 do
begin
sum := sum + levl;
lev[i] := sum; {Nine height zones, lev[1]-lev[8]}
end;
{Legend}
for i := 0 to 8 do
begin
SetFillPattern(GrayScale[i],GetMaxColor);
pt.x := 625;
pt.y := 10 + i * 15;
pt2.x := 639;
pt2.y := i * 15 + 20;
MakeRect(rct,pt,pt2);
FillPoly(sizeof(rect) div sizeof(PointType), rct);
DrawPoly(sizeof(rect) div sizeof(PointType), rct);
Str(lev[i]:8,legend);
OutTextXY(625, i * 15 + 20,legend);
SetTextJustify(LeftText,TopText); { restore defaults }
end;
{Map}
for row := 0 to size do
for col := 0 to size do
begin
i := 0;
while (surface.surfptr^[row, col] > lev[i]) do
i := i + 1; {Compare height to zones}
SetFillPattern(GrayScale[i],GetMaxColor);
{Choose pattern corresponding to zone}
paintpt(row, col);
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE wireframeB(srf : SurfaceRec; stepsize : longint);
{Draws wireframe of surface}
var
r, c,
highcount : LONGINT;
patch : Rhombus;
begin
{ enclose plotting area }
project(patch[0],srf,0,0);
project(patch[1],srf,0,size);
project(patch[2],srf,size,size);
project(patch[3],srf, size,0);
patch[4] := patch[0];
DrawPoly(sizeof(rhombus) div sizeof(PointType), patch);
highcount := size div stepsize;
{ plot the rows }
FOR c := 0 to highcount DO
FOR r := 0 TO highcount DO BEGIN
{Define patch}
project(patch[0], srf,(r * stepsize), (c * stepsize));
project(patch[1], srf,(r * stepsize), (c+1) * stepsize);
project(patch[2], srf,(r+1) * stepsize, (c+1) * stepsize);
project(patch[3], srf,((r+1) * stepsize), (c* stepsize));
patch[4] := patch[0];
SetFillPattern(grayscale[8],Black); { cover up behind }
FillPoly(sizeof(rhombus) div sizeof(PointType), patch);
DrawPoly(sizeof(rhombus) div sizeof(PointType), patch);
END;
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE wireframe(srf : SurfaceRec; stepsize : longint);
{Draws wireframe of surface}
var
r, c,
highcount : longint;
patch : Rhombus;
NewRow : BOOLEAN;
begin
highcount := size div stepsize;
{ plot the rows }
for c := 0 to highcount do
begin
NewRow := TRUE;
for r := 0 to highcount do
begin
project(patch[0], srf,(r * stepsize), (c * stepsize));
If NewRow then
begin
MoveTo(patch[0].X,patch[0].Y);
NewRow := FALSE;
end
else
{$IFDEF HIDDEN }
begin
HiddenLineTo(patch[0].X,patch[0].Y);
MoveTo(patch[0].X,patch[0].Y);
end;
{$ELSE }
LineTo(patch[0].X,patch[0].Y);
{$ENDIF }
end;
end;
{ plot the columns }
for r := 0 to highcount do
begin
NewRow := TRUE;
for c := 0 to highcount do
begin
project(patch[0], srf,(r * stepsize), (c * stepsize));
If NewRow then
begin
MoveTo(patch[0].X,patch[0].Y);
NewRow := FALSE;
end
else
{$IFDEF HIDDEN }
begin
HiddenLineTo(patch[0].X,patch[0].Y);
MoveTo(patch[0].X,patch[0].Y);
end;
{$ELSE }
LineTo(patch[0].X,patch[0].Y);
{$ENDIF }
end;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE shaded(srf : SurfaceRec; altitude, azimuth : WORD);
{Gets solar vector, and shades surface}
var
alt, az : FLOAT;
solar : Vector;
ch : CHAR;
begin
alt := Altitude;
alt := alt * pi / 180;
az := Azimuth;
az := az * pi / 180;
{Convert az/alt to three component unit vector}
solar[3] := sin(alt);
solar[2] := sin(az) * cos(alt);
solar[1] := cos(az) * cos(alt);
shadeframe(srf, solar); {Shade surface}
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE Animate(srf : SurfaceRec);
var
err : INTEGER;
tiltstr, rotastr : String;
ch : CHAR;
BEGIN
with srf.Orient do
begin
repeat
ClearViewPort;
wireframe(srf, 8);
str(tilt:3,tiltstr);
str(rota:3,rotastr);
OutTextXY(1,1,'Tilt: '+tiltstr+' Rotation: '+rotastr+
' Use Arrow keys. Hit "Q" to exit');
Ch := ReadKey;
CASE Ch OF
#0: { FUNCTION keys }
begin
ch := readkey;
case Ch of
#72: Tilt := (Tilt + 10 + 360) mod 360; { Up }
#75: Rota := (Rota + 10 + 360) mod 360; { Left }
#77: Rota := (Rota - 10 + 360) mod 360; { Right }
#80: Tilt := (Tilt - 10 + 360) mod 360; { Down }
end;
end;
#3 : BEGIN END;
END; {CASE}
CTilt := Cos(DTR(Tilt));
STilt := Sin(DTR(Tilt));
CRota := Cos(DTR(Rota));
SRota := Sin(DTR(Rota));
until (ch = #81) OR (ch = #113); { "Q" }
end {with};
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++}
(*
PROCEDURE ReadFile( DataFile : String);
BEGIN
{ read data file
writeln('Reading data file.');
assign(srfile,DataFile);
reset(srfile);
for row := 0 to size do
for col := 0 to size do
read(srfile, srf.surfptr^[row, col]);
close(srfile);
END;
*)
{ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
BEGIN {MAIN}
DegToRad := 180/pi/100;
END. {ThreeD}
|
unit DIRECTOUTPUT;
interface
uses Windows;
const
DLL = 'DirectOutput.dll';
// DeviceType_X52Pro = {0x29DAD506, 0xF93B, 0x4F20, { 0x85, 0xFA, 0x1E, 0x02, 0xC0, 0x4F, 0xAC, 0x17 } };
// Soft Buttons
SoftButton_Select = $00000001;
SoftButton_Up = $00000002;
SoftButton_Down = $00000004;
// Unused soft buttons
SoftButton_Left = $00000008;
SoftButton_Right = $00000010;
SoftButton_Back = $00000020;
Softbutton_Increment = $00000040;
SoftButton_Decrement = $00000080;
type
PFN_DIRECTOUTPUT_DEVICE_CALLBACK = procedure(HDEVICE:THandle; bAdded:Boolean; PCTXT:pointer);
PFN_DIRECTOUTPUT_SOFTBUTTON_CALLBACK = procedure(HDEVICE:THandle; DWBUTTONS:DWord; PCTXT:pointer);
PFN_DIRECTOUTPUT_PAGE_CALLBACK = procedure(HDEVICE:THandle; DWPAGE:Dword; BACTIVATED:Boolean; PCTXT:pointer);
{///============================================================================= }
{/// functions }
{///============================================================================= }
function DirectOutput_Initialize(const wszAppName: PWideString): HRESULT; stdcall; external DLL;
/// Initializes the DirectOutput library.
/// <param name="wszAppName">A null-terminated wide character string that specifies the name of the application.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_INVALIDARG: The argument is invalid. (According to Saitek. Not sure what would cause this in practice.)
/// E_HANDLE: The DirectOutputManager process could not be found.
/// This function must be called before calling any others. Call this function when you want to initialize the DirectOutput library.
function DirectOutput_Deinitialize(): HRESULT cdecl stdcall; external DLL;
/// Cleans up the DirectOutput library.
/// returns
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized or was already deinitialized.
/// This function must be called before termination. Call this function to clean up any resources allocated by DirectOutput_Initialize.
function DirectOutput_RegisterDeviceChangeCallback(pfnCb: PFN_DIRECTOUTPUT_DEVICE_CALLBACK; var pCtxt: pointer): HRESULT cdecl stdcall; external DLL;
/// Registers a callback function to be called when a device is added or removed.
/// <param name="pfnCb">A pointer to the callback function, to be called whenever a device is added or removed.</param>
/// <param name="pCtxt">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized.
/// Passing a NULL function pointer will disable the callback.
function DirectOutput_Enumerate() : HRESULT cdecl stdcall; external DLL;
/// Enumerates all currently attached DirectOutput devices.
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized.
/// Call this third when using the Saitek SDK; it must be called after registering a device change callback via RegisterDeviceChange().
function DirectOutput_RegisterSoftButtonChangeCallback(var hDevice: THandle; pfnCb: PFN_DIRECTOUTPUT_SOFTBUTTON_CALLBACK;
var pCtxt: pointer): HRESULT cdecl stdcall; external DLL;
/// Registers a callback with a device, that gets called whenever a "Soft Button" is pressed or released.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="lButtons">A pointer to the callback function to be called whenever a "Soft Button" is pressed or released.</param>
/// <param name="lContext">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: The device handle specified is invalid.
/// Passing a NULL function pointer will disable the callback.
function DirectOutput_RegisterPageChangeCallback(var hDevice: THandle; pfnCb: PFN_DIRECTOUTPUT_PAGE_CALLBACK;
var pCtxt: pointer): HRESULT cdecl stdcall; external DLL;
/// Registers a callback with a device, that gets called whenever the active page is changed.
/// <param name="hDevice">A handle to a device</param>
/// <param name="pfnCb">A pointer to the callback function to be called whenever the active page is changed.</param>
/// <param name="pCtxt">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: The device handle specified is invalid.
function DirectOutput_AddPage(var hDevice: THandle; dwPage: DWord;
const wszValue: string; bSetAsActive: Boolean): HRESULT cdecl stdcall; external DLL;
/// Adds a page to the specified device.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="wszValue">A string that specifies the name of this page.</param>
/// <param name="bSetAsActive">If this is true, then this page will become the active page. If false, this page will not change the active page.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_INVALIDARG: The dwPage parameter already exists.
/// E_HANDLE: The device handle specified is invalid.
/// Only one page per application should have bSetActive set to true.
/// The driver-defined default page is 0; adding another page 0 will overwrite the default page.
function DirectOutput_RemovePage(var hDevice: THandle; dwPage: DWord): HRESULT cdecl stdcall; external DLL;
/// Removes a page.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id.
/// E_HANDLE: The device handle specified is invalid.
function DirectOutput_SetLed(var hDevice: THandle; dwPage: DWORD; dwIndex: DWORD; dwValue: DWORD): HRESULT cdecl stdcall; external DLL;
/// Sets the state of a given LED indicator.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="dwIndex">A numeric identifier of the LED. Refer to the data sheet for each device to determine what LEDs are present.</param>
/// <param name="dwValue">The numeric value of a given state of a LED. For the x52 Pro, 0 is off and 1 is on.</param>
/// returns:
/// S_OK: The call completes successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id, or the dwLed argument does not specifiy a valid LED id.
/// E_HANDLE: The device handle specified is invalid.
/// To make a button's LED appear amber, enable both the Red and Yellow LEDs for that button.
function DirectOutput_SetString(var hDevice: THandle; dwPage: DWORD; dwIndex: DWORD;
cchValue: DWORD; const wszValue: WideString): HRESULT cdecl stdcall; external DLL;
/// Sets text strings on the MFD.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="dwIndex">A numeric identifier of the string. Refer to the data sheet for each device to determine what strings are present.</param>
/// <param name="cchValue">The number of wide characters in the string.</param>
/// <param name="wszValue">A null-terminated wide character string that specifies the value to display. Providing a null pointer will clear the string.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id, or the dwString argument does not reference a valid string id.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_HANDLE: The device handle specified is invalid.
/// AddPage() needs to be called before a string can be displayed.
/// The x52 Pro has only 3 lines/page, and any string longer than 16 characters will automatically scroll.
// DirectOutput_GetDeviceType: function(var hDevice: IN VOID; pGdDevice: OUT LPGUID): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
// not implemented
// DirectOutput_GetDeviceInstance: function(var hDevice: IN VOID; pGdInstance: OUT LPGUID): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
// not implemented
// DirectOutput_SetImage: function(var hDevice: IN VOID; dwPage: IN DWORD; dwIndex: IN DWORD;
// cbValue: IN DWORD; const pbValue: PIN UNSIGNED CHAR): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
// not implemented, the x52 pro does not support this
// DirectOutput_SetProfile: function(var hDevice: IN VOID; cchFilename: IN DWORD;
// const wszFilename: PIN WCHAR_T): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
// not implemented, there is no documentation
implementation
end.
|
unit ConnectionProperties.Cls;
interface
uses
SysUtils, Classes, UIRestore, Spring.Container, Spring.Services,
CommonConnection.Intf;
type
TCommonConnectionProperties = class(TInterfacedObject, ICommonConnectionProperties)
FItems : TStringList;
function EncodeValue(s : string): string;
function DecodeValue(s : string): string;
procedure SetStrValue(sIdent, Value : string);
function GetStrValue(sIdent: string): string;
// UserName
function GetUserName : string;
procedure SetUserName(const Value: string);
// Password
function GetPassword : string;
procedure SetPassword(const Value: string);
// ServerName
function GetServerName : string;
procedure SetServerName(const Value: string);
// DatabaseName
function GetDatabaseName : string;
procedure SetDatabaseName(const Value: string);
// PortNumber
function GetPortNumber : string;
procedure SetPortNumber(const Value: string);
// Protocol
function GetProtocol : string;
procedure SetProtocol(const Value: string);
// ServerLogin
function GetServerLogin : string;
procedure SetServerLogin(const Value: string);
// ServerPassword
function GetServerPassword : string;
procedure SetServerPassword(const Value: string);
// OSAuthentication
function GetOSAuthentication : boolean;
procedure SetOSAuthentication(const Value: boolean);
// ConnectionString
function GetConnectionString : String;
procedure SetConnectionString(Value: String);
function GetAsString: string;
procedure SetAsString(Value: string);
// DatabaseType
function GetServerTypeID : Integer;
procedure SetServerTypeID(Value: Integer);
property ServerTypeID : Integer read GetServerTypeID write SetServerTypeID;
property UserName : string read GetUserName write SetUserName;
property Password : string read GetPassword write SetPassword;
property ServerName : string read GetServerName write SetServerName;
property DatabaseName : string read GetDatabaseName write SetDatabaseName;
property PortNumber : string read GetPortNumber write SetPortNumber;
property Protocol: string read GetProtocol write SetProtocol;
property ServerLogin: string read GetServerLogin write SetServerLogin;
property ServerPassword: string read GetServerPassword write SetServerPassword;
property OSAuthentication: boolean read GetOSAuthentication write SetOSAuthentication;
property ConnectionString : string read GetConnectionString write SetConnectionString;
property AsString : string read GetAsString write SetAsString;
procedure SaveToFile(FileName: string);
procedure LoadFromFile(FileName: string);
procedure Assign(Value: ICommonConnectionProperties);
public
constructor Create;
destructor Destroy; override;
end;
implementation
const
C_ServerTypeID = 'ServerTypeID';
C_UserName = 'UserName';
C_Password = 'Password';
C_ServerName = 'ServerName';
C_DatabaseName = 'DatabaseName';
C_PortNumber = 'PortNumber';
C_Protocol = 'Protocol';
C_ServerLogin = 'ServerLogin';
C_ServerPassword = 'ServerPassword';
C_OSAuthentication = 'OSAuthentication';
C_ConnectionString = 'ConnectionString';
C_EQToText = 'xEQx';
C_CommaToText = 'xCOx';
C_SemiColonToText = 'xSCx';
C_DblQuoteToText = 'xDCx';
constructor TCommonConnectionProperties.Create;
begin
FItems := TStringList.Create;
OSAuthentication := False;
ServerName := '';
DatabaseName := '';
PortNumber := '';
Protocol := '';
ServerLogin := '';
ServerPassword := '';
ConnectionString := '';
end;
procedure TCommonConnectionProperties.Assign(Value: ICommonConnectionProperties);
begin
ServerTypeID := Value.ServerTypeID;
UserName := Value.UserName;
Password := Value.Password;
ServerName := Value.ServerName;
DatabaseName := Value.DatabaseName;
PortNumber := Value.PortNumber;
Protocol := Value.Protocol;
ServerLogin := Value.ServerLogin;
ServerPassword := Value.ServerPassword;
OSAuthentication := Value.OSAuthentication;
ConnectionString := Value.ConnectionString;
AsString := Value.AsString;
end;
function TCommonConnectionProperties.DecodeValue(s: string): string;
begin
Result := StringReplace(s, C_SemicolonToText, ';', [rfReplaceAll]);
Result := StringReplace(Result, C_CommaToText, ',', [rfReplaceAll]);
Result := StringReplace(Result, C_EQToText, '=', [rfReplaceAll]);
Result := StringReplace(Result, C_DblQuoteToText, '"', [rfReplaceAll]);
end;
destructor TCommonConnectionProperties.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
function TCommonConnectionProperties.EncodeValue(s: string): string;
begin
Result := StringReplace(s, '=', C_EQToText, [rfReplaceAll]);
Result := StringReplace(Result, ',', C_CommaToText, [rfReplaceAll]);
Result := StringReplace(Result, ';', C_SemicolonToText, [rfReplaceAll]);
Result := StringReplace(Result, '"', C_DblQuoteToText, [rfReplaceAll]);
end;
function TCommonConnectionProperties.GetAsString: string;
begin
Result := FItems.Text;
end;
function TCommonConnectionProperties.GetConnectionString: String;
begin
Result := GetStrValue(C_ConnectionString);
end;
function TCommonConnectionProperties.GetDatabaseName: string;
begin
Result := GetStrValue(C_DatabaseName);
end;
function TCommonConnectionProperties.GetOSAuthentication: boolean;
begin
Result := StrToBoolDef(FItems.Values[C_OSAuthentication], False);
end;
function TCommonConnectionProperties.GetPassword: string;
begin
Result := GetStrValue(C_Password);
end;
function TCommonConnectionProperties.GetPortNumber: string;
begin
Result := GetStrValue(C_PortNumber);
end;
function TCommonConnectionProperties.GetProtocol: string;
begin
Result := GetStrValue(C_Protocol);
end;
function TCommonConnectionProperties.GetServerLogin: string;
begin
Result := GetStrValue(C_ServerLogin);
end;
function TCommonConnectionProperties.GetServerName: string;
begin
Result := GetStrValue(C_ServerName);
end;
function TCommonConnectionProperties.GetServerPassword: string;
begin
Result := GetStrValue(C_ServerPassword);
end;
function TCommonConnectionProperties.GetServerTypeID: Integer;
begin
Result := StrToIntDef(GetStrValue(C_ServerTypeID), 0);
end;
function TCommonConnectionProperties.GetStrValue(sIdent: string): string;
begin
Result := DecodeValue(FItems.Values[sIdent]);
end;
function TCommonConnectionProperties.GetUserName: string;
begin
Result := GetStrValue(C_UserName);
end;
procedure TCommonConnectionProperties.LoadFromFile(FileName: string);
var
LItems : TStringList; iItems : IObjCleaner;
begin
if not FileExists(FileName) then
exit;
LItems := TStringList.Create; iItems := CreateObjCleaner(LItems);
LItems.LoadFromFile(FileName);
LItems.Values[C_Password] := DecryptPassword(LItems.Values[C_Password]);
LItems.Values[C_ServerPassword] := DecryptPassword(LItems.Values[C_ServerPassword]);
FItems.Text := LItems.Text;
end;
procedure TCommonConnectionProperties.SaveToFile(FileName: string);
var
LItems : TStringList; iItems : IObjCleaner;
begin
LItems := TStringList.Create; iItems := CreateObjCleaner(LItems);
LItems.Text := FItems.Text;
LItems.Values[C_Password] := EncryptPassword(Password);
LItems.Values[C_ServerPassword] := EncryptPassword(ServerPassword);
LItems.SaveToFile(FileName);
end;
procedure TCommonConnectionProperties.SetAsString(Value: string);
var
LItems : TStringList; iItems : IObjCleaner;
begin
LItems := TStringList.Create; iItems := CreateObjCleaner(LItems);
LItems.Text := StringReplace(Value, ',', #13#10, [rfReplaceAll]);
ServerTypeID := StrToIntDef(LItems.Values[C_ServerTypeID], 0);
UserName := LItems.Values[C_UserName];
Password := LItems.Values[C_Password];
ServerName := LItems.Values[C_ServerName];
DatabaseName := LItems.Values[C_DatabaseName];
PortNumber := LItems.Values[C_PortNumber];
Protocol := LItems.Values[C_Protocol];
ServerLogin := LItems.Values[C_ServerLogin];
ServerPassword := LItems.Values[C_ServerPassword];
OSAuthentication := StrToBoolDef(LItems.Values[C_OSAuthentication], False);
ConnectionString := LItems.Values[C_ConnectionString];
end;
procedure TCommonConnectionProperties.SetConnectionString(Value: String);
begin
SetStrValue(C_ConnectionString, Value);
end;
procedure TCommonConnectionProperties.SetDatabaseName(const Value: string);
begin
SetStrValue(C_DatabaseName, Value);
end;
procedure TCommonConnectionProperties.SetOSAuthentication(const Value: boolean);
begin
FItems.Values[C_OSAuthentication] := BoolToStr(Value);
end;
procedure TCommonConnectionProperties.SetPassword(const Value: string);
begin
SetStrValue(C_Password, Value);
end;
procedure TCommonConnectionProperties.SetPortNumber(const Value: string);
begin
SetStrValue(C_PortNumber, Value);
end;
procedure TCommonConnectionProperties.SetProtocol(const Value: string);
begin
SetStrValue(C_Protocol, Value);
end;
procedure TCommonConnectionProperties.SetServerLogin(const Value: string);
begin
SetStrValue(C_ServerLogin, Value);
end;
procedure TCommonConnectionProperties.SetServerName(const Value: string);
begin
SetStrValue(C_ServerName, Value);
end;
procedure TCommonConnectionProperties.SetServerPassword(const Value: string);
begin
SetStrValue(C_ServerPassword, Value);
end;
procedure TCommonConnectionProperties.SetServerTypeID(Value: Integer);
begin
FItems.Values[C_ServerTypeID] := IntToStr(Value);
end;
procedure TCommonConnectionProperties.SetStrValue(sIdent, Value: string);
begin
FItems.Values[sIdent] := EncodeValue(Value);
end;
procedure TCommonConnectionProperties.SetUserName(const Value: string);
begin
SetStrValue(C_UserName, Value);
end;
initialization
GlobalContainer.RegisterType<TCommonConnectionProperties>.Implements<ICommonConnectionProperties>;
end.
|
unit Contatos2.model.query;
interface
uses
FireDAC.Comp.Client, contatos2.model.conexao, contatos2.model.interfaces;
Type
TQuery = Class(TInterfacedObject, iQuery)
Private
FQuery: Tfdquery;
Con: iconexao;
Public
Constructor Create;
Destructor Destroy; Override;
Class function New: iQuery;
Function Query: tfdquery;
End;
implementation
uses
System.SysUtils;
{ TQuery }
constructor TQuery.Create;
begin
con := tconexao.New;
fquery := TFDQuery.Create(nil);
fquery.Connection := con.conexao;
end;
destructor TQuery.Destroy;
begin
FreeAndNil(FQuery);
inherited;
end;
class function TQuery.New: iQuery;
begin
Result:= self.Create;
end;
function TQuery.Query: tfdquery;
begin
Result:= FQuery;
end;
end.
|
unit ufrmFilterDBGrid;
interface
{$I ThsERP.inc}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Data.DB, Vcl.CheckLst, Vcl.AppEvnts, Vcl.ComCtrls,
Vcl.ExtCtrls, Vcl.Samples.Spin,
ufrmBase,
Ths.Erp.Helper.Edit;
type
TFieldName = class
private
FFieldName: string;
FDataType: TFieldType;
public
property FieldName: string read FFieldName write FFieldName;
property DataType: TFieldType read FDataType write FDataType;
constructor Create(AValue: string; ADataType: TFieldType);
end;
type
TfrmFilterDBGrid = class(TfrmBase)
lblFields: TLabel;
chklstFields: TCheckListBox;
rgFilterCriter: TRadioGroup;
Panel1: TPanel;
lblFilterKeyValue: TLabel;
edtFilter: TEdit;
procedure FormCreate(Sender: TObject); override;
procedure FormDestroy(Sender: TObject); override;
private
{ Private declarations }
public
{ Public declarations }
published
procedure FormShow(Sender: TObject); override;
procedure btnAcceptClick(Sender: TObject); override;
end;
implementation
uses
ufrmBaseDBGrid, Ths.Erp.Database.Singleton, Ths.Erp.Constants, Ths.Erp.Functions;
{$R *.dfm}
{ TFieldName }
constructor TFieldName.Create(AValue: string; ADataType: TFieldType);
begin
FFieldName := AValue;
FDataType:= ADataType;
end;
procedure TfrmFilterDBGrid.btnAcceptClick(Sender: TObject);
var
n1: Integer;
vFilter, vFilterCriter: string;
vStartLike, vEndLike: string;
begin
if edtFilter.Text <> '' then
begin
vFilter := '';
vFilterCriter := '';
vStartLike := '';
vEndLike := '';
case rgFilterCriter.ItemIndex of
0: vFilterCriter := '=';
1: begin vFilterCriter := ' LIKE '; vStartLike := '%'; vEndLike := '%'; end;
2: begin vFilterCriter := ' NOT LIKE '; vStartLike := '%'; vEndLike := '%'; end;
3: begin vFilterCriter := ' LIKE '; vEndLike := '%'; end;
4: begin vFilterCriter := ' LIKE '; vStartLike := '%'; end;
5: vFilterCriter := '<>';
6: vFilterCriter := '>';
7: vFilterCriter := '<';
8: vFilterCriter := '>=';
9: vFilterCriter := '<=';
end;
for n1 := 0 to chklstFields.Items.Count-1 do
begin
if chklstFields.Checked[n1] then
begin
if Assigned(chklstFields.Items.Objects[n1]) then
begin
if ((TFieldName(chklstFields.Items.Objects[n1]).FieldName <> '') and (TFieldName(chklstFields.Items.Objects[n1]).FieldName <> 'id'))
or ((TSingletonDB.GetInstance.User.IsAdmin.Value) and (TFieldName(chklstFields.Items.Objects[n1]).FieldName = 'id'))
then
begin
if vFilter <> '' then
vFilter := vFilter + ' OR ';
if (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftString)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftMemo)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftFmtMemo)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftFixedChar)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftWideString)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftWideMemo)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftMemo)
then
begin
vFilter := vFilter +
TFieldName(chklstFields.Items.Objects[n1]).FieldName +
vFilterCriter +
QuotedStr(vStartLike + edtFilter.Text + vEndLike);
end
else
if (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftSmallint)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftInteger)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftShortint)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftWord)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftFloat)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftCurrency)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftLargeint)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftLongWord)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftTime)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftTimeStamp)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftDate)
or (TFieldName(chklstFields.Items.Objects[n1]).DataType = ftDateTime)
then
begin
if (rgFilterCriter.ItemIndex <> 1)
and (rgFilterCriter.ItemIndex <> 2)
and (rgFilterCriter.ItemIndex <> 3)
and (rgFilterCriter.ItemIndex <> 4)
then
vFilter := vFilter + TFieldName(chklstFields.Items.Objects[n1]).FieldName + vFilterCriter + QuotedStr(vStartLike + edtFilter.Text + vEndLike);
end;
end;
end;
end;
end;
if TfrmBaseDBGrid(ParentForm).FilterGrid <> '' then
vFilter := ' AND ' + vFilter;
TfrmBaseDBGrid(ParentForm).FilterGrid := TfrmBaseDBGrid(ParentForm).FilterGrid + vFilter;
Close;
end;
end;
procedure TfrmFilterDBGrid.FormCreate(Sender: TObject);
var
n1: Integer;
vIDCiksin: Boolean;
begin
inherited;
btnAccept.Visible := True;
edtFilter.Clear;
vIDCiksin := TSingletonDB.GetInstance.User.IsAdmin.Value;
for n1 := 0 to TfrmBaseDBGrid(ParentForm).dbgrdBase.Columns.Count-1 do
begin
if vIDCiksin or (TfrmBaseDBGrid(ParentForm).dbgrdBase.Columns[n1].FieldName <> 'id')
then
chklstFields.AddItem(
TfrmBaseDBGrid(ParentForm).dbgrdBase.Columns[n1].Title.Caption,
TFieldName.Create(TfrmBaseDBGrid(ParentForm).dbgrdBase.Columns[n1].FieldName,
TfrmBaseDBGrid(ParentForm).dbgrdBase.Columns[n1].Field.DataType));
end;
end;
procedure TfrmFilterDBGrid.FormShow(Sender: TObject);
begin
inherited;
rgFilterCriter.Items.Clear;
rgFilterCriter.Items.Add('=');
rgFilterCriter.Items.Add(TranslateText('like', FrameworkLang.FilterLike, LngFilter, LngSystem));
rgFilterCriter.Items.Add(TranslateText('not like', FrameworkLang.FilterNotLike, LngFilter, LngSystem));
rgFilterCriter.Items.Add(TranslateText('with start...', FrameworkLang.FilterWithStart, LngFilter, LngSystem));
rgFilterCriter.Items.Add(TranslateText('...with end', FrameworkLang.FilterWithEnd, LngFilter, LngSystem));
rgFilterCriter.Items.Add('<>');
rgFilterCriter.Items.Add('>');
rgFilterCriter.Items.Add('<');
rgFilterCriter.Items.Add('>=');
rgFilterCriter.Items.Add('<=');
rgFilterCriter.ItemIndex := 1;
lblFields.Caption := TranslateText(lblFields.Caption, FrameworkLang.FilterSelectFilterFields, LngFilter, LngSystem);
btnAccept.Caption := TranslateText('FILTER', FrameworkLang.ButtonFilter, LngButton, LngSystem);
btnClose.Caption := TranslateText(btnClose.Caption, FrameworkLang.ButtonClose, LngButton, LngSystem);
Self.Caption := getFormCaptionByLang(Self.Name, Self.Caption);
lblFilterKeyValue.Caption := TranslateText(lblFilterKeyValue.Caption, 'Key Value', LngFilter, LngSystem);
rgFilterCriter.Caption := TranslateText(rgFilterCriter.Caption, 'Filter Criteria Title', LngFilter, LngSystem);
btnAccept.ImageIndex := IMG_FILTER;
btnAccept.HotImageIndex := IMG_FILTER;
edtFilter.CharCase := ecNormal;
chklstFields.SetFocus;
end;
procedure TfrmFilterDBGrid.FormDestroy(Sender: TObject);
var
n1: Integer;
begin
for n1 := 0 to chklstFields.Items.Count-1 do
if Assigned(chklstFields.Items.Objects[n1]) then
chklstFields.Items.Objects[n1].Free;
inherited;
end;
end.
|
unit uHelpManager;
interface
uses Windows;
type
THelpManager = class(TObject)
private
InProgress: boolean;
constructor Create;
public
HelpHandle: hWnd;
class function GetInstance: THelpManager;
function ExecHelp(Command: Word; Data: NativeInt; var CallHelp: Boolean): Boolean;
end;
implementation
uses ORSystem, SysUtils, Dialogs, ShellAPI, Forms;
var
HelpManager: THelpManager;
{=======================================================}
{ THelpManager - class used to manage the help system }
{=======================================================}
type
// List of contexts currently in use
THelpContexts = (hcNone,
hcLogin,
hcSignon,
hcConnect,
hcPatientSelectCbo,
hcPatientSelectForm,
hcCover,
hcProblem,
hcMeds,
hcOrders,
hcNotes,
hcConsults,
hcDischargeSumm,
hcLabs,
hcReports,
hcOptCoverDay,
hcOptCoverRemind,
hcOptOtherParam,
hcOptionsOK,
hcOptionsCancel,
hcOptionsApply,
hcOptDay,
hcOptDayLabDef,
hcOptDayVisitDef,
hcOptDayLabInp,
hcOptDayLabOutp,
hcOptStartStop,
hcOptRemind,
hcOptUp,
hcOptDown,
hcOptRemDelete,
hcOptRemAdd,
hcOptRemDisp,
hcOptRemNotDisp,
hcOptNotif,
hcOptNotifRemove,
hcOptNotifFlag,
hcOptSurrBtn,
hcOptNotifView,
hcOptOrderCheck,
hcOptOrderCheckView,
hcOptListTeam,
hcOptPatSelBtn,
hcOptPersList,
hcOptTeamBtn,
hcOptCombination,
hcOptPatSel,
hcOptPatSelListSrc,
hcOptPatSelSort,
hcOptPatSelProvider,
hcOptPatSelTreating,
hcOptPatSelTeam,
hcOptPatSelWard,
hcOptPatSelDayOfWeek,
hcOptPatSelVisitStart,
hcOptPatSelVisitStop,
hcOptList,
hcOptListAddByType,
hcOptListAddBy,
hcOptListPat,
hcOptListPersList,
hcOptListPersPat,
hcOptListAdd,
hcOptListAddAll,
hcOptListPersPatR,
hcOptListPersPatRA,
hcOptListSave,
hcOptListNew,
hcOptListDelete,
hcOptNewList,
hcOptNewListText,
hcOptTeam,
hcOptTeamPat,
hcOptTeamLst,
hcOptTeamUser,
hcOptTeamRemove,
hcOptTeamSubscr,
hcOptTeamPers,
hcOptTeamRestrict,
hcOptSurr,
hcOptSurrRemove,
hcOrderAlert,
hcOptSurrDate,
hcOptOther,
hcOptOtherTab,
hcOptOtherLast,
hcOptComb,
hcOptCombAddByType,
hcOptCombAddBy,
hcOptCombView,
hcOptCombAdd,
hcOptCombRemove,
hcOptNotesTab,
hcOptNotesBtn,
hcOptNotesTitle,
hcOptNotes,
hcOptNotesSave,
hcOptNotesVerify,
hcOptNotesAskSubj,
hcOptNotesCosigner,
hcOptTitle,
hcOptTitleDocClass,
hcOptTitleDocTitle,
hcOptTitleAdd,
hcOptTitleRemove,
hcOptTitleSave,
hcOptTitleDefault,
hcOptTitleYours,
hcOptCover,
hcOptOK,
hcOptCancel,
hcOptClose,
hcOptions,
hcTemplateEditor,
hcReminderDlg,
hcReminderTree,
hcReminderView,
hcUnknown);
const
// Context ids for contexts
CONTEXT_VALUES: array[THelpContexts] of integer = ( 0, // hcNone
1, // hcLogin
2, // hcSignon
4, // hcConnect
10, // hcPatientSelectCbo
20, // hcPatientSelectForm
1000, // hcCover
2000, // hcProblem
3000, // hcMeds
4000, // hcOrders
5000, // hcNotes
6000, // hcConsults
7000, // hcDischargeSumm
8000, // hcLabs
9000, // hcReports
9001, // hcOptCoverDay
9002, // hcOptCoverRemind
9003, // hcOptOtherParam
9007, // hcOptionsOK
9008, // hcOptionsCancel
9009, // hcOptionsApply
9010, // hcOptDay
9011, // hcOptDayLabDef
9012, // hcOptDayVisitDef
9013, // hcOptDayLabInp
9014, // hcOptDayLabOutp
9015, // hcOptStartStop
9020, // hcOptRemind
9021, // hcOptUp
9022, // hcOptDown
9023, // hcOptRemDelete
9024, // hcOptRemAdd
9025, // hcOptRemDisp
9026, // hcOptRemNotDisp
9030, // hcOptNotif
9031, // hcOptNotifRemove
9032, // hcOptNotifFlag
9033, // hcOptSurrBtn
9035, // hcOptNotifView
9040, // hcOptOrderCheck
9041, // hcOptOrderCheckView
9050, // hcOptListTeam
9051, // hcOptPatSelBtn
9052, // hcOptPersList
9053, // hcOptTeamBtn
9054, // hcOptCombination
9060, // hcOptPatSel
9061, // hcOptPatSelListSrc
9062, // hcOptPatSelSort
9063, // hcOptPatSelProvider
9064, // hcOptPatSelTreating
9065, // hcOptPatSelTeam
9066, // hcOptPatSelWard
9067, // hcOptPatSelDayOfWeek
9068, // hcOptPatSelVisitStart
9069, // hcOptPatSelVisitStop
9070, // hcOptList
9071, // hcOptListAddByType
9072, // hcOptListAddBy
9073, // hcOptListPat
9074, // hcOptListPersList
9075, // hcOptListPersPat
9076, // hcOptListAdd
9077, // hcOptListAddAll
9078, // hcOptListPersPatR
9079, // hcOptListPersPatRA
9080, // hcOptListSave
9081, // hcOptListNew
9082, // hcOptListDelete
9085, // hcOptNewList
9086, // hcOptNewListText
9090, // hcOptTeam
9091, // hcOptTeamPat
9092, // hcOptTeamLst
9093, // hcOptTeamUser
9094, // hcOptTeamRemove
9095, // hcOptTeamSubscr
9096, // hcOptTeamPers
9097, // hcOptTeamRestrict
9100, // hcOptSurr
9101, // hcOptSurrRemove
9102, // hcOrderAlert
9103, // hcOptSurrDate
9110, // hcOptOther
9111, // hcOptOtherTab
9112, // hcOptOtherLast
9120, // hcOptComb
9121, // hcOptCombAddByType
9122, // hcOptCombAddBy
9123, // hcOptCombView
9124, // hcOptCombAdd
9125, // hcOptCombRemove
9200, // hcOptNotesTab
9201, // hcOptNotesBtn
9202, // hcOptNotesTitle
9210, // hcOptNotes
9213, // hcOptNotesSave
9214, // hcOptNotesVerify
9215, // hcOptNotesAskSubj
9216, // hcOptNotesCosigner
9230, // hcOptTitle
9231, // hcOptTitleDocClass
9232, // hcOptTitleDocTitle
9233, // hcOptTitleAdd
9234, // hcOptTitleRemove
9235, // hcOptTitleSave
9236, // hcOptTitleDefault
9237, // hcOptTitleYours
9700, // hcOptCover
9996, // hcOptOK
9997, // hcOptCancel
9998, // hcOptClose
9999, // hcOptions
10000, // hcTemplateEditor
11100, // hcReminderDlg
11200, // hcReminderTree
11300, // hcReminderView
-1); // hcUnknown
// Context html files for contexts
CONTEXT_FILES: array[THelpContexts] of string = ('cprs.htm', // hcNone
'Signing_In_to_CPRS.htm', // hcLogin
'cprs.htm', // hcSignon
'cprs.htm', // hcConnect
'cprs.htm', // hcPatientSelectCbo
'Selecting_a_Patient.htm', // hcPatientSelectForm
'Overview__What_is_the_Cover_Sheet_.htm', // hcCover
'Problem_List.htm', // hcProblem
'Viewing_Medications.htm', // hcMeds
'Viewing_orders.htm', // hcOrders
'Viewing_Progress_Notes.htm', // hcNotes
'Consults.htm', // hcConsults
'Discharge_Summaries.htm', // hcDischargeSumm
'Viewing_Laboratory_Test_Results.htm', // hcLabs
'Viewing_a_Report.htm', // hcReports
'Cover_Sheet_Date_Range_Defaults.htm', // hcOptCoverDay
'cprs.htm', // hcOptCoverRemind
'Other_Parameters.htm', // hcOptOtherParam
'cprs.htm', // hcOptionsOK
'Cancel_button.htm', // hcOptionsCancel
'Apply_button.htm', // hcOptionsApply
'cprs.htm', // hcOptDay
'cprs.htm', // hcOptDayLabDef
'cprs.htm', // hcOptDayVisitDef
'Inpatient_Days.htm', // hcOptDayLabInp
'Outpatient_Days.htm', // hcOptDayLabOutp
'Start-Stop.htm', // hcOptStartStop
'Clinical_Reminders.htm', // hcOptRemind
'Up_arrow.htm', // hcOptUp
'Down_arrow.htm', // hcOptDown
'cprs.htm', // hcOptRemDelete
'cprs.htm', // hcOptRemAdd
'cprs.htm', // hcOptRemDisp
'cprs.htm', // hcOptRemNotDisp
'Notifications_Tab_(Tools___Options).htm', // hcOptNotif
'Remove_Pending_Notifications.htm', // hcOptNotifRemove
'cprs.htm', // hcOptNotifFlag
'Surrogate_Settings.htm', // hcOptSurrBtn
'Notifications_list.htm', // hcOptNotifView
'cprs.htm', // hcOptOrderCheck
'Order_Check_list.htm', // hcOptOrderCheckView
'cprs.htm', // hcOptListTeam
'Patient_Selection_Defaults.htm', // hcOptPatSelBtn
'Personal_Lists.htm', // hcOptPersList
'Teams_Information.htm', // hcOptTeamBtn
'Source_Combinations.htm', // hcOptCombination
'cprs.htm', // hcOptPatSel
'List_Source.htm', // hcOptPatSelListSrc
'Sort_Order.htm', // hcOptPatSelSort
'Primary_Provider.htm', // hcOptPatSelProvider
'Treating_Specialty.htm', // hcOptPatSelTreating
'Team_Personal.htm', // hcOptPatSelTeam
'Ward.htm', // hcOptPatSelWard
'Start-Stop_(Patient_Selection).htm', // hcOptPatSelDayOfWeek
'Start-Stop_(Patient_Selection).htm', // hcOptPatSelVisitStart
'cprs.htm', // hcOptPatSelVisitStop
'cprs.htm', // hcOptList
'Select_Patients_by.htm', // hcOptListAddByType
'Patient.htm', // hcOptListAddBy
'Patients_to_add.htm', // hcOptListPat
'Personal_Lists_(Personal_Lists).htm', // hcOptListPersList
'Patients_on_personal_list.htm', // hcOptListPersPat
'Add_button_(Personal_Lists).htm', // hcOptListAdd
'Add_All_button_(Personal_Lists).htm', // hcOptListAddAll
'Remove_button_(Personal_Lists).htm', // hcOptListPersPatR
'Remove_All_button_(Personal_Lists).htm', // hcOptListPersPatRA
'Save_Changes_button_(Personal_Lists).htm', // hcOptListSave
'New_List_button.htm', // hcOptListNew
'Delete_List_button.htm', // hcOptListDelete
'cprs.htm', // hcOptNewList
'cprs.htm', // hcOptNewListText
'cprs.htm', // hcOptTeam
'Patients_on_selected_teams.htm', // hcOptTeamPat
'Team_members.htm', // hcOptTeamLst
'You_are_on_these_teams.htm', // hcOptTeamUser
'Remove_yourself_from_this_team.htm', // hcOptTeamRemove
'Subscribe_to_a_team.htm', // hcOptTeamSubscr
'Include_personal_lists.htm', // hcOptTeamPers
'Restrict_Team_List_View.htm', // hcOptTeamRestrict
'Surrogate.htm', // hcOptSurr
'Remove_Surrogate.htm', // hcOptSurrRemove
'Send_MailMan_bulletin.htm', // hcOrderAlert
'Surrogate_Date_Range.htm', // hcOptSurrDate
'cprs.htm', // hcOptOther
'Initial_tab_when_CPRS_starts.htm', // hcOptOtherTab
'Use_last_selected_tab.htm', // hcOptOtherLast
'cprs.htm', // hcOptComb
'Select_Combination_source_by.htm', // hcOptCombAddByType
'Ward_(Source_Combinations).htm', // hcOptCombAddBy
'Combinations.htm', // hcOptCombView
'Add_button_(Source_Combinations).htm', // hcOptCombAdd
'Remove_button_(Source_Combinations).htm', // hcOptCombRemove
'cprs.htm', // hcOptNotesTab
'Notes_button.htm', // hcOptNotesBtn
'Document_Titles_button.htm', // hcOptNotesTitle
'cprs.htm', // hcOptNotes
'Interval_for_autosave.htm', // hcOptNotesSave
'Verify_note_title.htm', // hcOptNotesVerify
'Ask_subject.htm', // hcOptNotesAskSubj
'Default_cosigner.htm', // hcOptNotesCosigner
'cprs.htm', // hcOptTitle
'Document_class.htm', // hcOptTitleDocClass
'Document_titles.htm', // hcOptTitleDocTitle
'Add_button_(Document_Titles).htm', // hcOptTitleAdd
'Remove_button_(Document_Titles).htm', // hcOptTitleRemove
'Save_Changes_(Document_Titles).htm', // hcOptTitleSave
'Set_Default_Note_button.htm', // hcOptTitleDefault
'Your_list_of_titles.htm', // hcOptTitleYours
'cprs.htm', // hcOptCover
'cprs.htm', // hcOptOK
'Cancel_button_2.htm', // hcOptCancel
'Close_button.htm', // hcOptClose
'cprs.htm', // hcOptions
'Document_Templates_(overview).htm', // hcTemplateEditor
'The_Main_Reminders_Processing_Dialog.htm', // hcReminderDlg
'The_Reminders_Button_Tree_View.htm', // hcReminderTree
'Write_a_New_Progress_Note.htm', // hcReminderView
'cprs.htm'); // hcUnknown
{===========================================}
{ Substitued for Application.OnHelp event }
{ --------------------------------------- }
{ Command : Type of help command }
{ Data : Context }
{ CallHelp : Call Win help system }
{ Returns true if help called }
{===========================================}
function THelpManager.ExecHelp(Command: word; Data: NativeInt; var CallHelp: boolean): boolean;
var
hc: THelpContexts; // loop variable
errorcode: integer;
FilePath, FileName: string;
begin
CallHelp := False; // don't run the win help system
if not InProgress then begin
InProgress := True;
hc := hcNone;
while (hc <> hcUnknown) and (CONTEXT_VALUES[hc] <> Data) do inc(hc); // loop through and find a context
Filepath := FullToPathPart(Application.ExeName) + 'Help\';
Filename := Filepath + CONTEXT_FILES[hc];
// ShowMessage('Help: ' + inttostr(Data) + ' ' + Context_Files[hc]); errorcode := 33; // diagnostic
errorcode := ShellExecute(HelpHandle, 'open', PChar(Filename), nil, nil, SW_SHOWNORMAL); // Tell windows to bring up the html file with the default browser
case errorcode of
0: ShowMessage('Help system: The operating system is out of memory or resources.');
ERROR_FILE_NOT_FOUND: ShowMessage('Help system: ' + CONTEXT_FILES[hc] + ' was not found in ' + FilePath + '.');
ERROR_PATH_NOT_FOUND: ShowMessage('Help system: ' + FilePath + ' was not found.');
ERROR_BAD_FORMAT: ShowMessage('Help system: The .exe file is invalid (non-Microsoft Win32® .exe or error in .exe image).');
SE_ERR_ACCESSDENIED: ShowMessage('Help system: The operating system denied access to ' + Filename + '.');
SE_ERR_ASSOCINCOMPLETE: ShowMessage('Help system: The file name association is incomplete or invalid. (.htm)');
SE_ERR_DDEBUSY: ShowMessage('Help system: The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed.');
SE_ERR_DDEFAIL: ShowMessage('Help system: The DDE transaction failed.');
SE_ERR_DDETIMEOUT: ShowMessage('Help system: The DDE transaction could not be completed because the request timed out.');
SE_ERR_DLLNOTFOUND: ShowMessage('Help system: The specified dynamic-link library (DLL) was not found.');
SE_ERR_NOASSOC: ShowMessage('Help system: There is no application associated with the given file name extension. (.htm)');
SE_ERR_OOM: ShowMessage('Help system: There was not enough memory to complete the operation.');
SE_ERR_SHARE: ShowMessage('Help system: A sharing violation occurred.');
end;
Result := (errorcode >= 32);
InProgress := False;
end else begin
Result := True;
end;
end;
{ THelpManager }
constructor THelpManager.Create;
begin
inherited;
HelpHandle := Application.Handle;
InProgress := False;
end;
class function THelpManager.GetInstance: THelpManager;
begin
if not assigned(HelpManager) then
HelpManager := THelpManager.Create;
Result := HelpManager;
end;
initialization
finalization
if assigned(HelpManager) then
HelpManager.Free;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.JNI.PlayServices.GCM;
interface
uses
Androidapi.JNIBridge,
Androidapi.JNI.App,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
Androidapi.JNI.Support;
type
// ===== Forward declarations =====
JGCMIntentService = interface;//com.embarcadero.gcm.notifications.GCMIntentService
JGCMNativeListener = interface;//com.embarcadero.gcm.notifications.GCMNativeListener
JGCMNotification = interface;//com.embarcadero.gcm.notifications.GCMNotification
// ===== Interface declarations =====
JGCMIntentServiceClass = interface(JIntentServiceClass)
['{3C313CE8-558D-4B5A-AF86-F3127DE42168}']
{class} function init: JGCMIntentService; cdecl;
end;
[JavaSignature('com/embarcadero/gcm/notifications/GCMIntentService')]
JGCMIntentService = interface(JIntentService)
['{14005AC2-2BDC-4C05-8D36-BDB0175F48BA}']
end;
TJGCMIntentService = class(TJavaGenericImport<JGCMIntentServiceClass, JGCMIntentService>) end;
JGCMNativeListenerClass = interface(IJavaClass)
['{1D65A4A1-8EC2-46E5-9F2E-7E72593393F3}']
end;
[JavaSignature('com/embarcadero/gcm/notifications/GCMNativeListener')]
JGCMNativeListener = interface(IJavaInstance)
['{F53C16C0-C547-4827-8DAF-22110902E95D}']
procedure OnNotificationReceived(notification: JBundle); cdecl;
end;
TJGCMNativeListener = class(TJavaGenericImport<JGCMNativeListenerClass, JGCMNativeListener>) end;
JGCMNotificationClass = interface(JWakefulBroadcastReceiverClass)
['{15A7A116-7A4F-474E-85B9-92F6002C8A8F}']
{class} function init: JGCMNotification; cdecl;
end;
[JavaSignature('com/embarcadero/gcm/notifications/GCMNotification')]
JGCMNotification = interface(JWakefulBroadcastReceiver)
['{AE16CA93-AB9A-4752-BDD2-6B131A1CF61E}']
procedure onReceive(context: JContext; intent: JIntent); cdecl;
procedure setNativeListener(listener: JGCMNativeListener); cdecl;
end;
TJGCMNotification = class(TJavaGenericImport<JGCMNotificationClass, JGCMNotification>) end;
implementation
procedure RegisterTypes;
begin
TRegTypes.RegisterType('Androidapi.JNI.PlayServices.GCM.JGCMIntentService', TypeInfo(Androidapi.JNI.PlayServices.GCM.JGCMIntentService));
TRegTypes.RegisterType('Androidapi.JNI.PlayServices.GCM.JGCMNativeListener', TypeInfo(Androidapi.JNI.PlayServices.GCM.JGCMNativeListener));
TRegTypes.RegisterType('Androidapi.JNI.PlayServices.GCM.JGCMNotification', TypeInfo(Androidapi.JNI.PlayServices.GCM.JGCMNotification));
end;
initialization
RegisterTypes;
end.
|
unit caProfiler;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
SysUtils,
Classes,
Math,
// ca units
caClasses,
caUtils,
caConsts,
caLog;
type
EcaProfilerException = class(EcaException);
TcaMethodType = (mtEnter, mtExit);
//---------------------------------------------------------------------------
// IcaProfiler
//---------------------------------------------------------------------------
IcaProfiler = interface
['{62E0B12A-FF12-426D-BC1F-F18832893E0F}']
// Property methods
function GetActive: Boolean;
function GetShowMethodTrace: Boolean;
function GetTrackMethodUsage: Boolean;
procedure SetActive(const Value: Boolean);
procedure SetShowMethodTrace(const Value: Boolean);
procedure SetTrackMethodUsage(const Value: Boolean);
// Public methods
procedure AddToMethodSkipList(const AMethodName: String);
procedure ClearMethodSkipList;
procedure EnterMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
procedure ExitMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
procedure ShowMethodUsage;
// Public properties
property Active: Boolean read GetActive write SetActive;
property ShowMethodTrace: Boolean read GetShowMethodTrace write SetShowMethodTrace;
property TrackMethodUsage: Boolean read GetTrackMethodUsage write SetTrackMethodUsage;
end;
//---------------------------------------------------------------------------
// TcaProfiler
//---------------------------------------------------------------------------
TcaProfiler = class(TInterfacedObject, IcaProfiler)
private
// Property fields
FActive: Boolean;
FShowMethodTrace: Boolean;
FTrackMethodUsage: Boolean;
// Private fields
FMethodList: IcaStringList;
FMethodSkipList: IcaStringList;
FStack: IcaStringStack;
// Property methods
function GetActive: Boolean;
function GetShowMethodTrace: Boolean;
function GetTrackMethodUsage: Boolean;
procedure SetActive(const Value: Boolean);
procedure SetShowMethodTrace(const Value: Boolean);
procedure SetTrackMethodUsage(const Value: Boolean);
// Private methods
function Indent(AValue: Integer): String;
procedure CreateInterfaceObjects;
procedure LogMethod(const AMethodName, AStringParam: String; ANumParam: Double;
AMethodType: TcaMethodType; ALevel: Integer);
public
constructor Create;
destructor Destroy; override;
// Public methods
procedure AddToMethodSkipList(const AMethodName: String);
procedure ClearMethodSkipList;
procedure EnterMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
procedure ExitMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
procedure ShowMethodUsage;
// Public properties
property Active: Boolean read GetActive write SetActive;
property ShowMethodTrace: Boolean read GetShowMethodTrace write SetShowMethodTrace;
property TrackMethodUsage: Boolean read GetTrackMethodUsage write SetTrackMethodUsage;
end;
//---------------------------------------------------------------------------
// CProfilerFactory
//---------------------------------------------------------------------------
CProfilerFactory = class
public
class function Instance: IcaProfiler;
end;
var
Profiler: IcaProfiler;
implementation
//---------------------------------------------------------------------------
// TcaProfiler
//---------------------------------------------------------------------------
constructor TcaProfiler.Create;
begin
inherited;
CreateInterfaceObjects;
FActive := True;
FShowMethodTrace := True;
end;
destructor TcaProfiler.Destroy;
begin
inherited;
end;
// Public methods
procedure TcaProfiler.AddToMethodSkipList(const AMethodName: String);
begin
FMethodSkipList.Add(AMethodName);
end;
procedure TcaProfiler.ClearMethodSkipList;
begin
FMethodSkipList.Clear;
end;
procedure TcaProfiler.EnterMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
var
Level: Integer;
begin
if FActive then
begin
if not FMethodSkipList.Contains(AMethodName) then
begin
if FShowMethodTrace then
begin
Level := FStack.Push(AMethodName) + 1;
LogMethod(AMethodName, AStringParam, ANumParam, mtEnter, Level);
end;
if FTrackMethodUsage then
FMethodList.Add(AMethodName);
end;
end;
end;
procedure TcaProfiler.ExitMethod(const AMethodName: String; const AStringParam: String = ''; ANumParam: Double = cMinDouble);
var
Level: Integer;
begin
if FActive then
begin
if not FMethodSkipList.Contains(AMethodName) then
begin
if FShowMethodTrace then
begin
if FStack.Peek <> AMethodName then
raise EcaProfilerException.Create('Exits do not match Enters');
Level := FStack.Size;
LogMethod(AMethodName, AStringParam, ANumParam, mtExit, Level);
FStack.Pop;
end;
if FTrackMethodUsage then
FMethodList.Add(AMethodName);
end;
end;
end;
procedure TcaProfiler.ShowMethodUsage;
var
Index: Integer;
MethodIndex: Integer;
MethodName: String;
MethodUsage: IcaStringList;
MethodCount: Integer;
begin
MethodUsage := TcaStringList.Create;
// Build list
for Index := 0 to FMethodList.High do
begin
MethodName := FMethodList[Index];
MethodIndex := MethodUsage.IndexOf(MethodName);
if MethodIndex >= 0 then
begin
MethodCount := Integer(MethodUsage.Objects[MethodIndex]);
Inc(MethodCount);
MethodUsage.Objects[MethodIndex] := Pointer(MethodCount);
end
else
MethodUsage.AddObject(MethodName, Pointer(1));
end;
// Send list to log
for Index := 0 to MethodUsage.High do
Log.Send(MethodUsage[Index] + ' [ ' + IntToStr(Integer(MethodUsage.Objects[Index])) + ' ]');
end;
// Private methods
function TcaProfiler.Indent(AValue: Integer): String;
begin
Result := Utils.BuildString(#32, AValue * 4);
end;
procedure TcaProfiler.CreateInterfaceObjects;
begin
FMethodList := TcaStringList.Create;
FMethodSkipList := TcaStringList.Create;
FStack := TcaStringList.Create;
end;
procedure TcaProfiler.LogMethod(const AMethodName, AStringParam: String; ANumParam: Double;
AMethodType: TcaMethodType; ALevel: Integer);
var
Arrows: String;
TraceStr: String;
begin
case AMethodType of
mtEnter: Arrows := '>> ';
mtExit: Arrows := '<< ';
end;
TraceStr := Indent(ALevel - 1) + Arrows + AMethodName;
if AStringParam <> '' then
TraceStr := TraceStr + ' - ' + AStringParam + ' - ';
if ANumParam > cMinDouble Then
Log.Send(TraceStr, ANumParam)
else
Log.Send(TraceStr);
end;
// Property methods
function TcaProfiler.GetActive: Boolean;
begin
Result := FActive;
end;
function TcaProfiler.GetShowMethodTrace: Boolean;
begin
Result := FShowMethodTrace;
end;
function TcaProfiler.GetTrackMethodUsage: Boolean;
begin
Result := FTrackMethodUsage;
end;
procedure TcaProfiler.SetActive(const Value: Boolean);
begin
FActive := Value;
end;
procedure TcaProfiler.SetShowMethodTrace(const Value: Boolean);
begin
FShowMethodTrace := Value;
end;
procedure TcaProfiler.SetTrackMethodUsage(const Value: Boolean);
begin
FTrackMethodUsage := Value;
end;
//---------------------------------------------------------------------------
// CProfilerFactory
//---------------------------------------------------------------------------
class function CProfilerFactory.Instance: IcaProfiler;
const
FInstance: IcaProfiler = nil;
begin
if not Assigned(FInstance) then
FInstance := TcaProfiler.Create;
Result := FInstance;
end;
initialization
Profiler := CProfilerFactory.Instance;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1997 Master-Bank }
{ }
{*******************************************************}
unit RxGConst;
{ RX graphic support constants }
{
Reserved diapasone
from MaxExtStrID - 200
to MaxExtStrID - 230
}
interface
const
{ The minimal VCL's used string ID is 61440. The custom IDs must be
less that above. }
MaxExtStrID = 61300;
{ RxGIF }
const
SGIFImage = MaxExtStrID - 200;
SChangeGIFSize = MaxExtStrID - 201;
SNoGIFData = MaxExtStrID - 202;
SUnrecognizedGIFExt = MaxExtStrID - 203;
SWrongGIFColors = MaxExtStrID - 204;
SBadGIFCodeSize = MaxExtStrID - 205;
SGIFDecodeError = MaxExtStrID - 206;
SGIFEncodeError = MaxExtStrID - 207;
SGIFVersion = MaxExtStrID - 208;
implementation
{$R *.R32}
end. |
unit udmNFCe;
interface
uses
System.SysUtils, System.Classes, System.IniFiles, spdNFCe, System.Contnrs,
spdNFCeDataSets, Data.DB, nxdb, nxllComponent, nxsdServerEngine,
nxreRemoteServerEngine, nxllTransport, nxptBasePooledTransport,
nxtwWinsockTransport;
type
TdmNFe = class(TDataModule)
nfceDados: TspdNFCeDataSets;
nfceComp: TspdNFCe;
nxDB: TnxDatabase;
nxSE: TnxSession;
tTran: TnxTable;
tNFConfig: TnxTable;
tNFE: TnxTable;
tMovEst: TnxTable;
nxTCPIP: TnxWinsockTransport;
nxRSE: TnxRemoteServerEngine;
tTranID: TUnsignedAutoIncField;
tTranUID: TGuidField;
tTranUID_ref: TGuidField;
tTranStatusNFE: TByteField;
tTranNFE: TGuidField;
tTranTipoNFE: TByteField;
tTranDataHora: TDateTimeField;
tTranIncluidoEm: TDateTimeField;
tTranCliente: TLongWordField;
tTranTipo: TByteField;
tTranOpDevValor: TByteField;
tTranFunc: TStringField;
tTranTotal: TCurrencyField;
tTranDesconto: TCurrencyField;
tTranDescPerc: TFloatField;
tTranDescPorPerc: TBooleanField;
tTranTotLiq: TCurrencyField;
tTranPagEsp: TWordField;
tTranPago: TCurrencyField;
tTranDebitoAnt: TCurrencyField;
tTranDebito: TCurrencyField;
tTranDebitoPago: TCurrencyField;
tTranCreditoAnt: TCurrencyField;
tTranCredito: TCurrencyField;
tTranCreditoUsado: TCurrencyField;
tTranTroco: TCurrencyField;
tTranObs: TnxMemoField;
tTranCancelado: TBooleanField;
tTranCanceladoPor: TStringField;
tTranCanceladoEm: TDateTimeField;
tTranCaixa: TLongWordField;
tTranCaixaPag: TLongWordField;
tTranMaq: TWordField;
tTranNomeCliente: TStringField;
tTranSessao: TLongWordField;
tTranDescr: TStringField;
tTranQtdTempo: TFloatField;
tTranCredValor: TBooleanField;
tTranFidResgate: TBooleanField;
tTranPagFunc: TStringField;
tTranPagPend: TBooleanField;
tTranRecVer: TLongWordField;
tNFConfigEmitirNFCe: TBooleanField;
tNFConfigEmitirNFE: TBooleanField;
tNFConfigCertificadoDig: TStringField;
tNFConfigCFOP_NFCe: TWordField;
tNFConfigAutoEmitirNFCe: TBooleanField;
tNFConfigCRT: TByteField;
tNFConfigCSOSN_Padrao: TWordField;
tNFConfigCST_Padrao: TByteField;
tNFConfigNCM_Padrao: TStringField;
tNFConfigMostrarDadosNFE: TBooleanField;
tNFConfigModeloNFE: TStringField;
tNFConfigModeloNFCe: TStringField;
tNFConfigSerieNFCe: TStringField;
tNFConfigSerieNFe: TStringField;
tNFConfigInicioNFe: TLongWordField;
tNFConfigInicioNFCe: TLongWordField;
tNFConfigRazaoSocial: TStringField;
tNFConfigNomeFantasia: TStringField;
tNFConfigCNPJ: TStringField;
tNFConfigIE: TStringField;
tNFConfigEnd_Logradouro: TStringField;
tNFConfigEnd_Numero: TStringField;
tNFConfigEnd_Bairro: TStringField;
tNFConfigEnd_UF: TStringField;
tNFConfigEnd_CEP: TStringField;
tNFConfigEnd_Municipio: TStringField;
tNFConfigEnd_CodMun: TStringField;
tNFConfigEnd_CodUF: TByteField;
tNFConfigTelefone: TStringField;
tNFEID: TGuidField;
tNFENumSeq: TUnsignedAutoIncField;
tNFEModelo: TStringField;
tNFESerie: TStringField;
tNFENumero: TLongWordField;
tNFEChave: TStringField;
tNFEEntrada: TBooleanField;
tNFETipoDoc: TByteField;
tNFEDataHora: TDateTimeField;
tNFECFOP: TWordField;
tNFETran: TGuidField;
tNFERecibo: TStringField;
tNFEProtocolo: TStringField;
tNFEContingencia: TBooleanField;
tNFEStatus: TByteField;
tNFEStatusNF: TIntegerField;
tNFEXML: TnxMemoField;
tNFEXMLret: TnxMemoField;
tNFEProcessar: TBooleanField;
tNFEIncluidoEm: TDateTimeField;
tNFEEmitidoEm: TDateTimeField;
tNFEContingenciaEM: TDateTimeField;
tNFEProcessarEm: TDateTimeField;
tNFEDescricao: TStringField;
tNFEValor: TCurrencyField;
tMovEstID: TUnsignedAutoIncField;
tMovEstID_ref: TLongWordField;
tMovEstTran: TLongWordField;
tMovEstProduto: TLongWordField;
tMovEstQuant: TFloatField;
tMovEstUnitario: TCurrencyField;
tMovEstTotal: TCurrencyField;
tMovEstCustoU: TCurrencyField;
tMovEstItem: TByteField;
tMovEstDesconto: TCurrencyField;
tMovEstPago: TCurrencyField;
tMovEstPagoPost: TCurrencyField;
tMovEstDescPost: TCurrencyField;
tMovEstDataHora: TDateTimeField;
tMovEstPend: TBooleanField;
tMovEstIncluidoEm: TDateTimeField;
tMovEstEntrada: TBooleanField;
tMovEstCancelado: TBooleanField;
tMovEstAjustaCusto: TBooleanField;
tMovEstEstoqueAnt: TFloatField;
tMovEstCliente: TLongWordField;
tMovEstCaixa: TIntegerField;
tMovEstCategoria: TStringField;
tMovEstNaoControlaEstoque: TBooleanField;
tMovEstITran: TIntegerField;
tMovEstTipoTran: TByteField;
tMovEstSessao: TIntegerField;
tMovEstComissao: TCurrencyField;
tMovEstComissaoPerc: TFloatField;
tMovEstComissaoLucro: TBooleanField;
tMovEstPermSemEstoque: TBooleanField;
tMovEstFidResgate: TBooleanField;
tMovEstFidPontos: TFloatField;
tMovEstRecVer: TLongWordField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TncProcEmailThread = class (TThread)
protected
procedure Execute; override;
public
end;
var
dmNFe: TdmNFe;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses ncServBD;
{$R *.dfm}
procedure TdmNFe.DataModuleCreate(Sender: TObject);
begin
nxSe.ServerEngine := ncServBD.dmServidorBD.ServerEngine;
end;
end.
|
{*********************************************}
{ TeePreviewPanelEditor }
{ Copyright (c) 1999-2004 by David Berneda }
{*********************************************}
unit TeePreviewPanelEditor;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls,
{$ENDIF}
TeePreviewPanel, TeCanvas, TeePenDlg;
type
TFormPreviewPanelEditor = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
CBAllowMove: TCheckBox;
CBAllowResize: TCheckBox;
CBDragImage: TCheckBox;
CBAsBitmap: TCheckBox;
CBShowImage: TCheckBox;
BPaperColor: TButtonColor;
RGOrientation: TRadioGroup;
Panel1: TPanel;
Button1: TButton;
Button2: TButtonPen;
TabShadow: TTabSheet;
procedure FormShow(Sender: TObject);
procedure CBAllowMoveClick(Sender: TObject);
procedure CBAllowResizeClick(Sender: TObject);
procedure CBDragImageClick(Sender: TObject);
procedure CBAsBitmapClick(Sender: TObject);
procedure CBShowImageClick(Sender: TObject);
procedure RGOrientationClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
TeePreviewPanel1 : TTeePreviewPanel;
public
{ Public declarations }
Constructor CreatePanel(AOwner:TComponent; APanel:TTeePreviewPanel);
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeEdiPane, TeeProcs, TeeProCo, TeeShadowEditor;
Constructor TFormPreviewPanelEditor.CreatePanel(AOwner:TComponent; APanel:TTeePreviewPanel);
var Page : TTabSheet;
tmp : TFormTeePanel;
begin
inherited Create(AOwner);
TeePreviewPanel1:=APanel;
Page:=TTabSheet.Create(Self);
Page.Caption:=TeeCommanMsg_Panel;
Page.PageControl:=PageControl1;
TeeTranslateControl(Self);
tmp:=TFormTeePanel.CreatePanel(Self,TeePreviewPanel1);
tmp.Align:=alClient;
AddFormTo(tmp,Page,0);
end;
procedure TFormPreviewPanelEditor.FormShow(Sender: TObject);
begin
if Assigned(TeePreviewPanel1) then
begin
With TeePreviewPanel1 do
begin
CBAllowMove.Checked :=AllowMove;
CBAllowResize.Checked :=AllowResize;
CBDragImage.Checked :=DragImage;
CBAsBitmap.Checked :=AsBitmap;
CBShowImage.Checked :=ShowImage;
RGOrientation.ItemIndex:=Ord(Orientation);
Button2.LinkPen(Margins);
InsertTeeShadowEditor(TabShadow).RefreshControls(Shadow);
end;
BPaperColor.LinkProperty(TeePreviewPanel1,'PaperColor'); { do not translate }
end;
PageControl1.ActivePage:=TabSheet1;
end;
procedure TFormPreviewPanelEditor.CBAllowMoveClick(Sender: TObject);
begin
TeePreviewPanel1.AllowMove:=CBAllowMove.Checked
end;
procedure TFormPreviewPanelEditor.CBAllowResizeClick(Sender: TObject);
begin
TeePreviewPanel1.AllowResize:=CBAllowResize.Checked
end;
procedure TFormPreviewPanelEditor.CBDragImageClick(Sender: TObject);
begin
TeePreviewPanel1.DragImage:=CBDragImage.Checked
end;
procedure TFormPreviewPanelEditor.CBAsBitmapClick(Sender: TObject);
begin
TeePreviewPanel1.AsBitmap:=CBAsBitmap.Checked
end;
procedure TFormPreviewPanelEditor.CBShowImageClick(Sender: TObject);
begin
TeePreviewPanel1.ShowImage:=CBShowImage.Checked
end;
procedure TFormPreviewPanelEditor.RGOrientationClick(Sender: TObject);
begin
With TeePreviewPanel1 do
Case RGOrientation.ItemIndex of
0: Orientation:=ppoDefault;
1: Orientation:=ppoPortrait;
else
Orientation:=ppoLandscape;
end;
end;
procedure TFormPreviewPanelEditor.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
end.
|
unit PostPacksFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Grids, DBGrids, Menus, Db, ActnList, BtrDS,
SearchFrm, Utilits, Common, CommCons;
type
TPostPacksForm = class(TDataBaseForm)
ActionList: TActionList;
EditAction: TAction;
DelAction: TAction;
FindAction: TAction;
ChildMenu: TMainMenu;
OperItem: TMenuItem;
CopyItem: TMenuItem;
DelItem: TMenuItem;
EditBreaker: TMenuItem;
FindItem: TMenuItem;
DataSource: TDataSource;
EditPopupMenu: TPopupMenu;
DBGrid: TDBGrid;
BtnPanel: TPanel;
NameLabel: TLabel;
NameEdit: TEdit;
SearchIndexComboBox: TComboBox;
RcvCheckBox: TCheckBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SearchIndexComboBoxChange(Sender: TObject);
procedure NameEditChange(Sender: TObject);
procedure DelActionExecute(Sender: TObject);
procedure EditActionExecute(Sender: TObject);
private
{ Private declarations }
public
SearchForm: TSearchForm;
end;
var
PostPacksForm: TPostPacksForm;
implementation
uses
PostMachineFrm, PostPackFrm;
{$R *.DFM}
procedure TPostPacksForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TPostPacksForm.FormDestroy(Sender: TObject);
begin
PostPacksForm := nil;
end;
procedure TPostPacksForm.FormCreate(Sender: TObject);
begin
DataSource.DataSet := GetGlobalBase(biPost) as TExtBtrDataSet;
DefineGridCaptions(DBGrid, PatternDir+'PostPack.tab');
{with PostMachineForm do
begin
AddToolBtn(nil, Self);
AddToolBtn(EditAction, Self);
AddToolBtn(DelAction, Self);
AddToolBtn(nil, Self);
AddToolBtn(FindAction, Self);
end;}
SearchForm := TSearchForm.Create(Self);
SearchForm.SourceDBGrid := DBGrid;
DataSource.DataSet.Refresh;
SearchIndexComboBox.ItemIndex := 0;
SearchIndexComboBoxChange(Sender);
end;
procedure TPostPacksForm.SearchIndexComboBoxChange(Sender: TObject);
var
AllowMultiSel: Boolean;
Opt: TDBGridOptions;
begin
(DataSource.DataSet as TBtrDataSet).IndexNum := SearchIndexComboBox.ItemIndex;
case SearchIndexComboBox.ItemIndex of
0: NameEdit.MaxLength := 12;
else
NameEdit.MaxLength := 8;
end;
RcvCheckBox.Visible := SearchIndexComboBox.ItemIndex in [1,2];
AllowMultiSel := SearchIndexComboBox.ItemIndex in [0];
Opt := DBGrid.Options;
if (dgMultiSelect in Opt)<>AllowMultiSel then
begin
if AllowMultiSel then
Include(Opt, dgMultiSelect)
else
Exclude(Opt, dgMultiSelect);
DBGrid.Options := Opt;
end;
end;
procedure TPostPacksForm.NameEditChange(Sender: TObject);
var
I, Err: Integer;
Key1: packed record
kNameR: TAbonLogin;
kFlRcv: Char;
end;
begin
case SearchIndexComboBox.ItemIndex of
0:
begin
Val(NameEdit.Text, I, Err);
TExtBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(I, 0, bsGe);
end;
1,2:
begin
StrPLCopy(Key1.kNameR, UpperCase(NameEdit.Text), SizeOf(Key1.kNameR));
if RcvCheckBox.Checked then
Key1.kFlRcv := '1'
else
Key1.kFlRcv := '0';
TExtBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(Key1,
SearchIndexComboBox.ItemIndex, bsGe);
end;
end;
end;
procedure TPostPacksForm.DelActionExecute(Sender: TObject);
const
MesTitle: PChar = 'Удаление';
var
N: Integer;
begin
if not DataSource.DataSet.IsEmpty then
begin
DBGrid.SelectedRows.Refresh;
N := DBGrid.SelectedRows.Count;
if (N<2) and (MessageBox(Handle, PChar('Пакет будет удален. Вы уверены?'),
MesTitle, MB_YESNOCANCEL + MB_ICONQUESTION) = IDYES)
or (N>=2) and (MessageBox(Handle, PChar('Будет удалено пакетов: '
+IntToStr(DBGrid.SelectedRows.Count)+#13#10'Вы уверены?'),
MesTitle, MB_YESNOCANCEL + MB_ICONQUESTION) = IDYES) then
begin
if N>0 then
begin
DBGrid.SelectedRows.Delete;
DBGrid.SelectedRows.Refresh;
end
else
DataSource.DataSet.Delete;
end;
end;
end;
procedure TPostPacksForm.EditActionExecute(Sender: TObject);
var
PostPackForm: TPostPackForm;
SndPack: TSndPack;
Len: Integer;
begin
if not DataSource.DataSet.IsEmpty then
begin
Len := TExtBtrDataSet(DataSource.DataSet).GetBtrRecord(PChar(@SndPack));
Application.CreateForm(TPostPackForm, PostPackForm);
with PostPackForm do
begin
with SndPack do
begin
RecvEdit.Text := spNameR;
SendEdit.Text := spNameS;
ByteSEdit.Text := IntToStr(spByteS);
LenEdit.Text := IntToStr(spLength);
WordSEdit.Text := IntToStr(spWordS);
NumEdit.Text := IntToStr(spNum);
IderEdit.Text := IntToStr(spIder);
FlSndEdit.Text := spFlSnd;
DateSEdit.Text := BtrDateToStr(spDateS);
TimeSEdit.Text := BtrTimeToStr(spTimeS);
FlRcvEdit.Text := spFlRcv;
DateREdit.Text := BtrDateToStr(spDateR);
TimeREdit.Text := BtrTimeToStr(spTimeR);
VarMemo.Text := Copy(spText, 1, Len-(SizeOf(SndPack)-SizeOf(SndPack.spText)));
end;
if ShowModal=mrOk then
begin
end;
Free;
end;
end;
end;
end.
|
unit untInseminacao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.Mask, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TfrmInseminacao = class(TForm)
pnlCentro: TPanel;
pnlRodape: TPanel;
btnNovo: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnFechar: TBitBtn;
dbgDados: TDBGrid;
pnlTop: TPanel;
edtNumero: TEdit;
lblCodigo: TLabel;
btnPesquisar: TBitBtn;
lblEmissao: TLabel;
pnlDados: TPanel;
lblTouro: TLabel;
btnPesqTouro: TBitBtn;
edtDescrTouro: TEdit;
lblAnimal: TLabel;
btnPesqAnimal: TBitBtn;
edtDescrAnimal: TEdit;
lblServico: TLabel;
btnPesqServico: TBitBtn;
edtDescrServico: TEdit;
edtVlrUnit: TEdit;
lblVlrUnit: TLabel;
pgctrlDados: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Label4: TLabel;
edtCodTouro: TEdit;
edtCodAnimal: TEdit;
edtCodServico: TEdit;
btnAdd: TBitBtn;
btnDelete: TBitBtn;
edtObs: TMemo;
edtDtEmissao: TDateTimePicker;
edtCodVet: TEdit;
Label5: TLabel;
btnPesqVet: TBitBtn;
edtDescrVeterinario: TEdit;
edtID: TEdit;
qryAuxiliar: TFDQuery;
dtsAuxiliar: TDataSource;
dtsAuxMovi: TDataSource;
qryAuxMovi: TFDQuery;
edtTotal: TEdit;
qryAuxiliar1: TFDQuery;
dtsAuxiliar1: TDataSource;
lblFinalizada: TLabel;
qryMoviProduto: TFDQuery;
dtsMoviProduto: TDataSource;
edtCodProprietario: TEdit;
lblProprietario: TLabel;
btnPesqProprietario: TBitBtn;
edtDescrProprietario: TEdit;
rgTipoSemen: TRadioGroup;
rgTipoInseminacao: TRadioGroup;
procedure FormActivate(Sender: TObject);
procedure btnPesqTouroClick(Sender: TObject);
procedure btnPesqAnimalClick(Sender: TObject);
procedure btnPesqProprietarioClick(Sender: TObject);
procedure btnPesqServicoClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure edtNumeroExit(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnPesqVetClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure edtCodProprietarioExit(Sender: TObject);
procedure edtCodVetExit(Sender: TObject);
procedure edtCodTouroExit(Sender: TObject);
procedure edtCodServicoExit(Sender: TObject);
procedure edtCodAnimalExit(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure edtNumeroKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodProprietarioKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodVetKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodTouroKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodServicoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodAnimalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodProprietarioKeyPress(Sender: TObject; var Key: Char);
procedure edtCodVetKeyPress(Sender: TObject; var Key: Char);
procedure edtCodTouroKeyPress(Sender: TObject; var Key: Char);
procedure edtCodServicoKeyPress(Sender: TObject; var Key: Char);
procedure edtCodAnimalKeyPress(Sender: TObject; var Key: Char);
procedure btnCancelarClick(Sender: TObject);
procedure edtCodProprietarioChange(Sender: TObject);
procedure edtCodVetChange(Sender: TObject);
procedure edtCodTouroChange(Sender: TObject);
procedure edtCodServicoChange(Sender: TObject);
procedure edtCodAnimalChange(Sender: TObject);
procedure dbgDadosDblClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
private
{ Private declarations }
vEdita : Boolean; //Versao 1.1.0 - 25/05/2018
function ValidaCampos : Boolean;
function ValidaCamposInseminacao : Boolean;
function ValidaAnimal : Boolean;
procedure LimpaCampos;
procedure GravaGrid;
procedure Totalizar;
procedure GravaMoviProduto(vQtd : real; vIDProduto : String; vIDAnimal : String);
public
{ Public declarations }
vID : string;
fNovo : Boolean;
procedure CarregaGrid;
procedure PesquisaBD(vStatus : boolean);
procedure PesquisaAnimal(vStatus : boolean);
procedure PesquisaProprietario(vStatus : boolean);
procedure PesquisaServico(vStatus : boolean);
procedure PesquisaTouro(vStatus : boolean);
procedure PesquisaVeterinario(vStatus : boolean);
end;
var
frmInseminacao: TfrmInseminacao;
implementation
{$R *.dfm}
uses unstCadastroVeterinario, untCadastroAnimal, untCadastroProduto,
untCadastroProdutor, untCadastroServico, untDM, untFuncoes, untPesquisa,
untCadastroCria, untPrincipal;
{ TfrmInseminacao }
procedure TfrmInseminacao.btnAddClick(Sender: TObject);
begin
if ValidaCamposInseminacao then
begin
if ValidaAnimal then
begin
if vEdita = false then //Versao 1.1.0 - 25/05/2018
begin
DM.qryMoviInseminacao.Insert;
DM.qryMoviInseminacao.FieldByName('ID').AsString := IntToStr(frmFuncoes.AutoIncre('MOVI_INSEMINACAO', 'Novo'));
end
else //Versao 1.1.0 - 25/05/2018
begin
DM.qryMoviInseminacao.Edit; //Versao 1.1.0 - 25/05/2018
end;
DM.qryMoviInseminacao.FieldByName('ID_inseminacao').AsString := vID;
DM.qryMoviInseminacao.FieldByName('IDAnimal').AsString := edtCodAnimal.Text;
DM.qryMoviInseminacao.FieldByName('nome').AsString := edtDescrAnimal.Text;
DM.qryMoviInseminacao.FieldByName('IDServico').AsString := edtCodServico.Text;
DM.qryMoviInseminacao.FieldByName('descricao').AsString := edtDescrServico.Text;
DM.qryMoviInseminacao.FieldByName('vlr_unit').AsString := edtVlrUnit.Text;
DM.qryMoviInseminacao.FieldByName('ID_PRODUTO').AsString := DM.qryConfiguracao.FieldByName('produto_inseminacao').AsString;
DM.qryMoviInseminacao.FieldByName('confirmada').AsString := 'A';
DM.qryMoviInseminacao.FieldByName('data_confirmacao').AsString := '01/01/1900';
DM.qryMoviInseminacao.Post;
DM.qryMoviInseminacao.UpdateCursorPos;
edtCodAnimal.Clear;
edtDescrAnimal.Clear;
edtCodAnimal.SetFocus;
vEdita := False;
Totalizar;
end
else
begin
ShowMessage('Animal já inserido!');
edtCodAnimal.Clear;
edtDescrAnimal.Clear;
edtCodAnimal.SetFocus;
end;
end;
end;
procedure TfrmInseminacao.btnCancelarClick(Sender: TObject);
begin
if edtNumero.Text <> '' then
begin
if fNovo = False then
begin
PesquisaBD(True);
end
else
begin
edtNumero.Enabled := true;
edtNumero.Clear;
LimpaCampos;
btnNovo.Enabled := True;
btnGravar.Enabled := True;
btnExcluir.Enabled := True;
fNovo := False;
end;
end;
end;
procedure TfrmInseminacao.btnDeleteClick(Sender: TObject); //Versao 1.1.0 - 25/05/2018
begin
dm.qryMoviInseminacao.Delete;
edtCodAnimal.Clear;
edtDescrAnimal.Clear;
vEdita := False;
end;
procedure TfrmInseminacao.btnExcluirClick(Sender: TObject);
var
vQtdSemem : integer;
begin
if fNovo = False then
begin
vQtdSemem := dm.qryMoviInseminacao.RecordCount;
if dm.qryCadInseminacao.RecordCount > 0 then
begin
if Application.MessageBox('Deseja realmente excluir o registro?', 'Curral Novo', MB_YESNO) = mrYes then
begin
dm.qryCadInseminacao.Delete;
dm.qryCadInseminacao.ApplyUpdates(-1);
{if dm.qryCadInseminacao.ApplyUpdates(-1) = 0 then //Comentado na versao 1.1.0 - 16/05/2018
begin
frmFuncoes.ExecutaSQL('Update PRODUTO set estoque = estoque + ' + IntToStr(vQtdSemem), '', qryAuxiliar1);
frmFuncoes.ExecutaSQL('Update ANIMAL set estoque = estoque + ' + IntToStr(vQtdSemem) + ' where ID = ' + edtCodTouro.Text, '', qryAuxiliar1);
end;}
close;
end;
end;
end;
end;
procedure TfrmInseminacao.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TfrmInseminacao.btnGravarClick(Sender: TObject);
var
vQtdSemem : Real;
begin
if ValidaCampos then
begin
vQtdSemem := dm.qryMoviInseminacao.RecordCount;
if fNovo = True then
begin
dm.qryCadInseminacao.Append;
vID := IntToStr(frmFuncoes.AutoIncre('INSEMINACAO', 'Novo'));
dm.qryCadInseminacao.FieldByName('id').AsString := vID;
frmFuncoes.AutoIncre('INSEMINACAO', 'Gravar');
dm.qryCadInseminacao.FieldByName('numero').AsString := edtNumero.Text
end
else
begin
dm.qryCadInseminacao.Edit;
end;
dm.qryCadInseminacao.FieldByName('data').AsDateTime := edtDtEmissao.Date;
dm.qryCadInseminacao.FieldByName('id_produtor').AsString := edtCodProprietario.Text;
dm.qryCadInseminacao.FieldByName('id_veterinario').AsString := edtCodVet.Text;
dm.qryCadInseminacao.FieldByName('id_touro').AsString := edtCodTouro.Text;
dm.qryCadInseminacao.FieldByName('observacao').AsString := edtObs.Text;
dm.qryCadInseminacao.FieldByName('FINALIZADA').AsString := 'N';
dm.qryCadInseminacao.FieldByName('DT_FINALIZADA').AsString := '01/01/1900';
dm.qryCadInseminacao.FieldByName('NOMETOURO').AsString := edtDescrTouro.Text;
dm.qryCadInseminacao.FieldByName('alteracao').AsDateTime := Date+Time;
dm.qryCadInseminacao.FieldByName('usuario').AsString := inttostr(frmPrincipal.vUsuario);
dm.qryCadInseminacao.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
dm.qryCadInseminacao.FieldByName('TIPO_INSEMINACAO').AsInteger := rgTipoInseminacao.ItemIndex; //Versao 3.0.0 - 12/07/2022
dm.qryCadInseminacao.FieldByName('TIPO_SEMEN').AsInteger := rgTipoSemen.ItemIndex; //Versao 3.0.0 - 12/07/2022
dm.qryCadInseminacao.Post;
if dm.qryCadInseminacao.ApplyUpdates(-1) = 0 then
begin
GravaGrid;
{ //Comentado na versao 1.1.0 - 16/05/2018
frmFuncoes.ExecutaSQL('Update PRODUTO set estoque = estoque - ' + IntToStr(vQtdSemem), '', qryAuxiliar1);
frmFuncoes.ExecutaSQL('Update ANIMAL set estoque = estoque - ' + IntToStr(vQtdSemem) + ' where ID = ' + edtCodTouro.Text, '', qryAuxiliar1);
}
GravaMoviProduto(vQtdSemem, dm.qryConfiguracao.FieldByName('PRODUTO_INSEMINACAO').AsString, edtCodTouro.Text);
end;
btnNovo.Enabled := True;
btnExcluir.Enabled := True;
edtNumero.Enabled := True;
fNovo := False;
ShowMessage('Gravação efetuada com sucesso!');
end;
end;
procedure TfrmInseminacao.btnNovoClick(Sender: TObject);
begin
LimpaCampos;
fNovo := True;
vEdita := False;
CarregaGrid;
frmFuncoes.ExecutaSQL('Select * from INSEMINACAO WHERE ID IS NULL', 'Abrir', DM.qryCadInseminacao);
dm.qryCadInseminacao.Append;
btnNovo.Enabled := False;
btnGravar.Enabled := True;
btnExcluir.Enabled := False;
edtNumero.SetFocus;
edtID.Text := IntToStr(frmFuncoes.AutoIncre('INSEMINACAO', 'Novo'));
edtNumero.Text := frmFuncoes.FormataNumero(edtID.Text);
edtNumero.Enabled := false;
edtDtEmissao.SetFocus;
if dm.qryConfiguracao.FieldByName('VETERINARIO_PADRAO').AsString <> '' then
BEGIN
edtCodVet.Text := dm.qryConfiguracao.FieldByName('VETERINARIO_PADRAO').AsString;
PesquisaVeterinario(True);
END;
edtCodServico.Text := '1';
PesquisaServico(True);
end;
procedure TfrmInseminacao.btnPesqAnimalClick(Sender: TObject);
begin
PesquisaAnimal(False);
end;
procedure TfrmInseminacao.btnPesqProprietarioClick(Sender: TObject);
begin
PesquisaProprietario(False);
end;
procedure TfrmInseminacao.btnPesqServicoClick(Sender: TObject);
begin
PesquisaServico(False);
end;
procedure TfrmInseminacao.btnPesqTouroClick(Sender: TObject);
begin
PesquisaTouro(False);
end;
procedure TfrmInseminacao.btnPesquisarClick(Sender: TObject);
begin
if fNovo = False then
PesquisaBD(False);
end;
procedure TfrmInseminacao.btnPesqVetClick(Sender: TObject);
begin
PesquisaVeterinario(False);
end;
procedure TfrmInseminacao.CarregaGrid;
begin
frmFuncoes.ExecutaSQL('select MI.ID, MI.ID_INSEMINACAO, A.ID as IDAnimal, A.NOME, S.ID as IDServico, S.DESCRICAO, MI.VLR_UNIT, MI.CONFIRMADA, MI.DATA_CONFIRMACAO, MI.ID_PRODUTO ' +
' FROM ANIMAL A join MOVI_INSEMINACAO MI on (A.ID = MI.ID_ANIMAL) JOIN SERVICO S ON (S.ID = MI.ID_SERVICO) ' +
' Where MI.id_inseminacao = ' + vID + ' order by MI.ID', 'Abrir', DM.qryMoviInseminacao);
dbgDados.Columns.Items[0].Visible := False; //ID
dbgDados.Columns.Items[1].Visible := False; //ID_INSEMINACAO
dbgDados.Columns.Items[2].Visible := False; //ID_ANIMAL
dbgDados.Columns.Items[3].Visible := True; //NOME ANIMAL
dbgDados.Columns.Items[4].Visible := False; //ID_SERVICO
dbgDados.Columns.Items[5].Visible := True; //DESCR SERVICO
dbgDados.Columns.Items[6].Visible := True; //VLR_UNIT
dbgDados.Columns.Items[7].Visible := False; //CONFIRMADA
dbgDados.Columns.Items[8].Visible := False; //DATA_CONFIRMACAO
dbgDados.Columns.Items[9].Visible := False; //ID_PRODUTO
dbgDados.Columns.Items[3].Width := 150;
dbgDados.Columns.Items[5].Width := 150;
TFMTBCDField(dm.qryMoviInseminacao.FieldByName('vlr_unit')).DisplayFormat := '###,####,###,##0.00';
Totalizar;
end;
procedure TfrmInseminacao.dbgDadosDblClick(Sender: TObject); //Versao 1.1.0 - 25/05/2018
begin
vEdita := True;
edtCodAnimal.Text := DM.qryMoviInseminacao.FieldByName('idAnimal').AsString;
edtDescrAnimal.Text := DM.qryMoviInseminacao.FieldByName('nome').AsString;
end;
procedure TfrmInseminacao.dbgDadosDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if gdSelected in State then
begin
dbgDados.Canvas.Brush.Color := clNavy;
dbgDados.Canvas.Font.Color := clWhite;
end;
dbgDados.DefaultDrawDataCell(Rect, Column.Field, State);
end;
procedure TfrmInseminacao.edtNumeroExit(Sender: TObject);
begin
if fNovo = false then
begin
if Trim(edtNumero.Text) <> '' then
PesquisaBD(True);
end;
end;
procedure TfrmInseminacao.edtNumeroKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesquisarClick(Self);
end;
procedure TfrmInseminacao.FormActivate(Sender: TObject);
begin
LimpaCampos;
CarregaGrid;
edtNumero.SetFocus;
end;
procedure TfrmInseminacao.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmInseminacao.GravaGrid;
begin
if dm.qryMoviInseminacao.RecordCount > 0 then
begin
if fNovo = False then
frmFuncoes.ExecutaSQL('Delete from MOVI_INSEMINACAO where ID_inseminacao = ' + QuotedStr(vID), 'Executar', qryAuxiliar);
dm.qryMoviInseminacao.First;
while not dm.qryMoviInseminacao.Eof do
begin
frmFuncoes.ExecutaSQL('Select * from MOVI_INSEMINACAO where ID is null', 'Abrir', qryAuxMovi);
qryAuxMovi.Insert;
qryAuxMovi.FieldByName('ID').AsString := IntToStr(frmFuncoes.AutoIncre('MOVI_INSEMINACAO', 'Novo'));
qryAuxMovi.FieldByName('ID_inseminacao').AsString := vID;
qryAuxMovi.FieldByName('id_animal').AsString := DM.qryMoviInseminacao.FieldByName('idanimal').AsString;
qryAuxMovi.FieldByName('id_servico').AsString := DM.qryMoviInseminacao.FieldByName('idservico').AsString;
qryAuxMovi.FieldByName('vlr_unit').AsString := DM.qryMoviInseminacao.FieldByName('vlr_unit').AsString;
qryAuxMovi.FieldByName('ID_PRODUTO').AsString := DM.qryMoviInseminacao.FieldByName('ID_PRODUTO').AsString;
qryAuxMovi.FieldByName('confirmada').AsString := DM.qryMoviInseminacao.FieldByName('confirmada').AsString;
qryAuxMovi.FieldByName('data_confirmacao').AsString := DM.qryMoviInseminacao.FieldByName('data_confirmacao').AsString;
qryAuxMovi.Post;
qryAuxMovi.ApplyUpdates(-1);
frmFuncoes.AutoIncre('MOVI_INSEMINACAO', '');
dm.qryMoviInseminacao.Next;
end;
end;
end;
procedure TfrmInseminacao.GravaMoviProduto(vQtd: real; vIDProduto: String;
vIDAnimal : String);
begin
frmFuncoes.ExecutaSQL('Select * from MOVI_PRODUTO where ID is null', 'Abrir', qryMoviProduto);
qryMoviProduto.Insert;
qryMoviProduto.FieldByName('ID').AsString := IntToStr(frmFuncoes.AutoIncre('MOVI_PRODUTO', 'Novo'));
qryMoviProduto.FieldByName('NUMERO').AsString := qryMoviProduto.FieldByName('ID').AsString;
qryMoviProduto.FieldByName('ID_INSEMINACAO').AsString := vID;
qryMoviProduto.FieldByName('DATA').AsDateTime := edtDtEmissao.Date;
qryMoviProduto.FieldByName('ID_PRODUTO').AsString := vIDProduto;
qryMoviProduto.FieldByName('ID_ANIMAL').AsString := vIDAnimal;
qryMoviProduto.FieldByName('QUANTIDADE').AsFloat := vQtd;
qryMoviProduto.FieldByName('TIPO').AsString := 'S';
qryMoviProduto.FieldByName('UNIDADE').AsString := 'UN';
qryMoviProduto.FieldByName('ALTERACAO').AsDateTime := Date+Time;
qryMoviProduto.FieldByName('USUARIO').AsInteger := StrToInt(frmFuncoes.LerArquivoUsuario);
qryMoviProduto.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
qryMoviProduto.Post;
qryMoviProduto.ApplyUpdates(-1);
frmFuncoes.AutoIncre('MOVI_PRODUTO', '');
end;
procedure TfrmInseminacao.LimpaCampos;
begin
edtNumero.Clear;
edtDtEmissao.DateTime := Date;
edtCodProprietario.Clear;
edtDescrProprietario.Clear;
edtCodTouro.Clear;
edtDescrTouro.Clear;
edtCodVet.Clear;
edtDescrVeterinario.Clear;
edtCodServico.Clear;
edtDescrServico.Clear;
edtVlrUnit.Text := '0,00';
edtCodAnimal.Clear;
edtDescrAnimal.Clear;
edtObs.Clear;
vID := '0';
CarregaGrid;
end;
procedure TfrmInseminacao.PesquisaAnimal(vStatus: boolean);
begin
if Trim(edtCodProprietario.Text) <> '' then
begin
if vStatus = True then
begin
if Trim(edtCodAnimal.Text) <> '' then
BEGIN
//frmFuncoes.ExecutaSQL('Select * from ANIMAL where SEXO = ' + QuotedStr('F') + ' AND TIPO = ' + QuotedStr('Animal') + ' and ID = ' + QuotedStr(edtCodAnimal.Text) + ' AND PROPRIETARIO = ' + QuotedStr(edtCodProprietario.Text) + ' and ID NOT IN (SELECT ID_ANIMAL FROM MOVI_INSEMINACAO WHERE CONFIRMADA IN (' + QuotedStr('A') + ', ' + QuotedStr('S') + '))', 'Abrir', DM.qryAnimal);
frmFuncoes.ExecutaSQL(frmFuncoes.LerArquivoIni('INSEMINACAO', 'ANIMALF') + ' AND A.PROPRIETARIO = ' + QuotedStr(edtCodProprietario.Text) +
' and A.ID = ' + QuotedStr(edtCodAnimal.Text) + ' GROUP BY A.ID, A.NOME, A.IDENTIFICACAO, A.PROPRIETARIO, A.ESTOQUE', 'Abrir', DM.qryAnimal);
if DM.qryAnimal.RecordCount > 0 then
begin
edtDescrAnimal.Text := DM.qryAnimal.FieldByName('NOME').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodAnimal.SetFocus;
edtCodAnimal.Clear;
edtDescrAnimal.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'ANIMAL';
frmPesquisa.vTela := 'INSEMINACAO';
frmPesquisa.vComando := frmFuncoes.LerArquivoIni('INSEMINACAO', 'ANIMALF') + ' AND A.PROPRIETARIO = ' + QuotedStr(edtCodProprietario.Text) + ' GROUP BY A.ID, A.NOME, A.IDENTIFICACAO, A.PROPRIETARIO, A.ESTOQUE ORDER BY A.NOME';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end
else
begin
Application.MessageBox('Informe o Proprietário.', 'Curral Novo', MB_OK);
edtCodProprietario.SetFocus;
end;
end;
procedure TfrmInseminacao.PesquisaBD(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtNumero.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select I.*, MI.* from INSEMINACAO I JOIN MOVI_INSEMINACAO MI ON (MI.ID_INSEMINACAO = I.ID) WHERE NUMERO = ' + QuotedStr(edtNumero.Text), 'Abrir', DM.qryCadInseminacao);
if DM.qryCadInseminacao.RecordCount > 0 then
begin
vID := DM.qryCadInseminacao.FieldByName('ID').AsString;
edtID.Text := vID;
edtCodProprietario.Text := DM.qryCadInseminacao.FieldByName('id_produtor').AsString;
PesquisaProprietario(True);
edtCodVet.Text := DM.qryCadInseminacao.FieldByName('id_veterinario').AsString;
PesquisaVeterinario(True);
edtCodTouro.Text := DM.qryCadInseminacao.FieldByName('id_touro').AsString;
PesquisaTouro(True);
edtCodServico.Text := DM.qryCadInseminacao.FieldByName('id_servico').AsString;
PesquisaServico(True);
edtDtEmissao.Date := DM.qryCadInseminacao.FieldByName('data').AsDateTime;
CarregaGrid;
rgTipoSemen.ItemIndex := DM.qryCadInseminacao.FieldByName('TIPO_SEMEN').AsInteger;
rgTipoInseminacao.ItemIndex := DM.qryCadInseminacao.FieldByName('TIPO_INSEMINACAO').AsInteger;
if DM.qryCadInseminacao.FieldByName('FINALIZADA').AsString = 'S' then
BEGIN
btnGravar.Enabled := False;
btnExcluir.Enabled := False;
dbgDados.Enabled := False;
lblFinalizada.Visible := True;
END
else
begin
btnGravar.Enabled := True;
btnExcluir.Enabled := True;
dbgDados.Enabled := True;
lblFinalizada.Visible := False;
end;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtNumero.SetFocus;
edtNumero.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'INSEMINACAO';
frmPesquisa.vTela := 'INSEMINACAO';
frmPesquisa.vComando := 'Select I.NUMERO, I.DATA, P.NOME PRODUTOR, V.NOME VETERINARIO from INSEMINACAO I JOIN PRODUTOR P ON (P.ID = I.ID_PRODUTOR) JOIN VETERINARIO V ON (V.ID = I.ID_VETERINARIO) WHERE I.FINALIZADA = ' + QuotedStr('N') + ' ORDER BY I.NUMERO' ;
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmInseminacao.PesquisaProprietario(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodProprietario.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from PRODUTOR where ID = ' + QuotedStr(edtCodProprietario.Text), 'Abrir', DM.qryProprietario);
if DM.qryProprietario.RecordCount > 0 then
begin
edtDescrProprietario.Text := DM.qryProprietario.FieldByName('NOME').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodProprietario.SetFocus;
edtCodProprietario.Clear;
edtDescrProprietario.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'PRODUTOR';
frmPesquisa.vTela := 'INSEMINACAO';
frmPesquisa.vComando := 'Select ID, NOME, INSC_RURAL from PRODUTOR ORDER BY NOME';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmInseminacao.PesquisaServico(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodServico.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from SERVICO where ID = ' + QuotedStr(edtCodServico.Text), 'Abrir', DM.qryProprietario);
if DM.qryProprietario.RecordCount > 0 then
begin
edtDescrServico.Text := DM.qryProprietario.FieldByName('DESCRICAO').AsString;
edtVlrUnit.Text := DM.qryProprietario.FieldByName('valor').AsString;
TFMTBCDField(edtVlrUnit).DisplayFormat := '###,####,###,##0.00';
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodServico.SetFocus;
edtCodServico.Clear;
edtDescrServico.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'SERVICO';
frmPesquisa.vTela := 'INSEMINACAO';
frmPesquisa.vComando := 'Select ID, DESCRICAO, VALOR from SERVICO ORDER BY DESCRICAO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmInseminacao.PesquisaTouro(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodTouro.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from ANIMAL where SEXO = ' + QuotedStr('M') + ' and ID = ' + QuotedStr(edtCodTouro.Text), 'Abrir', DM.qryAnimal);
if DM.qryAnimal.RecordCount > 0 then
begin
edtDescrTouro.Text := DM.qryAnimal.FieldByName('NOME').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodTouro.SetFocus;
edtCodTouro.Clear;
edtDescrTouro.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'ANIMAL';
frmPesquisa.vTela := 'INSEMINACAO_T';
frmPesquisa.vComando := 'Select ID, NOME, IDENTIFICACAO, ESTOQUE, PROPRIETARIO from ANIMAL where SEXO = ' + QuotedStr('M') + ' ORDER BY NOME';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmInseminacao.PesquisaVeterinario(vStatus: boolean);
begin
if vStatus = True then
begin
frmFuncoes.ExecutaSQL('Select * from VETERINARIO where ID = ' + QuotedStr(edtCodVet.Text), 'Abrir', DM.qryVeterinario);
if DM.qryVeterinario.RecordCount > 0 then
begin
edtDescrVeterinario.Text := DM.qryVeterinario.FieldByName('nome').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodVet.SetFocus;
edtCodVet.Clear;
edtDescrVeterinario.Clear;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'VETERINARIO';
frmPesquisa.vTela := 'INSEMINACAO';
frmPesquisa.vComando := 'Select ID, NOME from VETERINARIO ORDER BY NOME';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmInseminacao.Totalizar;
var
vVlrTotal : Real;
begin
vVlrTotal := 0;
DM.qryMoviInseminacao.First;
while not DM.qryMoviInseminacao.Eof do
begin
vVlrTotal := vVlrTotal + DM.qryMoviInseminacao.FieldByName('vlr_unit').AsFloat;
DM.qryMoviInseminacao.Next;
end;
edtTotal.Text := FormatFloat('#,##0.00', vVlrTotal);
//TFMTBCDField(edtTotal).DisplayFormat := '###,####,###,##0.00';
end;
function TfrmInseminacao.ValidaAnimal: Boolean;
var
vRetorno : Boolean;
begin
vRetorno := True;
if vEdita = False then
begin
DM.qryMoviInseminacao.First;
while not DM.qryMoviInseminacao.Eof do
begin
if DM.qryMoviInseminacao.FieldByName('IDAnimal').AsString = edtCodAnimal.Text then
vRetorno := False;
DM.qryMoviInseminacao.Next;
end;
end;
Result := vRetorno;
end;
function TfrmInseminacao.ValidaCampos: Boolean;
var
vRetorno : Boolean;
begin
vRetorno := True;
if Trim(edtCodProprietario.Text) = '' then
begin
ShowMessage('Insira o Proprietário!');
edtCodProprietario.SetFocus;
vRetorno := False;
end;
if Trim(edtCodVet.Text) = '' then
begin
ShowMessage('Insira o Veterinário!');
edtCodVet.SetFocus;
vRetorno := False;
end;
if Trim(edtCodTouro.Text) = '' then
begin
ShowMessage('Insira o Touro!');
edtCodTouro.SetFocus;
vRetorno := False;
end;
if Trim(edtCodServico.Text) = '' then
begin
ShowMessage('Insira o Serviço!');
edtCodServico.SetFocus;
vRetorno := False;
end;
if dm.qryMoviInseminacao.RecordCount = 0 then
begin
if Trim(edtCodAnimal.Text) = '' then
begin
ShowMessage('Insira o Animal!');
edtCodAnimal.SetFocus;
vRetorno := False;
end;
end;
Result := vRetorno;
end;
function TfrmInseminacao.ValidaCamposInseminacao: Boolean;
var
vRetorno : Boolean;
begin
vRetorno := True;
if Trim(edtCodProprietario.Text) = '' then
begin
ShowMessage('Insira o Proprietário!');
edtCodProprietario.SetFocus;
vRetorno := False;
end
else if Trim(edtCodAnimal.Text) = '' then
begin
ShowMessage('Insira o Animal!');
edtCodAnimal.SetFocus;
vRetorno := False;
end
else if DM.qryMoviInseminacao.Locate('ID', edtCodAnimal.Text, [loCaseInsensitive, loPartialKey]) then
begin
ShowMessage('Animal já inserido!');
edtCodAnimal.SetFocus;
vRetorno := False;
end;
Result := vRetorno;
end;
procedure TfrmInseminacao.edtCodAnimalChange(Sender: TObject);
begin
if Trim(edtCodAnimal.Text) = '' then
edtDescrAnimal.Clear;
end;
procedure TfrmInseminacao.edtCodAnimalExit(Sender: TObject);
begin
if edtCodAnimal.Text <> '' then
begin
if ValidaCamposInseminacao then
begin
PesquisaAnimal(True);
end;
end;
end;
procedure TfrmInseminacao.edtCodAnimalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesqAnimalClick(Self);
end;
procedure TfrmInseminacao.edtCodAnimalKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmInseminacao.edtCodProprietarioChange(Sender: TObject);
begin
if Trim(edtCodProprietario.Text) = '' then
edtDescrProprietario.Clear;
end;
procedure TfrmInseminacao.edtCodProprietarioExit(Sender: TObject);
begin
if Trim(edtCodProprietario.Text) <> '' then
begin
PesquisaProprietario(True);
CarregaGrid;
end;
end;
procedure TfrmInseminacao.edtCodProprietarioKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesqProprietarioClick(Self);
end;
procedure TfrmInseminacao.edtCodProprietarioKeyPress(Sender: TObject;
var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmInseminacao.edtCodServicoChange(Sender: TObject);
begin
if Trim(edtCodServico.Text) = '' then
edtDescrServico.Clear;
end;
procedure TfrmInseminacao.edtCodServicoExit(Sender: TObject);
begin
if Trim(edtCodServico.Text) <> '' then
begin
PesquisaServico(True);
end;
end;
procedure TfrmInseminacao.edtCodServicoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesqServicoClick(Self);
end;
procedure TfrmInseminacao.edtCodServicoKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmInseminacao.edtCodTouroChange(Sender: TObject);
begin
if trim(edtCodTouro.Text) = '' then
edtDescrTouro.Clear;
end;
procedure TfrmInseminacao.edtCodTouroExit(Sender: TObject);
begin
if Trim(edtCodTouro.Text) <> '' then
begin
PesquisaTouro(True);
end;
end;
procedure TfrmInseminacao.edtCodTouroKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesqTouroClick(Self);
end;
procedure TfrmInseminacao.edtCodTouroKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmInseminacao.edtCodVetChange(Sender: TObject);
begin
if Trim(edtCodVet.Text) = '' then
edtDescrVeterinario.Clear;
end;
procedure TfrmInseminacao.edtCodVetExit(Sender: TObject);
begin
if Trim(edtCodVet.Text) <> '' then
begin
PesquisaVeterinario(True);
end;
end;
procedure TfrmInseminacao.edtCodVetKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesqVetClick(Self);
end;
procedure TfrmInseminacao.edtCodVetKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
end.
|
{****************************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{****************************************************************}
{ Delphi-Objective-C Bridge }
{ Interfaces for Cocoa framework CoreVideo }
{ }
{ Copyright (c) 2004 Apple Computer, Inc. All rights reserved. }
{ }
{ Translator: Embarcadero Technologies, Inc. }
{ Copyright (c) 2012-2014 Embarcadero Technologies, Inc. }
{****************************************************************}
unit Macapi.CoreVideo;
interface
uses
Posix.StdDef,
Macapi.ObjCRuntime,
Macapi.ObjectiveC, Macapi.CocoaTypes,
Macapi.CoreFoundation,
Macapi.Foundation;
const
COREVIDEO_SUPPORTS_COLORSPACE = 1;
COREVIDEO_SUPPORTS_DIRECT3D = 0;
COREVIDEO_SUPPORTS_DISPLAYLINK = 1;
COREVIDEO_SUPPORTS_IOSURFACE = 1;
COREVIDEO_SUPPORTS_OPENGL = 1;
kCVAttachmentMode_ShouldNotPropagate = 0;
kCVAttachmentMode_ShouldPropagate = 1;
kCVPixelBufferLock_ReadOnly = 1;
kCVPixelFormatType_16BE555 = 16;
kCVPixelFormatType_16BE565 = 1110783541;
kCVPixelFormatType_16Gray = 1647392359;
kCVPixelFormatType_16LE555 = 1278555445;
kCVPixelFormatType_16LE5551 = 892679473;
kCVPixelFormatType_16LE565 = 1278555701;
kCVPixelFormatType_1IndexedGray_WhiteIsZero = 33;
kCVPixelFormatType_1Monochrome = 1;
kCVPixelFormatType_24BGR = 842285639;
kCVPixelFormatType_24RGB = 24;
kCVPixelFormatType_2Indexed = 2;
kCVPixelFormatType_2IndexedGray_WhiteIsZero = 34;
kCVPixelFormatType_30RGB = 1378955371;
kCVPixelFormatType_32ABGR = 1094862674;
kCVPixelFormatType_32ARGB = 32;
kCVPixelFormatType_32AlphaGray = 1647522401;
kCVPixelFormatType_32BGRA = 1111970369;
kCVPixelFormatType_32RGBA = 1380401729;
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange = 875704422;
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange = 875704438;
kCVPixelFormatType_420YpCbCr8Planar = 2033463856;
kCVPixelFormatType_420YpCbCr8PlanarFullRange = 1714696752;
kCVPixelFormatType_422YpCbCr10 = 1983000880;
kCVPixelFormatType_422YpCbCr16 = 1983000886;
kCVPixelFormatType_422YpCbCr8 = 846624121;
kCVPixelFormatType_422YpCbCr8FullRange = 2037741158;
kCVPixelFormatType_422YpCbCr8_yuvs = 2037741171;
kCVPixelFormatType_422YpCbCr_4A_8BiPlanar = 1630697081;
kCVPixelFormatType_4444AYpCbCr16 = 2033463606;
kCVPixelFormatType_4444AYpCbCr8 = 2033463352;
kCVPixelFormatType_4444YpCbCrA8 = 1983131704;
kCVPixelFormatType_4444YpCbCrA8R = 1916022840;
kCVPixelFormatType_444YpCbCr10 = 1983131952;
kCVPixelFormatType_444YpCbCr8 = 1983066168;
kCVPixelFormatType_48RGB = 1647589490;
kCVPixelFormatType_4Indexed = 4;
kCVPixelFormatType_4IndexedGray_WhiteIsZero = 36;
kCVPixelFormatType_64ARGB = 1647719521;
kCVPixelFormatType_8Indexed = 8;
kCVPixelFormatType_8IndexedGray_WhiteIsZero = 40;
kCVReturnAllocationFailed = -6662;
kCVReturnDisplayLinkAlreadyRunning = -6671;
kCVReturnDisplayLinkCallbacksNotSet = -6673;
kCVReturnDisplayLinkNotRunning = -6672;
kCVReturnError = -6660;
kCVReturnFirst = -6660;
kCVReturnInvalidArgument = -6661;
kCVReturnInvalidDisplay = -6670;
kCVReturnInvalidPixelBufferAttributes = -6682;
kCVReturnInvalidPixelFormat = -6680;
kCVReturnInvalidPoolAttributes = -6691;
kCVReturnInvalidSize = -6681;
kCVReturnLast = -6699;
kCVReturnPixelBufferNotOpenGLCompatible = -6683;
kCVReturnPoolAllocationFailed = -6690;
kCVReturnSuccess = 0;
kCVReturnWouldExceedAllocationThreshold = -6689;
kCVSMPTETimeRunning = 2;
kCVSMPTETimeType24 = 0;
kCVSMPTETimeType25 = 1;
kCVSMPTETimeType2997 = 4;
kCVSMPTETimeType2997Drop = 5;
kCVSMPTETimeType30 = 3;
kCVSMPTETimeType30Drop = 2;
kCVSMPTETimeType5994 = 7;
kCVSMPTETimeType60 = 6;
kCVSMPTETimeValid = 1;
kCVTimeIsIndefinite = 1;
kCVTimeStampBottomField = 131072;
kCVTimeStampHostTimeValid = 2;
kCVTimeStampIsInterlaced = 196608;
kCVTimeStampRateScalarValid = 16;
kCVTimeStampSMPTETimeValid = 4;
kCVTimeStampTopField = 65536;
kCVTimeStampVideoHostTimeValid = 3;
kCVTimeStampVideoRefreshPeriodValid = 8;
kCVTimeStampVideoTimeValid = 1;
// ===== External functions =====
const
libCoreVideo = '/System/Library/Frameworks/CoreVideo.framework/CoreVideo';
function CVBufferGetAttachment(buffer: CVBufferRef; key: CFStringRef; attachmentMode: PCVAttachmentMode): CFTypeRef; cdecl; external libCoreVideo name _PU + 'CVBufferGetAttachment';
function CVBufferGetAttachments(buffer: CVBufferRef; attachmentMode: CVAttachmentMode): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVBufferGetAttachments';
procedure CVBufferPropagateAttachments(sourceBuffer: CVBufferRef; destinationBuffer: CVBufferRef); cdecl; external libCoreVideo name _PU + 'CVBufferPropagateAttachments';
procedure CVBufferRelease(buffer: CVBufferRef); cdecl; external libCoreVideo name _PU + 'CVBufferRelease';
procedure CVBufferRemoveAllAttachments(buffer: CVBufferRef); cdecl; external libCoreVideo name _PU + 'CVBufferRemoveAllAttachments';
procedure CVBufferRemoveAttachment(buffer: CVBufferRef; key: CFStringRef); cdecl; external libCoreVideo name _PU + 'CVBufferRemoveAttachment';
function CVBufferRetain(buffer: CVBufferRef): CVBufferRef; cdecl; external libCoreVideo name _PU + 'CVBufferRetain';
procedure CVBufferSetAttachment(buffer: CVBufferRef; key: CFStringRef; value: CFTypeRef; attachmentMode: CVAttachmentMode); cdecl; external libCoreVideo name _PU + 'CVBufferSetAttachment';
procedure CVBufferSetAttachments(buffer: CVBufferRef; theAttachments: CFDictionaryRef; attachmentMode: CVAttachmentMode); cdecl; external libCoreVideo name _PU + 'CVBufferSetAttachments';
function CVDisplayLinkCreateWithActiveCGDisplays(displayLinkOut: PCVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkCreateWithActiveCGDisplays';
function CVDisplayLinkCreateWithCGDisplay(displayID: CGDirectDisplayID; displayLinkOut: PCVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkCreateWithCGDisplay';
function CVDisplayLinkCreateWithCGDisplays(displayArray: PCGDirectDisplayID; count: CFIndex; displayLinkOut: PCVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkCreateWithCGDisplays';
function CVDisplayLinkCreateWithOpenGLDisplayMask(mask: CGOpenGLDisplayMask; displayLinkOut: PCVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkCreateWithOpenGLDisplayMask';
function CVDisplayLinkGetActualOutputVideoRefreshPeriod(displayLink: CVDisplayLinkRef): double; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetActualOutputVideoRefreshPeriod';
function CVDisplayLinkGetCurrentCGDisplay(displayLink: CVDisplayLinkRef): CGDirectDisplayID; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetCurrentCGDisplay';
function CVDisplayLinkGetCurrentTime(displayLink: CVDisplayLinkRef; outTime: PCVTimeStamp): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetCurrentTime';
function CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink: CVDisplayLinkRef): CVTime; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetNominalOutputVideoRefreshPeriod';
function CVDisplayLinkGetOutputVideoLatency(displayLink: CVDisplayLinkRef): CVTime; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetOutputVideoLatency';
function CVDisplayLinkGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkGetTypeID';
function CVDisplayLinkIsRunning(displayLink: CVDisplayLinkRef): Boolean; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkIsRunning';
procedure CVDisplayLinkRelease(displayLink: CVDisplayLinkRef); cdecl; external libCoreVideo name _PU + 'CVDisplayLinkRelease';
function CVDisplayLinkRetain(displayLink: CVDisplayLinkRef): CVDisplayLinkRef; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkRetain';
function CVDisplayLinkSetCurrentCGDisplay(displayLink: CVDisplayLinkRef; displayID: CGDirectDisplayID): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkSetCurrentCGDisplay';
function CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink: CVDisplayLinkRef; cglContext: CGLContextObj; cglPixelFormat: CGLPixelFormatObj): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext';
function CVDisplayLinkSetOutputCallback(displayLink: CVDisplayLinkRef; callback: CVDisplayLinkOutputCallback; userInfo: Pointer): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkSetOutputCallback';
function CVDisplayLinkStart(displayLink: CVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkStart';
function CVDisplayLinkStop(displayLink: CVDisplayLinkRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkStop';
function CVDisplayLinkTranslateTime(displayLink: CVDisplayLinkRef; inTime: PCVTimeStamp; outTime: PCVTimeStamp): CVReturn; cdecl; external libCoreVideo name _PU + 'CVDisplayLinkTranslateTime';
function CVGetCurrentHostTime: UInt64; cdecl; external libCoreVideo name _PU + 'CVGetCurrentHostTime';
function CVGetHostClockFrequency: double; cdecl; external libCoreVideo name _PU + 'CVGetHostClockFrequency';
function CVGetHostClockMinimumTimeDelta: UInt32; cdecl; external libCoreVideo name _PU + 'CVGetHostClockMinimumTimeDelta';
function CVImageBufferGetCleanRect(imageBuffer: CVImageBufferRef): CGRect; cdecl; external libCoreVideo name _PU + 'CVImageBufferGetCleanRect';
function CVImageBufferGetColorSpace(imageBuffer: CVImageBufferRef): CGColorSpaceRef; cdecl; external libCoreVideo name _PU + 'CVImageBufferGetColorSpace';
function CVImageBufferGetDisplaySize(imageBuffer: CVImageBufferRef): CGSize; cdecl; external libCoreVideo name _PU + 'CVImageBufferGetDisplaySize';
function CVImageBufferGetEncodedSize(imageBuffer: CVImageBufferRef): CGSize; cdecl; external libCoreVideo name _PU + 'CVImageBufferGetEncodedSize';
function CVOpenGLBufferAttach(openGLBuffer: CVOpenGLBufferRef; cglContext: CGLContextObj; face: GLenum; level: GLint; screen: GLint): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferAttach';
function CVOpenGLBufferCreate(allocator: CFAllocatorRef; width: size_t; height: size_t; attributes: CFDictionaryRef; bufferOut: PCVOpenGLBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferCreate';
function CVOpenGLBufferGetAttributes(openGLBuffer: CVOpenGLBufferRef): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferGetAttributes';
function CVOpenGLBufferGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferGetTypeID';
function CVOpenGLBufferPoolCreate(allocator: CFAllocatorRef; poolAttributes: CFDictionaryRef; openGLBufferAttributes: CFDictionaryRef; poolOut: PCVOpenGLBufferPoolRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolCreate';
function CVOpenGLBufferPoolCreateOpenGLBuffer(allocator: CFAllocatorRef; openGLBufferPool: CVOpenGLBufferPoolRef; openGLBufferOut: PCVOpenGLBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolCreateOpenGLBuffer';
function CVOpenGLBufferPoolGetAttributes(pool: CVOpenGLBufferPoolRef): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolGetAttributes';
function CVOpenGLBufferPoolGetOpenGLBufferAttributes(pool: CVOpenGLBufferPoolRef): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolGetOpenGLBufferAttributes';
function CVOpenGLBufferPoolGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolGetTypeID';
procedure CVOpenGLBufferPoolRelease(openGLBufferPool: CVOpenGLBufferPoolRef); cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolRelease';
function CVOpenGLBufferPoolRetain(openGLBufferPool: CVOpenGLBufferPoolRef): CVOpenGLBufferPoolRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferPoolRetain';
procedure CVOpenGLBufferRelease(buffer: CVOpenGLBufferRef); cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferRelease';
function CVOpenGLBufferRetain(buffer: CVOpenGLBufferRef): CVOpenGLBufferRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLBufferRetain';
function CVOpenGLTextureCacheCreate(allocator: CFAllocatorRef; cacheAttributes: CFDictionaryRef; cglContext: CGLContextObj; cglPixelFormat: CGLPixelFormatObj; textureAttributes: CFDictionaryRef; cacheOut: PCVOpenGLTextureCacheRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheCreate';
function CVOpenGLTextureCacheCreateTextureFromImage(allocator: CFAllocatorRef; textureCache: CVOpenGLTextureCacheRef; sourceImage: CVImageBufferRef; attributes: CFDictionaryRef; textureOut: PCVOpenGLTextureRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheCreateTextureFromImage';
procedure CVOpenGLTextureCacheFlush(textureCache: CVOpenGLTextureCacheRef; options: CVOptionFlags); cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheFlush';
function CVOpenGLTextureCacheGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheGetTypeID';
procedure CVOpenGLTextureCacheRelease(textureCache: CVOpenGLTextureCacheRef); cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheRelease';
function CVOpenGLTextureCacheRetain(textureCache: CVOpenGLTextureCacheRef): CVOpenGLTextureCacheRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureCacheRetain';
procedure CVOpenGLTextureGetCleanTexCoords(image: CVOpenGLTextureRef; lowerLeft: PGLfloat; lowerRight: PGLfloat; upperRight: PGLfloat; upperLeft: PGLfloat); cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureGetCleanTexCoords';
function CVOpenGLTextureGetName(image: CVOpenGLTextureRef): GLuint; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureGetName';
function CVOpenGLTextureGetTarget(image: CVOpenGLTextureRef): GLenum; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureGetTarget';
function CVOpenGLTextureGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureGetTypeID';
function CVOpenGLTextureIsFlipped(image: CVOpenGLTextureRef): Boolean; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureIsFlipped';
procedure CVOpenGLTextureRelease(texture: CVOpenGLTextureRef); cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureRelease';
function CVOpenGLTextureRetain(texture: CVOpenGLTextureRef): CVOpenGLTextureRef; cdecl; external libCoreVideo name _PU + 'CVOpenGLTextureRetain';
function CVPixelBufferCreate(allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; pixelBufferAttributes: CFDictionaryRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferCreate';
function CVPixelBufferCreateResolvedAttributesDictionary(allocator: CFAllocatorRef; attributes: CFArrayRef; resolvedDictionaryOut: PCFDictionaryRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferCreateResolvedAttributesDictionary';
function CVPixelBufferCreateWithBytes(allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; baseAddress: Pointer; bytesPerRow: size_t; releaseCallback: CVPixelBufferReleaseBytesCallback; releaseRefCon: Pointer; pixelBufferAttributes: CFDictionaryRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferCreateWithBytes';
function CVPixelBufferCreateWithIOSurface(allocator: CFAllocatorRef; surface: IOSurfaceRef; pixelBufferAttributes: CFDictionaryRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferCreateWithIOSurface';
function CVPixelBufferCreateWithPlanarBytes(allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; dataPtr: Pointer; dataSize: size_t; numberOfPlanes: size_t; planeBaseAddress: Pointer; planeWidth: Psize_t; planeHeight: Psize_t; planeBytesPerRow: Psize_t; releaseCallback: CVPixelBufferReleasePlanarBytesCallback; releaseRefCon: Pointer; pixelBufferAttributes: CFDictionaryRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferCreateWithPlanarBytes';
function CVPixelBufferFillExtendedPixels(pixelBuffer: CVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferFillExtendedPixels';
function CVPixelBufferGetBaseAddress(pixelBuffer: CVPixelBufferRef): Pointer; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetBaseAddress';
function CVPixelBufferGetBaseAddressOfPlane(pixelBuffer: CVPixelBufferRef; planeIndex: size_t): Pointer; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetBaseAddressOfPlane';
function CVPixelBufferGetBytesPerRow(pixelBuffer: CVPixelBufferRef): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetBytesPerRow';
function CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer: CVPixelBufferRef; planeIndex: size_t): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetBytesPerRowOfPlane';
function CVPixelBufferGetDataSize(pixelBuffer: CVPixelBufferRef): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetDataSize';
procedure CVPixelBufferGetExtendedPixels(pixelBuffer: CVPixelBufferRef; extraColumnsOnLeft: Psize_t; extraColumnsOnRight: Psize_t; extraRowsOnTop: Psize_t; extraRowsOnBottom: Psize_t); cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetExtendedPixels';
function CVPixelBufferGetHeight(pixelBuffer: CVPixelBufferRef): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetHeight';
function CVPixelBufferGetHeightOfPlane(pixelBuffer: CVPixelBufferRef; planeIndex: size_t): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetHeightOfPlane';
function CVPixelBufferGetIOSurface(pixelBuffer: CVPixelBufferRef): IOSurfaceRef; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetIOSurface';
function CVPixelBufferGetPixelFormatType(pixelBuffer: CVPixelBufferRef): OSType; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetPixelFormatType';
function CVPixelBufferGetPlaneCount(pixelBuffer: CVPixelBufferRef): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetPlaneCount';
function CVPixelBufferGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetTypeID';
function CVPixelBufferGetWidth(pixelBuffer: CVPixelBufferRef): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetWidth';
function CVPixelBufferGetWidthOfPlane(pixelBuffer: CVPixelBufferRef; planeIndex: size_t): size_t; cdecl; external libCoreVideo name _PU + 'CVPixelBufferGetWidthOfPlane';
function CVPixelBufferIsPlanar(pixelBuffer: CVPixelBufferRef): Boolean; cdecl; external libCoreVideo name _PU + 'CVPixelBufferIsPlanar';
function CVPixelBufferLockBaseAddress(pixelBuffer: CVPixelBufferRef; lockFlags: CVOptionFlags): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferLockBaseAddress';
function CVPixelBufferPoolCreate(allocator: CFAllocatorRef; poolAttributes: CFDictionaryRef; pixelBufferAttributes: CFDictionaryRef; poolOut: PCVPixelBufferPoolRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolCreate';
function CVPixelBufferPoolCreatePixelBuffer(allocator: CFAllocatorRef; pixelBufferPool: CVPixelBufferPoolRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolCreatePixelBuffer';
function CVPixelBufferPoolCreatePixelBufferWithAuxAttributes(allocator: CFAllocatorRef; pixelBufferPool: CVPixelBufferPoolRef; auxAttributes: CFDictionaryRef; pixelBufferOut: PCVPixelBufferRef): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolCreatePixelBufferWithAuxAttributes';
function CVPixelBufferPoolGetAttributes(pool: CVPixelBufferPoolRef): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolGetAttributes';
function CVPixelBufferPoolGetPixelBufferAttributes(pool: CVPixelBufferPoolRef): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolGetPixelBufferAttributes';
function CVPixelBufferPoolGetTypeID: CFTypeID; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolGetTypeID';
procedure CVPixelBufferPoolRelease(pixelBufferPool: CVPixelBufferPoolRef); cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolRelease';
function CVPixelBufferPoolRetain(pixelBufferPool: CVPixelBufferPoolRef): CVPixelBufferPoolRef; cdecl; external libCoreVideo name _PU + 'CVPixelBufferPoolRetain';
procedure CVPixelBufferRelease(texture: CVPixelBufferRef); cdecl; external libCoreVideo name _PU + 'CVPixelBufferRelease';
function CVPixelBufferRetain(texture: CVPixelBufferRef): CVPixelBufferRef; cdecl; external libCoreVideo name _PU + 'CVPixelBufferRetain';
function CVPixelBufferUnlockBaseAddress(pixelBuffer: CVPixelBufferRef; unlockFlags: CVOptionFlags): CVReturn; cdecl; external libCoreVideo name _PU + 'CVPixelBufferUnlockBaseAddress';
function CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes(allocator: CFAllocatorRef): CFArrayRef; cdecl; external libCoreVideo name _PU + 'CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes';
function CVPixelFormatDescriptionCreateWithPixelFormatType(allocator: CFAllocatorRef; pixelFormat: OSType): CFDictionaryRef; cdecl; external libCoreVideo name _PU + 'CVPixelFormatDescriptionCreateWithPixelFormatType';
procedure CVPixelFormatDescriptionRegisterDescriptionWithPixelFormatType(description: CFDictionaryRef; pixelFormat: OSType); cdecl; external libCoreVideo name _PU + 'CVPixelFormatDescriptionRegisterDescriptionWithPixelFormatType';
function kCVPixelBufferPixelFormatTypeKey: CFStringRef;
function kCVPixelBufferMemoryAllocatorKey: CFStringRef;
function kCVPixelBufferWidthKey: CFStringRef;
function kCVPixelBufferHeightKey: CFStringRef;
function kCVPixelBufferExtendedPixelsLeftKey: CFStringRef;
function kCVPixelBufferExtendedPixelsTopKey: CFStringRef;
function kCVPixelBufferExtendedPixelsRightKey: CFStringRef;
function kCVPixelBufferExtendedPixelsBottomKey: CFStringRef;
function kCVPixelBufferBytesPerRowAlignmentKey: CFStringRef;
function kCVPixelBufferCGBitmapContextCompatibilityKey: CFStringRef;
function kCVPixelBufferCGImageCompatibilityKey: CFStringRef;
function kCVPixelBufferOpenGLCompatibilityKey: CFStringRef;
function kCVPixelBufferPlaneAlignmentKey: CFStringRef;
function kCVPixelBufferIOSurfacePropertiesKey: CFStringRef;
function kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey: CFStringRef;
function kCVPixelBufferIOSurfaceOpenGLFBOCompatibilityKey: CFStringRef;
function kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey: CFStringRef;
implementation
function kCVPixelBufferPixelFormatTypeKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferPixelFormatTypeKey')^);
end;
function kCVPixelBufferMemoryAllocatorKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferMemoryAllocatorKey')^);
end;
function kCVPixelBufferWidthKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferWidthKey')^);
end;
function kCVPixelBufferHeightKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferHeightKey')^);
end;
function kCVPixelBufferExtendedPixelsLeftKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferExtendedPixelsLeftKey')^);
end;
function kCVPixelBufferExtendedPixelsTopKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferExtendedPixelsTopKey')^);
end;
function kCVPixelBufferExtendedPixelsRightKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferExtendedPixelsRightKey')^);
end;
function kCVPixelBufferExtendedPixelsBottomKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferExtendedPixelsBottomKey')^);
end;
function kCVPixelBufferBytesPerRowAlignmentKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferBytesPerRowAlignmentKey')^);
end;
function kCVPixelBufferCGBitmapContextCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferCGBitmapContextCompatibilityKey')^);
end;
function kCVPixelBufferCGImageCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferCGImageCompatibilityKey')^);
end;
function kCVPixelBufferOpenGLCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferOpenGLCompatibilityKey')^);
end;
function kCVPixelBufferPlaneAlignmentKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferPlaneAlignmentKey')^);
end;
function kCVPixelBufferIOSurfacePropertiesKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferIOSurfacePropertiesKey')^);
end;
function kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey')^);
end;
function kCVPixelBufferIOSurfaceOpenGLFBOCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferIOSurfaceOpenGLFBOCompatibilityKey')^);
end;
function kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey: CFStringRef;
begin
Result := CFStringRef(CocoaPointerConst(libCoreVideo, 'kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey')^);
end;
end.
|
Unit MainMenu;
Interface
Uses
Levels;
Type
{*************** LEVEL COLLECTIONS **************}
PNodo = ^Nodo;
Nodo = Record
Next : PNodo;
FName: String;
Item : Elems;
End;
PCollection = ^TCollection;
TCollection = Object
Private
Size : Integer;
First : PNodo;
Select : PNodo;
Public
Constructor Init;
Procedure InsertItem(LevelName : String; ImputItem : Elems);
Procedure GetItem(Index : Integer;
Var LevelName : String;
Var OutPutItem : Elems);
Function GetSize : Integer;
Destructor Done;
Virtual;
End;
{************** LEVEL OBJECTS ****************}
PMainMenu = ^TMainMenu;
TMainMenu = Object
Private
NameFile : String;
ListLevels: PCollection;
Public
Constructor Init(FileName : String);
Procedure Run(FileName, LevelName : String; Elem : Elems);
Procedure ReadFile;
Procedure Compile;
Destructor Done;
End;
Var
LineText : String[80];
LevelText : Text;
Implementation
Procedure TMainMenu.ReadFile;
Var
Name : String;
Item : Elems;
i : Integer;
Begin
Assign(LevelText, nameFile);
{$I-}
Reset(LevelText);
{$I+}
If IOresult = 0 Then
Begin
While Not Eof(LevelText) Do
Begin
Readln(LevelText, LineText);
{if first char is [, then is a name}
If LineText[1] = '[' Then
Begin
Name := '';
i := 2;
While ((i <= Length(LineText)) And (i <= 22)) Do
Begin
If LineText[i] <> ']' Then
Name := Name+LineText[i]
Else i := 23
End;
Readln;
For i := 1 To 20 Do
Begin
Readln(LevelText, LineText);
Item[i] := Copy(LineText, 1, 30);
End;
ListLevels^.InsertItem(Name, Item);
End;
End;
Close(LevelText);
End;
End;
Procedure TMainMenu.Compile;
Var
Posiction : Integer;
i : Integer;
Begin
Assign(LevelText, nameFile);
{$I-}
Reset(LevelText);
{$I+}
If IOresult = 0 Then
Begin
While Not Eof(LevelText) Do
Begin
Readln(LevelText, LineText);
If LineText[1] = '[' Then
Begin
End;
End;
Close(LevelText);
End;
End;
CONSTRUCTOR TMainMenu.Init(FileName : String);
Begin
NameFile := FileName;
New(ListLevels, Init);
Compile;
ReadFile;
End;
Procedure TMainMenu.Run(FileName, LevelName : String; Elem : Elems);
Begin
End;
DESTRUCTOR TMainMenu.Done;
Begin
Dispose(ListLevels, Done);
End;
{******* TCOLLECTION IMPLEMENTATION **************}
CONSTRUCTOR TCollection.Init;
Begin
First := Nil;
Select := Nil;
Size := 0;
End;
{***** INSERT AN ELEMENT ON THE LIST ***********}
Procedure TCollection.InsertItem(LevelName : String; ImputItem : Elems);
Var
Pont : PNodo;
Prev : PNodo;
Vazio: Boolean;
Begin
Inc(Size);
Vazio := True;
Pont := First;
While Pont <> Nil Do
Begin
Prev := Pont;
Pont := Pont^.Next;
Vazio := False;
End;
New(Pont);
Pont^.FName := LevelName;
Pont^.Item := ImputItem;
Pont^.Next := Nil;
If Not Vazio Then
Prev^.Next := Pont
Else
Begin
First := Pont;
Select := First;
End;
End;
Procedure TCollection.GetItem(Index : Integer;
Var LevelName : String;
Var OutPutItem : Elems);
Var
Pont : PNodo;
N : String;
Elem : Elems;
i : Integer;
Begin
N := '';
Pont := First;
i := 1;
While (i <= Index) And (Pont <> Nil) Do
Begin
If i = Index Then
Begin
N := Pont^.FName;
Elem := Pont^.Item;
End;
Pont := Pont^.Next;
Inc(i);
End;
LevelName := N;
OutPutItem := Elem;
End;
Function TCollection.GetSize;
Begin
GetSize := Size;
End;
DESTRUCTOR TCollection.Done;
Var
Pont : PNodo;
Begin
While First <> Nil Do
Begin
Pont := First;
First := First^.Next;
Dispose(Pont);
End;
End;
End.
End.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------}
unit untEasyImageSelect;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, untEasyButtons, ExtCtrls, untEasyPlateBaseForm,
untEasyDBConnection;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmImagesSelect = class(TfrmEasyPlateBaseForm)
imgVW16: TImageList;
Panel1: TPanel;
pnlBottom: TPanel;
lvMain: TListView;
btnCancel: TEasyBitButton;
btnOk: TEasyBitButton;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FControlFlag: Integer;
end;
function EasySelectImage: Integer;
var
frmImagesSelect: TfrmImagesSelect;
implementation
{$R *.dfm}
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmImagesSelect := TfrmImagesSelect.Create(Application);
Application.Handle := frmImagesSelect.EasyApplicationHandle;
if frmImagesSelect.FormStyle <> fsMDIChild then
frmImagesSelect.FormStyle := fsMDIChild;
if frmImagesSelect.WindowState <> wsMaximized then
frmImagesSelect.WindowState := wsMaximized;
frmImagesSelect.FormId := '{1923B93B-574C-4BA3-BD52-60DCD672EE72}';
Result := frmImagesSelect;
end;
function EasySelectImage: Integer;
begin
Result := -1;
frmImagesSelect := TfrmImagesSelect.Create(Application);
frmImagesSelect.BorderStyle := bsDialog;
frmImagesSelect.ShowModal;
with frmImagesSelect do
begin
if lvMain.Selected <> nil then
Result := lvMain.Selected.Index;
end;
frmImagesSelect.Free;
end;
procedure TfrmImagesSelect.FormCreate(Sender: TObject);
var
I : Integer;
ATmpListItem: TListItem;
begin
lvMain.Items.Clear;
imgVW16.Assign(DMEasyDBConnection.img16);
for I := 0 to imgVW16.Count - 1 do
begin
ATmpListItem := lvMain.Items.Add;
ATmpListItem.Caption := IntToStr(I);
ATmpListItem.ImageIndex := I;
end;
end;
procedure TfrmImagesSelect.FormResize(Sender: TObject);
begin
inherited;
btnOk.Left := pnlBottom.Width - 106;
btnCancel.Left := pnlBottom.Width - 184;
end;
procedure TfrmImagesSelect.btnOkClick(Sender: TObject);
var
SelectIndex: Integer;
begin
inherited;
if lvMain.Selected <> nil then
begin
SelectIndex := lvMain.Selected.Index;
if SelectIndex <> -1 then
Close
else
Beep;
end;
end;
procedure TfrmImagesSelect.btnCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
// Nama: Morgen Sudyanto
// NIM: 16518380
(* Tuliskan identitas di sini *)
Program TigaInteger;
(* Input: 3 integer: A, B, C *)
(* Output: Sifat integer dari A, B, C (positif/negatif/nol dan ganjil/genap)
Nilai maksimum, minimum, dan nilai tengah *)
(* KAMUS *)
var
A, B, C : integer;
nilaitengah : integer;
(* PROCEDURE DAN FUNCTION *)
procedure CekInteger (x : integer);
(* I.S.: x terdefinisi *)
(* F.S.: Jika x positif dan genap, maka tertulis di layar: POSITIF-GENAP
Jika x positif dan ganjil, maka tertulis di layar: POSITIF-GANJIL
Jika x negatif, maka tertulis di layar: NEGATIF
Jika x nol, maka tertulis di layar: NOL *)
(* Tuliskan realisasi prosedur CekInteger di bawah ini *)
begin
if ((x>0) and (x mod 2 = 0)) then begin
writeln('POSITIF-GENAP');
end else if ((x>0) and (x mod 2 = 1)) then begin
writeln('POSITIF-GANJIL');
end else if (x<0) then begin
writeln('NEGATIF');
end else begin
writeln('NOL');
end;
end;
function Max (a, b, c : integer) : integer;
(* menghasilkan nilai terbesar di antara a, b, c *)
(* Tuliskan realisasi fungsi Max di bawah ini *)
begin
if ((a>=b) and (a>=c)) then begin
Max:=a;
end else if ((b>=a) and (b>=c)) then begin
Max:=b;
end else begin
Max:=c;
end;
end;
function Min (a, b, c : integer): integer;
(* menghasilkan nilai terkecil di antara a, b, c *)
(* Tuliskan realisasi fungsi Min di bawah ini *)
begin
if ((a<=b) and (a<=c)) then begin
Min:=a;
end else if ((b<=a) and (b<=c)) then begin
Min:=b;
end else begin
Min:=c;
end;
end;
(* PROGRAM UTAMA *)
begin
(* Input *)
readln(A);
readln(B);
readln(C);
(* Menuliskan sifat integer *)
CekInteger(A);
CekInteger(B);
CekInteger(C);
(* Penulisan maksimum, minimum, dan nilai tengah *)
writeln(Max(A,B,C));
writeln(Min(A,B,C));
nilaitengah := A + B + C - Max(A,B,C) - Min(A,B,C);
writeln(nilaitengah);
end.
|
unit SearchFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, ComCtrls, DBGrids, Utilits;
type
TSearchForm = class(TForm)
ScrollBox: TScrollBox;
StatusBar: TStatusBar;
BtnPanel: TPanel;
OkBtn: TBitBtn;
CancelBtn: TBitBtn;
ProgressBar: TProgressBar;
ModeComboBox: TComboBox;
CaseSensCheckBox: TCheckBox;
BeginRadioButton: TRadioButton;
EndRadioButton: TRadioButton;
procedure OkBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtnPanelResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FSourceDBGrid: TDBGrid;
FControlIsInited: Boolean;
protected
procedure SetSourceDBGrid(ASourceDBGrid: TDBGrid);
procedure InitControls;
public
property ControlIsInited: Boolean read FControlIsInited default False;
property SourceDBGrid: TDBGrid read FSourceDBGrid write SetSourceDBGrid;
procedure ClickCheckBox(Sender: TObject);
procedure ChangeEdit(Sender: TObject);
end;
implementation
{$R *.DFM}
procedure TSearchForm.InitControls;
var
I,Y,W: Integer;
CB: TCheckBox;
E: TEdit;
T: array[0..255] of Char;
S: TSize;
begin
if not FControlIsInited
and (FSourceDBGrid <> nil)
and (FSourceDBGrid.DataSource<>nil)
and (FSourceDBGrid.DataSource.DataSet<>nil)
and FSourceDBGrid.DataSource.DataSet.Active then
begin
I:=ControlCount;
while I>0 do
begin
Dec(I);
if (Controls[I] is TEdit) or (Controls[I] is TCheckBox)
then Controls[I].Free;
end;
with FSourceDBGrid.Columns do
begin
Y:=8;
for I:=1 to Count do
begin
CB:=TCheckBox.Create(ScrollBox);
with CB do
begin
Caption:=Items[I-1].Title.Caption;
StrPCopy(T,Caption);
GetTextExtentPoint32(Canvas.Handle,T,StrLen(T),S);
SetBounds(17,Y,S.CX+24,Abs(CB.Font.Height)+2);
OnClick:=ClickCheckBox;
Parent:=ScrollBox;
Tag:=Items[I-1].Field.Index;
Show;
Y:=Y+Height+2;
end;
E:=TEdit.Create(CB);
with E do
begin
W:=Items[I-1].Width+40;
if W<100 then W:=100;
SetBounds(17,Y,W,Abs(E.Font.Height)+2);
OnChange:=ChangeEdit;
Parent:=ScrollBox;
Show;
Y:=Y+Height+5;
end;
end;
end;
FControlIsInited := True;
end;
end;
procedure TSearchForm.SetSourceDBGrid(ASourceDBGrid: TDBGrid);
begin
FSourceDBGrid := ASourceDBGrid;
InitControls;
end;
procedure TSearchForm.ClickCheckBox(Sender: TObject);
var
I: Integer;
begin
with ScrollBox do begin
I:=ComponentCount-1;
while (I>=0) and not((Components[I] is TCheckBox)
and (Components[I] as TCheckBox).Checked) do Dec(I);
end;
OkBtn.Enabled:= I>=0;
end;
procedure TSearchForm.ChangeEdit(Sender: TObject);
begin
if Sender is TEdit then with Sender as TEdit do
if Owner is TCheckBox then (Owner as TCheckBox).Checked:=Length(Text)>0;
end;
procedure TSearchForm.OkBtnClick(Sender: TObject);
var
CB: TCheckBox;
I,J,K: Integer;
S, S2: string;
begin
CancelBtn.Enabled:= not CancelBtn.Enabled;
if not CancelBtn.Enabled then
with SourceDBGrid.DataSource.DataSet do
begin
OkBtn.Caption := '&Стоп';
K := 0;
ProgressBar.Max := RecordCount;
StatusBar.Panels[0].Width := ProgressBar.Width;
ProgressBar.Show;
if BeginRadioButton.Checked and Eof then //Изменено Меркуловым
First;
if EndRadioButton.Checked and BoF then
Last;
//while not EoF and (K=0) and not CancelBtn.Enabled
// and not BoF do //Изменено Меркуловым
repeat
//begin
if BeginRadioButton.Checked then //Добавлено Меркуловым
Next
else if EndRadioButton.Checked then //Добавлено Меркуловым
Prior; //Добавлено Меркуловым
with ScrollBox do
begin
I := ComponentCount-1; K:=1;
while (I>=0) and (K<>0) do
begin
CB := Components[I] as TCheckBox;
if CB.Checked then
begin
J := CB.Tag;
S := (CB.Components[0] as TEdit).Text;
S2 := Fields.Fields[J].AsString;
if not CaseSensCheckBox.Checked then
begin
S := RusUpperCase(S);
S2 := RusUpperCase(S2);
end;
case ModeComboBox.ItemIndex of
0:
K := Pos(S, S2);
1:
begin
K := Length(S);
if K<=Length(S2) then
begin
if StrLComp(PChar(S), PChar(S2), K)<>0 then K:=0;
end
else K := 0;
end;
else
begin
K := Length(S);
if K=Length(S2) then
begin
if StrLComp(PChar(S), PChar(S2), K)=0 then
K:=1
else
K:=0;
end
else K := 0;
end;
end;
end;
Dec(I);
end;
end;
ProgressBar.Position:=RecNo;
Application.ProcessMessages;
//end;
until EoF or (K<>0) or CancelBtn.Enabled or BoF;
ProgressBar.Hide;
StatusBar.Panels[0].Width := 0;
CancelBtn.Enabled:= True;
OkBtn.Caption:='&Найти';
{if K<>0 then
begin
LastRadioButton.Checked := True; //Изменено
//BeginCheckBox.Checked := False;
Self.Close;
end
else
BeginRadioCheckBox.Checked := EoF;} //Изменено
end;
end;
procedure TSearchForm.FormShow(Sender: TObject);
begin
InitControls;
ClickCheckBox(Sender);
end;
const
BtrDist=5;
procedure TSearchForm.BtnPanelResize(Sender: TObject);
begin
CancelBtn.Left := BtnPanel.ClientWidth-CancelBtn.Width-2*BtrDist;
OkBtn.Left:= CancelBtn.Left-OkBtn.Width-BtrDist;
end;
procedure TSearchForm.FormCreate(Sender: TObject);
const
Border=2;
begin
with ProgressBar do
begin
Parent := StatusBar;
SetBounds(0, Border, Width, StatusBar.Height - Border);
end;
ModeComboBox.ItemIndex := 2;
BtnPanelResize(Sender);
end;
end.
|
program Scanner;
uses crt;
TYPE
TokenType = ( tNone, tIdentifier, tInteger, tReal,
tCharConstant, tString, tPlus, tMin,
tMult, tDiv, tAssignment, tTitikDua,
tRange, tKoma, tTitik, tTitikKoma, tEqual,
tInequal, tLess, tLessEqu, tGreater, tGreaterEqu,
tKurungSikuBuka, tKurungSikuTutup, tKurungBuka, tKurungTutup,
tKeyAND, tKeyARRAY, tKeyBEGIN, tKeyCONST, tKeyCASE, tKeyDIV,
tKeyDO, tKeyDOWNTO, tKeyELSE, tKeyEND, tKeyFILE, tKeyFOR, tKeyFUNCTION,
tKeyGOTO, tKeyIF, tKeyIN, tKeyLABEL, tKeyMOD, tKeyNIL, tKeyNOT, tKeyOF,
tKeyOR, tKeyPACKED, tKeyPROCEDURE, tKeyPROGRAM, tKeyRECORD, tKeyREPEAT,
tKeySET, tKeyTHEN, tKeyTO, tKeyTYPE, tKeyUNTIL, tKeyVAR, tKeyWHILE, tKeyWITH
);
ScanErrorType = ( errNone, errScanUnexpChar, errScanFloat, errScanInt, errScanApostExp, errScanUnexpEOF );
CONST
EndFile = #26;
JmlKeyword = 46;
Keyword : ARRAY [1..JmlKeyword] OF STRING [9] = ('AND', 'ARRAY', 'BEGIN', 'BOOLEAN', 'CASE',
'CONST', 'CHAR', 'DIV', 'DO', 'DOWNTO', 'END',
'ELSE', 'FILE', 'FOR', 'FUNCTION', 'GOTO', 'IF',
'IN', 'INTEGER', 'LABEL', 'MOD', 'NIL', 'NOT',
'PROGRAM', 'REAL', 'RECORD', 'REPEAT', 'STRING', 'THEN',
'TO', 'TYPE', 'VAR', 'WHILE', 'WITH');
eMax = 38;
eMin = -38;
JmlSigDgt = 5;
ValMax = 16383;
MaxInfo = 128;
VAR
ScanStr : STRING;
Token : TokenType;
inum : LONGINT;
rnum : RELAL;
CC : CHAR;
FileSource, FileRes : STRING;
InFile, ResFIle : TEXT;
ErrCounter Integer;
LineCounter : Integer;
lokasi : ARRAY [1..MaxInfo] of STRING;
jinfo : integer;
FUNCTION OpenFile : BOOLEAN;
VAR i : INTEGER;
Open1, Open2 : BOOLEAN;
BEGIN
WRITELN;
WRITE('FILE WILL BE PARSED (.PAS) : ');
READLN(FileSource);
i:=POS('.',FileSource);
IF i<>0 THEN FileSource:=COPY(FileSource,1,i-1);
WRITE('Output File (.TXT) : ');
READLN(FileRes);WRITELN;
i:=POS(',',FileRes);
IF i<>0 THEN FileRes:=COPY(FileRes,1,i-1);
OpenFile := TRUE;
{$I-}
ASSIGN(InFile, FileSource+' .PAS');
RESET(InFile);
{$I+}
IF IOResult <> 0 THEN
BEGIN
WRITELN('FILE', FileSource, '.PAS doesn''t exist...');
OpenFile:=FALSE;
END
ELSE
BEGIN
{$I-}
ASSIGN(ResFile, FileRes+' .TXT');
REWRITE(ResFile);
{$I+}
IF IOResult <> 0 THEN
BEGIN
WRITELN(FileRes,'.TXT can''t be made...');
OpenFile:=FALSE;
END;
END;
END;
FUNCTION UpperCase(Str:STRING) : STRING;
VAR
i:INTEGER;
BEGIN
FOR i:=1 TO LENGTH(Str) DO
Str[i]:=UpCase(Str[i]);
UpperCase:=Str;
END;
PROCEDURE IncLine(var LineCounter : Integer);
BEGIN
GOTOXY(1, WHEREY);
LineCounter := LineCounter+1;
WRITE('processing line : ',LineCounter);
END;
PROCEDURE ReadChar;
BEGIN
READ(InFile,CC);
END;
PROCEDURE ProsErr(err:ScanErrorType);
BEGIN
GOTOXY(25, WHEREY);
WRITE('eror : ');
CASE err OF
errScanUnexpChar : BEGIN WRITE('Unexpected Character',CC);ReadChar;
END;
errScanApostExp : WRITE(#39'expected ');
errScanUnexpEOF : BEGIN WRITE('Unexcepted End Of File');Readln;Halt;
END;
errScanFloat : WRITE('Floating point format error');
WRITE('Integer value error');
END;
READLN;
END;
PROCEDURE WriteFile;
var
i : integer;
adainfo : boolean;
BEGIN
WRITE (ResFile, ' ');
WRITE (ResFile,Ord(Token):2);
WRITE (ResFile, ' ');
CASE TOKEN of tIdentifier :
begin
adainfo := false;
i:=0;
repeat
i:=i+1;
if lokasi[i] = ScanStr then adainfo := true;
until (adainfo) or (i>jinfo);
if (not adainfo) and (jinfo)<maxinfo) then
begin
jinfo:=jinfo+1
lokasi[jinfo]:=ScanStr;
WRITE(ResFile, jinfo:4);
end
else
WRITE(ResFile, i:4);
WRITE(ResFile, ' '+ScanStr);
end;
tInteger :
begin
if(jinfo<maxinfo) then
begin
jinfo:=jinfo+1;
lokasi[jinfo]:=ScanStr;
WRITE(ResFile, jinfo:4);
end;
WRITE(ResFile, ' ');
WRITE(ResFile, rnum);
end;
tReal :
begin
if (jinfo)<maxinfo) then
begin
jinfo:=jinfo+1
lokasi[jinfo]:=ScanStr;
WRITE(ResFile, jinfo:4);
end;
WRITE(ResFile, ' ');
WRITE(ResFile, rnum);
end;
tCharConstant, tString :
begin
if (jinfo)<maxinfo) then
begin
jinfo:=jinfo+1
lokasi[jinfo]:=ScanStr;
WRITE(ResFile, jinfo:4);
WRITE(ResFile, ' ');
WRITE(ResFile, ScanStr)
end;
end;
else
begin
WRITE(ResFile, jinfo:4);
WRITE(ResFile, ' ');
WRITE(ResFile, ScanStr)
end;
end;
WRITELN(ResFile,'');
END;
{Prosedur Scan }
PROCEDURE SCAN;
CONST
SPACE = #32;
TAB = #9;
CR = #13;
LF = #10;
VAR AdaToken : BOOLEAN;
i,j,k,e : INTEGER;
KeyToken : TokenType ABSOLUTE k;
TampStr : STRING;
Error : ScanErrorType;
Ex, Comment : BOOLEAN;
PROCEDURE GetExp;
VAR pangkat, sign : INTEGER;
BEGIN
sign:=1; pangkat:=0;
ReadChar;
IF CC IN ['+','-'] THEN
BEGIN
IF CC='-' THEN sign:=-1;
ReadChar;
END;
IF NOT (CC IN['0'..'9']) THEN Error:=errScanFloat
ELSE (there is a numeric char after E|e)
BEGIN
REPEAT
pangkat:=10*pangkat+ORD(CC)-ORD('0');
ReadChar;
UNTIL NOT (CC IN['0'..'9']);
e:=e+pangkat*sign;
END;
END;
PROCEDURE KonverToReal;
VAR s:integer; d,t : REAL;
BEGIN
IF k+e>eMax THEN Error:=errScanFloat
ELSE
If k+e>eMin THEN rnum:=0
ELSE
BEGIN
s:=abs(e); t:=1.0, d:=10.0;
REPEAT
WHILE NOT ODD(s) DO
BEGIN s:=s DIV 2; d:=sqr(d); END;
s:=s-1; t:=d*t;
UNTIL s=0;
IF e>=0 THEN rnum:=rnum*t ELSE rnum:=rnum/t;
END;
END;
BEGIN
AdaToken := FALSE;
WHILE (NOT AdaToken) DO
BEGIN
Error:=errNone; Comment:=FALSE; Token:=None;
WHILE CC IN [CR,LF,TAB, SPACE] DO
BEGIN
IF CC=LF THEN IncLine(LineCounter);
ReadChar;
END;
IF CC=EndFile THEN EXIT;
CASE CC OF
'a'..'z','A'..'Z';
BEGIN
ScanStr:='';
REPEAT
ScanStr:=ScanStr+CC;
ReadChar;
UNTIL NOT (CC IN['a'..'z','A'..'Z','0'..'9','-']);
TampStr:=UpperCase(ScanStr);
i:=1; j:=JmlKeyWord;
REPEAT
k:=(i+j) DIV 2;
IF TampStr<=KeyWord[k] THEN j:=k-1;
IF TampStr<=KeyWord[k] THEN j:=k-1;
UNTIL i>j;
IF i-j>1 THEN
BEGIN k:=k+ORD(tKurungTutup); Token:=KeyToken; END
ELSE
BEGIN Token:=tIdentifier;
ScanStr:=COPY(ScanStr,1,10); END;
END;
BEGIN
k:=0, inum:=0; Token:=tInteger;
REPEAT
inum:=inum*10 + ORD(CC) - ORD ('0');
k:=k+1;
ReadChar;
UNTIL NOT (CC IN ['0'..'9']);
IF (k>JmlSigDgt) OR (inum>ValMax) THEN
BEGIN
ReadChar;
IF CC='.' THEN
BEGIN ScanStr:='..';
ELSE
BEGIN
IF NOT (CC IN ['0'..'9']) THEN
BEGIN
Error:=ErrScanFloat;
IF CC IN ['e','E'] THEN GetExp;
END
ELSE
BEGIN
Token:=tReal; rnum:=inum; e:=0;
REPEAT;
rnum:=rnum*10 + ORD(CC) - ORD ('0');
ReadChar;
UNTIL NOT (CC IN ['0'..'9']);
IF CC IN ['e','E'] THEN GetExp;
IF (Error<>errScanFloat) AND (e<>0) THEN KonverToReal;
END;
END;
END
ELSE
IF CC IN ['e','E'] THEN
BEGIN
Token:=tReal; rnum:=inum; e:=0; GetExp;
IF (Error<>errScanFloat) AND (e<>0) THEN KonverToReal;
END;
END;
BEGIN
ScanStr:=CC;
ReadChar;
IF CC<>'*' THEN Token:=tKurungBuka
ELSE
BEGIN
Comment:=TRUE;
ReadChar;
IF CC<>EndFile THEN
BEGIN
REPEAT
WHILE NOT (CC IN ['*',EndFile]) DO
BEGIN
IF CC=LF THEN IncLine(LineCounter);
ReadChar;
END;
IF CC='*' THEN ReadChar;
IF CC='*' THEN IncLine(LineCounter);
UNTIL CC IN [')',EndFile];
IF CC=')' THEN ReadChar ELSE
Error:=errScanUnexpEOF;
END
ELSE Error:=errScanUnexpEOF;
END;
END;
BEGIN
Comment:=TRUE;
REPEAT
ReadChar;
IF CC='*' THEN IncLine(LineCounter);
UNTIL CC IN [')',EndFile];
IF CC=')' THEN ReadChar ELSE
Error:=errScanUnexpEOF;
END;
BEGIN
ScanStr:=''; Ex:=FALSE;
WHILE NOT Ex DO
BEGIN
REPEAT
ScanStr:=ScanStr+CC;
ReadChar;
UNTIL (CC IN ['''',LF,EndFile]);
IF CC IN [LF,EndFile] THEN
BEGIN
Ex:=TRUE;
IF CC=LF THEN
BEGIN
IncLine(LineCounter);
Error:=errScanApostExp;
END
ELSE Error:=errScanUnexp;
END
ELSE
BEGIN
ScanStr:=ScanStr+CC;
ReadChar;
IF CC<>'''' THEN Ex:=TRUE;
END;
END;
IF NOT (ERROR IN [errScanApostExp, errScanUnexpEOF]) THEN
BEGIN
DELETE(ScanStr, LENGTH(ScanStr),1);
DELETE(ScanStr,1,1);
IF LENGTH(ScanStr)>1 THEN Token:=tString
ELSE
BEGIN inum:=ORD(ScanStr[1]);
Token:=tCharConstant; END;
END;
END;
':' :
BEGIN
ScanStr:=CC;
ReadChar;
IF CC='=' THEN
BEGIN
Token:=tAssignment; ScanStr:=ScanStr+CC;
ReadChar;
END
ELSE
IF ScanStr='..' THEN Token:=tRange
ELSE Token:=tTitikDua;
'<' :
BEGIN
ScanStr:=CC;
ReadChar;
IF CC='=' THEN
BEGIN
Token:=tLessEqu; ScanStr:=ScanStr+CC;
ReadChar;
END
ELSE
IF CC='>' THEN
BEGIN
Token:=tInEqu; ScanStr:=ScanStr+CC;
ReadChar;
END
ELSE Token:=tLess;
END;
'>' :
BEGIN
ScanStr:=CC;
ReadChar;
IF CC='=' THEN
BEGIN
Token:=tGreaterEqu; ScanStr:=ScanStr+CC;
ReadChar;
END
ELSE Token:=tGreater;
END;
'.' :
BEGIN
ReadChar;
IF ScanStr='..' THEN
Token := tRange
ELSE
BEGIN
Token:=tTitik;
ScanStr:='.';
END;
END;
'+','-','*','/',',',';','=',')','[',']':
BEGIN
ScanStr:=CC;
CASE CC OF
'+': Token:=tPlus;
'-': Token:=tMin;
'*': Token:=tMult;
'/': Token:=tDiv;
',': Token:=tKoma;
';': Token:=tTitikKoma;
'=': Token:=tEqual;
')': Token:=tKurungTutup;
'[': Token:=tKurungSikuBuka;
']': Token:=tKurungSikuTutup;
END;
ReadChar;
END;
ELSE Error:=errScanUnexpChar;
END;
IF (((NOT Comment) AND (Error<>errScanUnexpChar)) OR (CC=EndFile)) THEN
AdaToken:=TRUE;
IF Error<>ErrNone THEN ProsErr(Error);
END;
END;
{PROGRAM UTAMA }
BEGIN
if OpenFile then
begin
readchar;
jinfo:=0;
Writeln(ResFile, 'Internal Number Location Token');
Writeln(ResFile, '------------------------------');
while (CC<>EndFile) do
begin
SCAN;
WriteFile;
end;
end;
Close(ResFile);
END.
|
unit uFrame2;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
UI.Standard, UI.Base, UI.Edit, uBaseFrame{Base Frame for project};
type
TLoginEvent = reference to procedure (AView: TFrame; AUserName, APassword: string);
TFrame2 = class(TFrame)
LinearLayout1: TLinearLayout;
btnBack: TTextView;
tvTitle: TTextView;
LinearLayout2: TLinearLayout;
EditView2: TEditView;
EditView3: TEditView;
ButtonView1: TButtonView;
procedure btnBackClick(Sender: TObject);
procedure ButtonView1Click(Sender: TObject);
private
{ Private declarations }
FOnLogin: TLoginEvent;
function GetEnableLogin: Boolean;
procedure SetEnableLogin(const Value: Boolean);
protected
procedure DoCreate(); override;
public
{ Public declarations }
property OnLogin: TLoginEvent read FOnLogin write FOnLogin;
property EnableLogin: Boolean read GetEnableLogin write SetEnableLogin;
end;
implementation
{$R *.fmx}
procedure TFrame2.btnBackClick(Sender: TObject);
begin
Finish;
end;
procedure TFrame2.ButtonView1Click(Sender: TObject);
begin
if Assigned(OnLogin) then
OnLogin(Self, EditView2.Text, EditView3.Text);
end;
procedure TFrame2.DoCreate;
begin
inherited;
FOnLogin := nil;
LinearLayout2.Visible := False;
end;
function TFrame2.GetEnableLogin: Boolean;
begin
Result := LinearLayout2.Visible;
end;
procedure TFrame2.SetEnableLogin(const Value: Boolean);
begin
LinearLayout2.Visible := Value;
end;
end.
|
unit FocusProto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
WiseDaq, WiseFocus, StdCtrls, ExtCtrls, ComCtrls;
type
TProtoFrame = class(TForm)
FocusBox: TGroupBox;
UpButton: TButton;
DownButton: TButton;
EncLabel: TLabel;
EncValue: TLabel;
FullUpButton: TButton;
FullDownButton: TButton;
StopButton: TButton;
mainTimer: TTimer;
SpeedLabel: TLabel;
SpeedVal: TLabel;
StatusBar: TStatusBar;
procedure StartUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure EndUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure StartDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure EndDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure FullUpClick(Sender: TObject);
procedure FullDownClick(Sender: TObject);
procedure StopButtonClick(Sender: TObject);
procedure onMainTimer(Sender: TObject);
private
{ tbd }
public
end;
var
ProtoFrame: TProtoFrame;
wisefocus1: TWiseFocus;
implementation
{$R *.dfm}
procedure TProtoFrame.StartUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
wisefocus1.StartUp;
end;
procedure TProtoFrame.EndUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
wisefocus1.StopUp;
end;
procedure TProtoFrame.StartDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
wisefocus1.StartDown
end;
procedure TProtoFrame.EndDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
wisefocus1.StopDown;
end;
procedure TProtoFrame.FormCreate(Sender: TObject);
begin
wisefocus1 := TWiseFocus.Create;
mainTimer.Enabled := true;
end;
procedure TProtoFrame.FullUpClick(Sender: TObject);
begin
wisefocus1.FullUp;
end;
procedure TProtoFrame.FullDownClick(Sender: TObject);
begin
wisefocus1.FullDown;
end;
procedure TProtoFrame.StopButtonClick(Sender: TObject);
begin
wisefocus1.Stop;
end;
procedure TProtoFrame.onMainTimer(Sender: TObject);
begin
FocusBox.Caption := Format(' Focus (%s)', [wisefocus1.StateStr]);
EncValue.Caption := Format('%d', [wisefocus1.Value]);
SpeedVal.Caption := Format('%d', [wisefocus1.Speed]);
StatusBar.SimpleText := wisefocus1.Status;
end;
initialization
if not WiseDaqsInfoInitialized then
InitDaqsInfo();
end.
|
unit FC.Trade.Trader.Factory;
{$I Compiler.inc}
interface
uses Windows,Classes,SysUtils, BaseUtils,Serialization, Generics.Collections, Collections.List, Collections.Map,
FC.Definitions,FC.Trade.Trader.Base;
type
TStockTraderInfo = class (TInterfacedObject,IStockTraderInfo)
private
FName: string;
FIID: TGUID;
FCategory: string;
FClass : TStockTraderClass;
public
property Class_: TStockTraderClass read FClass;
function IID : TGUID;
function Category: string;
function Name : string;
constructor Create(const aCategory, aName: string; aClass: TStockTraderClass;aIID : TGUID);
destructor Destroy; override;
end;
IStockTraderFactoryEx = interface (IStockTraderFactory)
['{3DB61007-BD94-4ADC-A3C3-97593FBF5C99}']
//Регистрация класса трейдера. Указывается категория, имя, класс трейдера, идентифкатор интерфейса
procedure RegisterTrader(const aCategory, aName: string; aClass: TStockTraderClass; aIID: TGUID; aHidden: boolean=false);
function FindTrader(const aCategory, aName: string; aClass: TStockTraderClass): IStockTraderInfo;
end;
TStockTraderFactory = class (TInterfacedObject,IStockTraderFactory, IStockTraderFactoryEx, Serialization.IClassFactory)
private type
TStockTraderInfoContainer = TInterfacedObjectContainer<TStockTraderInfo>;
private
FTraderList: TOwnedOjectList<TStockTraderInfoContainer>;
FTraderMap : TOwnedObjectValueMap<TGUID,TStockTraderInfoContainer>;
function GetTraderInfoImpl(index: integer) : TStockTraderInfo;
protected
//from Serialization.IClassFactory
function CreateInstance(const aClassName: string): TObject;
constructor Create;
public
destructor Destroy; override;
//from IStockTraderFactoryEx
function GetImplObject:TStockTraderFactory;
//From IStockTraderFactory
function TraderCount: integer;
function GetTraderInfo(index: integer) : IStockTraderInfo;
procedure GetAllTraderCategories(aList: TStrings);
procedure GetAlTradersForCategory(const aCategory: string; aList: TList<integer>);
function CreateTrader(index: integer): IStockTrader; overload;
function CreateTrader(const aIID: TGUID): IStockTrader; overload;
procedure RegisterTrader(const aCategory, aName: string; aClass: TStockTraderClass; aIID: TGUID; aHidden: boolean=false);
function FindTrader(const aCategory, aName: string; aClass: TStockTraderClass): IStockTraderInfo;
property Traders[index: integer]: TStockTraderInfo read GetTraderInfoImpl;
end;
function TraderFactory: IStockTraderFactoryEx;
implementation
uses FC.Singletons;
function TraderFactory: IStockTraderFactoryEx;
begin
result:=(FC.Singletons.TraderFactory as IStockTraderFactoryEx);
end;
{ TStockTraderInfo }
constructor TStockTraderInfo.Create(const aCategory, aName: string;aClass: TStockTraderClass; aIID: TGUID);
begin
inherited Create;
FCategory:=aCategory;
FName:=aName;
FClass:=aClass;
FIID:=aIID;
end;
function TStockTraderInfo.Category: string;
begin
result:=FCategory;
end;
function TStockTraderInfo.IID: TGUID;
begin
result:=FIID;
end;
function TStockTraderInfo.Name: string;
begin
result:=FName;
end;
destructor TStockTraderInfo.Destroy;
begin
inherited;
end;
{ TStockTraderFactory }
constructor TStockTraderFactory.Create;
begin
FTraderList:=TOwnedOjectList<TStockTraderInfoContainer>.Create;
FTraderMap:=TOwnedObjectValueMap<TGUID,TStockTraderInfoContainer>.Create;
FTraderMap.AllowAppendRewrite:=false;
Serialization.TClassFactory.RegisterClassFactory(self);
end;
destructor TStockTraderFactory.Destroy;
begin
FTraderList.Free;
FTraderMap.Free;
inherited;
end;
function TStockTraderFactory.FindTrader(const aCategory, aName: string; aClass: TStockTraderClass): IStockTraderInfo;
var
i: integer;
begin
result:=nil;
for I := 0 to TraderCount-1 do
begin
if (Traders[i].Category=aCategory) and (Traders[i].Name=aName) and (Traders[i].Class_=aClass) then
begin
result:=Traders[i];
break;
end;
end;
end;
function TStockTraderFactory.TraderCount: integer;
begin
result:=FTraderList.Count;
end;
function TStockTraderFactory.CreateTrader(index: integer): IStockTrader;
var
aInfo : TStockTraderInfo;
aRes : TStockTraderBase;
begin
aInfo:=Traders[index];
aRes:=aInfo.Class_.CreateNaked;
aRes.IID:=aInfo.IID;
aRes.SetCategory(aInfo.Category);
aRes.SetName(aInfo.Name);
result:=aRes;
end;
function TStockTraderFactory.CreateTrader(const aIID: TGUID): IStockTrader;
var
aInfoContainer : TStockTraderInfoContainer;
aInfo: TStockTraderInfo;
aRes : TStockTraderBase;
begin
if not FTraderMap.Lookup(aIID,aInfoContainer) then
raise EStockError.Create(Format('Trader %s not found',[GUIDToString(aIID)]));
aInfo:=aInfoContainer.Value;
aRes:=aInfo.Class_.CreateNaked;
aRes.IID:=aInfo.IID;
aRes.SetCategory(aInfo.Category);
aRes.SetName(aInfo.Name);
result:=aRes;
end;
procedure TStockTraderFactory.RegisterTrader(const aCategory, aName: string;aClass: TStockTraderClass; aIID: TGUID; aHidden: boolean=false);
var
aInfo: TStockTraderInfo;
aInfoContainer : TStockTraderInfoContainer;
begin
if FTraderMap.Lookup(aIID,aInfoContainer) then
raise EStockError.CreateFmt('Duplicate IID. Same value was set to %s',[aInfoContainer.Value.FName]);
aInfo:=TStockTraderInfo.Create(aCategory,aName, aClass,aIID);
if not aHidden then
FTraderList.Add(TStockTraderInfoContainer.Create(aInfo));
FTraderMap.Add(aIID,TStockTraderInfoContainer.Create(aInfo));
end;
function TStockTraderFactory.GetTraderInfo(index: integer): IStockTraderInfo;
begin
result:=GetTraderInfoImpl(index);
end;
procedure TStockTraderFactory.GetAllTraderCategories(aList: TStrings);
var
i: integer;
begin
for i:=0 to TraderCount-1 do
begin
if aList.IndexOf(Traders[i].Category)=-1 then
aList.Add(Traders[i].Category)
end;
end;
procedure TStockTraderFactory.GetAlTradersForCategory(const aCategory: string; aList: TList<integer>);
var
i: integer;
begin
for i:=0 to TraderCount-1 do
begin
if AnsiSameText(aCategory,Traders[i].Category) then
aList.Add(i);
end;
end;
function TStockTraderFactory.GetTraderInfoImpl(index: integer): TStockTraderInfo;
begin
result:=FTraderList[index].Value;
end;
function TStockTraderFactory.GetImplObject: TStockTraderFactory;
begin
result:=self;
end;
function TStockTraderFactory.CreateInstance(const aClassName: string): TObject;
var
aInfo: TStockTraderInfo;
it : TMapIterator<TGUID,TStockTraderInfoContainer>;
begin
result:=nil;
FTraderMap.GetFirst(it);
while it.Valid do
begin
aInfo:=it.Value.Value;
if (aInfo.Class_.ClassName=aClassName) then
begin
result:=aInfo.Class_.CreateNaked;
break;
end;
FTraderMap.GetNext(it);
end;
end;
initialization
FC.Singletons.SetTraderFactory(TStockTraderFactory.Create);
end.
|
{*******************************************************}
{ }
{ Delphi Indy Abstraction Framework }
{ }
{ Copyright(c) 1995-2010 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit IPPeerResStrs;
interface
resourcestring
sIPProcsNotDefined = 'IPProcs is not defined. Make sure IndyPeerImpl (or an alternative IP Implementation unit) is in the uses clause';
sIPProcNotSupported = 'Registered IPProc peer does not implement the IIPPeerProcs interface. Make sure IndyPeerImpl (or an alternative IP Implementation unit) is in the uses clause';
sIPPeerNotRegisteredDefault = 'No peer with the interface with guid %s has been registered. Make sure IndyPeerImpl is in the uses clause';
sIPPeerNotRegisteredId = 'No peer with the interface with guid %s has been registered with the current implementation (%s)';
sPeerCreationFailed = 'Unable to create Peer for: %s using the implementation %s. Check to make sure the peer class is registered and that it implements the correct interface';
sPeerReservedID = 'Cannot use the reserved implementationID "%s"';
implementation
end.
|
unit clsDataConnect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Dialogs, Forms,
StdCtrls, ADODB, Inifiles, clsDbInterface, MConnect, clsClientDtSet,SConnect;
type
TdataConnect = class(Tobject)
ObjConnection: TSocketConnection;
constructor Create();
procedure DataAdd(DBInterface: IDBInterface; const obj: TObject);
procedure DataEdit(DBInterface: IDBInterface; const obj: TObject);
procedure DataDelete(DBInterface: IDBInterface; const obj: TObject);
function DataQuery(SQLStr: string): TClientDtSet;
Procedure DataExecute(SQLStr: string);
end;
implementation
{ TdataConnect }
constructor TDataConnect.Create;
var
iniFile: Tinifile;
strAPServer:string;
begin
ObjConnection:=TSocketConnection.Create(nil);
try
iniFile := Tinifile.Create(ExtractFilePath(Application.ExeName) + 'Sfisini.ini');
strAPServer:=iniFile.ReadString('APSERVER', 'IPDEF', '');
if strAPServer='' then MessageDlg('AP Server Does not exist!',mtInformation,[mbok],0);
ObjConnection.Address :=strAPServer;
ObjConnection.ServerName:='AP_ODAC.RMD_ODAC';
if strAPServer='' then ObjConnection.Free;
finally
iniFile.Free;
end;
end;
procedure TdataConnect.DataAdd(DBInterface: IDBInterface; const obj: TObject);
begin
DBInterface.Add(obj);
end;
procedure TdataConnect.DataEdit(DBInterface: IDBInterface; const obj: TObject);
begin
DBInterface.Edit(obj);
end;
procedure TdataConnect.DataDelete(DBInterface: IDBInterface; const obj: TObject);
begin
DBInterface.Delete(obj);
end;
function TdataConnect.DataQuery(SQLStr: string): TClientDtSet;
var
ObjDataSet: TClientDtSet;
begin
ObjDataSet := TClientDtSet.Create(nil);
objDataSet.RemoteServer:=ObjConnection;
objDataSet.ProviderName:='OraDataSetProQuery';
objDataSet.CommandText:=SQLStr;
ObjDataSet.Open;
Result := ObjDataSet;
//ObjDataSet.Close;
//ObjDataSet.Free;
end;
procedure TdataConnect.DataExecute(SQLStr: string);
var
ObjDataSet: TClientDtSet;
begin
ObjDataSet := TClientDtSet.Create(nil);
objDataSet.RemoteServer:=ObjConnection;
objDataSet.ProviderName:='OraDataSetProQuery';
objDataSet.CommandText:=SQLStr;
ObjDataSet.Execute;
ObjDataSet.Close;
ObjDataSet.Free;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ScktComp;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
ButtonDirectPrint: TButton;
GroupBox2: TGroupBox;
EditPrinterIP: TEdit;
GroupBox3: TGroupBox;
ButtonPrintFromFile: TButton;
RichEditDirectPrint: TRichEdit;
ClientSocket1: TClientSocket;
OpenDialog1: TOpenDialog;
procedure ButtonDirectPrintClick(Sender: TObject);
procedure ButtonPrintFromFileClick(Sender: TObject);
procedure ClientSocket1Write(Sender: TObject;
Socket: TCustomWinSocket);
private
LabelFormat : string;
procedure PrintLabel(format : string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ButtonDirectPrintClick(Sender: TObject);
begin
PrintLabel(RichEditDirectPrint.Text);
end;
procedure TForm1.ButtonPrintFromFileClick(Sender: TObject);
var
aFile : TextFile;
aFormat : string;
aTextLine : string;
begin
if OpenDialog1.Execute() then
begin
AssignFile(aFile, OpenDialog1.FileName);
Reset(aFile);
aFormat := '';
while not EOF(aFile) do
begin
ReadLn(aFile, aTextLine);
aFormat := aFormat + aTextLine;
end;
Closefile(aFile);
ShowMessage(aFormat);
PrintLabel(aFormat);
end;
end;
procedure TForm1.PrintLabel(format: string);
begin
ClientSocket1.Port := 9100;
ClientSocket1.Host := EditPrinterIP.Text;
ClientSocket1.Address := '127.0.0.1';
LabelFormat := format;
ClientSocket1.Active := True;
end;
procedure TForm1.ClientSocket1Write(Sender: TObject;
Socket: TCustomWinSocket);
begin
Socket.SendText(LabelFormat);
end;
end.
|
(*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit CreateProjectUwsgiTaskFactoryImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskIntf,
TaskFactoryIntf,
TextFileCreatorIntf,
ContentModifierIntf,
CreateProjectTaskFactoryImpl;
type
(*!--------------------------------------
* Factory class for create project task for
* FastCGI web application
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TCreateProjectUwsgiTaskFactory = class(TCreateProjectTaskFactory)
protected
function buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask; override;
end;
implementation
uses
DirectoryCreatorImpl,
InitGitRepoTaskImpl,
CommitGitRepoTaskImpl,
CreateDirTaskImpl,
CreateAppConfigsTaskImpl,
CreateAdditionalFilesTaskImpl,
CreateShellScriptsTaskImpl,
CreateUwsgiAppBootstrapTaskImpl,
CreateProjectTaskImpl;
function TCreateProjectUwsgiTaskFactory.buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask;
begin
result := TCreateProjectTask.create(
TCreateDirTask.create(TDirectoryCreator.create()),
TCreateShellScriptsTask.create(textFileCreator, contentModifier, 'bin'),
TCreateAppConfigsTask.create(textFileCreator, contentModifier),
TCreateAdditionalFilesTask.create(textFileCreator, contentModifier),
TCreateUwsgiAppBootstrapTask.create(textFileCreator, contentModifier),
TInitGitRepoTask.create(TCommitGitRepoTask.create())
);
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ExtCtrls,
uDiagnosisService;
type
TNaraeonSSDToolsDiag = class(TService)
tDiagnosis: TTimer;
procedure ServiceCreate(Sender: TObject);
procedure ServiceDestroy(Sender: TObject);
procedure tDiagnosisTimer(Sender: TObject);
procedure ServiceExecute(Sender: TService);
private
DiagnosisService: TDiagnosisService;
procedure WaitForTerminate;
procedure InitializeAndWaitForEnd;
public
function GetServiceController: TServiceController; override;
end;
var
NaraeonSSDToolsDiag: TNaraeonSSDToolsDiag;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
NaraeonSSDToolsDiag.Controller(CtrlCode);
end;
function TNaraeonSSDToolsDiag.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TNaraeonSSDToolsDiag.InitializeAndWaitForEnd;
begin
DiagnosisService.InitializePhysicalDriveList;
WaitForTerminate;
end;
procedure TNaraeonSSDToolsDiag.ServiceCreate(Sender: TObject);
begin
DiagnosisService := TDiagnosisService.Create;
{$IFDEF DEBUG} InitializeAndWaitForEnd; {$ENDIF}
end;
procedure TNaraeonSSDToolsDiag.ServiceDestroy(Sender: TObject);
begin
if DiagnosisService <> nil then
FreeAndNil(DiagnosisService);
end;
procedure TNaraeonSSDToolsDiag.ServiceExecute(Sender: TService);
begin
InitializeAndWaitForEnd;
end;
procedure TNaraeonSSDToolsDiag.WaitForTerminate;
const
DelayedStartup = 30000;
begin
Sleep(DelayedStartup);
tDiagnosis.Enabled := true;
tDiagnosis.OnTimer(self);
{$IFNDEF DEBUG}
while not Terminated do
ServiceThread.ProcessRequests(true);
{$ELSE}
while true do
Sleep(1);
{$ENDIF}
tDiagnosis.Enabled := false;
end;
procedure TNaraeonSSDToolsDiag.tDiagnosisTimer(Sender: TObject);
begin
DiagnosisService.Diagnosis;
if not DiagnosisService.IsThereAnySupportedDrive then
DoStop;
end;
end.
|
unit Ths.Erp.Database.Table.View;
interface
{$I ThsERP.inc}
uses
Forms, SysUtils, Classes, Dialogs, WinSock, System.Rtti,
FireDAC.Stan.Param, Data.DB, FireDAC.Comp.Client,
Ths.Erp.Database.Table;
type
TView = class(TTable)
private
protected
published
public
procedure Listen();override;
procedure Unlisten();override;
procedure Notify();override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
procedure Delete(pPermissionControl: Boolean=True); override;
function LogicalSelect(pFilter: string; pLock, pWithBegin, pPermissionControl: Boolean):Boolean;override;
function LogicalInsert(out pID: Integer; pWithBegin, pWithCommit, pPermissionControl: Boolean):Boolean;override;
function LogicalUpdate(pWithCommit, pPermissionControl: Boolean):Boolean;override;
function LogicalDelete(pWithCommit, pPermissionControl: Boolean):Boolean;override;
end;
implementation
uses
Ths.Erp.Database.Singleton, Ths.Erp.Constants, Ths.Erp.Functions;
{ TView }
procedure TView.Listen;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
procedure TView.Notify;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
procedure TView.Unlisten;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
function TView.LogicalSelect(pFilter: string; pLock, pWithBegin,
pPermissionControl: Boolean): Boolean;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
function TView.LogicalInsert(out pID: Integer; pWithBegin, pWithCommit,
pPermissionControl: Boolean): Boolean;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
function TView.LogicalUpdate(pWithCommit, pPermissionControl: Boolean): Boolean;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
function TView.LogicalDelete(pWithCommit, pPermissionControl: Boolean): Boolean;
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
procedure TView.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
procedure TView.Update(pPermissionControl: Boolean=True);
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
procedure TView.Delete(pPermissionControl: Boolean);
begin
raise Exception.Create(
TranslateText('Unsupported process!', FrameworkLang.MessageUnsupportedProcess, LngMsgData, LngSystem) + AddLBs + self.ClassName);
end;
end.
|
unit uPrinterInfo8;
interface
uses windows, sysutils, classes, forms, uPrinterConstsAndTypes,
uPrintException, printers, winspool, uCommonProc, registry, strutils,
dialogs, math, JclDateTime, IniFiles;
function PrinterSupportsPostscript(aPrinterName:string): Boolean;
function CapturePrinterInfo8(Sender: TForm; APrinterName: PChar; ADestStream: TStream; aForceA4:boolean):string;
procedure RestorePrinterInfo8(APrinterName: PChar; ASourceStream: TStream);
function pDevModeasJson(PI8: PPrinterInfo8):string;
function GetPrinterInfo8asJson(APrinterName: PChar; ASourceStream: TStream):string;
function GetPrinterInfoAsJson(aPrinterName:string; aPrinter: TPrinter): string;
function DeletePrinter(APrinterName: PChar):boolean;
function DeletePrinterDriver(aDriverName, aEnvironment: string):boolean;
function EnumPrinterDrivers: TStrings;
function EnumMonitors: TStrings;
function EnumPrinters: TStrings;
function EnumPorts: TStrings;
function EnumAllForms: TStrings;
function getDriverEnvironment(aDriverName:string):string;
function printerDriverExists(aDriverName:string):boolean;
function printerExists(aPrinterName:string):boolean;
function addPrinter(aPrinterName, aPortName, pDriverName, pPrintProcessor:string):boolean;
function addPrinterDriver(aDriverName, aEnvironment, aPath, aDriverEnvDir:string):boolean;
const
DPD_DELETE_UNUSED_FILES = 1;
DPD_DELETE_SPECIFIC_VERSION = 2;
DPD_DELETE_ALL_FILES = 4;
MAX_PORTNAME_LEN = 63 +1; // port name length
MAX_NETWORKNAME_LEN = 48 +1; // host name length
MAX_SNMP_COMMUNITY_STR_LEN = 32 +1; // SNMP Community String Name
MAX_QUEUENAME_LEN = 32 +1; // lpr print que name
MAX_IPADDR_STR_LEN = 15 +1; // ip address; string version
MAX_DEVICEDESCRIPTION_STR_LEN = 256+1;
PROTOCOL_RAWTCP_TYPE = 1; // The port expects RAW print data.
PROTOCOL_LPR_TYPE = 2; // The port expects to be driven as an LPR port.
ERROR_INSUFFICIENT_BUFFER = 122;
// FLAGS for AddPrinterDriverEx.
APD_STRICT_UPGRADE = $00000001;
APD_STRICT_DOWNGRADE = $00000002;
APD_COPY_ALL_FILES = $00000004;
APD_COPY_NEW_FILES = $00000008;
APD_COPY_FROM_DIRECTORY = $00000010;
type
_PORT_DATA_1 = record
sztPortName : Array[0..MAX_PORTNAME_LEN] of WChar;
dwVersion,
dwProtocol,
cbSize,
dwReserved : Cardinal;
sztHostAddress : Array[0..MAX_NETWORKNAME_LEN] of WChar;
sztSNMPCommunity : Array[0..MAX_SNMP_COMMUNITY_STR_LEN] of WChar;
dwDoubleSpool : Cardinal;
sztQueue : Array[0..MAX_QUEUENAME_LEN] of WChar;
sztIPAddress : Array[0..MAX_IPADDR_STR_LEN] of WChar;
Reserved : Array[0..540] of Byte;
dwPortNumber,
dwSNMPEnabled,
dwSNMPDevIndex : Cardinal;
end;
PPortData1 = ^_PORT_DATA_1;
TPortData1 = _PORT_DATA_1;
{$EXTERNALSYM _FORM_INFO_2A}
_FORM_INFO_2A = record
Flags: DWORD;
pName: PAnsiChar;
Size: TSize;
ImageableArea: TRect;
end;
{$EXTERNALSYM _FORM_INFO_2W}
_FORM_INFO_2W = record
Flags: DWORD;
pName: PWideChar;
Size: TSize;
ImageableArea: TRect;
end;
{$EXTERNALSYM _FORM_INFO_2}
_FORM_INFO_2 = _FORM_INFO_2A;
TFormInfo2A = _FORM_INFO_2A;
TFormInfo2W = _FORM_INFO_2W;
TFormInfo2 = TFormInfo2A;
{$EXTERNALSYM FORM_INFO_2A}
FORM_INFO_2A = _FORM_INFO_2A;
{$EXTERNALSYM FORM_INFO_2W}
FORM_INFO_2W = _FORM_INFO_2W;
{$EXTERNALSYM FORM_INFO_2}
FORM_INFO_2 = FORM_INFO_2A;
PDriverInfo6A = ^TDriverInfo6A;
PDriverInfo6W = ^TDriverInfo6W;
PDriverInfo6 = PDriverInfo6A;
{$EXTERNALSYM _DRIVER_INFO_6A}
_DRIVER_INFO_6A = record
cVersion: DWORD;
pName: PAnsiChar; { QMS 810 }
pEnvironment: PAnsiChar; { Win32 x86 }
pDriverPath: PAnsiChar; { c:\drivers\pscript.dll }
pDataFile: PAnsiChar; { c:\drivers\QMS810.PPD }
pConfigFile: PAnsiChar; { c:\drivers\PSCRPTUI.DLL }
pHelpFile: PAnsiChar; { c:\drivers\PSCRPTUI.HLP }
pDependentFiles: PAnsiChar; { PSCRIPT.DLL\0QMS810.PPD\0PSCRIPTUI.DLL\0PSCRIPTUI.HLP\0PSTEST.TXT\0\0 }
pMonitorName: PAnsiChar; { "PJL monitor" }
pDefaultDataType: PAnsiChar; { "EMF" }
pszzPreviousNames: PAnsiChar;
ftDriverDate: FILETIME;
dwlDriverVersion : ULONG;
pszMfgName : PAnsiChar; pszOEMUrl : PAnsiChar;
pszHardwareID : PAnsiChar;
pszProvider : PAnsiChar;
end;
{$EXTERNALSYM _DRIVER_INFO_6W}
_DRIVER_INFO_6W = record
cVersion: DWORD;
pName: PWideChar; { QMS 810 }
pEnvironment: PWideChar; { Win32 x86 }
pDriverPath: PWideChar; { c:\drivers\pscript.dll }
pDataFile: PWideChar; { c:\drivers\QMS810.PPD }
pConfigFile: PWideChar; { c:\drivers\PSCRPTUI.DLL }
pHelpFile: PWideChar; { c:\drivers\PSCRPTUI.HLP }
pDependentFiles: PWideChar; { PSCRIPT.DLL\0QMS810.PPD\0PSCRIPTUI.DLL\0PSCRIPTUI.HLP\0PSTEST.TXT\0\0 }
pMonitorName: PWideChar; { "PJL monitor" }
pDefaultDataType: PWideChar; { "EMF" }
pszzPreviousNames: PWideChar;
ftDriverDate: FILETIME;
dwlDriverVersion : ULONG;
pszMfgName : PWideChar;
pszOEMUrl : PWideChar;
pszHardwareID : PWideChar;
pszProvider : PWideChar;
end;
{$EXTERNALSYM _DRIVER_INFO_6}
_DRIVER_INFO_6 = _DRIVER_INFO_6A;
TDriverInfo6A = _DRIVER_INFO_6A;
TDriverInfo6W = _DRIVER_INFO_6W;
TDriverInfo6 = TDriverInfo6A;
{$EXTERNALSYM DRIVER_INFO_6A}
DRIVER_INFO_6A = _DRIVER_INFO_6A;
{$EXTERNALSYM DRIVER_INFO_6W}
DRIVER_INFO_6W = _DRIVER_INFO_6W;
{$EXTERNALSYM DRIVER_INFO_6}
DRIVER_INFO_6 = DRIVER_INFO_6A;
{$EXTERNALSYM AddPortExA}
function AddPortExA(pName: PAnsiChar; hWnd: HWND; pPort: Pointer; pMonitorName: PAnsiChar): BOOL; stdcall;
function AddPrinterDriverExA(pName: PAnsiChar; Level: DWORD; pDriverInfo: Pointer; dwFileCopyFlags:DWORD): BOOL; stdcall;
function XcvData(hXcv: Cardinal;
pszDataName: LPCWSTR;//PWideChar;
pInputData: Pointer;
cbInputData: Cardinal;
pOutputData: PBYTE;
cbOutputData: Cardinal;
pcbOutputNeeded: PDWORD;
pdwStatus: PDWORD): Boolean; stdcall;
implementation
function AddPortExA; external winspl name 'AddPortExA';
function AddPrinterDriverExA; external winspl name 'AddPrinterDriverExA';
function XcvData; external winspl name 'XcvDataW';
function PrinterSupportsPostscript(aPrinterName:string): Boolean;
const
POSTSCRIPT_PASSTHROUGH = 4115;
POSTSCRIPT_IDENTIFY = 4117;
Escapes: array[0..2] of Cardinal = (POSTSCRIPT_DATA, POSTSCRIPT_IDENTIFY, POSTSCRIPT_PASSTHROUGH);
var
res: Integer;
pidx: Integer;
i: Integer;
begin
Result := false;
pidx := Printer.Printers.IndexOf(aPrinterName);
if pidx>-1 then begin
Printer.PrinterIndex := pidx;
for i := Low(Escapes) to High(Escapes) do begin
res := ExtEscape(printer.Handle, QUERYESCSUPPORT, sizeof(Escapes[0]), @Escapes[i], 0, nil);
if res = 0 then begin
Result := true;
Break;
end;
end;
end;
end;
function DeletePrinter(APrinterName: PChar):boolean;
var
HPrinter : THandle;
BytesNeeded: Cardinal;
PrinterDefaults: TPrinterDefaults;
begin
result := false;
with PrinterDefaults do begin
DesiredAccess := PRINTER_ALL_ACCESS;
pDatatype := nil;
pDevMode := nil;
end;
if OpenPrinter(APrinterName, HPrinter, @PrinterDefaults) then begin
try
SetLastError(0);
if not GetPrinter(HPrinter, 8, nil, 0, @BytesNeeded) then
result := winspool.DeletePrinter(HPrinter);
finally
ClosePrinter(HPrinter);
end;
if not result then
raise exception.Create('DeletePrinter, '+SysErrorMessage(GetLastError));
end else begin
raise eNexPrinterNotFound.Create(APrinterName);
end;
end;
function printerExists(aPrinterName:string):boolean;
var
slprinters : TStrings;
begin
slprinters := EnumPrinters;
try
result := slprinters.indexof(aPrinterName)>-1;
finally
slprinters.free;
end;
end;
function EnumPrinterDrivers: TStrings;
var
Buffer, DriverInfo: PChar;
NumInfo: DWORD;
cbNeeded: DWORD;
i: Integer;
Level: Byte;
pName : PChar;
pEnvironment : PChar;
r : longbool;
err : Integer;
begin
Result := TStringList.Create;
cbNeeded := 0;
pName := nil;
pEnvironment := 'all';
Level := 1;
r := winspool.EnumPrinterDrivers (pName, pEnvironment, Level, nil, 0, cbNeeded, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('EnumPrinterDrivers, '+SysErrorMessage(err));
if cbNeeded > 0 then begin
GetMem(Buffer, cbNeeded);
try
if not winspool.EnumPrinterDrivers ( pName, pEnvironment, Level, PByte(Buffer), cbNeeded, cbNeeded, NumInfo) then Exit;
DriverInfo := Buffer;
for i := 0 to NumInfo - 1 do begin
Result.Add(PDriverInfo1(DriverInfo)^.pName);
Inc(DriverInfo, SizeOf(TDriverInfo1));
end;
finally
FreeMem(Buffer, cbNeeded);
end;
end;
end;
function EnumPorts: TStrings;
var
Buffer, PortInfo: PChar;
NumInfo: DWORD;
cbNeeded: DWORD;
i: Integer;
Level: Byte;
pName : PChar;
r : longbool;
err : Integer;
begin
Result := TStringList.Create;
cbNeeded := 0;
pName := nil;
Level := 1;
r := winspool.EnumPorts (pName, Level, nil, 0, cbNeeded, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('EnumPorts, '+SysErrorMessage(err));
if cbNeeded > 0 then begin
GetMem(Buffer, cbNeeded);
try
if not winspool.EnumPorts ( pName, Level, PByte(Buffer), cbNeeded, cbNeeded, NumInfo) then Exit;
PortInfo := Buffer;
for i := 0 to NumInfo - 1 do begin
Result.Add(PPortInfo1(PortInfo)^.pName);
Inc(PortInfo, SizeOf(TPortInfo1));
end;
finally
FreeMem(Buffer, cbNeeded);
end;
end;
end;
function EnumMonitors: TStrings;
var
Buffer, MonitorInfo: PChar;
NumInfo: DWORD;
cbNeeded: DWORD;
i: Integer;
Level: Byte;
pName : PChar;
r : longbool;
err : Integer;
begin
Result := TStringList.Create;
cbNeeded := 0;
pName := nil;
Level := 1;
r := winspool.EnumMonitors (pName, Level, nil, 0, cbNeeded, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('EnumMonitors, '+SysErrorMessage(err));
if cbNeeded > 0 then begin
GetMem(Buffer, cbNeeded);
try
if not winspool.EnumMonitors( pName, Level, PByte(Buffer), cbNeeded, cbNeeded, NumInfo) then Exit;
MonitorInfo := Buffer;
for i := 0 to NumInfo - 1 do begin
Result.Add(PMonitorInfo1(MonitorInfo)^.pName);
Inc(MonitorInfo, SizeOf(TMonitorInfo1));
end;
finally
FreeMem(Buffer, cbNeeded);
end;
end;
end;
function EnumAllForms: TStrings;
const
kKey = '\SYSTEM\CurrentControlSet\Control\Print\Forms';
var
r : TRegistry;
slForms : TStringlist;
Buffer: array[0..127] of Char;
i, b: Integer;
begin
Result := TStringList.Create;
slForms := TStringlist.create;
r := TRegistry.create;
try
r.RootKey := HKEY_LOCAL_MACHINE;
if r.OpenKey(kKey, false) then begin
r.GetValueNames(slForms);
//Buffer := pAnsiChar(dupestring(#32, sizeof(TFormInfo1)));
for i:=0 to slForms.count-1 do begin
b := r.ReadBinaryData(slForms[i], Buffer, sizeof(TFormInfo1));
showmessage(
PFormInfo1(@Buffer[0])^.pName + #13#10 +
inttostr( PFormInfo1(@Buffer[0])^.Size.cx ) + #13#10 +
inttostr( PFormInfo1(@Buffer[0])^.Size.cy ) + #13#10 +
inttostr( b )
);
end;
r.CloseKey;
end;
finally
r.free;
slForms.free;
end;
{
cbNeeded := 0;
pName := nil;
Level := 2;
r:=winspool.EnumForms (pName, pEnvironment, Level, nil, 0, cbNeeded, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('EnumAllForms, '+SysErrorMessage(err));
if cbNeeded > 0 then begin
GetMem(Buffer, cbNeeded);
try
if not winspool.EnumPrinterDrivers ( pName, pEnvironment, Level, PByte(Buffer), cbNeeded, cbNeeded, NumInfo) then Exit;
DriverInfo := Buffer;
for i := 0 to NumInfo - 1 do begin
Result.Add(PDriverInfo1(DriverInfo)^.pName);
Inc(DriverInfo, SizeOf(TDriverInfo1));
end;
finally
FreeMem(Buffer, cbNeeded);
end;
end; }
end;
function printerDriverExists(aDriverName:string):boolean;
begin
result := getDriverEnvironment(aDriverName)>'';
end;
function getDriverEnvironment(aDriverName:string):string;
var
Buffer, DriverInfo: PChar;
NumInfo: DWORD;
cbNeeded: DWORD;
i: Integer;
Level: Byte;
pName : PChar;
pEnvironment : PChar;
r : longbool;
err : Integer;
begin
Result := '';
cbNeeded := 0;
pName := nil;
pEnvironment := pchar('all');
Level := 2;
SetLastError(0);
r := winspool.EnumPrinterDrivers (pName, pEnvironment, Level, nil, 0, cbNeeded, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('getDriverEnvironment, '+SysErrorMessage(err));
if cbNeeded > 0 then begin
GetMem(Buffer, cbNeeded);
try
if not winspool.EnumPrinterDrivers ( pName, pEnvironment, Level, PByte(Buffer), cbNeeded, cbNeeded, NumInfo) then Exit;
DriverInfo := Buffer;
for i := 0 to NumInfo - 1 do begin
if sametext(aDriverName, PDriverInfo2(DriverInfo)^.pName) then begin
Result := PDriverInfo2(DriverInfo)^.pEnvironment;
break;
end;
Inc(DriverInfo, SizeOf(TDriverInfo2));
end;
finally
FreeMem(Buffer, cbNeeded);
end;
end;
end;
function addPrinterDriver(aDriverName, aEnvironment, aPath, aDriverEnvDir:string):boolean;
var
Level: Byte;
pName, pEnvironment, pDriverDirectory : PAnsiChar;
DriverInfo : TDriverInfo6;
printerDriverPathFrom, printerDriverPath : string;
cbBuf, cbNeeded, dwFileCopyFlags : dword;
r : longbool;
err ,i, j : Integer;
Buffer1: array[0..127] of Char;
depfiles: array[0..1023] of Char;
slFiles, slDepenFiles : TStringList;
slLoad : TIniFile;
aDriverPath : string;
aDataFile : string;
aConfigFile : string;
aHelpFile : string;
begin
result := false;
printerDriverPathFrom := aPath+aDriverName+'\'+aDriverEnvDir+'\';
if not fileexists(aPath+aDriverName+'.ini') then
raise exception.Create('addPrinterDriver, '+aPath+aDriverName+'.ini missing');
slFiles := TStringList.create;
slDepenFiles := TStringList.create;
slLoad := TIniFile.Create(aPath+aDriverName+'.ini');
try
aDriverPath := slLoad.ReadString(aDriverEnvDir, 'DriverPath','');
aDataFile := slLoad.ReadString(aDriverEnvDir, 'DataFile','');
aConfigFile := slLoad.ReadString(aDriverEnvDir, 'ConfigFile','');
aHelpFile := slLoad.ReadString(aDriverEnvDir, 'HelpFile','');
slDepenFiles.Text := strutils.ReplaceStr( slLoad.ReadString(aDriverEnvDir, 'DependentFiles',''),';',#13#10);
finally
slLoad.Free;
end;
slFiles.add(aDriverPath);
slFiles.add(aDataFile);
slFiles.add(aConfigFile);
slFiles.add(aHelpFile);
try
fillchar(depfiles, 1024, #0);
j:=0;
for i:=0 to slDepenFiles.count-1 do begin
sysutils.StrCopy(@depfiles[j], pansichar(slDepenFiles[i]));
inc(j, length(slDepenFiles[i])+1);
end;
SetLastError(0);
pName := nil;
pEnvironment := pchar(aEnvironment);
level := 1;
cbBuf := 128;
pDriverDirectory := @buffer1[0];
r := GetPrinterDriverDirectory(pName, pEnvironment, level, pDriverDirectory, cbBuf, cbNeeded);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('addPrinterDriver, '+SysErrorMessage(err));
printerDriverPath := pDriverDirectory+'\';
forcedirectories(printerDriverPath);
for i:=0 to slDepenFiles.count-1 do
copyfile(pchar(printerDriverPathFrom + '\'+slDepenFiles[i]), pchar(printerDriverPath+'\'+slDepenFiles[i]), false);
for i:=0 to slFiles.count-1 do
copyfile(pchar(printerDriverPathFrom + '\'+slFiles[i]), pchar(printerDriverPath+'\'+slFiles[i]), false);
pName := nil;
Level := 3;
DriverInfo.cVersion := 3; //win2000, xp level
DriverInfo.pName := pchar(aDriverName);
DriverInfo.pEnvironment := pchar(aEnvironment); //'Windows NT x86';
DriverInfo.pDriverPath := PAnsiChar(printerDriverPath+aDriverPath);
DriverInfo.pDataFile := PAnsiChar(printerDriverPath+aDataFile);
DriverInfo.pConfigFile := PAnsiChar(printerDriverPath+aConfigFile);
DriverInfo.pHelpFile := PAnsiChar(printerDriverPath+aHelpFile);
DriverInfo.pDependentFiles := @depfiles[0];
DriverInfo.pMonitorName := PAnsiChar('Redirected Port');
DriverInfo.pDefaultDataType := PAnsiChar('RAW');
DriverInfo.pszzPreviousNames := PAnsiChar('');
DriverInfo.ftDriverDate.dwLowDateTime := 0;
DriverInfo.ftDriverDate.dwHighDateTime := 0;
DriverInfo.dwlDriverVersion := 0; // DWORDLONG; 88 15 2 a0 01 00 05 00
DriverInfo.pszMfgName := PAnsiChar('');
DriverInfo.pszOEMUrl := PAnsiChar('');
DriverInfo.pszHardwareID := PAnsiChar('');
DriverInfo.pszProvider := PAnsiChar('');
dwFileCopyFlags := APD_COPY_ALL_FILES;
SetLastError(0);
result := AddPrinterDriverExA( pName, Level, @DriverInfo, dwFileCopyFlags );
err := GetLastError;
for i:=0 to slDepenFiles.count-1 do
deletefile(printerDriverPath+slDepenFiles[i]);
for i:=0 to slFiles.count-1 do
deletefile(printerDriverPath+slFiles[i]);
if not result then
raise exception.Create('addPrinterDriver, ('+inttostr(err) + ') '+SysErrorMessage(err));
finally
slFiles.Free;
slDepenFiles.Free;
end;
end;
function EnumPrinters: TStrings;
var
Buffer, PrinterInfo: PChar;
Flags, Count, NumInfo: DWORD;
i: Integer;
Level: Byte;
r : longbool;
err : Integer;
begin
Result := TStringList.Create;
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
Flags := PRINTER_ENUM_LOCAL;
Level := 4;
end else
begin
Flags := PRINTER_ENUM_LOCAL;
Level := 5;
end;
Count := 0;
r:=winspool.EnumPrinters(Flags, nil, Level, nil, 0, Count, NumInfo);
err := GetLastError;
if (not(r) and (err<>ERROR_INSUFFICIENT_BUFFER)) then
raise exception.Create('EnumPrinters, '+SysErrorMessage(err));
if Count > 0 then
begin
GetMem(Buffer, Count);
try
if not winspool.EnumPrinters(Flags, nil, Level, PByte(Buffer), Count, Count, NumInfo) then Exit;
PrinterInfo := Buffer;
for i := 0 to NumInfo - 1 do
begin
if Level = 4 then begin
Result.Add(PPrinterInfo4(PrinterInfo)^.pPrinterName);
Inc(PrinterInfo, SizeOf(TPrinterInfo4));
end else begin
Result.Add(PPrinterInfo5(PrinterInfo)^.pPrinterName);
Inc(PrinterInfo, SizeOf(TPrinterInfo5));
end;
end;
finally
FreeMem(Buffer, Count);
end;
end;
end;
function DeletePrinterDriver(aDriverName, aEnvironment: string):boolean;
var
pServerName:pchar;
pEnvironment:pchar;
pDriverName:pchar;
begin
pServerName := nil;
pEnvironment:= PAnsiChar(aEnvironment);
pDriverName := PAnsiChar(aDriverName);
SetLastError(0);
result := winspool.DeletePrinterDriver(pServerName, pEnvironment, pDriverName);
if not result then
raise exception.Create('DeletePrinterDriver, '+SysErrorMessage(GetLastError));
end;
function addPrinter(aPrinterName, aPortName, pDriverName, pPrintProcessor:string):boolean;
var
pServerName:pchar;
pPrinter: PPrinterInfo2;
begin
new(pPrinter);
try
pServerName := nil;
pPrinter^.pServerName := nil;
pPrinter^.pShareName := nil;
pPrinter^.pComment := nil;
pPrinter^.pLocation := nil;
pPrinter^.pDevMode := nil;
pPrinter^.pSepFile := nil;
pPrinter^.pDatatype := nil;
pPrinter^.pParameters := nil;
pPrinter^.pSecurityDescriptor := nil;
pPrinter^.Attributes := 0;
pPrinter^.Priority := 0;
pPrinter^.DefaultPriority := 0;
pPrinter^.StartTime := 0;
pPrinter^.UntilTime := 0;
pPrinter^.Status := 0;
pPrinter^.cJobs := 0;
pPrinter^.AveragePPM :=0;
pPrinter^.pPrinterName := pAnsiChar(aPrinterName);
pPrinter^.pPortName := pAnsiChar(aPortName);
pPrinter^.pDriverName := pAnsiChar(pDriverName);
pPrinter^.pPrintProcessor := pAnsiChar(pPrintProcessor);
result := winspool.Addprinter(pServerName,2,pPrinter)<>0;
if not result then
raise exception.Create('addPrinter, '+SysErrorMessage(GetLastError));
finally
Dispose(pPrinter);
end;
end;
function CapturePrinterInfo8(Sender: TForm; APrinterName: PChar; ADestStream: TStream; aForceA4:boolean):string;
var
HPrinter : THandle;
InfoSize,
BytesNeeded: Cardinal;
PI8: PPrinterInfo8;
PrinterDefaults: TPrinterDefaults;
begin
result := '';
with PrinterDefaults do
begin
DesiredAccess := PRINTER_ACCESS_USE;
pDatatype := nil;
pDevMode := nil;
end;
if OpenPrinter(APrinterName, HPrinter, @PrinterDefaults) then begin
try
SetLastError(0);
//Determine the number of bytes to allocate for the PRINTER_INFO_2 construct...
if not GetPrinter(HPrinter, 8, nil, 0, @BytesNeeded) then
begin
//Allocate memory space for the PRINTER_INFO_2 pointer (PrinterInfo2)...
PI8 := AllocMem(BytesNeeded);
try
InfoSize := SizeOf(TPrinterInfo8);
if GetPrinter(HPrinter, 8, PI8, BytesNeeded, @BytesNeeded) then begin
//PrinterProperties(0, hPrinter);
if DocumentProperties(Sender.handle, hPrinter, APrinterName, PI8.pDevMode^,
PI8.pDevMode^, DM_IN_PROMPT or DM_IN_BUFFER or DM_OUT_BUFFER)=IDOK then begin
if aForceA4 then begin
// A4 210 x 297 mm', 'A4', 2100, 2970, DMPAPER_A4
PI8.pDevMode^.dmPaperSize := DMPAPER_A4;
PI8.pDevMode^.dmPaperLength := 2970;
PI8.pDevMode^.dmPaperWidth := 2100;
end;
ADestStream.Write(PChar(PI8)[InfoSize], BytesNeeded - InfoSize);
result := pDevModeasJson(PI8);
end;
end;
finally
FreeMem(PI8, BytesNeeded);
end;
end;
finally
ClosePrinter(HPrinter);
end;
end else begin
raise eNexPrinterNotFound.Create(APrinterName);
end;
end;
procedure RestorePrinterInfo8(APrinterName: PChar; ASourceStream: TStream);
var
HPrinter : THandle;
InfoSize,
BytesNeeded: Cardinal;
PI8: PPrinterInfo8;
PrinterDefaults: TPrinterDefaults;
begin
with PrinterDefaults do
begin
DesiredAccess := PRINTER_ALL_ACCESS; //PRINTER_ACCESS_USE;
pDatatype := nil;
pDevMode := nil;
end;
if OpenPrinter(APrinterName, HPrinter, @PrinterDefaults) then begin
try
SetLastError(0);
//Determine the number of bytes to allocate for the PRINTER_INFO_2 construct...
if not GetPrinter(HPrinter, 8, nil, 0, @BytesNeeded) then
begin
//Allocate memory space for the PRINTER_INFO_2 pointer (PrinterInfo2)...
PI8 := AllocMem(BytesNeeded);
try
InfoSize := SizeOf(TPrinterInfo8);
if GetPrinter(HPrinter, 8, PI8, BytesNeeded, @BytesNeeded) then
begin
ASourceStream.ReadBuffer(PChar(PI8)[InfoSize], ASourceStream.size);
// Apply settings to the printer
if DocumentProperties(0, hPrinter, APrinterName, PI8.pDevMode^,
PI8.pDevMode^, DM_IN_BUFFER or DM_OUT_BUFFER) = IDOK then
begin
SetPrinter(HPrinter, 8, PI8, 0); // Ignore the result of this call...
end;
end;
finally
FreeMem(PI8, BytesNeeded);
end;
end;
finally
ClosePrinter(HPrinter);
end;
end else begin
raise eNexPrinterNotFound.Create(APrinterName);
end;
end;
function GetPrinterInfo8asJson(APrinterName: PChar; ASourceStream: TStream):string;
var
HPrinter : THandle;
InfoSize,
BytesNeeded: Cardinal;
PI8: PPrinterInfo8;
PrinterDefaults: TPrinterDefaults;
begin
result := '';
with PrinterDefaults do
begin
DesiredAccess := PRINTER_ALL_ACCESS; //PRINTER_ACCESS_USE;
pDatatype := nil;
pDevMode := nil;
end;
if OpenPrinter(APrinterName, HPrinter, @PrinterDefaults) then begin
try
SetLastError(0);
//Determine the number of bytes to allocate for the PRINTER_INFO_2 construct...
if not GetPrinter(HPrinter, 8, nil, 0, @BytesNeeded) then
begin
//Allocate memory space for the PRINTER_INFO_2 pointer (PrinterInfo2)...
PI8 := AllocMem(BytesNeeded);
try
InfoSize := SizeOf(TPrinterInfo8);
if GetPrinter(HPrinter, 8, PI8, BytesNeeded, @BytesNeeded) then
begin
ASourceStream.ReadBuffer(PChar(PI8)[InfoSize], ASourceStream.size);
result := pDevModeasJson(PI8);
end;
finally
FreeMem(PI8, BytesNeeded);
end;
end;
finally
ClosePrinter(HPrinter);
end;
end else begin
raise eNexPrinterNotFound.Create(APrinterName);
end;
end;
function GetPrinterInfoAsJson(aPrinterName:string; aPrinter: TPrinter): string;
var
s: string;
begin
result := '';
aPrinter.PrinterIndex := aPrinter.Printers.IndexOf(aPrinterName);
//aPrinter.SetPrinter(pAnsiChar(aPrinterName),'WINSPOOL','', 0);
result := result + '"name": "' + aPrinterName +'",';
if aPrinter.Orientation = poPortrait then s:='Portrait' else s:='Landscape';
result := result + '"orientation": "' + s +'",';
result := result + '"PHYSICALWIDTH": ' + inttostr( GetDeviceCaps(aPrinter.Handle, PHYSICALWIDTH) ) +',' ;
result := result + '"PHYSICALHEIGHT": ' + inttostr( GetDeviceCaps(aPrinter.Handle, PHYSICALHEIGHT) ) +',' ;
result := result + '"PHYSICALOFFSETX": ' + inttostr( GetDeviceCaps(aPrinter.Handle, PHYSICALOFFSETX) ) +',' ;
result := result + '"PHYSICALOFFSETY": ' + inttostr( GetDeviceCaps(aPrinter.Handle, PHYSICALOFFSETY) ) +',' ;
result := result + '"HORZRES": ' + inttostr( GetDeviceCaps(aPrinter.Handle, HORZRES) ) +',' ;
result := result + '"VERTRES": ' + inttostr( GetDeviceCaps(aPrinter.Handle, VERTRES) ) +',' ;
result := result + '"LOGPIXELSX": ' + inttostr( GetDeviceCaps(aPrinter.Handle, LOGPIXELSX) ) +',' ;
result := result + '"LOGPIXELSY": ' + inttostr( GetDeviceCaps(aPrinter.Handle, LOGPIXELSY) ) ;
end;
function pDevModeasJson(PI8: PPrinterInfo8):string;
var
aPaper : TPaper;
begin
result := '';
result := result + '"dmDeviceName":"' + PI8.pDevMode.dmDeviceName+'",';
result := result + '"dmSpecVersion":' + inttostr(PI8.pDevMode.dmSpecVersion)+',';
result := result + '"dmDriverVersion":' + inttostr(PI8.pDevMode.dmDriverVersion )+',';
result := result + '"dmSize":' + inttostr(PI8.pDevMode.dmSize )+',';
if PI8.pDevMode.dmOrientation =1 then
result := result + '"dmOrientation":"Portrait",'
else
result := result + '"dmOrientation":"Landscape",';
aPaper := FPaperlist.getByDMPaper(PI8.pDevMode.dmPaperSize);
if aPaper<>nil then begin
result := result + '"dmPaperSize":"'+getPaperConstsAsText(PI8.pDevMode.dmPaperSize)+'",';
result := result + '"dmPaperSizeName":"'+aPaper.Name+'",';
result := result + '"dmPaperSizeShortName":"'+aPaper.ShortName+'",';
result := result + '"dmPaperSizeAdobeName":"'+aPaper.AdobeName+'",';
result := result + '"dmPaperLength":' + inttostr(aPaper.Height )+',';
result := result + '"dmPaperWidth":' + inttostr(aPaper.Width )+',';
end else begin
result := result + '"dmPaperSize":"'+getPaperConstsAsText(PI8.pDevMode.dmPaperSize)+'",';
result := result + '"dmPaperSizeName":"",';
result := result + '"dmPaperSizeShortName":"",';
result := result + '"dmPaperSizeAdobeName":"",';
result := result + '"dmPaperLength":' + inttostr(PI8.pDevMode.dmPaperLength )+',';
result := result + '"dmPaperWidth":' + inttostr(PI8.pDevMode.dmPaperWidth )+',';
end;
result := result + '"dmScale":' + inttostr(PI8.pDevMode.dmScale )+',';
result := result + '"dmCopies":' + inttostr(PI8.pDevMode.dmCopies )+',';
result := result + '"dmDefaultSource":"'+getSourceConsts(PI8.pDevMode.dmDefaultSource)+'",';
result := result + '"dmDefaultSourceDesc":"'+getSourceNames(PI8.pDevMode.dmDefaultSource)+'",';
case PI8.pDevMode.dmPrintQuality of
DMRES_DRAFT : result := result + '"dmPrintQuality":"Draft",';
DMRES_HIGH : result := result + '"dmPrintQuality":"High",';
DMRES_LOW : result := result + '"dmPrintQuality":"Low",';
DMRES_MEDIUM : result := result + '"dmPrintQuality":"Medium",';
else
result := result + '"dmPrintQuality":' + inttostr(PI8.pDevMode.dmPrintQuality )+',';
end;
case PI8.pDevMode.dmColor of
DMCOLOR_COLOR : result := result + '"dmColor":"Color",';
DMCOLOR_MONOCHROME : result := result + '"dmColor":"Monochrome",';
end;
case PI8.pDevMode.dmDuplex of
DMDUP_HORIZONTAL : result := result + '"dmDuplex":"Horizontal",';
DMDUP_SIMPLEX : result := result + '"dmDuplex":"Simplex",';
DMDUP_VERTICAL : result := result + '"dmDuplex":"Vertical",';
end;
result := result + '"dmYResolution":' + inttostr(PI8.pDevMode.dmYResolution )+',';
case PI8.pDevMode.dmTTOption of
DMTT_BITMAP : result := result + '"dmTTOption":"BITMAP",';
DMTT_DOWNLOAD : result := result + '"dmTTOption":"DOWNLOAD",';
DMTT_DOWNLOAD_OUTLINE : result := result + '"dmTTOption":"DOWNLOAD_OUTLINE",';
DMTT_SUBDEV : result := result + '"dmTTOption":"SUBDEV",';
else
result := result + '"dmTTOption":' + inttostr(PI8.pDevMode.dmTTOption )+',';
end;
case PI8.pDevMode.dmCollate of
DMCOLLATE_FALSE : result := result + '"dmCollate":"False",';
DMCOLLATE_TRUE : result := result + '"dmCollate":"True",';
end;
result := result + '"dmFormName":"' + PI8.pDevMode.dmFormName+'",';
result := result + '"dmLogPixels":' + inttostr(PI8.pDevMode.dmLogPixels )+',';
result := result + '"dmBitsPerPel":' + inttostr(PI8.pDevMode.dmBitsPerPel )+',';
result := result + '"dmPelsWidth":' + inttostr(PI8.pDevMode.dmPelsWidth )+',';
result := result + '"dmPelsHeight":' + inttostr(PI8.pDevMode.dmPelsHeight )+',';
result := result + '"dmDisplayFlags":' + inttostr(PI8.pDevMode.dmDisplayFlags )+',';
result := result + '"dmDisplayFrequency":' + inttostr(PI8.pDevMode.dmDisplayFrequency )+',';
case PI8.pDevMode.dmICMMethod of
DMICMMETHOD_DEVICE : result := result + '"dmICMMethod":"DEVICE",';
DMICMMETHOD_DRIVER : result := result + '"dmICMMethod":"DRIVER",';
DMICMMETHOD_NONE : result := result + '"dmICMMethod":"NONE",';
DMICMMETHOD_SYSTEM : result := result + '"dmICMMethod":"SYSTEM",';
DMICMMETHOD_USER : result := result + '"dmICMMethod":"USER",';
else
result := result + '"dmICMMethod":' + inttostr(PI8.pDevMode.dmICMMethod )+',';
end;
case PI8.pDevMode.dmICMIntent of
DMICM_ABS_COLORIMETRIC : result := result + '"dmICMIntent":"ABS_COLORIMETRIC",';
DMICM_COLORIMETRIC : result := result + '"dmICMIntent":"COLORIMETRIC",';
DMICM_CONTRAST : result := result + '"dmICMIntent":"CONTRAST",';
DMICM_SATURATE : result := result + '"dmICMIntent":"SATURATE",';
DMICM_USER : result := result + '"dmICMIntent":"USER",';
else
result := result + '"dmICMIntent":' + inttostr(PI8.pDevMode.dmICMIntent )+',';
end;
case PI8.pDevMode.dmMediaType of
DMMEDIA_GLOSSY : result := result + '"dmMediaType":"GLOSSY",';
DMMEDIA_STANDARD : result := result + '"dmMediaType":"STANDARD",';
DMMEDIA_TRANSPARENCY : result := result + '"dmMediaType":"TRANSPARENCY",';
DMMEDIA_USER : result := result + '"dmMediaType":"USER",';
else
result := result + '"dmMediaType":' + inttostr(PI8.pDevMode.dmMediaType )+',';
end;
case PI8.pDevMode.dmDitherType of
DMDITHER_COARSE : result := result + '"dmDitherType ":"COARSE",';
DMDITHER_ERRORDIFFUSION : result := result + '"dmDitherType ":"ERRORDIFFUSION",';
DMDITHER_FINE : result := result + '"dmDitherType ":"FINE",';
DMDITHER_GRAYSCALE : result := result + '"dmDitherType ":"GRAYSCALE",';
DMDITHER_LINEART : result := result + '"dmDitherType ":"LINEART",';
DMDITHER_NONE : result := result + '"dmDitherType ":"NONE",';
DMDITHER_RESERVED6 : result := result + '"dmDitherType ":"RESERVED6",';
DMDITHER_RESERVED7 : result := result + '"dmDitherType ":"RESERVED7",';
DMDITHER_RESERVED8 : result := result + '"dmDitherType ":"RESERVED8",';
DMDITHER_RESERVED9 : result := result + '"dmDitherType ":"RESERVED9",';
DMDITHER_USER : result := result + '"dmDitherType ":"USER",';
else
result := result + '"dmDitherType ":' + inttostr(PI8.pDevMode.dmDitherType )+',';
end;
result := result + '"dmICCManufacturer":' + inttostr(PI8.pDevMode.dmICCManufacturer )+',';
result := result + '"dmICCModel":' + inttostr(PI8.pDevMode.dmICCModel )+',';
result := result + '"dmPanningWidth":' + inttostr(PI8.pDevMode.dmPanningWidth )+',';
result := result + '"dmPanningHeight":' + inttostr(PI8.pDevMode.dmPanningHeight ) ;
end;
end.
|
unit ufrmPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
// Integer types :
Int1 : Byte; // 0 to 255
Int2 : ShortInt; // -127 to 127
Int3 : Word; // 0 to 65,535
Int4 : SmallInt; // -32,768 to 32,767
Int5 : LongWord; // 0 to 4,294,967,295
Int6 : Cardinal; // 0 to 4,294,967,295
Int7 : LongInt; // -2,147,483,648 to 2,147,483,647
Int8 : Integer; // -2,147,483,648 to 2,147,483,647
Int9 : Int64; // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
// Decimal types :
Dec1 : Single; // 7 significant digits, exponent -38 to +38
Dec2 : Currency; // 50+ significant digits, fixed 4 decimal places
Dec3 : Double; // 15 significant digits, exponent -308 to +308
Dec4 : Extended; // 19 significant digits, exponent -4932 to +4932
//EXAMPLE 1.
const
YOUNG_AGE = 23; // Small integer constant
MANY = 300; // Bigger integer constant
RICH = 100000.00; // Decimal number : note no thousand commas
var
Age : Byte; // Smallest positive integer type
Books : SmallInt; // Bigger signed integer
Salary : Currency; // Decimal used to hold financial amounts
Expenses : Currency;
TakeHome : Currency;
//EXAMPLE 2
var
myInt : Integer; // Define integer and decimal variables
myDec : Single;
begin
//EXAMPLE 1:
//Assigning to and from number variables
Age := YOUNG_AGE; // Assign from a predefined constant
Books := MANY + 45; // Assign from a mix of constants (expression)
Salary := RICH; // Assign from a predefined constant
Expenses := 12345.67; // Assign from a literal constant
TakeHome := Salary; // Assign from another variable
TakeHome := TakeHome - Expenses; // Assign from an expression
{ Age is set to 23
Books is set to 345
Salary is set to 100000.00
Expenses is set to 12345.67
TakeHome is set to 87654.33 }
//************************************************************************
//EXAMPLE 2:
//Numerical operators
{ + : Add one number to another
- : Subtract one number from another
* : Multiply two numbers
/ : Divide one decimal number by another
div : Divide one integer number by another
mod : Remainder from dividing one integer by }
myInt := 20; // myInt is now 20
myInt := myInt + 10; // myInt is now 30
myInt := myInt - 5; // myInt is now 25
myInt := myInt * 4; // myInt is now 100
myInt := 14 div 3; // myInt is now 4 (14 / 3 = 4 remainder 2)
myInt := 14 mod 3; // myInt is now 2 (14 / 3 = 4 remainder 2)
myInt := 12 * 3 - 4; // myInt is now 32 (* comes before -)
myInt := 12 * (3 - 4); // myInt is now -12 (brackets come before *)
myDec := 2.222 / 2.0; // myDec is now 1.111
//*************************************************************
//Numeric NATIVE functions and procedures:
///Func: Abs - Gives the absolute value of a number (- sign is removed)
//---function Abs ( Number : Numeric type ) : Numeric type;
{
Example code : Illustrating absolute values of different data types
var
float, bigFloat : single;
int : Integer;
varVar : Variant;
begin
float := -1.5; // Small negative floating point number
bigFloat := -4.56E100; // Infinite negative floating point number
int := -7; // Negative integer
varVar := '-98'; // Variants are converted to floating point!
ShowMessage('Abs(float) = '+FloatToStr(Abs(float)));
ShowMessage('Abs(bigFloat) = '+FloatToStr(Abs(bigFloat)));
ShowMessage('Abs(int) = '+FloatToStr(Abs(int)));
// Variants are converted into Extended floating types
float := Abs(varVar);
ShowMessage('Abs(varVar) = '+FloatToStr(float));
end; }
///Func: Max - Gives the maximum of two integer values
//---function Max ( const A, B : Integer|Int64|Single|Double|Extended ) : Integer|Int64|Single|Double|Extended;
{ Example code : Illustrate integer use of Max
var
int1, int2, int3 : Integer;
begin
int1 := 37;
int2 := 38;
int3 := Max(int1, int2);
end;
Show full unit code
Max(int1, int2) = 38
Example code : Illustrating Max of mixed number types
var
int1 : Integer;
float1 : single;
begin
int1 := 37;
float1 := 37.5;
float1 := Max(float1, int1);
end;
Show full unit code
Max(float1, int1) = 37.5
}
///Func: Min - Gives the minimum of two integer values
//--- function Min ( const A, B : Integer|Int64|Single|Double|Extended ) : Integer|Int64|Single|Double|Extended;
{Example code : Illustrate integer use of Min
var
int1, int2, int3 : Integer;
begin
int1 := 37;
int2 := 38;
int3 := Min(int1, int2);
end;
Show full unit code
Min(int1, int2) = 37
Example code : Illustrating Min of mixed number types
var
int1 : Integer;
float1 : single;
begin
int1 := 38;
float1 := 37.5;
float1 := Min(float1, int1);
end;
Show full unit code
Min(float1, int1) = 37.5 }
///Func: Mean - Gives the average for a set of numbers
//---function Mean ( const DataArray : array of Double ) : Extended;
{ Example code : Calculate the mean of a set of 5 numbers
var
numbers : array[1..5] of Double;
aveVal, meanVal : Double;
begin
// Set up the array of 5 floating point numbers
numbers[1] := 1.0;
numbers[2] := 2.5;
numbers[3] := 3.0;
numbers[4] := 4.5;
numbers[5] := 25.0;
// Metodo plus NOOB kkkk - Calculate the average of these numbers
aveVal := (numbers[1] + numbers[2] + numbers[3] +
numbers[4] + numbers[5]) / 5;
// Metodo Less NOOB - Calculate the mean of these numbers
meanVal := Mean(numbers);
// Show these values
ShowMessage('Average = '+FloatToStr(aveVal));
ShowMessage('Mean = '+FloatToStr(meanVal));
end;
Show full unit code
Average = 7.2
Mean = 7.2 }
///Func
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Str1 : Char; // Holds a single character, small alphabet
Str2 : WideChar; // Holds a single character, International alphabet
Str3 : AnsiChar; // Holds a single character, small alphabet
Str4 : ShortString; // Holds a string of up to 255 Char's
Str5 : String; // Holds strings of Char's of any size desired
Str6 : AnsiString; // Holds strings of AnsiChar's any size desired
Str7 : WideString; // Holds strings of WideChar's of any size desired
//String processing routines
{ AnsiLeftStr Returns leftmost characters of a string
AnsiMidStr Returns middle characters of a string
AnsiRightStr Returns rightmost characters of a string
AnsiStartsStr Does a string start with a substring?
AnsiContainsStr Does a string contain another?
AnsiEndsStr Does a string end with a substring?
AnsiIndexStr Check substring list against a string
AnsiMatchStr Check substring list against a string
AnsiReverseString Reverses characters in a string
AnsiReplacStr Replaces all substring occurences
DupeString Repeats a substring n times
StrScan Scans a string for a specific character
StuffString Replaces part of a string text
Trim Removes leading and trailing white space
TrimLeft Removes leading white space
TrimRight Removes trailing white space
Examples:
var
Source, Target : string;
begin
Source := '12345678';
Target := Copy(Source, 3, 4); // Target now = '3456'
Target := '12345678';
Insert('-+-', Target, 3); // Target now = '12-+-345678'
Target := '12345678';
Delete(Target, 3, 4); // Target now = '1278'
Target := StringOfChar('S', 5); // Target now = 'SSSSS'
Source := 'This is a way to live A big life';
// Target set to 'This is THE way to live THE big life'
Target := StringReplace(before, ' a ', ' THE ',
[rfReplaceAll, rfIgnoreCase]);
}
//
begin
end;
procedure TForm1.Button3Click(Sender: TObject);
var
smallString : string[2];
smallString2 : ShortString;
begin
//TYPES STRING AND CHARS
{
Type AnsiChar A character type guaranteed to be 8 bits in size
Type AnsiString A data type that holds a string of AnsiChars
Type CHAR Variable type holding a single character
Type ShortString Defines a string of up to 255 characters
Type STRING A data type that holds a string of characters
Type WideChar Variable type holding a single International character
Type WideString A data type that holds a string of WideChars
}
//Example: ShortString Type - Defines a string of up to 255 characters
// Assign to our small string
smallString := 'ABCD';
ShowMessageFmt('smallString size = %d',[SizeOf(smallString)]);
ShowMessageFmt('smallString = %S',[smallString]);
{ Result
smallString size = 3
smallString = AB }
// Assign to our slightly bigger string
smallString2 := 'ABCD';
ShowMessageFmt('smallString2 size = %d',[SizeOf(smallString2)]);
ShowMessageFmt('smallString2 = %S',[smallString2]);
{ Result
smallishString size = 256
smallishString = ABCD }
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
{ Função AnsiCompareStr Compare duas strings para igualdade (Upper case letters > Lower case letters OU Lower case letters > Numbers
Função AnsiCompareText Compare duas strings para igualdade, ignorando maiúsculas e minúsculas oBS. Em delphi Letras> Números
Função AnsiContainsStr Retorna verdadeiro se uma string contém uma substring, diferencia maiúsculas de minúsculas - A função AnsiContainsStr procura por uma string Needle em uma string Haystack , retornando true se a encontrar. Caso contrário, falso.
Função AnsiContainsText Retorna verdadeiro se uma string contém uma substring, não diferencia maiúsculas de minúsculas
Função AnsiEndsStr Retorna verdadeiro se uma string termina com uma substring
Função AnsiIndexStr Compara uma string com uma lista de strings - retorna o índice de correspondência
Função AnsiLeftStr Extrai caracteres da esquerda de uma string
Função AnsiLowerCase Alterar caracteres maiúsculos em uma string para minúsculos
Função AnsiMatchStr Retorna verdadeiro se uma string corresponder exatamente a uma de uma lista de strings
Função AnsiMidStr Retorna uma substring dos caracteres do meio de uma string
Função AnsiPos Encontre a posição de uma corda na outra
Função AnsiReplaceStr Substitui uma parte de uma string por outra
Função AnsiReverseString Inverte a sequência de letras em uma string
Função AnsiRightStr Extrai caracteres da direita de uma string
Função AnsiStartsStr Retorna verdadeiro se uma string começar com uma substring
Função AnsiUpperCase Alterar caracteres minúsculos em uma string para maiúsculas
Procedimento AppendStr Concatene uma corda com a ponta da outra
Função CompareStr Compare duas strings para ver qual é maior que a outra
Função CompareText Compare duas strings para igualdade, ignorando maiúsculas e minúsculas
Função Concat Concatena uma ou mais strings em uma string
Função cópia de Crie uma cópia de parte de uma string ou array
Procedimento Excluir Exclua uma seção de caracteres de uma string
Função DupeString Cria uma string contendo cópias de uma substring
Função Alto Retorna o maior valor de um tipo ou variável
Procedimento Inserir Insira uma corda em outra corda
Função LastDelimiter Encontre a última posição dos caracteres selecionados em uma string
Função Comprimento Retorna o número de elementos em uma matriz ou string
Função LowerCase Alterar caracteres maiúsculos em uma string para minúsculos
Procedimento Jogada Copie bytes de dados de uma fonte para um destino
Função Pos Encontre a posição de uma corda na outra
Procedimento ProcessPath Divida uma string de unidade / caminho / nome de arquivo em suas partes constituintes
Procedimento SetLength Altera o tamanho de uma string ou o (s) tamanho (s) de uma matriz
Procedimento SetString Copia caracteres de um buffer em uma string
Função StringOfChar Cria uma string com um caractere repetido várias vezes
Função StringReplace Substitua uma ou mais substrings encontradas em uma string
Função StrScan Pesquisa um caractere específico em uma string constante
Função StuffString Substitui uma parte de uma string por outra
Modelo TReplaceFlags Define opções para a rotina StringReplace
Função Aparar Remove espaços em branco à esquerda e à direita de uma string
Função TrimLeft Remove os espaços em branco iniciais de uma string
Função TrimRight Remove espaços em branco à direita de uma string
Modelo TStringList Contém uma lista de strings de comprimento variável
Função UpCase Converter um valor Char em maiúsculas
Função UpperCase Alterar caracteres minúsculos em uma string para maiúsculas
Função WrapText Adicione alimentações de linha em uma string para simular a quebra de linha }
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
{ //CONVERSIONS FROM
Função Formato Formatação rica de números e texto em uma string
Função StringToWideChar Converte uma string normal em um buffer com terminação WideChar 0
Função StrToCurr Converta uma string numérica em um valor monetário
Função StrToDate Converte uma string de data em um valor TDateTime
Função StrToDateTime Converte uma string de data + hora em um valor TDateTime
Função StrToFloat Converte uma string numérica em um valor de ponto flutuante
Função StrToInt Converte uma string inteira em um valor inteiro
Função StrToInt64 Converta uma string inteira em um valor Int64
Função StrToInt64Def Converta uma string em um valor Int64 com o padrão
Função StrToIntDef Converta uma string em um valor inteiro com o padrão
Função StrToTime Converte uma string de hora em um valor TDateTime
Modelo TFormatSettings Um registro para manter valores de localidade para funções thread-safe
Variável TwoDigitYearCenturyWindow Define o limite de século para conversões de sequência de anos de 2 dígitos
Procedimento Val Converte strings numéricas em valores inteiros e de ponto flutuante }
{ CONVERSION TO
Variável CurrencyDecimals Define a contagem de dígitos decimais na função Format
Variável CurrencyFormat Define a colocação da string de moeda nas funções de exibição de moeda
Variável CurrencyString A string de moeda usada nas funções de exibição de moeda
Função CurrToStrF Converta um valor de moeda em uma string com formatação
Função DateTimeToStr Converte valores de data e hora TDateTime em uma string
Procedimento DateTimeToString Formatação rica de uma variável TDateTime em uma string
Função DateToStr Converte um valor de data TDateTime em uma string
Variável Separador decimal O caractere usado para exibir o ponto decimal
Função FloatToStr Converte um valor de ponto flutuante em uma string
Função FloatToStrF Converta um valor de ponto flutuante em uma string com formatação
Função Formato Formatação rica de números e texto em uma string
Função FormatCurr Formatação rica de um valor de moeda em uma string
Função FormatDateTime Formatação rica de uma variável TDateTime em uma string
Função FormatFloat Formatação rica de um número de ponto flutuante em uma string
Função Caixa de entrada Exibe uma caixa de diálogo que pede a entrada de texto do usuário, com o padrão
Função InputQuery Exibe uma caixa de diálogo que pede a entrada de texto do usuário
Função IntToHex Converter um inteiro em uma string hexadecimal
Função IntToStr Converte um inteiro em uma string
Variável LongDateFormat Versão longa da data para formato de string
Variável LongDayNames Uma matriz de nomes de dias da semana, começando 1 = domingo
Variável LongMonthNames Uma matriz de dias dos nomes dos meses, começando 1 = janeiro
Variável LongTimeFormat Versão longa do tempo para o formato da string
Variável NegCurrFormat Define a formatação do valor negativo em exibições de moeda
Função Ord Fornece o valor ordinal de um número inteiro, caractere ou enum
Variável ShortDateFormat Versão compacta da data para formato de string
Variável ShortDayNames Uma matriz de nomes de dias da semana, começando 1 = domingo
Variável ShortMonthNames Uma matriz de dias dos nomes dos meses, começando em 1 = janeiro
Variável ShortTimeFormat Versão curta do tempo para o formato da string
Procedimento Str Converte um número inteiro ou de ponto flutuante em uma string
Modelo TFormatSettings Um registro para manter valores de localidade para funções thread-safe
Variável ThousandSeparator O caractere usado para exibir o separador de milhares
Função WideCharToString Copia uma string WideChar terminada em nulo para uma string normal }
{ DISPLAYING
Função Formato Formatação rica de números e texto em uma string
Função Caixa de entrada Exibe uma caixa de diálogo que pede a entrada de texto do usuário, com o padrão
Função InputQuery Exibe uma caixa de diálogo que pede a entrada de texto do usuário
Função MessageDlg Exibe uma mensagem, símbolo e botões selecionáveis
Função MessageDlgPos Exibe uma mensagem mais botões em uma determinada posição da tela
Procedimento Mostrar mensagem Mostra uma string em uma caixa de diálogo simples com um botão OK
Procedimento ShowMessageFmt Exibir dados formatados em uma caixa de diálogo simples com um botão OK
Procedimento ShowMessagePos Exibe uma string em uma caixa de diálogo simples em uma determinada posição da tela
Modelo TFloatFormat Formatos para uso em funções de exibição de número de ponto flutuante
Modelo TFormatSettings Um registro para manter valores de localidade para funções thread-safe
Modelo TPrintDialog Classe que cria uma seleção de impressora e diálogo de controle }
end;
procedure TForm1.Button6Click(Sender: TObject);
type
RegFile = record
campo1:integer;
campo2:string[30];
end;
var
myWord, myWord1, myWord2 : Word;
myFile : File of Word;
//Example 2
MeuArqBin: file of RegFile;
begin
{ Neste artigo veremos como manipular arquivos binários. Ainda hoje, algumas aplicações fazem uso de arquivos binários
para armazenar e trocar informações de maneira mais segura do que é possível com arquivos texto.
Arquivos binários guardam informações no "formato de máquina". Por isso, se um arquivo desse tipo for aberto em um editor de texto comum
não será possível a sua leitura de maneira compreensível. Para evitar que os dados fiquem desprotegidos, acessíveis para que
qualquer usuário possa ler, gravaríamos estas informações em formato binário. }
// Try to open the Test.bin binary file for writing to
AssignFile(myFile, 'Test.cus');
ReWrite(myFile); //ReWrite - Open a text or binary file for write access
// Write a couple of lines of Word data to the file
myWord1 := 234;
myWord2 := 567;
Write(myFile, myWord1, myWord2); // Write data to a binary or text file. The write procedure writes a single line of data to a file
// Close the file
CloseFile(myFile);
// Reopen the file in read only mode
Reset(myFile); //The Reset procedure opens a file given by FileHandle for read, write or read and write access.
{
OBS:
Is for binary files. Before using Reset, you must set FileMode to one of the following:
fmOpenRead : Read only
fmOpenWrite : Write only
fmOpenReadWrite : Read and write
Exemple:
FileMode := fmOpenRead; // Reopen the file in read only mode
Reset(myFile);
}
// Display the file contents
while not Eof(myFile) do
begin
Read(myFile, myWord);
ShowMessage(IntToStr(myWord));
end;
// Close the file for the last time
CloseFile(myFile);
//***************************************************
AssignFile(MeuArqBin, 'Arq1.bin');
ReWrite(MeuArqBin);
//pulando record
//MeuArqBin.
end;
end.
|
unit Assessment;
interface
type
TRecommendation = (rcApprove, rcReject);
type
TAssessment = class(TObject)
private
FRecommendation: TRecommendation;
FRecommendedAmount: currency;
public
property Recommendation: TRecommendation read FRecommendation write FRecommendation;
property RecommendedAmount: currency read FRecommendedAmount write FRecommendedAmount;
constructor Create; overload;
constructor Create(const rec: integer; const recAmt: currency); overload;
end;
implementation
constructor TAssessment.Create;
begin
inherited;
end;
constructor TAssessment.Create(const rec: Integer; const recAmt: currency);
begin
FRecommendation := TRecommendation(rec);
FRecommendedAmount := recAmt;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_TabControl;
{$I FMX_Defines.inc}
interface
uses
Classes, UITypes, FMX_Types, FMX_Controls;
type
{ TTabItem }
TTabItem = class(TTextControl)
private
FIndex: Integer;
FContent: TContent;
FIsSelected: Boolean;
procedure SetIndex(const Value: Integer);
protected
procedure ApplyStyle; override;
procedure SetVisible(const Value: Boolean); override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure AddObject(AObject: TFmxObject); override;
procedure Realign; override;
procedure Select(ASelected: Boolean);
published
{ trigger }
property IsSelected: Boolean read FIsSelected;
{ props }
property AutoTranslate default True;
property Font;
property Index: Integer read FIndex write SetIndex;
property TextAlign default TTextAlign.taLeading;
property VertTextAlign;
property Text;
property StyleLookup;
property WordWrap default True;
end;
{ TTabControl }
TTabControl = class(TStyledControl, IItemsContainer)
private
FTabIndex: Integer;
FOnChange: TNotifyEvent;
FTabHeight: Single;
FFullSize: Boolean;
FBackground: TControl;
procedure SetTabIndex(const Value: integer);
procedure SetTabHeight(const Value: Single);
procedure SetFullSize(const Value: Boolean);
procedure FixTabSize;
{ IItemContainer }
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
function GetActiveTab: TTabItem;
procedure SetActiveTab(const Value: TTabItem);
protected
function GetTabItem(AIndex: Integer): TTabItem;
function GetTabCount: Integer;
procedure Resize; virtual;
procedure ApplyStyle; override;
procedure FreeStyle; override;
procedure PaintChildren; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Realign; override;
procedure AddObject(AObject: TFmxObject); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
property TabCount: Integer read GetTabCount;
property Tabs[AIndex: Integer]: TTabItem read GetTabItem;
property ActiveTab: TTabItem read GetActiveTab write SetActiveTab;
published
property StyleLookup;
property FullSize: Boolean read FFullSize write SetFullSize default False;
property TabIndex: Integer read FTabIndex write SetTabIndex default -1;
property TabHeight: Single read FTabHeight write SetTabHeight;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
uses
Types, FMX_Ani, FMX_Layouts;
type
THackTabItem = class(TTabItem);
{ TTabItem }
constructor TTabItem.Create(AOwner: TComponent);
begin
inherited;
FContent := TContent.Create(nil);
FContent.Parent := Self;
FContent.Locked := True;
FContent.Stored := False;
FContent.HitTest := False;
FContent.Visible := False;
FDesignInteractive := True;
FAutoTranslate := True;
TextAlign := TTextAlign.taLeading;
Height := 20;
Width := 80;
HitTest := True;
end;
procedure TTabItem.AddObject(AObject: TFmxObject);
begin
if (FContent <> nil) and (AObject <> FContent) and (AObject <> FResourceLink) then
FContent.AddObject(AObject)
else
inherited;
end;
procedure TTabItem.ApplyStyle;
begin
inherited;
if (Parent <> nil) and (Parent is TTabControl) and
(TTabControl(Parent).TabIndex = Index) then
Select(True)
else
Select(False)
end;
destructor TTabItem.Destroy;
begin
inherited;
end;
procedure TTabItem.Realign;
var
P: TPointF;
S: TPointF;
begin
if FDisableAlign then
Exit;
FDisableAlign := True;
try
if (FContent <> nil) and (Parent <> nil) and (Parent is TTabControl) then
begin
P.X := TTabControl(Parent).Margins.Left + FContent.Padding.Left;
P.Y := Self.Height + TTabControl(Parent).Margins.Top + FContent.Padding.Top;
P := AbsoluteToLocal(TTabControl(Parent).LocalToAbsolute(P));
S.X := TTabControl(Parent).Width - TTabControl(Parent).Margins.Left - TTabControl(Parent).Margins.Right - FContent.Padding.Left -
FContent.Padding.Right;
S.Y := TTabControl(Parent).Height - Self.Height -
TTabControl(Parent).Margins.Top - TTabControl(Parent).Margins.Bottom -
FContent.Padding.Top - FContent.Padding.Bottom;
FContent.SetBounds(P.X, P.Y, S.X, S.Y);
end;
finally
FDisableAlign := False;
end;
inherited;
end;
procedure TTabItem.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Single);
begin
inherited;
if Button = TMouseButton.mbLeft then
begin
if (Parent <> nil) and (Parent is TTabControl) then
begin
TTabControl(Parent).TabIndex := Index;
end;
end;
end;
procedure TTabItem.Select(ASelected: Boolean);
begin
FIsSelected := ASelected;
StartTriggerAnimation(Self, 'IsSelected');
ApplyTriggerEffect(Self, 'IsSelected');
end;
procedure TTabItem.SetIndex(const Value: Integer);
begin
if FIndex <> Value then
begin
inherited Index := Value;
Realign;
end;
end;
procedure TTabItem.SetVisible(const Value: Boolean);
var
S: TTabItem;
begin
if Value <> Visible then
begin
S := TTabControl(Parent).GetTabItem(TTabControl(Parent).TabIndex);
inherited;
if not Visible and IsSelected then
begin
Select(False);
TTabControl(Parent).FTabIndex := -1;
if Index >= TTabControl(Parent).TabCount then
TTabControl(Parent).TabIndex := TTabControl(Parent).TabCount - 1
else
TTabControl(Parent).TabIndex := Index;
end
else
begin
TTabControl(Parent).Realign;
if S <> nil then
begin
TTabControl(Parent).FTabIndex := -1;
TTabControl(Parent).TabIndex := S.Index;
end;
end;
end;
end;
procedure TTabItem.Resize;
begin
inherited ;
if Assigned(Parent) then
begin
TTabControl(Parent).Realign;
TTabControl(Parent).FixTabSize;
end;
end;
{ TTabControl }
constructor TTabControl.Create(AOwner: TComponent);
begin
inherited;
FTabIndex := -1;
AutoCapture := True;
Width := 200;
Height := 200;
FTabHeight:= 20;
SetAcceptsControls(False);
end;
destructor TTabControl.Destroy;
begin
inherited;
end;
procedure TTabControl.FixTabSize;
var
AWidth, AutoWidth, MinWidth: Single;
i: integer;
fitWidth: Single;
bChanged: boolean;
begin
bChanged := False;
// check for total width larger than the client area of the component
AutoWidth := 0;
for i := 0 to TabCount - 1 do
AutoWidth := AutoWidth + Tabs[i].Width;
if AutoWidth > Width then
begin
AutoWidth := Width;
AWidth := AutoWidth / TabCount;
MinWidth := Canvas.TextWidth('X...');
if AWidth < MinWidth then
AWidth := MinWidth;
for i := 0 to TabCount - 1 do
Tabs[i].Width := AWidth;
bChanged := True;
end;
if bChanged then Realign;
end;
procedure TTabControl.FreeStyle;
begin
inherited;
FBackground := nil;
end;
function TTabControl.GetActiveTab: TTabItem;
begin
if (TabIndex >= 0) and (TabIndex < TabCount) then
Result := Tabs[TabIndex]
else
Result := nil;
end;
function TTabControl.GetItem(const AIndex: Integer): TFmxObject;
begin
Result := Tabs[AIndex];
end;
function TTabControl.GetItemsCount: Integer;
begin
Result := TabCount;
end;
procedure TTabControl.AddObject(AObject: TFmxObject);
begin
if (AObject <> FResourceLink) and not (AObject is TEffect) and not(AObject is TAnimation) and
not (AObject is TTabItem) and (ActiveTab <> nil) then
begin
ActiveTab.AddObject(AObject);
end
else
inherited;
if AObject is TTabItem then
begin
Realign;
// ensures all tabs are resized to the dimension of their text width
FixTabSize;
end;
end;
procedure TTabControl.ApplyStyle;
var
B: TFmxObject;
begin
inherited;
B := FindStyleResource('background');
if (B <> nil) and (B is TControl) then
FBackground := TControl(B);
Realign;
end;
procedure TTabControl.PaintChildren;
var
Sel: TTabItem;
SaveOp: Single;
begin
Sel := GetTabItem(TabIndex);
if (Sel <> nil) and (Sel.Visible) then
begin
SaveOp := Sel.Opacity;
Sel.FDisablePaint := True;
inherited;
Sel.FDisablePaint := False;
Canvas.SetMatrix(Sel.AbsoluteMatrix);
Sel.Painting;
Sel.Paint;
Sel.PaintChildren;
end
else
inherited;
end;
procedure TTabControl.Realign;
var
Idx, i: Integer;
CurX, CurY: Single;
AutoWidth, MaxHeight: Single;
B: TFmxObject;
begin
if FDisableAlign then
Exit;
FDisableAlign := True;
try
{ move all non TabItem to end of list }
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if not(TFmxObject(FChildren[i]) is TTabItem) then
TFmxObject(FChildren[i]).Index := FChildren.Count - 1;
{ calc max height }
MaxHeight := 0;
Idx := 0;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if TFmxObject(FChildren[i]) is TTabItem then
with TTabItem(FChildren[i]) do
begin
if not Visible then
Continue;
FIndex := Idx;
if Height + Padding.top + Padding.bottom > MaxHeight then
MaxHeight := Height + Padding.top + Padding.bottom;
Idx := Idx + 1;
end;
if Idx = 0 then
MaxHeight := 0
else if FTabHeight > 0 then
MaxHeight := FTabHeight;
{ background }
if FResourceLink <> nil then
begin
B := FResourceLink;
if (B <> nil) and (B is TControl) then
begin
TControl(B).Align := TAlignLayout.alNone;
TControl(B).SetBounds(TControl(B).Padding.left, MaxHeight + TControl(B).Padding.top,
Width - TControl(B).Padding.left - TControl(B).Padding.top,
Height - MaxHeight - TControl(B).Padding.top - TControl(B).Padding.bottom);
TControl(B).BringToFront;
end;
end;
{ align }
CurX := 0;
CurY := 0;
AutoWidth:= Width;
if FBackground <> nil then
AutoWidth := Width - FBackground.Margins.left - FBackground.Margins.right;
if FFullSize and (Idx > 0) then
AutoWidth := AutoWidth / Idx
else
AutoWidth := AutoWidth;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if TFmxObject(FChildren[i]) is TTabItem then
with TTabItem(FChildren[i]) do
begin
if not Visible then
Continue;
Align := TAlignLayout.alNone;
FContent.Align := TAlignLayout.alNone;
FContent.Visible := Index = TabIndex;
FContent.DesignVisible := (Index = TabIndex);
FContent.ClipChildren := True;
if FContent.Visible then
FContent.BringToFront;
if FFullSize then
SetBounds(CurX + Padding.left, CurY + Padding.top, AutoWidth,
MaxHeight - Padding.top - Padding.bottom)
else
SetBounds(CurX + Padding.left, CurY + Padding.top, Width,
MaxHeight - Padding.top - Padding.bottom);
CurX := CurX + Padding.left + Width + Padding.right;
end;
finally
FDisableAlign := False;
end;
inherited;
end;
function TTabControl.GetTabCount: Integer;
var
i: Integer;
begin
Result := 0;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if TFmxObject(FChildren[i]) is TTabItem then
begin
if TTabItem(FChildren[i]).Visible then
begin
Inc(Result);
end;
end;
end;
function TTabControl.GetTabItem(AIndex: Integer): TTabItem;
var
Idx, i: Integer;
begin
{ calc max height }
Idx := 0;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if TFmxObject(FChildren[i]) is TTabItem then
begin
if TTabItem(FChildren[i]).Visible then
begin
if (Idx = AIndex) then
begin
Result := TTabItem(FChildren[i]);
Exit;
end;
Inc(Idx);
end;
end;
Result := nil;
end;
procedure TTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Single);
begin
inherited;
if Button = TMouseButton.mbLeft then
Realign;
end;
procedure TTabControl.SetTabIndex(const Value: Integer);
begin
if FTabIndex <> Value then
begin
if GetTabItem(FTabIndex) <> nil then
GetTabItem(FTabIndex).Select(False);
FTabIndex := Value;
Realign;
if GetTabItem(FTabIndex) <> nil then
GetTabItem(FTabIndex).Select(True);
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
procedure TTabControl.SetActiveTab(const Value: TTabItem);
begin
TabIndex := Value.Index;
end;
procedure TTabControl.SetTabHeight(const Value: Single);
var
i: Integer;
begin
if FTabHeight <> Value then
begin
FTabHeight := Value;
for i := 0 to TabCount - 1 do
Tabs[i].Height:= Value;
Realign;
end;
end;
procedure TTabControl.SetFullSize(const Value: Boolean);
begin
if FFullSize <> Value then
begin
FFullSize := Value;
Realign;
end;
end;
procedure TTabControl.Resize;
begin
FixTabSize;
inherited ;
end;
initialization
RegisterFmxClasses([TTabControl, TTabItem]);
end.
|
// Materia: Introduccion a la Algoritmica y Programacion 2016
// Proyecto fin de año "Juego PasaPalabra".
// Comisión n°2 - Grupo n°7
// Integrantes:
// - Elena, Pablo.
// - Gremiger, Santiago.
// - Martinez, Christian.
// **********************
// Unit dedicada exclusivamente a la declaracion de todos los nuevos tipos.
unit unitTipos;
interface
const
color_logo = 13;//Magenta claro
borde = 11;//Cyan claro
texto_select = 0; //Negro
texto_fondoSelect = 15; //Fondo blanco
texto_unSelect = 15;//Blanco
texto_fondoUnSelect = 0;//Fondo Negro
texto_base = 7;//Gris Claro
texto_titulo = 9;//Azul Claro
texto_titulo2 = 15;//Blanco
texto_correcto = 10;//Verde Claro
texto_incorrecto = 4;//Rojo
texto_pasa = 14;//Amarillo
type
//Tipo para la dificultad del del juego.
TDificultad = (FACIL,DIFICIL);
TPalabra=record
palabra:string[20];//Lista de caracteres(lse) debe ser
letra:char;
end;
{***************************************************************}
{**************************** LISTAS ***************************}
{***************************************************************}
//Tipo de la informacion que va a contener la lista.
TInfo= record
caracter: char;
visible: boolean; {Ver el caracter. "True" para visible, "False" para oculto}
end;
TPuntero = ^TNodo; //Puntero a un nodo de la lista.
//Representa un nodo de la lista.
TNodo = record
info: TInfo;
next: TPuntero; //Puntero al nodo siguiente.
end;
TLista = record
pri: TPuntero; //Puntero al primer nodo de la lista.
ult: TPuntero; //Puntero al ultimo nodo de la lista.
cant : integer; //Contiene la cantidad de nodos que tiene la lista.
end;
{***************************************************************}
{**************************** ROSCA ****************************}
{***************************************************************}
//Campo para cada palabra del arreglo TRosca.
TPalabraRosca = record
letra: char; //Letra a la que pertenece la palabra.
palabra: TLista; //Palabra almacenada en una LSE.
jugar: boolean; //Ver la palabra. "True" para visible, "False" para oculto.
color: integer;//Segun su valor mostrara un color en la rosca. [0:Neutro -1:Correcto -2:Incorrecto -3:PasaPalabra]
end;
//Arreglo de "TPalabraRosca". Contiene las 26 palabras.
TRosca = array[1..26] of TPalabraRosca;
TRegPalabras = record
letra: char;
palabra: TLista;
end;
{***************************************************************}
{*************************** USUARIO ***************************}
{***************************************************************}
//Tipo al que pertenece el archivo "usuarios.dat"
TListaUsuarios = string[30];
{****************************************************************}
{*************************** PUNTAJES ***************************}
{****************************************************************}
TPuntaje = record
nombre : string; //Nombre del usuario.
puntaje: integer; //Puntaje.
dif: TDificultad; //Dificultad del puntaje obtenido.
end;
//LSE que contiene los usarios
TPunt_TListaPuntajes = ^TListaPuntajes;
TListaPuntajes = record
usuario: TPuntaje;
next: TPunt_TListaPuntajes;
end;
{***************************************************************}
{*************************** ARCHIVO ***************************}
{***************************************************************}
TfileTexto = text; //Archivo "palabras.txt"
TfilePuntajes = file of TPuntaje; //Archivo "puntaje.dat"
TfileUsuarios = file of TListaUsuarios; //Archivo usuarios.dat
TfilePalabra = file of TPalabra; //Archivo "palabras.dat"
{****************************************************************}
TDatosJuego = record
user: TListaUsuarios; //Nombre del usuario actual;
pasPal_rest: integer; // PasaPalabras restantes (1..3).
pasPal_usd: integer; //PasaPalabras usadas en total.
i: integer; //Indice de la rosca.
ronda: integer; //N° de vuelta.
salida: boolean; //Salida de la partida actual.
punt_act: integer; //Puntaje actual.
dif: TDificultad; //Dificultad de la partida actual
correctas: integer; //Cantidad de palabras correctas.
incorrectas: integer; //Cantidad de palabras incorrectas.
end;
implementation
end.
|
unit FIToolkit.Commons.FiniteStateMachine.Consts;
interface
uses
FIToolkit.Localization;
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
implementation
end.
|
unit Unit3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Math, Unit1, Unit2,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm3 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Button2: TButton;
Timer1: TTimer;
Label3: TLabel;
Label4: TLabel;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Edit2KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure Edit2Enter(Sender: TObject);
procedure Edit2Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
DIVIATE_TIME = 1000;
DIVIATE_SPEED = 60;
var
Form3: TForm3;
speed, time, trueTotalSymbols: longint;
smpPhrase, login: string;
smpTime, smpSpeed, smpAvgTotalTime, smpAvgSpeed: longint;
implementation
{$R *.dfm}
procedure TForm3.Button1Click(Sender: TObject);
var
login, phrase: string;
begin
phrase := Form3.Edit2.Text;
phrase := phrase.Trim;
smpPhrase := smpPhrase.Trim;
{
ShowMessage(phrase + '+++' + smpPhrase );
ShowMessage(IntToStr(smpAvgTotalTime) + '+++' + IntToStr(time) );
ShowMessage(IntToStr(smpAvgSpeed) + '+++' + IntToStr(speed) );
}
if (phrase = smpPhrase) then
if (smpAvgTotalTime + DIVIATE_TIME >= time) and
(smpAvgTotalTime - DIVIATE_TIME <= time) then
if (smpAvgSpeed + DIVIATE_SPEED >= speed) and
(smpAvgSpeed - DIVIATE_SPEED <= speed) then
begin
Form2.Show;
Form3.Visible := false;
end else ShowMessage('Личность не установлена! Повторите попытку ввода идентификационной фразы!');
end;
procedure TForm3.Button2Click(Sender: TObject);
begin
Form1.Show;
Form3.Visible := false;
end;
procedure TForm3.Edit1Change(Sender: TObject);
begin
smpPhrase := '';
firstTick := 0;
end;
procedure TForm3.Edit2Click(Sender: TObject);
begin
Form3.Edit2.Clear;
firstTick := 0;
end;
procedure TForm3.Edit2Enter(Sender: TObject);
var
f: string;
begin
login := Form3.Edit1.Text;
f := 'params.' + login.Trim;
if (FileExists(f)) then
begin
if (smpPhrase.IsEmpty) then
begin
AssignFile(input, f); reset(input);
readln(input, smpPhrase);
// readln(smpTime);
// readln(smpSpeed);
readln(input, smpAvgTotalTime);
readln(input, smpAvgSpeed);
CloseFile(input);
//ShowMessage(smpPhrase);
trueTotalSymbols := length(smpPhrase);
Form3.Timer1.Enabled := true;
end;
end else
begin
ShowMessage('Такого пользователя не существует...');
end;
end;
procedure TForm3.Edit2KeyPress(Sender: TObject; var Key: Char);
begin
currentTick := GetTickCount;
if (firstTick = 0) then
begin
Form3.Timer1.Enabled := true;
firstTick := GetTickCount;
end;
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
Form3.Edit1.Clear;
Form3.Edit2.Clear;
smpPhrase := '';
end;
procedure TForm3.FormShow(Sender: TObject);
begin
Form3.Edit1.Clear;
Form3.Edit2.Clear;
smpPhrase := '';
end;
procedure TForm3.Timer1Timer(Sender: TObject);
var
wpm: longint;
diff: extended;
posLastSymb: longint;
begin
currentText := Form3.Edit2.Text;
totalSymbols := length(currentText);
if totalSymbols < 1 then
firstTick := 0;
if totalSymbols = trueTotalSymbols then
Form3.Timer1.Enabled := false;
if ((firstTick > 0) and (firstTick <> currentTick)) then
begin
diff := currentTick - firstTick;
wpm := ceil(totalSymbols / (diff / 1000 / 60));
end else
begin
diff := 0;
wpm := 1;
end;
speed := wpm;
time := ceil(diff);
Form3.Label3.Caption := 'Скорость: ' + IntToStr(speed);
Form3.Label4.Caption := 'Время: ' + IntToStr(time);
end;
end.
|
unit frmMainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls,
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.MSAcc, FireDAC.Phys.MSAccDef, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait, Data.DB,
FireDAC.Comp.UI, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Buttons, DBGrids,
Data.Win.ADODB, Controls, Buttons, Classes, StdCtrls;
type
TfrmMain = class(TForm)
btnOrders: TSpeedButton;
btnSearch: TSpeedButton;
btnMenu: TSpeedButton;
btnWorkers: TSpeedButton;
btnPositions: TSpeedButton;
btnStudents: TSpeedButton;
grboxSecCommands: TGroupBox;
grboxCommonCommands: TGroupBox;
procedure btnOrdersClick(Sender: TObject);
procedure btnSearchClick(Sender: TObject);
procedure btnMenuClick(Sender: TObject);
procedure btnStudentsClick(Sender: TObject);
procedure btnWorkersClick(Sender: TObject);
procedure btnPositionsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
workerIDLog: string;
implementation
{$R *.dfm}
uses
frmOrdersUnit, frmSearchUnit,
frmMenuUnit, frmStudentUnit,
frmWorkerUnit, frmPositionUnit;
function checkWorker(workerID: string) : boolean;
begin
try
frmOrders.FDQuery1.Open('SELECT Slujitel_id FROM Slujiteli where Slujitel_id=' + workerID);
checkWorker := not frmOrders.FDQuery1.Eof;
frmOrders.FDQuery1.Close;
except
checkWorker := false;
end;
end;
procedure TfrmMain.btnMenuClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmMenu.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
procedure TfrmMain.btnOrdersClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmOrders.workerID := workerIDLog;
frmOrders.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
procedure TfrmMain.btnPositionsClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmPositions.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
procedure TfrmMain.btnSearchClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmSearch.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
procedure TfrmMain.btnStudentsClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmStudents.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
procedure TfrmMain.btnWorkersClick(Sender: TObject);
var
isPressedOK: boolean;
begin
workerIDLog := string.Empty;
isPressedOK := InputQuery('Идентификация на служител', 'ID на служител:', workerIDLog);
if isPressedOK then begin
if checkWorker(workerIDLog) then begin
frmWorkers.Show;
end
else begin
MessageDlg('Грешен код!', mtCustom, [mbOK], 0)
end;
end;
end;
end.
|
unit AConfiguracaoECF;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
ExtCtrls, PainelGradiente, Db, Localizacao, DBTables, Tabela, StdCtrls,
Mask, DBCtrls, Buttons, ComCtrls, BotaoCadastro, Componentes1, numericos, UnECF,
DBClient, unSistema;
type
TFConfiguracaoECF = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
CFGECF: TSQL;
DataCFGECF: TDataSource;
localiza: TConsultaPadrao;
CFGECFCODPLANOCONTAS: TWideStringField;
CFGECFCODCLIENTEPADRAO: TFMTBCDField;
CFGECFNUMTIPOECF: TFMTBCDField;
PanelColor1: TPanelColor;
BotaoAlterar1: TBotaoAlterar;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
Fechar: TBitBtn;
PageControl: TPageControl;
PGeral: TTabSheet;
Label1: TLabel;
Label2: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
EClientePadrao: TDBEditLocaliza;
EPlanoContas: TDBEditLocaliza;
ETipoECF: TComboBoxColor;
Label5: TLabel;
PAliquotas: TTabSheet;
LAliquotas: TListBoxColor;
BAdicionar: TBitBtn;
Label6: TLabel;
ENovoAliquota: Tnumerico;
CFGECFCODOPERACAOESTOQUE: TFMTBCDField;
DBEditLocaliza1: TDBEditLocaliza;
Label7: TLabel;
SpeedButton3: TSpeedButton;
Label8: TLabel;
CGeraFinanceiro: TDBCheckBox;
CBaixarEstoque: TDBCheckBox;
CFGECFINDGERAFINANCEIRO: TWideStringField;
CFGECFINDBAIXAESTOQUE: TWideStringField;
CMostrarFormaPagamento: TDBCheckBox;
CFGECFINDFORMAPAGAMENTOCOTACAO: TWideStringField;
CFGECFINDUTILIZAGAVETA: TWideStringField;
CUtilizarGaveta: TDBCheckBox;
CFGECFINDDESCONTOCOTACAO: TWideStringField;
CDescontoCotacaoECF: TDBCheckBox;
CFGECFCODCONDICAOPAGAMENTO: TFMTBCDField;
DBEditLocaliza2: TDBEditLocaliza;
Label9: TLabel;
SpeedButton4: TSpeedButton;
Label10: TLabel;
CFGECFD_ULT_ALT: TSQLTimeStampField;
PanelColor2: TPanelColor;
PanelColor3: TPanelColor;
Label11: TLabel;
EPorta: TComboBoxColor;
CFGECFNUMPORTA: TFMTBCDField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CFGECFAfterEdit(DataSet: TDataSet);
procedure CFGECFAfterPost(DataSet: TDataSet);
procedure ETipoECFChange(Sender: TObject);
procedure FecharClick(Sender: TObject);
procedure BAdicionarClick(Sender: TObject);
procedure CFGECFBeforePost(DataSet: TDataSet);
procedure EPortaChange(Sender: TObject);
private
{ Private declarations }
FunECF : TRBFuncoesECF;
procedure CarregaAliquotas;
public
{ Public declarations }
end;
var
FConfiguracaoECF: TFConfiguracaoECF;
implementation
uses APrincipal, FunSQl, FunObjeto, FunString;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFConfiguracaoECF.FormCreate(Sender: TObject);
begin
FunECF := TRBFuncoesECF.cria(nil,FPrincipal.BaseDados);
AdicionaSQLAbreTabela(CFGECF,'Select * from CFG_ECF ');
PageControl.ActivePageIndex := 0;
IniciallizaCheckBox([CGeraFinanceiro,CBaixarEstoque,CUtilizarGaveta,CMostrarFormaPagamento,CDescontoCotacaoECF], 'T', 'F');
AtualizaLocalizas([EClientePadrao,EPlanoContas]);
ETipoECF.ItemIndex := CFGECFNUMTIPOECF.AsInteger;
ETipoECF.Enabled := false;
EPorta.ItemIndex := CFGECFNUMPORTA.AsInteger;
CarregaAliquotas;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFConfiguracaoECF.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunEcf.free;
CFGECF.close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFConfiguracaoECF.CFGECFAfterEdit(DataSet: TDataSet);
begin
ETipoECF.Enabled := TRUE;
end;
{******************************************************************************}
procedure TFConfiguracaoECF.CFGECFAfterPost(DataSet: TDataSet);
begin
ETipoECF.Enabled := false;
Sistema.MarcaTabelaParaImportar('CFG_ECF');
end;
{******************************************************************************}
procedure TFConfiguracaoECF.CFGECFBeforePost(DataSet: TDataSet);
begin
CFGECFD_ULT_ALT.AsDateTime := Sistema.RDataServidor;
end;
{******************************************************************************}
procedure TFConfiguracaoECF.EPortaChange(Sender: TObject);
begin
if CFGECF.State = dsedit then
CFGECFNUMPORTA.AsInteger := EPorta.ItemIndex;
end;
{******************************************************************************}
procedure TFConfiguracaoECF.ETipoECFChange(Sender: TObject);
begin
if CFGECF.State = dsedit then
CFGECFNUMTIPOECF.AsInteger := ETipoECF.ItemIndex;
end;
{******************************************************************************}
procedure TFConfiguracaoECF.CarregaAliquotas;
var
VpfAliquotas : String;
begin
VpfAliquotas := FunECF.RAliquotas;
while VpfAliquotas <> ''do
begin
LAliquotas.Items.Add(DeletaChars(CopiaAteChar(VpfAliquotas,','),','));
VpfAliquotas := DeleteAteChar(VpfAliquotas,',');
end;
end;
{******************************************************************************}
procedure TFConfiguracaoECF.FecharClick(Sender: TObject);
begin
close;
end;
procedure TFConfiguracaoECF.BAdicionarClick(Sender: TObject);
begin
FunECF.AdicionaAliquotaICMS(ENovoAliquota.Avalor);
LAliquotas.Items.add(ENovoAliquota.Text);
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFConfiguracaoECF]);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: VRMLParser<p>
VRML file format parser.<p>
<b>History :</b><font size=-1><ul>
<li>02/04/07 - DaStr - Added $I GLScene.inc
<li>29/03/07 - DaStr - Added missing parameters in procedure's implementation
(thanks Burkhard Carstens) (Bugtracker ID = 1681409)
<li>25/01/05 - SG - Added ShapeHints (creaseAngle), Normal and TexCoord support
<li>14/01/05 - SG - Added to CVS
</ul></font>
}
unit VRMLParser;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils, System.Types,
//GLS
GLVectorTypes, GLVectorLists, GLUtils;
type
TVRMLNode = class
private
FNodes : TList;
FParent : TVRMLNode;
FName,
FDefName : String;
function GetNode(index : Integer) : TVRMLNode;
public
constructor Create; virtual;
constructor CreateOwned(AParent : TVRMLNode);
destructor Destroy; override;
function Count : Integer;
procedure Clear;
procedure Add(node : TVRMLNode);
procedure Remove(node : TVRMLNode);
procedure Delete(index : Integer);
property Nodes[index : Integer] : TVRMLNode read GetNode; default;
property Parent : TVRMLNode read FParent;
property Name : String read FName write FName;
property DefName : String read FDefName write FDefName;
end;
TVRMLSingleArray = class (TVRMLNode)
private
FValues : TSingleList;
public
constructor Create; override;
destructor Destroy; override;
property Values : TSingleList read FValues;
end;
TVRMLIntegerArray = class (TVRMLNode)
private
FValues : TIntegerList;
public
constructor Create; override;
destructor Destroy; override;
property Values : TIntegerList read FValues;
end;
TVRMLMaterial = class (TVRMLNode)
private
FDiffuseColor,
FAmbientColor,
FSpecularColor,
FEmissiveColor : TVector3f;
FTransparency,
FShininess : Single;
FHasDiffuse,
FHasAmbient,
FHasSpecular,
FHasEmissive,
FHasTransparency,
FHasShininess : Boolean;
public
constructor Create; override;
property DiffuseColor : TVector3f read FDiffuseColor write FDiffuseColor;
property AmbientColor : TVector3f read FAmbientColor write FAmbientColor;
property SpecularColor : TVector3f read FSpecularColor write FSpecularColor;
property EmissiveColor : TVector3f read FEmissiveColor write FEmissiveColor;
property Transparency : Single read FTransparency write FTransparency;
property Shininess : Single read FShininess write FShininess;
property HasDiffuse : Boolean read FHasDiffuse write FHasDiffuse;
property HasAmbient : Boolean read FHasAmbient write FHasAmbient;
property HasSpecular : Boolean read FHasSpecular write FHasSpecular;
property HasEmissive : Boolean read FHasEmissive write FHasEmissive;
property HasTransparency : Boolean read FHasTransparency write FHasTransparency;
property HasShininess : Boolean read FHasShininess write FHasShininess;
end;
TVRMLUse = class (TVRMLNode)
private
FValue : String;
public
property Value : String read FValue write FValue;
end;
TVRMLShapeHints = class (TVRMLNode)
private
FCreaseAngle : Single;
public
property CreaseAngle : Single read FCreaseAngle write FCreaseAngle;
end;
TVRMLTransform = class (TVRMLNode)
private
FCenter : TVector3f;
FRotation : TVector4f;
FScaleFactor : TVector3f;
public
constructor Create; override;
property Center : TVector3f read FCenter write FCenter;
property Rotation : TVector4f read FRotation write FRotation;
property ScaleFactor : TVector3f read FScaleFactor write FScaleFactor;
end;
TVRMLParser = class
private
FCursor : Integer;
FTokens : TStringList;
FRootNode : TVRMLNode;
FCurrentNode : TVRMLNode;
FAllowUnknownNodes : Boolean;
FDefines : TList;
protected
function ReadToken : String;
function ReadSingle : Single;
function ReadVector3f : TVector3f;
function ReadVector4f : TVector4f;
procedure ReadUnknownArray(defname : String = '');
procedure ReadUnknownHeirachy(defname : String = '');
procedure ReadUnknown(unknown_token : String; defname : String = '');
procedure ReadPointArray(defname : String = '');
procedure ReadCoordIndexArray(defname : String = '');
procedure ReadNormalIndexArray(defname : String = '');
procedure ReadTextureCoordIndexArray(defname : String = '');
procedure ReadCoordinate3(defname : String = '');
procedure ReadNormal(defname : String = '');
procedure ReadTextureCoordinate2(defname : String = '');
procedure ReadMaterial(defname : String = '');
procedure ReadIndexedFaceSet(defname : String = '');
procedure ReadTransform(defname : String = '');
procedure ReadShapeHints(defname : String = '');
procedure ReadSeparator(defname : String = '');
procedure ReadGroup(defname : String = '');
procedure ReadDef;
procedure ReadUse;
public
constructor Create;
destructor Destroy; override;
procedure Parse(Text : String);
property RootNode : TVRMLNode read FRootNode;
property AllowUnknownNodes : Boolean read FAllowUnknownNodes write FAllowUnknownNodes;
end;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
implementation
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
function CreateVRMLTokenList(Text : String) : TStringList;
const
cSymbols : array[0..3] of char = ( '{','}','[',']' );
var
i,j,p : Integer;
str, token : String;
begin
Result:=TStringList.Create;
Result.Text:=Text;
for i:=0 to Result.Count-1 do begin
p:=Pos('#', Result[i]);
if p>0 then
Result[i]:=Copy(Result[i], 1, p-1);
end;
Result.CommaText:=Result.Text;
for j:=0 to Length(cSymbols)-1 do begin
i:=0;
repeat
token:=Result[i];
p:=Pos(cSymbols[j], token);
if (p>0) and (token<>cSymbols[j]) then begin
str:=Copy(token, p+1, Length(token)-p);
if (p = 1) then begin
Result.Delete(i);
Result.Insert(i, trim(str));
Result.Insert(i, cSymbols[j]);
end else begin
Result.Delete(i);
if Length(str)>0 then
Result.Insert(i, trim(str));
Result.Insert(i, cSymbols[j]);
Result.Insert(i, trim(Copy(token, 1, p-1)));
end;
end;
Inc(i);
until i >= Result.Count-1;
end;
end;
// ---------------
// --------------- TVRMLNode ---------------
// ---------------
// Create
//
constructor TVRMLNode.Create;
begin
FNodes:=TList.Create;
end;
// CreateOwned
//
constructor TVRMLNode.CreateOwned(AParent : TVRMLNode);
begin
Create;
if Assigned(AParent) then
AParent.Add(Self);
end;
// Destroy
//
destructor TVRMLNode.Destroy;
begin
Clear;
FNodes.Free;
inherited;
end;
// GetNode
//
function TVRMLNode.GetNode(index : Integer) : TVRMLNode;
begin
Result:=TVRMLNode(FNodes[index]);
end;
// Count
//
function TVRMLNode.Count : Integer;
begin
Result:=FNodes.Count;
end;
// Clear
//
procedure TVRMLNode.Clear;
begin
while FNodes.Count>0 do
Delete(0);
end;
// Add
//
procedure TVRMLNode.Add(node : TVRMLNode);
begin
if not Assigned(node) then exit;
if Assigned(node.Parent) then
node.Parent.FNodes.Remove(node);
FNodes.Add(node);
node.FParent:=Self;
end;
// Remove
//
procedure TVRMLNode.Remove(node : TVRMLNode);
begin
if not Assigned(node) then exit;
FNodes.Remove(node);
node.Free;
end;
// Delete
//
procedure TVRMLNode.Delete(index : Integer);
begin
if (index<0) or (index>=Count) then exit;
Nodes[index].Free;
FNodes.Delete(index);
end;
// ---------------
// --------------- TVRMLSingleArray ---------------
// ---------------
// Create
//
constructor TVRMLSingleArray.Create;
begin
inherited;
FValues:=TSingleList.Create;
end;
// Destroy
//
destructor TVRMLSingleArray.Destroy;
begin
FValues.Free;
inherited;
end;
// ---------------
// --------------- TVRMLIntegerArray ---------------
// ---------------
// Create
//
constructor TVRMLIntegerArray.Create;
begin
inherited;
FValues:=TIntegerList.Create;
end;
// Destroy
//
destructor TVRMLIntegerArray.Destroy;
begin
FValues.Free;
inherited;
end;
// ---------------
// --------------- TVRMLMaterial ---------------
// ---------------
// Create
//
constructor TVRMLMaterial.Create;
begin
inherited;
// Default shininess value
FHasDiffuse:=False;
FHasAmbient:=False;
FHasSpecular:=False;
FHasEmissive:=False;
FHasTransparency:=False;
FHasShininess:=False;
end;
// ---------------
// --------------- TVRMLTransform ---------------
// ---------------
// Create
//
constructor TVRMLTransform.Create;
begin
inherited;
FScaleFactor.V[0]:=1;
FScaleFactor.V[1]:=1;
FScaleFactor.V[2]:=1;
end;
// ---------------
// --------------- TVRMLParser ---------------
// ---------------
// Create
//
constructor TVRMLParser.Create;
begin
FDefines:=TList.Create;
FRootNode:=TVRMLNode.Create;
FRootNode.Name:='Root';
FAllowUnknownNodes:=False;
end;
// Destroy
//
destructor TVRMLParser.Destroy;
begin
FDefines.Free;
FRootNode.Free;
inherited;
end;
// ReadToken
//
function TVRMLParser.ReadToken : String;
begin
if FCursor<FTokens.Count then begin
Result:=LowerCase(FTokens[FCursor]);
Inc(FCursor);
end else
Result:='';
end;
// ReadUnknownArray
//
procedure TVRMLParser.ReadUnknownArray(defname : String );
var
token : String;
begin
if AllowUnknownNodes then begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Unknown array';
end;
repeat
token:=ReadToken;
if token = '' then
exit;
until token = ']';
if AllowUnknownNodes then
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadUnknownHeirachy
//
procedure TVRMLParser.ReadUnknownHeirachy(defname : String );
var
token : String;
begin
if AllowUnknownNodes then begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Unknown heirachy';
end;
repeat
token:=ReadToken;
if token = '' then
exit
else
ReadUnknown(token);
until token = '}';
if AllowUnknownNodes then
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadUnknown
//
procedure TVRMLParser.ReadUnknown(unknown_token : String; defname : String);
begin
if unknown_token = '{' then
ReadUnknownHeirachy
else if unknown_token = '[' then
ReadUnknownArray
else if (unknown_token<>'}') and (unknown_token<>']') and AllowUnknownNodes then begin
TVRMLNode.CreateOwned(FCurrentNode).Name:='UNKNOWN['+unknown_token+']';
end;
end;
// ReadSingle
//
function TVRMLParser.ReadSingle : Single;
begin
Result:=GLUtils.StrToFloatDef(ReadToken,0);
end;
// ReadVector3f
//
function TVRMLParser.ReadVector3f : TVector3f;
begin
Result.V[0]:=ReadSingle;
Result.V[1]:=ReadSingle;
Result.V[2]:=ReadSingle;
end;
// ReadVector4f
//
function TVRMLParser.ReadVector4f : TVector4f;
begin
Result.V[0]:=ReadSingle;
Result.V[1]:=ReadSingle;
Result.V[2]:=ReadSingle;
Result.V[3]:=ReadSingle;
end;
// ReadPointArray
//
procedure TVRMLParser.ReadPointArray(defname : String );
var
token : String;
begin
FCurrentNode:=TVRMLSingleArray.CreateOwned(FCurrentNode);
FCurrentNode.Name:='PointArray';
repeat
token:=ReadToken;
if token = '' then exit;
until token = '[';
repeat
token:=ReadToken;
if token = '' then
exit
else if token <> ']' then
TVRMLSingleArray(FCurrentNode).Values.Add(GLUtils.StrToFloatDef(token,0));
until token = ']';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadCoordIndexArray
//
procedure TVRMLParser.ReadCoordIndexArray(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLIntegerArray.CreateOwned(FCurrentNode);
FCurrentNode.Name:='CoordIndexArray';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '[';
repeat
token:=ReadToken;
if token = '' then
exit
else if token <> ']' then
TVRMLIntegerArray(FCurrentNode).Values.Add(StrToInt(token));
until token = ']';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadNormalIndexArray
//
procedure TVRMLParser.ReadNormalIndexArray(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLIntegerArray.CreateOwned(FCurrentNode);
FCurrentNode.Name:='NormalIndexArray';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '[';
repeat
token:=ReadToken;
if token = '' then
exit
else if token <> ']' then
TVRMLIntegerArray(FCurrentNode).Values.Add(StrToInt(token));
until token = ']';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadTextureCoordIndexArray
//
procedure TVRMLParser.ReadTextureCoordIndexArray(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLIntegerArray.CreateOwned(FCurrentNode);
FCurrentNode.Name:='TextureCoordIndexArray';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '[';
repeat
token:=ReadToken;
if token = '' then
exit
else if token <> ']' then
TVRMLIntegerArray(FCurrentNode).Values.Add(StrToInt(token));
until token = ']';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadMaterial
//
procedure TVRMLParser.ReadMaterial(defname : String);
var
token : String;
begin
FCurrentNode:=TVRMLMaterial.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Material';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
with TVRMLMaterial(FCurrentNode) do begin
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'diffusecolor' then begin
DiffuseColor:=ReadVector3f;
HasDiffuse:=True;
end else if token = 'ambientcolor' then begin
AmbientColor:=ReadVector3f;
HasAmbient:=True;
end else if token = 'specularcolor' then begin
SpecularColor:=ReadVector3f;
HasSpecular:=True;
end else if token = 'emissivecolor' then begin
EmissiveColor:=ReadVector3f;
HasEmissive:=True;
end else if token = 'transparency' then begin
Transparency:=ReadSingle;
HasTransparency:=True;
end else if token = 'shininess' then begin
Shininess:=ReadSingle;
HasShininess:=True;
end else if token<>'}' then
ReadUnknown(token);
until token = '}';
end;
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadCoordinate3
//
procedure TVRMLParser.ReadCoordinate3(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Coordinate3';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'point' then
ReadPointArray
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadNormal
//
procedure TVRMLParser.ReadNormal(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Normal';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'vector' then
ReadPointArray
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadTextureCoordinate2
//
procedure TVRMLParser.ReadTextureCoordinate2(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='TextureCoordinate2';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'point' then
ReadPointArray
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadIndexedFaceSet
//
procedure TVRMLParser.ReadIndexedFaceSet(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='IndexedFaceSet';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'coordindex' then
ReadCoordIndexArray
else if token = 'normalindex' then
ReadNormalIndexArray
else if token = 'texturecoordindex' then
ReadTextureCoordIndexArray
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadTransform
//
procedure TVRMLParser.ReadTransform(defname : String);
var
token : String;
begin
FCurrentNode:=TVRMLTransform.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Transform';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
with TVRMLTransform(FCurrentNode) do begin
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'rotation' then
Rotation:=ReadVector4f
else if token = 'center' then
Center:=ReadVector3f
else if token = 'scalefactor' then
ScaleFactor:=ReadVector3f
else if token<>'}' then
ReadUnknown(token);
until token = '}';
end;
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadShapeHints
//
procedure TVRMLParser.ReadShapeHints(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLShapeHints.CreateOwned(FCurrentNode);
FCurrentNode.Name:='ShapeHints';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'creaseangle' then
TVRMLShapeHints(FCurrentNode).CreaseAngle:=ReadSingle
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadSeparator
//
procedure TVRMLParser.ReadSeparator(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Separator';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'def' then
ReadDef
else if (token = 'group') or (token = 'switch') then
ReadGroup
else if token = 'separator' then
ReadSeparator
else if token = 'use' then
ReadUse
else if token = 'shapehints' then
ReadShapeHints
else if token = 'transform' then
ReadTransform
else if token = 'material' then
ReadMaterial
else if token = 'coordinate3' then
ReadCoordinate3
else if token = 'normal' then
ReadNormal
else if token = 'texturecoordinate2' then
ReadTextureCoordinate2
else if token = 'indexedfaceset' then
ReadIndexedFaceSet
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadGroup
//
procedure TVRMLParser.ReadGroup(defname : String = '');
var
token : String;
begin
FCurrentNode:=TVRMLNode.CreateOwned(FCurrentNode);
FCurrentNode.Name:='Group';
FCurrentNode.DefName:=defname;
repeat
token:=ReadToken;
if token = '' then exit;
until token = '{';
repeat
token:=ReadToken;
if token = '' then
exit
else if token = 'def' then
ReadDef
else if (token = 'group') or (token = 'switch') then
ReadGroup
else if token = 'separator' then
ReadSeparator
else if token = 'use' then
ReadUse
else if token = 'shapehints' then
ReadShapeHints
else if token = 'transform' then
ReadTransform
else if token = 'material' then
ReadMaterial
else if token = 'coordinate3' then
ReadCoordinate3
else if token = 'indexedfaceset' then
ReadIndexedFaceSet
else if token<>'}' then
ReadUnknown(token);
until token = '}';
FCurrentNode:=FCurrentNode.Parent;
end;
// ReadDef
//
procedure TVRMLParser.ReadDef;
var
defname, token : String;
begin
defname:=ReadToken;
token:=ReadToken;
if (token = 'group') or (token = 'switch') then
ReadGroup(defname)
else if token = 'separator' then
ReadSeparator(defname)
else if token = 'transform' then
ReadTransform(defname)
else if token = 'material' then
ReadMaterial(defname)
else if token = 'coordinate3' then
ReadCoordinate3(defname)
else if token = 'indexedfaceset' then
ReadIndexedFaceSet(defname)
else
ReadUnknown(token);
end;
// ReadUse
//
procedure TVRMLParser.ReadUse;
begin
with TVRMLUse.CreateOwned(FCurrentNode) do begin
name:='Use';
Value:=ReadToken;
end;
end;
// Parse
//
procedure TVRMLParser.Parse(Text : String);
var
token : String;
begin
FTokens:=CreateVRMLTokenList(Text);
FCursor:=0;
FCurrentNode:=FRootNode;
try
repeat
token:=ReadToken;
if token = 'def' then
ReadDef
else if (token = 'group') or (token = 'switch') then
ReadGroup
else if token = 'separator' then
ReadSeparator
else if token = 'use' then
ReadUse
else if token = 'shapehints' then
ReadShapeHints
else if token = 'transform' then
ReadTransform
else if token = 'material' then
ReadMaterial
else if token = 'coordinate3' then
ReadCoordinate3
else if token = 'indexedfaceset' then
ReadIndexedFaceSet
else
ReadUnknown(token);
until FCursor>=FTokens.Count;
finally
FTokens.Free;
end;
end;
end.
|
unit VCLVirtualKeyingForm;
interface
uses
WinApi.Windows, WinApi.Messages, System.SysUtils, System.Classes, System.UITypes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls,
CCR.VirtualKeying;
type
TForm1 = class(TForm)
lblCharsToType: TLabel;
edtCharsToType: TEdit;
btnTypeInEdit: TButton;
btnTypeIn10Secs: TButton;
edtTarget: TEdit;
btnDoAppExitHotkey: TButton;
tmrType: TTimer;
procedure btnTypeInEditClick(Sender: TObject);
procedure btnTypeIn10SecsClick(Sender: TObject);
procedure btnDoAppExitHotkeyClick(Sender: TObject);
procedure tmrTypeTimer(Sender: TObject);
strict private
FCountdown: Integer;
FDoneTypeIn10SecsMsg: Boolean;
FSequenceToTypeOnTimer: IVirtualKeySequence;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
resourcestring
STypeIn10SecsMsg = '10 seconds after you click OK, whatever is the active window will have ''' +
'%s'' typed into it - try bringing up Notepad or TextEdit, for example.';
procedure TForm1.btnTypeInEditClick(Sender: TObject);
begin
edtTarget.SetFocus;
TVirtualKeySequence.Execute(edtCharsToType.Text);
end;
procedure TForm1.btnDoAppExitHotkeyClick(Sender: TObject);
begin
TVirtualKeySequence.Execute(ShortCut(VK_F4, [ssAlt]));
end;
procedure TForm1.btnTypeIn10SecsClick(Sender: TObject);
begin
if not FDoneTypeIn10SecsMsg then
begin
FDoneTypeIn10SecsMsg := True;
MessageDlg(Format(STypeIn10SecsMsg, [edtCharsToType.Text]), TMsgDlgType.mtInformation,
[TMsgDlgBtn.mbOK], 0);
end;
FSequenceToTypeOnTimer := TVirtualKeySequence.Create;
FSequenceToTypeOnTimer.AddKeyPresses(edtCharsToType.Text);
FCountdown := 11;
tmrTypeTimer(nil);
tmrType.Enabled := True;
end;
procedure TForm1.tmrTypeTimer(Sender: TObject);
begin
Dec(FCountdown);
if FCountdown > 0 then
Caption := Format('%ds to go...', [FCountdown])
else
begin
tmrType.Enabled := False;
FSequenceToTypeOnTimer.Execute;
FSequenceToTypeOnTimer := nil;
Caption := 'Typed!'
end
end;
end.
|
unit uFrmMain;
interface
uses
System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls,
Vcl.Forms, Vcl.Dialogs, uTelegramAPI, uTelegramAPI.Interfaces, uConsts,
Vcl.StdCtrls, uClassMessageDTO, Vcl.ExtCtrls, Vcl.Buttons, System.IOUtils;
type
TForm1 = class(TForm)
BtnSendFile: TButton;
EdtTokenBot: TEdit;
Memo1: TMemo;
BtnSendMsg: TButton;
BtnSendWithButtons: TButton;
Button1: TButton;
BtnSendLocation: TButton;
Button2: TButton;
SpeedButton1: TSpeedButton;
EdtUserId: TEdit;
Label1: TLabel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure BtnSendFileClick(Sender: TObject);
procedure BtnSendMsgClick(Sender: TObject);
procedure BtnSendWithButtonsClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure BtnSendLocationClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
FTelegram: iTelegramAPI;
FAsyncHttp: TThread;
procedure OnAPIError(AExcept: Exception);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
EdtTokenBot.Text := 'YOUR_API_TOKEN_HERE';
// use the button "getUpdates" for get chats IDs(only messages sent to your bot)
EdtUserId.Text := 'USERID_FOR_SEND_MESSAGES';
FTelegram := TTelegramAPI.New();
FTelegram
.OnError(OnAPIError)
.SetUserID(EdtUserId.Text)
.SetBotToken(EdtTokenBot.Text);
Memo1.Clear;
end;
procedure TForm1.BtnSendFileClick(Sender: TObject);
begin
FTelegram.SendFile('C:\File.zip');
Memo1.Text := FTelegram.GetResult();
end;
procedure TForm1.BtnSendMsgClick(Sender: TObject);
begin
FTelegram.SendMsg('Hey there!');
Memo1.Text := FTelegram.GetResult();
end;
procedure TForm1.BtnSendWithButtonsClick(Sender: TObject);
var
pButtons: TTelegramButtons;
begin
pButtons := TTelegramButtons.Create;
with pButtons do
begin
Add('Lamp 1 Off', 'https://domain.com/lamp1/off');
Add('Lamp 1 On', 'https://domain.com/lamp1/on');
Add('Lamp 2 Off', 'https://domain.com/lamp2/off');
Add('Lamp 2 On', 'https://domain.com/lamp2/on');
end;
FTelegram.SendMsgWithButtons('Hi!', pButtons);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
pChatList: TChatMessageDTOList;
pChat: TChatMessageDTO;
begin
pChatList := TChatMessageDTOList.Create;
pChat := TChatMessageDTO.Create;
FTelegram.GetUpdates(pChatList);
for pChat in pChatList do
ShowMessage(pChat.Message.Text + ' - ' + pChat.Message.From.Id.ToString);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if not Assigned(FAsyncHttp) then
begin
FAsyncHttp := TThread.CreateAnonymousThread(
procedure
var
pChatList: TChatMessageDTOList;
begin
pChatList := TChatMessageDTOList.Create;
while True do
begin
pChatList.Clear;
FTelegram.GetUpdates(pChatList);
FAsyncHttp.Synchronize(FAsyncHttp,
procedure
var
pChat: TChatMessageDTO;
begin
Memo1.Lines.Clear;
Memo1.Lines.Add('-' + TimeToStr(Now()));
for pChat in pChatList do
Memo1.Lines.Add(pChat.Message.Text);
Memo1.Lines.Add('-');
end);
FAsyncHttp.Sleep(5000);
end;
end);
FAsyncHttp.Start();
end;
end;
procedure TForm1.BtnSendLocationClick(Sender: TObject);
begin
FTelegram.SendLocation('51.519138', '-0.129028');
end;
procedure TForm1.OnAPIError(AExcept: Exception);
begin
TThread.Synchronize(TThread.Current, procedure
begin
MessageDlg(AExcept.Message, mtWarning, [mbOK], 0);
end);
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
FTelegram.SetBotToken(EdtTokenBot.Text);
FTelegram.SetUserID(EdtUserId.Text);
end;
end.
|
unit GRUPO;
interface
uses
Classes,
DB,
SysUtils,
Generics.Collections,
ormbr.mapping.attributes,
ormbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
ormbr.mapping.register, PRODUTO;
type
[Entity]
[Table('GRUPO','')]
[PrimaryKey('ID', AutoInc, NoSort, True, 'Chave primária')]
TGRUPO = class
private
FID: Integer;
FGRUPA60DESCR: String;
fProdutos: TObjectList<TPRODUTO>;
{ Private declarations }
public
constructor create;
destructor destroy; override;
{ Public declarations }
[Restrictions([NoUpdate, NotNull])]
[Column('GRUPICOD', ftInteger)]
//[Dictionary('GRUPICOD','Mensagem de validação','','','',taCenter)]
property id: Integer read FID write FID;
[Column('GRUPA60DESCR', ftString)]
property GRUPA60DESCR:String read FGRUPA60DESCR write FGRUPA60DESCR;
[Restrictions([NoValidate])]
property Produtos: TObjectList<TPRODUTO> read fProdutos write fProdutos;
end;
implementation
constructor TGRUPO.create;
begin
fProdutos := TObjectList<TPRODUTO>.Create;
end;
destructor TGRUPO.destroy;
begin
fProdutos.Free;
inherited;
end;
initialization
TRegisterClass.RegisterEntity(TGRUPO);
end.
|
unit WebService.Consumir;
interface
uses
Soap.SOAPHTTPTrans, System.Classes;
type
IConsumirWS = interface
['{B36C8BDA-FDF9-4167-B5A5-BE339ADEDDDC}']
procedure SetURL(const Value: string);
procedure SetUsername(const Value: string);
procedure SetPassword(const Value: string);
procedure SetAction(const Value: string);
procedure SetContentHeader(const Value: string);
procedure SetSendTimeOut(const Value: Integer);
procedure SetReceiveTimeOut(const Value: Integer);
procedure SetUTF8inHeader(const Value: Boolean);
procedure ContentHeaderBeforePost(const HTTPReqResp: THTTPReqResp; Data: Pointer);
procedure setProperties();
function Post(const pRequest: string): string;
function Get(): string;
property URL: string write SetURL;
property Username: string write SetUsername;
property Password: string write SetPassword;
property Action: string write SetAction;
property ContentHeader: string write SetContentHeader;
property SendTimeOut: Integer write SetSendTimeOut;
property ReceiveTimeOut: Integer write SetReceiveTimeOut;
property UTF8inHeader: Boolean write SetUTF8inHeader;
end;
TConsumirWS = class(TInterfacedObject, IConsumirWS)
private
FAction: string;
FURL: string;
FContentHeader: string;
FUsername: string;
FPassword: string;
FUTF8inHeader: Boolean;
FSendTimeOut: Integer;
FReceiveTimeOut: Integer;
FReqResp: THTTPReqResp;
procedure SetURL(const Value: string);
procedure SetAction(const Value: string);
procedure SetContentHeader(const Value: string);
procedure SetReceiveTimeOut(const Value: Integer);
procedure SetSendTimeOut(const Value: Integer);
procedure SetUTF8inHeader(const Value: Boolean);
procedure SetPassword(const Value: string);
procedure SetUsername(const Value: string);
protected
procedure ContentHeaderBeforePost(const HTTPReqResp: THTTPReqResp; Data: Pointer);
public
procedure setProperties();
function Post(const pRequest: string): string;
function Get(): string;
class function new(AOwner: TComponent): IConsumirWS;
property URL: string write SetURL;
property Action: string write SetAction;
property ContentHeader: string write SetContentHeader;
property SendTimeOut: Integer write SetSendTimeOut;
property ReceiveTimeOut: Integer write SetReceiveTimeOut;
property UTF8inHeader: Boolean write SetUTF8inHeader;
property Username: string write SetUsername;
property Password: string write SetPassword;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils, Winapi.WinInet, System.StrUtils;
{ TConsumirWS }
constructor TConsumirWS.Create(AOwner: TComponent);
begin
FReqResp := THTTPReqResp.Create(AOwner);
SendTimeOut := 60000;
ReceiveTimeOut := 60000;
URL := EmptyStr;
Action := EmptyStr;
ContentHeader := EmptyStr;
UTF8inHeader := True;
FUsername := EmptyStr;
FPassword := EmptyStr;
end;
destructor TConsumirWS.Destroy;
begin
FreeAndNil(FReqResp);
inherited;
end;
class function TConsumirWS.new(AOwner: TComponent): IConsumirWS;
begin
Result := Self.Create(AOwner);
end;
function TConsumirWS.Post(const pRequest: string): string;
var
request, response: TStringStream;
begin
request := TStringStream.Create;
response := TStringStream.Create;
try
try
request.WriteString(pRequest);
setProperties();
FReqResp.Execute(request, response);
Result := response.DataString;
except
on E: ESOAPHTTPException do
raise Exception.Create(E.Message);
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
FreeAndNil(request);
FreeAndNil(response);
end;
end;
function TConsumirWS.Get(): string;
var
response: TStringStream;
begin
response := TStringStream.Create('', TEncoding.UTF8);
try
try
setProperties();
FReqResp.Get(response);
Result := response.DataString;
except
on E: ESOAPHTTPException do
raise Exception.Create(E.Message);
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
FreeAndNil(response);
end;
end;
procedure TConsumirWS.SetAction(const Value: string);
begin
FAction := Value;
end;
procedure TConsumirWS.SetContentHeader(const Value: string);
begin
FContentHeader := Value;
end;
procedure TConsumirWS.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TConsumirWS.setProperties();
begin
FReqResp.URL := FURL;
FReqResp.UserName := FUsername;
FReqResp.Password := FPassword;
FReqResp.SoapAction := FAction;
FReqResp.UseUTF8InHeader := FUTF8inHeader;
FReqResp.SendTimeout := FSendTimeOut;
FReqResp.ReceiveTimeout := FReceiveTimeOut;
FReqResp.InvokeOptions := [soNoValueForEmptySOAPAction, soNoSOAPActionHeader, soPickFirstClientCertificate];
if FContentHeader <> EmptyStr then
FReqResp.OnBeforePost := ContentHeaderBeforePost;
end;
procedure TConsumirWS.SetReceiveTimeOut(const Value: Integer);
begin
FReceiveTimeOut := Value;
end;
procedure TConsumirWS.SetSendTimeOut(const Value: Integer);
begin
FSendTimeOut := Value;
end;
procedure TConsumirWS.SetURL(const Value: string);
begin
FURL := Value;
end;
procedure TConsumirWS.SetUsername(const Value: string);
begin
FUsername := Value;
end;
procedure TConsumirWS.SetUTF8inHeader(const Value: Boolean);
begin
FUTF8inHeader := Value;
end;
procedure TConsumirWS.ContentHeaderBeforePost(const HTTPReqResp: THTTPReqResp; Data: Pointer);
begin
try
HttpAddRequestHeaders(Data, PChar(FContentHeader), length(FContentHeader), HTTP_ADDREQ_FLAG_REPLACE);
HTTPReqResp.CheckContentType;
except
on e: Exception do
raise Exception.Create('Falha ao montar HEADER da requisição. Motivo: ' + e.Message);
end;
end;
end.
|
unit uWSEndereco;
interface
uses System.Classes, System.SysUtils, REST.Json, uRestApp, System.JSON;
const
cEndServico : string = 'https://viacep.com.br';
type TWSEndereco = class
private
Flogradouro: string;
Fibge: string;
Fbairro: string;
Fuf: string;
Fcep: string;
Flocalidade: string;
Funidade: string;
Fcomplemento: string;
Fgia: string;
procedure Setbairro(const Value: string);
procedure Setcep(const Value: string);
procedure Setcomplemento(const Value: string);
procedure Setgia(const Value: string);
procedure Setibge(const Value: string);
procedure Setlocalidade(const Value: string);
procedure Setlogradouro(const Value: string);
procedure Setuf(const Value: string);
procedure Setunidade(const Value: string);
public
property cep : string read Fcep write Setcep;
property logradouro : string read Flogradouro write Setlogradouro;
property complemento : string read Fcomplemento write Setcomplemento;
property bairro : string read Fbairro write Setbairro;
property localidade : string read Flocalidade write Setlocalidade;
property uf : string read Fuf write Setuf;
property unidade : string read Funidade write Setunidade;
property ibge : string read Fibge write Setibge;
property gia : string read Fgia write Setgia;
end;
type TRestConsultaEndereco = class
public
class function buscaEndereco(ACep: String): TWSEndereco;
end;
implementation
{ TWSEndereco }
procedure TWSEndereco.Setbairro(const Value: string);
begin
Fbairro := Value;
end;
procedure TWSEndereco.Setcep(const Value: string);
begin
Fcep := Value;
end;
procedure TWSEndereco.Setcomplemento(const Value: string);
begin
Fcomplemento := Value;
end;
procedure TWSEndereco.Setgia(const Value: string);
begin
Fgia := Value;
end;
procedure TWSEndereco.Setibge(const Value: string);
begin
Fibge := Value;
end;
procedure TWSEndereco.Setlocalidade(const Value: string);
begin
Flocalidade := Value;
end;
procedure TWSEndereco.Setlogradouro(const Value: string);
begin
Flogradouro := Value;
end;
procedure TWSEndereco.Setuf(const Value: string);
begin
Fuf := Value;
end;
procedure TWSEndereco.Setunidade(const Value: string);
begin
Funidade := Value;
end;
{ TRestConsultaEndereco }
class function TRestConsultaEndereco.buscaEndereco(ACep: String): TWSEndereco;
var
restApi : TRestApp;
jsonRetorno : TJSONObject;
begin
try
result := TWSEndereco.Create;
restApi := TRestApp.create;
restApi.host := cEndServico;
restApi.service := 'ws/' + ACep + '/json';
jsonRetorno := TJSONObject( restApi.executarServico);
TJson.JsonToObject(Result, jsonRetorno, []);
finally
FreeAndNil(restApi);
end;
end;
end.
|
unit uSqlFormat_DB2;
interface
uses
uSQLFormat_a, uSQLFormat_c, uAbstractProcessor, uMd, Db;
type
TSQLFormat_DB2 = class(TSQLFormat_c)
public
function getVal(AField: TAbstractDataRow; AIdx: integer): string; override;
function getEqOp(AMetaField: TMetaField): string; override;
function getDDLFieldIdent(AField: PMetaField): string; override;
function getDMLFieldIdent(AField: PMetaField): string; override;
function getDataTypeString(AType: TFieldType; ASize: integer): string; override;
function getSymCommentBegin: string; override;
function getSymCommentEnd: string; override;
function get1LineComment: string; override;
end;
implementation
uses
uWriterConst_h, uDFDB2WriterConst_h, uWriterTypes_h,
uWriterUtils, uDB2TableAccess,
uCustomTableAccess,
uSQLFormatUtil, uKrnl_r, SysUtils;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.getVal(AField: TAbstractDataRow; AIdx: integer): string;
var
lChr: char;
lFormats: TFormatSettings;
begin
// no inherited (abstract)
CheckFieldsAccess(AField, AIdx);
case AField.MetaField[AIdx].DataType of
dtString: Result := AnsiQuotedStr(AField.StringValue[AIdx], CHyphen);
dtInteger: Result := IntToStr(AField.IntValue[AIdx]);
dtDouble: //B2923
begin
lFormats.DecimalSeparator := CDecimalSeparator_dot;
Result := FloatToStr(AField.FloatValue[AIdx], lFormats);
end;
dtChar:
begin
lChr := AField.CharValue[AIdx];
if lChr = #0 then
Result := AnsiQuotedStr('', CHyphen)
else
Result := AnsiQuotedStr(lChr, CHyphen);
end;
dtBoolean:
if AField.BoolValue[AIdx] then
Result := IntToStr(CTrue_DbIntMapping)
else
Result := IntToStr(CFalse_DbIntMapping);
dtDate: Result := Format('DATE(%s)',
[AnsiQuotedStr(getAnsiDateStr(AField.DateValue[AIdx]), CHyphen)]);
dtTime: Result := Format('TIME(%s)', //B2923
[AnsiQuotedStr(FormatDateTime(CDb2TimeFormatString, AField.TimeValue[AIdx]), CHyphen)]);
dtDateTime: Result := Format('TIMESTAMP(%s)', //B2923
[AnsiQuotedStr(FormatDateTime(CDb2TimeStampFormatString, AField.DateTimeValue[AIdx]), CHyphen)]);
dtInt64: Result := IntToStr(AField.Int64Value[AIdx]);
else
raise EWriterIntern.Fire(self, 'Type not supported');
end;
end;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.getDDLFieldIdent(AField: PMetaField): string;
begin
// no inherited (abstract)
checkAssigned(AField);
Result := TDB2TableAccess.getDbAttribStr(AField^.Identifier);
end;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.getDMLFieldIdent(AField: PMetaField): string;
begin
// no inherited (abstract)
checkAssigned(AField);
Result := AField^.Identifier;
end;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.getDataTypeString(AType: TFieldType; ASize: integer): string;
begin
// no inherited (abstract)
case AType of
ftSmallInt: Result := 'SMALLINT';
ftInteger: Result := 'INTEGER';
ftWord: Result := 'INTEGER';
ftLargeInt: Result := 'DEC(19,0)';
ftBoolean: Result := 'SMALLINT';
ftAutoInc: Result := 'INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY'; // no CYCLE attribute here, would violate identity (2005-01-01)
...
ftDate: Result := 'DATE';
ftTime: Result := 'TIME';
ftDateTime, ftTimeStamp: Result := 'TIMESTAMP';
ftBlob: Result := 'BLOB'; //the length/size doesn't need to be specified
...
else
raise EWriterIntern.Fire(self, 'Type not supported: ' + Format('%d', [Integer(AType)]));
end;
end;
function TSQLFormat_DB2.getSymCommentBegin: string;
begin
// no inherited (abstract)
Result := '/*'; //begin of SQL comment
end;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.getSymCommentEnd: string;
begin
// no inherited (abstract)
Result := '*/'; //end of SQL comment
end;
//----------------------------------------------------------------------------
//2004-09-06 12:54 N,MN:
function TSQLFormat_DB2.getEqOp(AMetaField: TMetaField): string;
begin
if (AMetaField.DataType = dtString) and
GetStringIsLobField(AMetaField.MaxLength, CDb2MaxLenDbString) then
Result := ' LIKE '
else
Result := inherited getEqOp(AMetaField);
end;
//----------------------------------------------------------------------------
function TSQLFormat_DB2.get1LineComment: string;
begin
Result := '--';
end;
end.
|
unit MediaProcessing.ProcessorListFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,MediaProcessing.Definitions, ComCtrls, ExtendControls, Buttons,
StdCtrls, ActnList, ToolWin, ImgList, ExtCtrls, Vcl.Menus;
type
TMediaServerProcessorListItemData = class;
TfrmMediaProcessorList = class(TFrame)
alActions: TActionList;
acAddMediaProcessor: TAction;
acMediaProcessorProps: TAction;
acDeleteMediaProcessor: TAction;
ilActions: TImageList;
Panel1: TPanel;
lvMediaServerProcessors: TExtendListView;
ToolBar1: TToolBar;
ToolButton2: TToolButton;
ToolButton1: TToolButton;
ToolButton3: TToolButton;
paOriginalStreamType: TPanel;
buGetStreamType: TExtendSpeedBtn;
laMediaServerStreamType: TLabel;
cbMediaServerStreamType: TExtendComboBox;
ExtendButton1: TExtendButton;
pmPopup: TPopupMenu;
acCopy: TAction;
acPaste: TAction;
N1: TMenuItem;
N2: TMenuItem;
procedure acAddMediaProcessorExecute(Sender: TObject);
procedure acAddMediaProcessorUpdate(Sender: TObject);
procedure acMediaProcessorPropsExecute(Sender: TObject);
procedure acMediaProcessorPropsUpdate(Sender: TObject);
procedure acDeleteMediaProcessorExecute(Sender: TObject);
procedure acDeleteMediaProcessorUpdate(Sender: TObject);
procedure lvMediaServerProcessorsDblClick(Sender: TObject);
procedure lvMediaServerProcessorsDeletion(Sender: TObject; Item: TListItem);
procedure cbMediaServerStreamTypeChange(Sender: TObject);
procedure acCopyExecute(Sender: TObject);
procedure acCopyUpdate(Sender: TObject);
procedure acPasteUpdate(Sender: TObject);
procedure acPasteExecute(Sender: TObject);
private
FOnDataChanged: TNotifyEvent;
FOutputStreamTypeFilter: TStreamType;
FAcceptableMediaTypes: TMediaTypeSet;
class function GetMediaProcessorListItemData(aListItem: TListItem): TMediaServerProcessorListItemData;
function AddMediaProcessor(const aIID: TGUID): TMediaServerProcessorListItemData;
function GetOriginalStreamType: TStreamType;
procedure SetOriginalStreamType(const Value: TStreamType);
function GetOutputStreamType: TStreamType;
function GetChangingOriginalStreamTypeAvailable: boolean;
procedure SetChangingOriginalStreamTypeAvailable(const Value: boolean);
function GetMediaProcessor(index: integer): TMediaServerProcessorListItemData;
function GetOriginalStreamTypeList(index: integer): TStreamType;
protected
function GetEnabled: boolean; override;
procedure SetEnabled(Value: boolean); override;
procedure DoDataChanged;
public
constructor Create(aOwner: TComponent); override;
procedure LoadData(aData: TBytes);
function SaveData: TBytes;
property MediaProcessors[index: integer]: TMediaServerProcessorListItemData read GetMediaProcessor;
function MediaProcessorCount:integer;
property OriginalStreamType: TStreamType read GetOriginalStreamType write SetOriginalStreamType;
property OutputStreamType: TStreamType read GetOutputStreamType;
//Ограничение на выходные типы фильтров
property OutputStreamTypeFilter: TStreamType read FOutputStreamTypeFilter write FOutputStreamTypeFilter;
property ChangingOriginalStreamTypeAvailable: boolean read GetChangingOriginalStreamTypeAvailable write SetChangingOriginalStreamTypeAvailable;
function OriginalStreamTypeListCount: integer;
property OriginalStreamTypeList[index: integer]:TStreamType read GetOriginalStreamTypeList;
procedure FillOriginalStreamTypeList(aMediaType: TMediaType);
procedure RemoveFromOriginalStreamTypeList(aStreamType: TStreamType);
property OnDataChanged: TNotifyEvent read FOnDataChanged write FOnDataChanged;
property AcceptableMediaTypes: TMediaTypeSet read FAcceptableMediaTypes write FAcceptableMediaTypes;
end;
TMediaServerProcessorListItemData = class
MediaProcessor: IMediaProcessor;
end;
implementation
uses VCLUtils, MediaProcessing.Global, MediaProcessing.ChooseProcessorDialog, ClipBrd,IdGlobal;
{$R *.dfm}
var
CF_MEDIA_PROCESSORS: array [TMediaType] of word;
type
TFriendlyClipboard = class (TClipboard);
procedure TfrmMediaProcessorList.acAddMediaProcessorExecute(Sender: TObject);
var
aStreamType: TStreamType;
aIID : TGUID;
begin
inherited;
aStreamType:=Low(TStreamType);
if cbMediaServerStreamType.ItemIndex<>-1 then
aStreamType:=TStreamType(cbMediaServerStreamType.CurrentItemData);
if MediaProcessorCount>0 then
aStreamType:= self.MediaProcessors[MediaProcessorCount-1].MediaProcessor.Info.OutputStreamType;
if TfmChooseMediaProcessorDialog.Run(aStreamType,FOutputStreamTypeFilter,aIID) then
begin
AddMediaProcessor(aIID);
with lvMediaServerProcessors.Items[MediaProcessorCount-1] do
begin
Selected:=true;
Focused:=true;
end;
DoDataChanged;
end;
end;
procedure TfrmMediaProcessorList.acAddMediaProcessorUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=self.Enabled and (MediaProcessorCount>0) or (cbMediaServerStreamType.ItemIndex<>-1);
buGetStreamType.Visible:=Assigned(buGetStreamType.OnClick);
end;
procedure TfrmMediaProcessorList.acCopyExecute(Sender: TObject);
var
aData: TBytes;
aMediaType: TMediaType;
begin
aData:=SaveData;
for aMediaType := Low(TMediaType) to High(TMediaType) do
if aMediaType in FAcceptableMediaTypes then
TFriendlyClipboard(Clipboard).SetBuffer(CF_MEDIA_PROCESSORS[aMediaType],aData[0],Length(aData));
end;
procedure TfrmMediaProcessorList.acCopyUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=MediaProcessorCount>0;
end;
procedure TfrmMediaProcessorList.acMediaProcessorPropsExecute(Sender: TObject);
begin
GetMediaProcessorListItemData(lvMediaServerProcessors.Selected).MediaProcessor.ShowCustomProperiesDialog;
DoDataChanged;
end;
procedure TfrmMediaProcessorList.acMediaProcessorPropsUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=self.Enabled and (lvMediaServerProcessors.Selected<>nil) and (GetMediaProcessorListItemData(lvMediaServerProcessors.Selected).MediaProcessor.HasCustomProperties);
end;
procedure TfrmMediaProcessorList.acPasteExecute(Sender: TObject);
var
Data: THandle;
aBytes: TBytes;
DataPtr: Pointer;
aMediaType: TMediaType;
begin
Clipboard.Open;
try
for aMediaType := Low(TMediaType) to High(TMediaType) do
if aMediaType in FAcceptableMediaTypes then
begin
Data := GetClipboardData(CF_MEDIA_PROCESSORS[aMediaType]);
if Data = 0 then
Exit;
DataPtr := GlobalLock(Data);
if DataPtr = nil then
Exit;
try
SetLength(aBytes,GlobalSize(Data));
Move(DataPtr^, aBytes[0], Length(aBytes));
finally
GlobalUnlock(Data);
end;
break;
end;
finally
Clipboard.Close;
end;
LoadData(aBytes);
DoDataChanged;
end;
procedure TfrmMediaProcessorList.acPasteUpdate(Sender: TObject);
var
aMediaType: TMediaType;
b: boolean;
begin
b:=false;
for aMediaType := Low(TMediaType) to High(TMediaType) do
if aMediaType in FAcceptableMediaTypes then
b:=b or Clipboard.HasFormat(CF_MEDIA_PROCESSORS[aMediaType]);
TAction(Sender).Enabled:=b;
end;
procedure TfrmMediaProcessorList.acDeleteMediaProcessorExecute(Sender: TObject);
var
i: integer;
begin
inherited;
i:=lvMediaServerProcessors.Selected.Index;
lvMediaServerProcessors.Selected.Free;
if MediaProcessorCount>i then
begin
lvMediaServerProcessors.Items[i].Selected:=true;
lvMediaServerProcessors.Items[i].Focused:=true;
end
else begin
if MediaProcessorCount>0 then
begin
lvMediaServerProcessors.Items[MediaProcessorCount-1].Selected:=true;
lvMediaServerProcessors.Items[MediaProcessorCount-1].Focused:=true;
end
end;
DoDataChanged;
end;
procedure TfrmMediaProcessorList.acDeleteMediaProcessorUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=self.Enabled and (lvMediaServerProcessors.Selected<>nil) and (lvMediaServerProcessors.Selected.Index=MediaProcessorCount-1);
end;
function TfrmMediaProcessorList.GetChangingOriginalStreamTypeAvailable: boolean;
begin
result:=cbMediaServerStreamType.Enabled;
end;
function TfrmMediaProcessorList.GetEnabled: boolean;
begin
result:=inherited GetEnabled;
end;
function TfrmMediaProcessorList.GetMediaProcessor(index: integer): TMediaServerProcessorListItemData;
begin
result:=GetMediaProcessorListItemData(lvMediaServerProcessors.Items[index]);
end;
class function TfrmMediaProcessorList.GetMediaProcessorListItemData(aListItem: TListItem): TMediaServerProcessorListItemData;
begin
Assert(aListItem<>nil);
Assert(aListItem.Data<>nil);
result:=aListItem.Data;
end;
function TfrmMediaProcessorList.GetOriginalStreamType: TStreamType;
begin
if cbMediaServerStreamType.ItemIndex=-1 then
result:=0
else
result:=TStreamType(cbMediaServerStreamType.CurrentItemData)
//raise Exception.Create('Не указан исходный тип потока');
end;
function TfrmMediaProcessorList.GetOriginalStreamTypeList(
index: integer): TStreamType;
begin
result:=TStreamType(cbMediaServerStreamType.Items.Data[index]);
end;
function TfrmMediaProcessorList.GetOutputStreamType: TStreamType;
begin
result:=OriginalStreamType;
if MediaProcessorCount>0 then
result:=MediaProcessors[MediaProcessorCount-1].MediaProcessor.Info.OutputStreamType;
end;
procedure TfrmMediaProcessorList.LoadData(aData: TBytes);
var
i: Integer;
aByteStream: TBytesStream;
aIID : TGUID;
begin
lvMediaServerProcessors.Items.Clear;
if Length(aData)>0 then
begin
aByteStream:=TBytesStream.Create(aData);
try
//Processors
aByteStream.ReadBuffer(i,sizeof(i));
Assert(i<1000);
for i := 0 to i-1 do
begin
aByteStream.Read(aIID,sizeof(aIID));
AddMediaProcessor(aIID).MediaProcessor.LoadCustomProperties(aByteStream);
end;
finally
aByteStream.Free;
end;
if MediaProcessorCount>0 then
begin
lvMediaServerProcessors.Items[0].Selected:=true;
lvMediaServerProcessors.Items[0].Focused:=true;
end;
end;
end;
procedure TfrmMediaProcessorList.lvMediaServerProcessorsDblClick(
Sender: TObject);
begin
acMediaProcessorProps.Execute;
end;
procedure TfrmMediaProcessorList.lvMediaServerProcessorsDeletion(
Sender: TObject; Item: TListItem);
begin
TObject(Item.Data).Free;
Item.Data:=nil;
end;
function TfrmMediaProcessorList.MediaProcessorCount: integer;
begin
result:=lvMediaServerProcessors.Items.Count;
end;
function TfrmMediaProcessorList.OriginalStreamTypeListCount: integer;
begin
result:=cbMediaServerStreamType.Items.Count;
end;
procedure TfrmMediaProcessorList.RemoveFromOriginalStreamTypeList(aStreamType: TStreamType);
var
i: integer;
begin
inherited;
for i := 0 to OriginalStreamTypeListCount-1 do
if OriginalStreamTypeList[i]=aStreamType then
begin
cbMediaServerStreamType.Items.Delete(i);
if cbMediaServerStreamType.ItemIndex=-1 then
cbMediaServerStreamType.ItemIndex:=0;
break;
end;
end;
function TfrmMediaProcessorList.SaveData: TBytes;
var
i: Integer;
aListItemData: TMediaServerProcessorListItemData;
aByteStream: TBytesStream;
aIID : TGUID;
begin
aByteStream:=TBytesStream.Create(nil);
try
i:=MediaProcessorCount;
aByteStream.Write(i,sizeof(i));
for i := 0 to MediaProcessorCount-1 do
begin
aListItemData:=Self.MediaProcessors[i];
aIID:=aListItemData.MediaProcessor.Info.TypeID;
aByteStream.Write(aIID,sizeof(aIID));
aListItemData.MediaProcessor.SaveCustomProperties(aByteStream);
end;
result:=Copy(aByteStream.Bytes,0,aByteStream.Size);
finally
aByteStream.Free;
end;
end;
procedure TfrmMediaProcessorList.SetChangingOriginalStreamTypeAvailable(
const Value: boolean);
begin
cbMediaServerStreamType.Enabled:=Value;
laMediaServerStreamType.Enabled:=Value;
buGetStreamType.Enabled:=Value;
end;
procedure TfrmMediaProcessorList.SetEnabled(Value: boolean);
var
i: integer;
begin
for i := 0 to ComponentCount-1 do
if Components[i] is TControl then
TControl(Components[i]).Enabled:=Value;
inherited SetEnabled(Value);
end;
procedure TfrmMediaProcessorList.SetOriginalStreamType(const Value: TStreamType);
begin
cbMediaServerStreamType.ItemIndex:=cbMediaServerStreamType.Items.IndexOfData(integer(Value));
end;
function TfrmMediaProcessorList.AddMediaProcessor(
const aIID: TGUID): TMediaServerProcessorListItemData;
var
aData : TMediaServerProcessorListItemData;
aInfo : TMediaProcessorInfo;
aItem : TListItem;
s: string;
begin
aInfo:=MediaProceccorFactory.GetMediaProcessorInfoByTypeID(aIID);
aData:=TMediaServerProcessorListItemData.Create;
aData.MediaProcessor:=MediaProceccorFactory.CreateMediaProcessor(aIID,false);
aItem:=lvMediaServerProcessors.Items.Add;
aItem.Caption:=aInfo.Name;
if Length(aInfo.InputStreamTypes)=1 then
s:=GetStreamTypeName(aInfo.InputStreamTypes[0])
else
s:=StreamTypesToFourccString(aInfo.InputStreamTypes);
aItem.SubItems.Add(s);
aItem.SubItems.Add(GetStreamTypeName(aInfo.OutputStreamType));
aItem.SubItems.Add(aInfo.Description);
aItem.Data:=aData;
result:=aData;
end;
procedure TfrmMediaProcessorList.cbMediaServerStreamTypeChange(Sender: TObject);
var
aFirstMP: TMediaServerProcessorListItemData;
begin
if MediaProcessorCount>0 then
begin
aFirstMP:=self.MediaProcessors[0];
if not aFirstMP.MediaProcessor.Info.CanAcceptInputStreamType(GetOriginalStreamType) and (Length(aFirstMP.MediaProcessor.Info.InputStreamTypes)>0) then
begin
if MsgBox.ConfirmWarningFmt(Handle,
'Выбранный тип потока несовместим с первым в очереди медиа-процессором. '+
'Чтобы использовать новый тип потока, вы должны очистить список медиа-процессоров. Выполнить очистку? '+
'Нажмите "Нет", чтобы оставить список медиа-процессоров и вернуть тип потока в исходный вариант',
[]) then
lvMediaServerProcessors.Items.Clear
else
SetOriginalStreamType(aFirstMP.MediaProcessor.Info.InputStreamTypes[0]);
end;
end;
end;
constructor TfrmMediaProcessorList.Create(aOwner: TComponent);
begin
inherited;
AcceptableMediaTypes:=AllMediaTypes;
end;
procedure TfrmMediaProcessorList.DoDataChanged;
begin
if Assigned(FOnDataChanged) then
FOnDataChanged(self);
end;
procedure TfrmMediaProcessorList.FillOriginalStreamTypeList(aMediaType: TMediaType);
var
st: integer;
begin
inherited;
cbMediaServerStreamType.Items.Clear;
for st := 0 to High(stKnownTypes[aMediaType]) do
cbMediaServerStreamType.Items.AddData(GetStreamTypeName(stKnownTypes[aMediaType][st]),stKnownTypes[aMediaType][st]);
if cbMediaServerStreamType.Items.Count>0 then
cbMediaServerStreamType.ItemIndex:=0;
cbMediaServerStreamType.Sorted:=true;
end;
procedure InitClipboardFormats;
var
aMediaType: TMediaType;
s: string;
begin
for aMediaType := Low(TMediaType) to High(TMediaType) do
begin
s:='Media Processors. '+MediaTypeNames[aMediaType]; { Do not localize }
CF_MEDIA_PROCESSORS[aMediaType]:=RegisterClipboardFormat(PChar(s));
end;
end;
initialization
InitClipboardFormats;
end.
|
unit UDMMySql;
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.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client, FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL,
FireDAC.Comp.UI, IniFiles, Forms, ULogData, ULogType;
type
TDMMySql = class(TDataModule)
Connection: TFDConnection;
WaitCursor: TFDGUIxWaitCursor;
MySQLDriverLink: TFDPhysMySQLDriverLink;
private
{ Private declarations }
procedure LoadParams;
public
{ Public declarations }
function TestConnection : Boolean;
end;
var
DMMySql: TDMMySql;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMMySql }
procedure TDMMySql.LoadParams;
var
ArqIni: TIniFile;
Params : TStringList;
begin
ArqIni := TIniFile.Create(ExtractFileDir(Application.ExeName) + '\Connection.ini');
Params := TStringList.Create;
Params.Add('DriverID=MySQL');
Params.Add('Server=' + ArqIni.ReadString('MySql','Server','localhost'));
Params.Add('Port=' + ArqIni.ReadString('MySql','Port','3306'));
Params.Add('User_Name=' + ArqIni.ReadString('MySql','User_Name',''));
Params.Add('Password=' + ArqIni.ReadString('MySql','Password',''));
Connection.Params.Clear;
Connection.Params.AddStrings(Params);
end;
function TDMMySql.TestConnection: Boolean;
begin
try
LoadParams;
Connection.Connected := True;
Result := True;
Connection.Connected := False;
except
on E:Exception do
begin
TLogData.SaveLog(E.Message,'Teste de conex„o com MySql',ltError);
Result := False;
end;
end;
end;
end.
|
unit intensive.Controller.DTO.Cliente;
interface
uses
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs,
FireDAC.Phys.SQLiteWrapper.Stat,
FireDAC.VCLUI.Wait,
FireDAC.Comp.UI,
Data.DB,
FireDAC.Comp.Client,
intensive.Model.Entity.Cliente,
intensive.Controller.DTO.Interfaces,
intensive.Services.Generic;
type
TClienteDTO = class(TInterfacedObject, iClienteDTO)
private
FEntity : TCliente;
FService : iService<TCliente>;
public
constructor Create;
destructor Destroy; override;
class function New : iClienteDTO;
function Id(Value : Integer) : iClienteDTO; overload;
function Id : Integer; overload;
function Nome(Value : String) : iClienteDTO; overload;
function Nome : String; overload;
function Telefone(Value : String) : iClienteDTO; overload;
function Telefone : String; overload;
function Build : iService<TCliente>;
end;
implementation
function TClienteDTO.Build: iService<TCliente>;
begin
Result := FSErvice;
end;
constructor TClienteDTO.Create;
begin
FEntity := TCliente.Create;
FService := TService<TCliente>.New(FEntity);
end;
destructor TClienteDTO.Destroy;
begin
FEntity.DisposeOf;
inherited;
end;
function TClienteDTO.Id: Integer;
begin
Result := FEntity.Id;
end;
function TClienteDTO.Id(Value: Integer): iClienteDTO;
begin
Result := Self;
FEntity.Id := Value;
end;
class function TClienteDTO.New : iClienteDTO;
begin
Result := Self.Create;
end;
function TClienteDTO.Nome: String;
begin
Result := FEntity.Nome;
end;
function TClienteDTO.Nome(Value: String): iClienteDTO;
begin
Result := Self;
FEntity.Nome := Value;
end;
function TClienteDTO.Telefone(Value: String): iClienteDTO;
begin
Result := Self;
FEntity.Telefone := Value;
end;
function TClienteDTO.Telefone: String;
begin
Result := FEntity.Telefone;
end;
end.
|
unit DAF_JSON;
interface
uses
superobject, DB, DBClient, Classes;
function RemoveReservedChar(s:WideString): WideString;
type
TDAFJSON = class
private
FFieldSise: Integer;
procedure ProcessJsonSO(var Result: TClientDataSet; joJSON: ISuperObject; FieldChild: TFieldDef = nil); overload;
procedure FillCDSFromJsonSO(const joJSON: ISuperObject; var cds: TClientDataSet); overload;
//Mormot
procedure ProcessJson(vJson: Variant; cds: TClientDataSet; FieldDef: TFieldDef = nil; Value: Boolean = False);
procedure FillCDSFromJson(vJson: Variant; cds: TClientDataSet);
public
constructor Create;
property FieldSise: Integer read FFieldSise write FFieldSise;
class function CreateCDSFromJsonSO(JSON: string; FieldChild: TFieldDef = nil; cdsName: string = 'MainDataset'): TClientDataSet;
class function GetFieldDetail(Source: TDataSet; FieldName: string): TField;
class function GetObjectJSON(SuperObject: ISuperObject; Name: WideString): ISuperObject;
class procedure SetJson(SuperObject: ISuperObject; Name: WideString; Value: Boolean); overload;
class procedure SetJson(SuperObject: ISuperObject; Name: WideString; Value: Double); overload;
class procedure SetJson(SuperObject: ISuperObject; Name: WideString; Value: Int64); overload;
class procedure SetJson(SuperObject: ISuperObject; Name: WideString; Value: ISuperObject); overload;
class procedure SetJson(SuperObject: ISuperObject; Name: WideString; Value: WideString); overload;
//Mormot
class function CreateCDSFromJson(sJson: string; cdsName: string = 'MainDataset'): TClientDataSet;
end;
implementation
uses
StrUtils, SysUtils, SynCommons, Variants;
procedure CreateFieldDef(AMemData: TDataSet; pName: string; pDataType: TFieldType; pSize: Integer = 0; pRequired: Boolean = False); overload;
begin
if (AMemData <> nil) and (pName <> '') then
begin
with AMemData.FieldDefs.AddFieldDef do
begin
Name := pName;
if pDataType = ftInteger then
DataType := DB.ftCurrency
else
DataType := pDataType;
Size := pSize;
Required := pRequired;
end;
end;
end;
procedure CreateField(AMemData: TDataSet; pName: string; pDataType: TFieldType; pSize: Integer = 0; pRequired: Boolean = False); overload;
begin
if (AMemData <> nil) and (pName <> '') then
begin
with AMemData.FieldDefs.AddFieldDef do
begin
Name := pName;
if pDataType = ftInteger then
DataType := DB.ftCurrency
else
DataType := pDataType;
Size := pSize;
Required := pRequired;
CreateField(AMemData);
end;
end;
end;
procedure CreateField(AMemData: TDataSet; pName: string; pDisplayName: string; pDataType: TFieldType; pSize: Integer = 0; pRequired: Boolean = False); overload;
begin
if (AMemData <> nil) and (pName <> '') then
begin
CreateField(AMemData, pName, pDataType, pSize, pRequired);
AMemData.FieldByName(pName).DisplayLabel := pDisplayName;
end;
end;
procedure CreateFieldChildDef(AField: TFieldDef; pName: string; pDataType: TFieldType; pSize: Integer = 0; pRequired: Boolean = False);
begin
with AField.AddChild do
begin
Name := pName;
if pDataType = ftInteger then
DataType := DB.ftCurrency
else
DataType := pDataType;
Size := pSize;
Required := pRequired;
end;
end;
{ TDAFJSON }
constructor TDAFJSON.Create;
begin
FFieldSise := 32000;
end;
procedure TDAFJSON.FillCDSFromJson(vJson: Variant; cds: TClientDataSet);
var
dvdJson: TDocVariantData;
I: Integer;
V: Variant;
cdsNested: TClientDataSet;
FieldName: string;
begin
dvdJson := TDocVariantData(vJson);
if dvdJson.Kind = dvArray then
begin
for I := 0 to dvdJson.Count - 1 do
begin
FillCDSFromJson(dvdJson.Values[I], cds);
end;
end
else if dvdJson.Kind = dvObject then
begin
if cds.IsEmpty then
cds.Insert
else
cds.Append;
for I := 0 to dvdJson.Count - 1 do
begin
FieldName := UTF8ToString(dvdJson.Names[I]);
V := _JsonFast(UTF8Encode(VarToStr(dvdJson.Values[I])));
if TDocVariantData(V).Kind <> dvUndefined then
begin
if not((TDocVariantData(V).Kind = dvArray) and (TDocVariantData(V).Count = 0)) then
begin
cdsNested := TClientDataSet(TDataSetField(cds.FieldByName(FieldName)).NestedDataSet);
FillCDSFromJson(dvdJson.Values[I], TClientDataSet(cdsNested));
end;
end
else
begin
if cds.FindField(FieldName) <> nil then
cds.FieldByName(FieldName).Value := dvdJson.Values[I];
end;
end;
cds.Post;
end;
end;
procedure TDAFJSON.FillCDSFromJsonSO(const joJSON: ISuperObject; var cds: TClientDataSet);
var
ArrayItem: TSuperAvlEntry;
ArrayItens: ISuperObject;
I: Integer;
FieldName: string;
FieldValue: string;
cdsNested: TDataSet;
Item: TSuperAvlEntry;
begin
if joJSON.IsType(stObject) then
begin
cds.Append;
for Item in joJSON.AsObject do
begin
if Item.Value.IsType(stArray) then
begin
cdsNested := TDataSetField(cds.FieldByName(Item.Name)).NestedDataSet;
FillCDSFromJsonSO(Item.Value, TClientDataSet(cdsNested));
end
else if Item.Value.IsType(stObject) then
begin
cdsNested := TDataSetField(cds.FieldByName(Item.Name)).NestedDataSet;
FillCDSFromJsonSO(Item.Value, TClientDataSet(cdsNested));
end
else
begin
if cds.FindField(Item.Name) <> nil then // todo - verificar pq a venda com chave 43160502308702000405650010000002371000002370 dá exception de field tef_bandeira not found
cds.FieldByName(Item.Name).AsString := Item.Value.AsString;
end;
end;
cds.Post;
end
else if joJSON.IsType(stArray) then
begin
for I := 0 to joJSON.AsArray.Length - 1 do
begin
ArrayItens := joJSON.AsArray[I];
cds.Append;
for ArrayItem in ArrayItens.AsObject do
begin
FieldName := ArrayItem.Name;
FieldValue := ArrayItem.Value.AsString;
if ArrayItem.Value.IsType(stObject) then
begin
cdsNested := TDataSetField(cds.FieldByName(FieldName)).NestedDataSet;
FillCDSFromJsonSO(ArrayItem.Value, TClientDataSet(cdsNested));
end
else if ArrayItem.Value.IsType(stArray) then
begin
cdsNested := TDataSetField(cds.FieldByName(FieldName)).NestedDataSet;
FillCDSFromJsonSO(ArrayItem.Value, TClientDataSet(cdsNested));
end
else
begin
cds.FieldByName(FieldName).AsString := FieldValue;
end;
end;
cds.Post;
end;
end;
end;
class function TDAFJSON.CreateCDSFromJson(sJson: string; cdsName: string): TClientDataSet;
var
DAFJson: TDAFJSON;
tmpstr: RawUTF8;
begin
DAFJson := TDAFJSON.Create;
try
Result := TClientDataSet.Create(nil);
Result.Name := cdsName;
{$IFDEF UNICODE}
tmpstr := UTF8Encode(sJson);
{$ELSE}
tmpstr := sJson;
{$ENDIF}
DAFJson.ProcessJson(_Json(tmpstr), Result);
Result.CreateDataSet;
DAFJson.FillCDSFromJson(_Json(tmpstr), Result);
finally
DAFJson.Free;
end;
end;
class function TDAFJSON.CreateCDSFromJsonSO(JSON: string; FieldChild: TFieldDef; cdsName: string): TClientDataSet;
var
oJSON: ISuperObject;
DAFJson: TDAFJSON;
begin
DAFJson := TDAFJSON.Create;
try
Result := TClientDataSet.Create(nil);
Result.Name := cdsName;
oJSON := SO(JSON);
DAFJson.ProcessJsonSO(Result, oJSON, FieldChild);
if Result.FieldDefs.Count > 0 then
begin
Result.CreateDataSet;
DAFJson.FillCDSFromJsonSO(oJSON, Result);
end;
finally
DAFJson.Free;
end;
end;
class function TDAFJSON.GetFieldDetail(Source: TDataSet; FieldName: string): TField;
begin
Result := Source.FindField(FieldName);
if Result = nil then
raise Exception.Create('Não foi encontrado o field ' + FieldName);
if Result.DataType <> ftDataSet then
raise Exception.Create('O Field ' + FieldName + ' não é um detail!');
end;
class function TDAFJSON.GetObjectJSON(SuperObject: ISuperObject; Name: WideString): ISuperObject;
var
Item: TSuperObjectIter;
begin
Result := nil;//TSuperObject.Create(stNull);
Name := RemoveReservedChar(Name);
try
if ObjectFindFirst(SuperObject, Item) then
repeat
if Item.key = Name then
begin
Result := Item.val;
Break;
end;
until not ObjectFindNext(Item);
finally
ObjectFindClose(Item);
end;
end;
procedure TDAFJSON.ProcessJson(vJson: Variant; cds: TClientDataSet; FieldDef: TFieldDef; Value: Boolean);
var
dvdJson: TDocVariantData;
I: Integer;
FieldValue, V: Variant;
FieldName: string;
FieldType: TFieldType;
FieldSize: Integer;
procedure CreateField(vJson2: Variant; cds: TClientDataSet; FieldDef: TFieldDef);
var
dvdJson2: TDocVariantData;
begin
dvdJson2 := TDocVariantData(vJson2);
if dvdJson2.Kind = dvUndefined then
begin
if FieldDef = nil then
begin
if (cds.FieldDefs.IndexOf(FieldName) = -1) then
CreateFieldDef(cds, FieldName, FieldType, FieldSize);
end
else
begin
if (FieldDef.ChildDefs.IndexOf(FieldName) = -1) then
CreateFieldChildDef(FieldDef, FieldName, FieldType, FieldSize);
end;
end
else
begin
if FieldDef <> nil then
begin
if (FieldDef.ChildDefs.IndexOf(FieldName) = -1) then
CreateFieldChildDef(FieldDef, FieldName, ftDataSet);
ProcessJson(V, cds, FieldDef.ChildDefs.Find(FieldName));
end
else
begin
if not((TDocVariantData(V).Kind = dvArray) and (TDocVariantData(V).Count = 0)) then
begin
if (cds.FieldDefs.IndexOf(FieldName) = -1) then
CreateFieldDef(cds, FieldName, ftDataSet);
ProcessJson(V, cds, cds.FieldDefs.Find(FieldName));
end;
end;
end;
end;
begin
dvdJson := TDocVariantData(vJson);
if dvdJson.Kind = dvArray then
begin
for I := 0 to dvdJson.Count - 1 do
begin
ProcessJson(dvdJson.Values[I], cds, FieldDef);
end;
end
else if dvdJson.Kind = dvObject then
begin
for I := 0 to dvdJson.Count - 1 do
begin
FieldName := UTF8ToString(dvdJson.Names[I]);
FieldValue := dvdJson.Values[I];
if not Value then
begin
FieldSize := 0;
case VarType(FieldValue) and VarTypeMask of
varEmpty:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varNull:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varSmallInt: FieldType := ftSmallint;
varInteger: FieldType := ftInteger;
varSingle: FieldType := ftInteger;
varDouble: FieldType := ftFloat;
varCurrency: FieldType := ftFloat;
varDate: FieldType := ftDateTime;
varOleStr:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varDispatch:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varError:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varBoolean: FieldType := ftBoolean;
varVariant:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varUnknown:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varByte: FieldType := ftBytes;
varWord: FieldType := ftWord;
varLongWord: FieldType := ftInteger;
varInt64: FieldType := ftLargeint;
varStrArg:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varString:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varAny:
begin
FieldType := ftString;
FieldSize := 32000;
end;
varTypeMask:
begin
FieldType := ftString;
FieldSize := 32000;
end;
end;
end;
V := _JsonFast(UTF8Encode(VarToStr(FieldValue)));
if TDocVariantData(V).Kind = dvUndefined then
CreateField(V, cds, FieldDef)
else
CreateField(dvdJson.Values[I], cds, FieldDef);
end;
end;
end;
procedure TDAFJSON.ProcessJsonSO(var Result: TClientDataSet; joJSON: ISuperObject; FieldChild: TFieldDef);
procedure CreateFieldsSO(ArrayItem: TSuperAvlEntry; Result: TClientDataSet; FieldChild: TFieldDef);
var
FieldName, FieldValue: string;
begin
FieldName := ArrayItem.Name;
FieldValue := ArrayItem.Value.AsString;
if ArrayItem.Value.IsType(stArray) then
begin
if FieldChild <> nil then
begin
if (FieldChild.ChildDefs.IndexOf(FieldName) = -1) then
CreateFieldChildDef(FieldChild, FieldName, ftDataSet);
ProcessJsonSO(Result, ArrayItem.Value, FieldChild.ChildDefs.Find(FieldName));
end
else
begin
if (Result.FieldDefs.IndexOf(FieldName) = -1) then
CreateFieldDef(Result, FieldName, ftDataSet);
ProcessJsonSO(Result, ArrayItem.Value, Result.FieldDefs.Find(FieldName));
end;
end
else if ArrayItem.Value.IsType(stObject) then
begin
if FieldChild <> nil then
begin
if (FieldChild.ChildDefs.IndexOf(FieldName) = -1) then
CreateFieldChildDef(FieldChild, FieldName, ftDataSet);
ProcessJsonSO(Result, ArrayItem.Value, FieldChild.ChildDefs.Find(FieldName));
end
else
begin
if (Result.FieldDefs.IndexOf(FieldName) = -1) then
CreateFieldDef(Result, FieldName, ftDataSet);
ProcessJsonSO(Result, ArrayItem.Value, Result.FieldDefs.Find(FieldName));
end;
end
else
begin
if FieldChild = nil then
begin
if (Result.FieldDefs.IndexOf(FieldName) = -1) then
CreateFieldDef(Result, FieldName, ftString, FieldSise);
end
else
begin
if (FieldChild.ChildDefs.IndexOf(FieldName) = -1) then
CreateFieldChildDef(FieldChild, FieldName, ftString, FieldSise);
end;
end;
end;
var
ArrayItem: TSuperAvlEntry;
ArrayItens: ISuperObject;
I: Integer;
begin
if joJSON.IsType(stObject) then
begin
for ArrayItem in joJSON.AsObject do
begin
CreateFieldsSO(ArrayItem, Result, FieldChild);
end;
end
else if joJSON.IsType(stArray) then
begin
for I := 0 to joJSON.AsArray.Length - 1 do
begin
ArrayItens := joJSON.AsArray[I];
for ArrayItem in ArrayItens.AsObject do
begin
CreateFieldsSO(ArrayItem, Result, FieldChild);
end;
end;
end;
end;
class procedure TDAFJSON.SetJson(SuperObject: ISuperObject; Name: WideString;
Value: Boolean);
begin
SuperObject.B[RemoveReservedChar(Name)] := Value;
end;
class procedure TDAFJSON.SetJson(SuperObject: ISuperObject; Name: WideString;
Value: Double);
begin
SuperObject.D[RemoveReservedChar(Name)] := Value;
end;
class procedure TDAFJSON.SetJson(SuperObject: ISuperObject; Name: WideString;
Value: Int64);
begin
SuperObject.I[RemoveReservedChar(Name)] := Value;
end;
class procedure TDAFJSON.SetJson(SuperObject: ISuperObject; Name: WideString;
Value: ISuperObject);
begin
SuperObject.N[RemoveReservedChar(Name)] := Value;
end;
class procedure TDAFJSON.SetJson(SuperObject: ISuperObject; Name, Value: WideString);
begin
SuperObject.S[RemoveReservedChar(Name)] := Value;
end;
function RemoveReservedChar(s: WideString): WideString;
begin
Result :=
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
AnsiReplaceStr(
s, #0, ''
), #8, ''
), #9, ''
), #10, ''
), #12, ''
), #13, ''
), #32, ''
), '"', ''
), '.', ''
), '[', ''
), ']', ''
), '{', ''
), '}', ''
), '(', ''
), ')', ''
), ',', ''
), ':', ''
);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 29 Backtrack Method
}
program
VertexTransitivity;
const
MaxN = 100;
var
N : Integer;
G : array [1 .. MaxN, 1 .. MaxN] of Integer;
M : array [1 .. MaxN, 1 .. MaxN] of Boolean;
D, P : array [1 .. MaxN] of Integer;
I, J, T, L : Integer;
Fl : Boolean;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, G[I, J]); G[J, I] := G[I, J];
Inc(D[I], G[I, J]); Inc(D[J], G[I, J]);
end;
Readln(F);
end;
Close(F);
end;
procedure NonVT;
begin
Writeln('Graph is not vertex transitive.');
Halt;
end;
procedure Swap (A, B : Integer);
begin T := P[A]; P[A] := P[B]; P[B] := T; end;
procedure Found;
var
A : Integer;
begin
Fl := True;
for A := 1 to N do
if P[P[A]] = A then
begin M[A, P[A]] := True; M[P[A], A] := True; end;
end;
procedure BT (V : Integer);
var
K : Integer;
begin
if (V = I) or (V = J) then BT(V + 1);
if V > N then begin Found; Exit; end;
for K := N downto V do if (K <> I) and (K <> J) then
begin
Swap(V, K);
for L := 1 to V do if G[L, V] <> G[P[L], P[V]] then Break;
if L = V then BT(V + 1);
Swap(V, K);
if Fl then Exit;
end;
end;
procedure Solve;
begin
for I := 1 to N do if D[I] <> D[1] then NonVT;
for I := 1 to N do P[I] := I;
for I := 1 to N do
for J := 1 to I - 1 do
if not M[I, J] then
begin
Fl := False;
Swap(I, J);
BT(1);
if not Fl then
NonVT;
Swap(I, J);
end;
Writeln('Graph is vertex transitive.');
end;
begin
ReadInput;
Solve;
end.
|
{*******************************************************}
{ }
{ Midas RemoteDataModule Pooler Demo }
{ }
{*******************************************************}
unit SrvrDM;
{
This is the Remote Data Module (RDM) that is going to be pooled.
The differences between this RDM and a regular RDM are as follows;
1) In order to share RDMs the client must be stateless. This means that the
IProvider interface cannot be used in conjunction with pooling. Below
you'll notice the procedure Select that is used to retrieve data.
2) The RDMs need to run in their own thread. In order to do this for out of
process servers, you can use the ThreadedClassFactory included in this
demo.
3) This class is an internal accesible class only and is not registered in the
registry. All access to this object is done from the pooler object. If
you look in the Type Library you will see 2 different CoClasses for this
project. One is for this class and one is for the Pooler.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, BdeProv, ActiveX, DataBkr, Server_TLB,
Db, DBTables, ThrddCF;
type
TPooledRDM = class(TDataModule, IPooledRDM)
Session1: TSession;
Database1: TDatabase;
Query1: TQuery;
private
{ Private declarations }
public
{ Public declarations }
protected
procedure Select(const SQLStr: WideString; out Data: OleVariant); safecall;
end;
var
PooledRDM: TPooledRDM;
{ Need a reference to the ClassFactory so the pooler can create instances of the
class. }
RDMFactory: TThreadedClassFactory;
implementation
{$R *.DFM}
{ Select is used to retrieve all the data from a query. This is done so the
server can be stateless. }
procedure TPooledRDM.Select(const SQLStr: WideString;
out Data: OleVariant);
begin
Query1.SQL.Text := SQLStr;
Data := Query1.Provider.Data;
end;
initialization
RDMFactory := TThreadedClassFactory.Create(ComServer, TPooledRDM,
Class_PooledRDM, ciInternal);
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TTeeBISource VCL Editor Dialog }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Chart.Source;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCLTee.TeeSourceEdit, Vcl.StdCtrls,
VCLTee.TeCanvas, Vcl.ExtCtrls, VCLBI.Chart.Source;
type
TValueControl=record
public
Text : TLabel;
Combo : TComboBox;
end;
TBISourceEditor = class(TBaseSourceEditor)
GroupFields: TScrollBox;
LLabels: TLabel;
CBLabelsField: TComboFlat;
PanelData: TPanel;
BSelectData: TButton;
LData: TLabel;
procedure BSelectDataClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BApplyClick(Sender: TObject);
procedure CBLabelsFieldChange(Sender: TObject);
private
{ Private declarations }
FValueControls : Array of TValueControl;
procedure ChangedCombo(Sender: TObject);
procedure CreateControls;
procedure DestroyCombos;
procedure FillCombos;
procedure RefreshControls;
procedure RefreshDataLabel;
function Source:TTeeBISource;
public
{ Public declarations }
class procedure Edit(const AOwner:TComponent; const ASource:TTeeBISource); static;
end;
implementation
|
unit JcfIdeMain;
{ AFS 7 Jan 2K
JEDI Code Format IDE plugin main class
global object that implements the callbacks from the menu items }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is JcfIdeMain, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ freepascal }SysUtils, Classes,
{ lazarus design time }
LazIDEIntf, SrcEditorIntf, IDEMsgIntf, ProjectIntf,
{ local}
EditorConverter, FileConverter, ConvertTypes;
type
TJcfIdeMain = class(TObject)
private
fcEditorConverter: TEditorConverter;
fcFileConverter: TFileConverter;
procedure MakeEditorConverter;
procedure LogIDEMessage(const psFile, psMessage: string;
const peMessageType: TStatusMessageType;
const piY, piX: integer);
procedure FormatFile(const psFileName: string);
procedure ClearToolMessages;
procedure ConvertEditor(const pciEditor: TSourceEditorInterface);
protected
public
constructor Create;
destructor Destroy; override;
procedure DoFormatCurrentIDEWindow(Sender: TObject);
procedure DoFormatProject(Sender: TObject);
procedure DoFormatOpen(Sender: TObject);
procedure DoRegistrySettings(Sender: TObject);
procedure DoFormatSettings(Sender: TObject);
procedure DoAbout(Sender: TObject);
end;
implementation
uses
{ lazarus }
Menus, Dialogs, Controls,
{ jcf }
JcfStringUtils,
{ local }
fAbout{, fAllSettings, JcfRegistrySettings, fRegistrySettings};
function FileIsAllowedType(const psFileName: string): boolean;
const
ALLOWED_FILE_TYPES: array[1..5] of string = ('.pas', '.pp', '.dpr', '.lpr', '.dpk');
begin
Result := StrIsOneOf(StrRight(psFileName, 4), ALLOWED_FILE_TYPES);
end;
function GetCurrentProject: TLazProject;
begin
Result := LazarusIDE.ActiveProject;
end;
constructor TJcfIdeMain.Create;
begin
inherited;
{ both of these are created on demand }
fcEditorConverter := nil;
fcFileConverter := nil;
end;
destructor TJcfIdeMain.Destroy;
begin
FreeAndNil(fcEditorConverter);
FreeAndNil(fcFileConverter);
inherited;
end;
procedure TJcfIdeMain.DoFormatCurrentIDEWindow(Sender: TObject);
begin
if (SourceEditorWindow = nil) or (SourceEditorWindow.ActiveEditor = nil) then
begin
LogIdeMessage('', 'No current window', mtInputError, -1, -1);
exit;
end;
ConvertEditor(SourceEditorWindow.ActiveEditor);
end;
procedure TJcfIdeMain.ConvertEditor(const pciEditor: TSourceEditorInterface);
begin
MakeEditorConverter;
ClearToolMessages;
fcEditorConverter.Clear;
fcEditorConverter.BeforeConvert;
fcEditorConverter.Convert(pciEditor);
fcEditorConverter.AfterConvert;
end;
procedure TJcfIdeMain.DoFormatProject(Sender: TObject);
var
lazProject: TLazProject;
lazFile: TLazProjectFile;
liLoop: integer;
lsMsg: string;
begin
lazProject := GetCurrentProject;
if lazProject = nil then
exit;
lsMsg := 'JEDI Code Format of ' + lazProject.MainFile.FileName + NativeLineBreak +
'Are you sure that you want to format all ' + IntToStr(lazProject.FileCount) +
' files in the project.';
if MessageDlg(lsMsg, mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
exit;
ClearToolMessages;
{ loop through all modules in the project }
for liLoop := 0 to lazProject.FileCount - 1 do
begin
lazFile := lazProject.Files[liLoop];
FormatFile(lazFile.FileName);
end;
end;
procedure TJcfIdeMain.DoFormatOpen(Sender: TObject);
var
lciEditor: TSourceEditorInterface;
liLoop: integer;
begin
MakeEditorConverter;
if (SourceEditorWindow = nil) then
Exit;
ClearToolMessages;
fcEditorConverter.BeforeConvert;
for liLoop := 0 to SourceEditorWindow.Count - 1 do
begin
lciEditor := SourceEditorWindow.Items[liLoop];
// check that it's open, and a .pas or .dpr
if (lciEditor <> nil) and (FileIsAllowedType(lciEditor.FileName)) then
begin
fcEditorConverter.Convert(lciEditor);
end;
end;
fcEditorConverter.AfterConvert;
end;
procedure TJcfIdeMain.FormatFile(const psFileName: string);
begin
if not FileExists(psFileName) then
exit;
// check that it's a .pas or .dpr
if not FileIsAllowedType(psFileName) then
exit;
if fcFileConverter = nil then
begin
fcFileConverter := TFileConverter.Create;
fcFileConverter.OnStatusMessage := LogIDEMessage;
end;
fcFileConverter.ProcessFile(psFileName);
end;
procedure TJcfIdeMain.DoFormatSettings(Sender: TObject);
{var
lfAllSettings: TFormAllSettings;
}
begin
ShowMessage('unimplemented');
{ TODO: convert JCF settings form (it contains some TJvXXX components atm)
if not GetRegSettings.HasRead then
GetRegSettings.ReadAll;
lfAllSettings := TFormAllSettings.Create(nil);
try
lfAllSettings.Execute;
finally
lfAllSettings.Release;
end;
}
end;
procedure TJcfIdeMain.DoAbout(Sender: TObject);
var
lcAbout: TfrmAboutBox;
begin
lcAbout := TfrmAboutBox.Create(nil);
try
lcAbout.ShowModal;
finally
lcAbout.Free;
end;
end;
procedure TJcfIdeMain.DoRegistrySettings(Sender: TObject);
{var
lcAbout: TfmRegistrySettings;
}
begin
ShowMessage('unimplemented');
{ TODO: convert JCF registry settings (it contains some TJvXXX components atm)
if not GetRegSettings.HasRead then
GetRegSettings.ReadAll;
lcAbout := TfmRegistrySettings.Create(nil);
try
lcAbout.Execute;
finally
lcAbout.Free;
end;
}
end;
procedure TJcfIdeMain.LogIDEMessage(const psFile, psMessage: string;
const peMessageType: TStatusMessageType;
const piY, piX: integer);
var
lazMessages: TIDEMessagesWindowInterface;
begin
{ no empty lines in this log }
if psMessage = '' then
exit;
lazMessages := IDEMessagesWindow;
if lazMessages = nil then
exit;
if (piY >= 0) and (piX >= 0) then
lazMessages.AddMsg('JCF: ' + psMessage, psFile, 0)
//lazMessages.AddToolMessage(psFile, psMessage, 'JCF', piY, piX)
else
lazMessages.AddMsg('JCF: ' + psFile + ' ' + psMessage, '', 0);
//lazMessages.AddTitleMessage('JCF: ' + psFile + ' ' + psMessage);
end;
procedure TJcfIdeMain.MakeEditorConverter;
begin
if fcEditorConverter = nil then
begin
fcEditorConverter := TEditorConverter.Create;
fcEditorConverter.OnStatusMessage := LogIDEMessage;
end;
Assert(fcEditorConverter <> nil);
end;
procedure TJcfIdeMain.ClearToolMessages;
var
lazMessages: TIDEMessagesWindowInterface;
begin
lazMessages := IDEMessagesWindow;
if lazMessages = nil then
exit;
lazMessages.Clear;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program C11BEAU;
Uses Math;
Var
countA,countB,maxA,maxB,res :Int64;
t :ShortInt;
procedure Enter;
begin
Read(countA,countB,maxA,maxB);
end;
procedure Swap(var i,j :Int64);
var
tmp :Int64;
begin
tmp:=i; i:=j; j:=tmp;
end;
procedure Greedy;
begin
if (maxA=0) then countA:=0;
if (maxB=0) then countB:=0;
if (countA>countB) then
begin
Swap(countA,countB);
Swap(maxA,maxB);
end;
res:=countA+Min(countB,(countA+1)*maxB);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Read(t);
repeat
Dec(t);
Enter;
Greedy;
WriteLn(res);
until (t=0);
Close(Input); Close(Output);
End. |
unit mCoverSheetDisplayPanel_WidgetClock;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Proof of concept and a fun idea.
*
* Notes:
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Menus,
Vcl.ImgList,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
mCoverSheetDisplayPanel,
iCoverSheetIntf;
type
TfraCoverSheetDisplayPanel_WidgetClock = class(TfraCoverSheetDisplayPanel)
tmrClock: TTimer;
lblTime: TStaticText;
procedure tmrClockTimer(Sender: TObject);
private
{ Private declarations }
fUse24HourClock: TMenuItem;
fShowDayOfWeek: TMenuItem;
protected
{ Protected declerations }
procedure Use24HourClock(Sender: TObject);
procedure ShowDayOfWeek(Sender: TObject);
public
constructor Create(aOwner: TComponent); override;
end;
var
fraCoverSheetDisplayPanel_WidgetClock: TfraCoverSheetDisplayPanel_WidgetClock;
implementation
{$R *.dfm}
{ TfraCoverSheetDisplayPanel_WidgetClock }
constructor TfraCoverSheetDisplayPanel_WidgetClock.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
fUse24HourClock := NewItem('Use 24 Hour Clock', 0, False, True, Use24HourClock, 0, 'pmnClock_Use24Hour');
fShowDayOfWeek := NewItem('Show Day Of Week', 0, False, True, ShowDayOfWeek, 0, 'pmnClock_ShowDayOfWeek');
pmn.Items.Add(NewItem('-', 0, False, False, nil, 0, 'pmnClock_Separator'));
pmn.Items.Add(fUse24HourClock);
pmn.Items.Add(fShowDayOfWeek);
tmrClock.Interval := 60000;
tmrClockTimer(nil);
tmrClock.Enabled := True;
end;
procedure TfraCoverSheetDisplayPanel_WidgetClock.ShowDayOfWeek(Sender: TObject);
begin
fShowDayOfWeek.Checked := not fShowDayOfWeek.Checked;
tmrClockTimer(Sender);
end;
procedure TfraCoverSheetDisplayPanel_WidgetClock.Use24HourClock(Sender: TObject);
begin
fUse24HourClock.Checked := not fUse24HourClock.Checked;
tmrClockTimer(Sender);
end;
procedure TfraCoverSheetDisplayPanel_WidgetClock.tmrClockTimer(Sender: TObject);
var
aDayOfWeek: string;
begin
if fShowDayOfWeek.Checked then
aDayOfWeek := #13#10 + FormatDateTime('dddd', Now) + #13#10
else
aDayOfWeek := #13#10;
if fUse24HourClock.Checked then
lblTime.Caption := aDayOfWeek + FormatDateTime('mmm d, yyyy', Now) + #13#10 + 'Time: ' + FormatDateTime('hhnn', Now)
else
lblTime.Caption := aDayOfWeek + FormatDateTime('mmm d, yyyy', Now) + #13#10 + 'Time: ' + FormatDateTime('h:nn am/pm', Now);
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
ExtCtrls, StdCtrls, testmod, titreebuildvisitor;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Panel1: TPanel;
TV: TTreeView;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
TVM: TVisObjToTree;
testMod: TestModel;
testList: TestModelList;
FDataMappings: TTiTVDataMappings;
public
procedure setupdatamappings;
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
{//Purpose:
A visitor that will build a TreeView based on the Mappings given.
Usage:
var
lVisitor: TVisObjToTree;
begin
lVisitor := TVisObjToTree.Create(FTreeView);
lVisitor.DataMappings := DataMappings;
lVisitor.IncludeDeleted := False;
Data.Iterate( lVisitor );
end;
//}
procedure TForm1.FormCreate(Sender: TObject);
begin
testmod := TestModel.Create;
testList := TestModelList.Create;
FDataMappings := TTiTVDataMappings.Create(nil);
SetupDataMappings;
TVM := TVisObjToTree.Create(TV);
try
TVM.DataMappings := FDataMappings;
TVM.IncludeDeleted := False;
testlist.Iterate(TVM);
//gContactManager.ContactList.Iterate(lVisitor);
finally
//TVM lVisitor.Free;
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FDatamappings.Free;
testmod.Free;
testList.Free;
end;
procedure TForm1.setupdatamappings;
var
lMap: TtiTVDataMapping;
begin
lMap := TtiTVDataMapping(FDataMappings.Add(TestModel, 'Caption', 0));
lMap.CanInsert := False;
lMap.CanEdit := False;
lMap.CanDelete := False;
//lMap := TtiTVDataMapping(FDataMappings.Add(TAddress, 'Caption', 1));
//lMap.CanInsert := False;
//lMap.CanEdit := False;
//lMap.CanDelete := False;
// lMap := TtiTVDataMapping(FDataMappings.Add(TtiDBMetaDataField, 'Caption', 2));
// lMap.CanInsert := False;
// lMap.CanEdit := False;
// lMap.CanDelete := False;
end;
end.
|
unit Event1;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TfrmEvents = class(TForm)
GroupBox1: TGroupBox;
btnOpenDatabase: TButton;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
btnGenerateEvent: TButton;
Label1: TLabel;
btnRegisterEvents: TButton;
btnClearEvents: TButton;
lbReceived: TListBox;
ebEvent: TEdit;
moRegister: TMemo;
btnCloseDatabase: TButton;
procedure btnClearEventsClick(Sender: TObject);
procedure btnGenerateEventClick(Sender: TObject);
procedure btnRegisterEventsClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnOpenDatabaseClick(Sender: TObject);
procedure btnCloseDatabaseClick(Sender: TObject);
end;
var
frmEvents: TfrmEvents;
implementation
uses Event2, DB, DBTables, BDE;
{$R *.dfm}
procedure TfrmEvents.btnClearEventsClick(Sender: TObject);
begin
lbReceived.Clear;
end;
procedure TfrmEvents.btnGenerateEventClick(Sender: TObject);
begin
with dmEvents do
begin
Database1.StartTransaction;
StoredProc1.Prepare;
StoredProc1.Params[0].AsString := ebEvent.Text;
StoredProc1.ExecProc;
Database1.Commit;
end;
end;
procedure TfrmEvents.btnRegisterEventsClick(Sender: TObject);
begin
with dmEvents.IBEventAlerter1 do
begin
UnregisterEvents;
Events.Assign(moRegister.Lines);
RegisterEvents;
end;
end;
procedure TfrmEvents.FormDestroy(Sender: TObject);
begin
with dmEvents do
begin
IBEventAlerter1.UnregisterEvents;
Database1.Connected := False;
end;
GroupBox2.Enabled := False;
GroupBox3.Enabled := False;
GroupBox4.Enabled := False;
Label1.Enabled := False;
btnGenerateEvent.Enabled := False;
btnRegisterEvents.Enabled := False;
btnClearEvents.Enabled := False;
end;
procedure TfrmEvents.btnOpenDatabaseClick(Sender: TObject);
begin
dmEvents.Database1.Connected := True;
GroupBox2.Enabled := True;
GroupBox3.Enabled := True;
GroupBox4.Enabled := True;
Label1.Enabled := True;
btnGenerateEvent.Enabled := True;
btnRegisterEvents.Enabled := True;
btnClearEvents.Enabled := True;
btnCloseDatabase.Enabled := True;
btnOpenDatabase.Enabled:=False;
end;
procedure TfrmEvents.btnCloseDatabaseClick(Sender: TObject);
begin
dmEvents.IBEventAlerter1.UnregisterEvents;
dmEvents.Database1.Connected := False;
GroupBox2.Enabled := False;
GroupBox3.Enabled := False;
GroupBox4.Enabled := False;
Label1.Enabled := False;
btnGenerateEvent.Enabled := False;
btnRegisterEvents.Enabled := False;
btnClearEvents.Enabled := False;
btnCloseDatabase.Enabled := False;
btnOpenDatabase.Enabled := True;
end;
end.
|
unit ClassChess;
interface
uses ClassBoard, ClassPlayer, Types, ExtCtrls;
type TChess = class
private
Figures : TFigures;
Board : TBoard;
Players : array[1..2] of TPlayer;
procedure InitBoard;
function IsMat( Move : TMove ) : boolean;
procedure MakeMove( Move : TMove );
public
function Play : integer;
constructor Create( BoardImage : TImage );
destructor Destroy; override;
end;
var Chess : TChess;
implementation
uses ClassComputer;
//==============================================================================
// Constructor
//==============================================================================
procedure TChess.InitBoard;
var I, J : integer;
begin
for I := 1 to 8 do
for J := 1 to 8 do
Figures[I,J] := 0;
for I := 1 to 8 do
Figures[I,7] := 1;
for I := 1 to 5 do
Figures[I,8] := I+1;
Figures[6,8] := 4;
Figures[7,8] := 3;
Figures[8,8] := 2;
for I := 1 to 2 do
for J := 1 to 8 do
Figures[J,I] := -Figures[J,9-I];
Board.Repaint( Figures );
end;
constructor TChess.Create( BoardImage : TImage );
begin
inherited Create;
Board := TBoard.Create( BoardImage );
Players[1] := TComp.Create;
Players[2] := TComp.Create;
InitBoard;
end;
//==============================================================================
// Destructor
//==============================================================================
destructor TChess.Destroy;
begin
Players[1].Free;
Players[2].Free;
Board.Free;
inherited;
end;
//==============================================================================
// Chess play
//==============================================================================
function TChess.IsMat( Move : TMove ) : boolean;
begin
Result := False;
end;
procedure TChess.MakeMove( Move : TMove );
begin
Figures[Move.B.X,Move.B.Y] := Figures[Move.A.X,Move.A.Y];
Figures[Move.A.X,Move.A.Y] := 0;
Board.Repaint( Figures );
end;
//==============================================================================
// I N T E R F A C E
//==============================================================================
function TChess.Play : integer;
var I : integer;
NewMove : TMove;
begin
Result := 0;
repeat
for I := 1 to 2 do
begin
NewMove := Players[I].MakeMove( Figures );
if (not IsMat( NewMove )) then MakeMove( NewMove )
else
begin
Result := I;
break;
end;
end;
break;
until (Result <> 0);
end;
end.
|
{-Test prog for Anubis-OMAC, we Aug.2008}
{ Reproduce Anubis part of Tom St Denis' OMAC_TV.TXT}
program t_anomac;
{$i STD.INC}
{$ifdef APPCONS}
{$apptype console}
{$endif}
uses
{$ifdef WINCRT}
wincrt,
{$endif}
ANU_Base, ANU_OMAC, Mem_Util;
const
final: array[0..15] of byte = ($87,$b0,$c4,$8f,$3d,$15,$5a,$d8,
$5d,$05,$02,$d9,$4a,$45,$72,$de);
{---------------------------------------------------------------------------}
procedure omac_tv;
var
err, i, n: integer;
key, tag: TANUBlock;
inbuf: array[0..2*ANUBLKSIZE] of byte;
ctx: TANUContext;
begin
{Uppercase from HexStr}
HexUpper := true;
for i:=0 to ANUBLKSIZE-1 do key[i] := i;
for n:=0 to 2*ANUBLKSIZE do begin
for i:=0 to n-1 do inbuf[i] := i;
err := ANU_OMAC_Init(key,8*ANUBLKSIZE,ctx);
if err=0 then err := ANU_OMAC_Update(@inbuf,n,ctx);
if err<>0 then begin
writeln('ANU_OMAC error: ', err);
end;
ANU_OMAC_Final(tag,ctx);
writeln(n:3,': ', HexStr(@tag,16));
key := tag;
end;
if not compmem(@final,@tag, sizeof(final)) then writeln('Diff for final tag');
end;
begin
omac_tv;
end.
|
{
unit RegisterComp
ES: unidad para registrar los componentes que no dependen de ningún framework
EN: unit to register the components that no depend of any framework
=========================================================================
History:
ver 1.0.0
ES:
nuevo: registra el componente TGMGeoCode.
nuevo: registra el componente TGMGroundOverlay.
EN:
new: register the TGMGeoCode component.
new: register the TGMGroundOverlay component.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
Unit to register the components that no depend of any framework.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Unidad para registrar los componentes que no dependen de ningún framework.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit RegisterComp;
{$I ..\gmlib.inc}
{$IFNDEF DELPHI2009}
{$R ..\Resources\gmlibres.res}
{$ENDIF}
interface
{*------------------------------------------------------------------------------
The Register procedure register the components.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento Register registra los componentes.
-------------------------------------------------------------------------------}
procedure Register;
implementation
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMInfoWindow, GMGeoCode, GMGroundOverlay, GMHeatmap;
procedure Register;
begin
RegisterComponents('GoogleMaps', [TGMInfoWindow, TGMGeoCode, TGMGroundOverlay,
TGMHeatmap
]);
end;
end.
|
unit BaseQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls,
NotifyEvents, System.Contnrs, System.Generics.Collections, DBRecordHolder;
type
TParamRec = record
FieldName: String;
Value: Variant;
DataType: TFieldType;
CaseInsensitive: Boolean;
FullName: String;
Operation: String;
public
constructor Create(const AFullName: String; const AValue: Variant;
const ADataType: TFieldType = ftInteger;
const ACaseInsensitive: Boolean = False; const AOperation: String = '=');
end;
TQueryBase = class(TFrame)
FDQuery: TFDQuery;
Label1: TLabel;
private
FDetailParameterName: string;
FFDUpdateRecordEvent: TFDUpdateRecordEvent;
FFDUpdateSQL: TFDUpdateSQL;
FMaxUpdateRecCount: Integer;
FSQL: string;
FUpdateRecCount: Integer;
class var
function GetCashedRecordBalance: Integer;
function GetFDUpdateSQL: TFDUpdateSQL;
function GetParentValue: Integer;
{ Private declarations }
protected
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
procedure DoOnQueryUpdateRecord(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
procedure DoOnUpdateRecordException(AException: Exception); virtual;
procedure FDQueryUpdateRecordOnClient(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
function GetHaveAnyChanges: Boolean; virtual;
function GetHaveAnyNotCommitedChanges: Boolean; virtual;
property FDUpdateSQL: TFDUpdateSQL read GetFDUpdateSQL;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure BeginApplyUpdatesOnClient;
procedure ClearUpdateRecCount;
procedure DeleteFromClient;
procedure EndApplyUpdatesOnClient;
procedure FetchFields(const AFieldNames: TArray<String>;
const AValues: TArray<Variant>; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); overload;
procedure FetchFields(ARecordHolder: TRecordHolder;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions); overload;
procedure IncUpdateRecCount;
procedure Load(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>); overload;
procedure SetParameters(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>);
function Search(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>; TestResult: Integer = -1)
: Integer; overload;
function SearchEx(AParams: TArray<TParamRec>; TestResult: Integer = -1;
ASQL: String = ''): Integer;
function SetParamType(const AParamName: String;
AParamType: TParamType = ptInput; ADataType: TFieldType = ftInteger)
: TFDParam;
function SetParamTypeEx(const AParamName: String; AValue: Variant;
AParamType: TParamType = ptInput; ADataType: TFieldType = ftInteger)
: TFDParam;
procedure UpdateFields(AFields: TArray<TField>; AValues: TArray<Variant>;
AUpdateNullFieldsOnly: Boolean);
property CashedRecordBalance: Integer read GetCashedRecordBalance;
property DetailParameterName: string read FDetailParameterName
write FDetailParameterName;
property HaveAnyChanges: Boolean read GetHaveAnyChanges;
property ParentValue: Integer read GetParentValue;
property SQL: string read FSQL;
{ Public declarations }
published
end;
implementation
uses System.Math, RepositoryDataModule, StrHelper, MapFieldsUnit,
System.StrUtils;
{$R *.dfm}
{ TfrmDataModule }
constructor TQueryBase.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// Максимальное количество обновлённых записей в рамках одной транзакции
FMaxUpdateRecCount := 1000;
end;
destructor TQueryBase.Destroy;
begin
inherited;
end;
procedure TQueryBase.AfterConstruction;
begin
inherited;
// Сохраняем первоначальный SQL
FSQL := FDQuery.SQL.Text;
end;
procedure TQueryBase.ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQueryBase.ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQueryBase.ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQueryBase.BeginApplyUpdatesOnClient;
begin
Assert(not Assigned(FFDUpdateRecordEvent));
FFDUpdateRecordEvent := FDQuery.OnUpdateRecord;
FDQuery.OnUpdateRecord := FDQueryUpdateRecordOnClient;
end;
procedure TQueryBase.EndApplyUpdatesOnClient;
begin
Assert(Assigned(FFDUpdateRecordEvent));
FDQuery.OnUpdateRecord := FFDUpdateRecordEvent;
FFDUpdateRecordEvent := nil
end;
// Есть-ли изменения не сохранённые в БД
function TQueryBase.GetHaveAnyChanges: Boolean;
begin
Result := FDQuery.State in [dsEdit, dsInsert];
if Result then
Exit;
// Если все изменения кэшируются на стороне клиента
if FDQuery.CachedUpdates then
begin
Result := FDQuery.ChangeCount > 0;
end
else
begin
// если транзакция не завершена
Result := FDQuery.Connection.InTransaction and GetHaveAnyNotCommitedChanges;
end;
end;
procedure TQueryBase.ClearUpdateRecCount;
begin
FUpdateRecCount := 0;
end;
procedure TQueryBase.DeleteFromClient;
begin
Assert(FDQuery.RecordCount > 0);
BeginApplyUpdatesOnClient;
try
FDQuery.Delete;
finally
EndApplyUpdatesOnClient;
end;
end;
procedure TQueryBase.DoOnQueryUpdateRecord(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
if ARequest in [arDelete, arInsert, arUpdate] then
begin
// try
// Если произошло удаление
if ARequest = arDelete then
begin
ApplyDelete(ASender, ARequest, AAction, AOptions);
AAction := eaApplied;
end;
// Операция добавления записи на клиенте
if ARequest = arInsert then
begin
ApplyInsert(ASender, ARequest, AAction, AOptions);
AAction := eaApplied;
end;
// Операция обновления записи на клиенте
if ARequest = arUpdate then
begin
ApplyUpdate(ASender, ARequest, AAction, AOptions);
AAction := eaApplied;
end;
{
except
on E: Exception do
begin
AAction := eaFail;
DoOnUpdateRecordException(E);
end;
end;
}
end
// else
// AAction := eaSkip;
end;
procedure TQueryBase.DoOnUpdateRecordException(AException: Exception);
begin
raise AException;
end;
procedure TQueryBase.FDQueryUpdateRecordOnClient(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
inherited;
AAction := eaApplied;
end;
procedure TQueryBase.FetchFields(const AFieldNames: TArray<String>;
const AValues: TArray<Variant>; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
var
ASQL: string;
i: Integer;
S: string;
V: Variant;
begin
Assert(Low(AFieldNames) = Low(AValues));
Assert(High(AFieldNames) = High(AValues));
ASQL := 'SELECT ';
for i := Low(AFieldNames) to High(AFieldNames) do
begin
V := AValues[i];
Assert(not VarIsNull(V));
if VarIsStr(V) then
S := QuotedStr(V)
else
begin
S := V;
// Если у нас вещественное число,
// надо в SQL запросе в качестве разделителя использовать точку
if VarIsType(V, [varDouble, varCurrency]) then
S := S.Replace(',', '.');
end;
S := S + ' ' + AFieldNames[i];
if i > Low(AFieldNames) then
ASQL := ASQL + ', ';
ASQL := ASQL + S;
end;
case ARequest of
arInsert:
FDUpdateSQL.InsertSQL.Text := ASQL;
arUpdate:
FDUpdateSQL.ModifySQL.Text := ASQL;
end;
FDUpdateSQL.Apply(ARequest, AAction, AOptions);
end;
procedure TQueryBase.FetchFields(ARecordHolder: TRecordHolder;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
ASQL: string;
i: Integer;
S: string;
V: Variant;
begin
ASQL := 'SELECT ';
for i := 0 to ARecordHolder.Count - 1 do
begin
V := ARecordHolder[i].Value;
if VarIsNull(V) then
Continue;
if VarIsStr(V) then
S := QuotedStr(V)
else
begin
S := V;
// Если у нас вещественное число,
// надо в SQL запросе в качестве разделителя использовать точку
if VarIsType(V, [varDouble, varCurrency]) then
S := S.Replace(',', '.');
end;
S := S + ' ' + ARecordHolder[i].FieldName;
if i > 0 then
ASQL := ASQL + ', ';
ASQL := ASQL + S;
end;
case ARequest of
arInsert:
FDUpdateSQL.InsertSQL.Text := ASQL;
arUpdate:
FDUpdateSQL.ModifySQL.Text := ASQL;
end;
FDUpdateSQL.Apply(ARequest, AAction, AOptions);
end;
function TQueryBase.GetCashedRecordBalance: Integer;
var
AClone: TFDMemTable;
begin
Result := 0;
// Exit;
if not FDQuery.Active then
Exit;
// Если все изменения кэшируются на стороне клиента
if FDQuery.CachedUpdates then
begin
// Создаём клона
AClone := TFDMemTable.Create(Self);
try
AClone.CloneCursor(FDQuery);
// Добавляем кол-во добавленных
AClone.FilterChanges := [rtInserted];
Result := AClone.RecordCount;
// Вычитаем кол-во удалённых
AClone.FilterChanges := [rtDeleted];
Result := Result - AClone.RecordCount;
finally
FreeAndNil(AClone);
end;
end
else
Result := IfThen(FDQuery.State in [dsInsert], 1, 0);
end;
function TQueryBase.GetFDUpdateSQL: TFDUpdateSQL;
begin
if FFDUpdateSQL = nil then
begin
FFDUpdateSQL := TFDUpdateSQL.Create(Self);
FFDUpdateSQL.DataSet := FDQuery;
end;
Result := FFDUpdateSQL;
end;
function TQueryBase.GetHaveAnyNotCommitedChanges: Boolean;
begin
Result := True;
end;
function TQueryBase.GetParentValue: Integer;
begin
Assert(DetailParameterName <> '');
Result := FDQuery.Params.ParamByName(DetailParameterName).AsInteger;
end;
procedure TQueryBase.IncUpdateRecCount;
begin
Assert(FDQuery.Connection.InTransaction);
Assert(FUpdateRecCount < FMaxUpdateRecCount);
Inc(FUpdateRecCount);
if FUpdateRecCount >= FMaxUpdateRecCount then
begin
// Делаем промежуточный коммит
FDQuery.Connection.Commit;
FUpdateRecCount := 0;
end;
end;
procedure TQueryBase.Load(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>);
begin
FDQuery.DisableControls;
try
FDQuery.Close;
SetParameters(AParamNames, AParamValues);
FDQuery.Open;
finally
FDQuery.EnableControls;
end;
end;
procedure TQueryBase.SetParameters(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>);
var
i: Integer;
begin
Assert(Low(AParamNames) = Low(AParamValues));
Assert(High(AParamNames) = High(AParamValues));
for i := Low(AParamNames) to High(AParamNames) do
begin
FDQuery.ParamByName(AParamNames[i]).Value := AParamValues[i];
end;
end;
function TQueryBase.Search(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>; TestResult: Integer = -1): Integer;
begin
Load(AParamNames, AParamValues);
Result := FDQuery.RecordCount;
if TestResult >= 0 then
Assert(Result = TestResult);
end;
function TQueryBase.SearchEx(AParams: TArray<TParamRec>;
TestResult: Integer = -1; ASQL: String = ''): Integer;
var
AParamNames: TList<String>;
AFormatStr: string;
ANewValue: string;
ANewSQL: string;
AValues: TList<Variant>;
i: Integer;
begin
Assert(Length(AParams) > 0);
// Восстанавливаем первоначальный SQL или используем заданный
ANewSQL := IfThen(ASQL.IsEmpty, SQL, ASQL);
for i := Low(AParams) to High(AParams) do
begin
// Если поиск нечувствительный к регистру
if AParams[i].CaseInsensitive then
AFormatStr := 'upper(%s) %s upper(:%s)'
else
AFormatStr := '%s %s :%s';
ANewValue := Format(AFormatStr, [AParams[i].FullName, AParams[i].Operation,
AParams[i].FieldName]);
// Делаем замену в SQL запросе
ANewSQL := ReplaceInSQL(ANewSQL, ANewValue, i);
end;
// Меняем SQL запрос
FDQuery.SQL.Text := ANewSQL;
AParamNames := TList<String>.Create;
AValues := TList<Variant>.Create;
try
// Создаём параметры SQL запроса
for i := Low(AParams) to High(AParams) do
begin
SetParamType(AParams[i].FieldName, ptInput, AParams[i].DataType);
AParamNames.Add(AParams[i].FieldName);
AValues.Add(AParams[i].Value);
end;
// Выполняем поиск
Result := Search(AParamNames.ToArray, AValues.ToArray, TestResult);
finally
FreeAndNil(AParamNames);
FreeAndNil(AValues);
end;
end;
function TQueryBase.SetParamType(const AParamName: String;
AParamType: TParamType = ptInput; ADataType: TFieldType = ftInteger)
: TFDParam;
begin
Result := FDQuery.FindParam(AParamName);
Assert(Result <> nil);
Result.ParamType := AParamType;
Result.DataType := ADataType;
end;
function TQueryBase.SetParamTypeEx(const AParamName: String; AValue: Variant;
AParamType: TParamType = ptInput; ADataType: TFieldType = ftInteger)
: TFDParam;
begin
Assert(not VarIsNull(AValue));
Result := SetParamType(AParamName, AParamType, ADataType);
Result.Value := AValue;
end;
procedure TQueryBase.UpdateFields(AFields: TArray<TField>;
AValues: TArray<Variant>; AUpdateNullFieldsOnly: Boolean);
var
f: TField;
i: Integer;
V: Variant;
begin
Assert(FDQuery.State in [dsInsert, dsEdit]);
Assert(Length(AFields) > 0);
Assert(Length(AFields) = Length(AValues));
// Обновляет пустые значения полей на значения из ADataSet
for i := Low(AFields) to High(AFields) do
begin
f := AFields[i];
V := AValues[i];
// Если NULL или пустая строка
if ((not AUpdateNullFieldsOnly) or (f.IsNull or f.AsString.Trim.IsEmpty))
and (not VarIsNull(V) and (not VarToStr(V).Trim.IsEmpty)) then
f.Value := V;
end;
end;
constructor TParamRec.Create(const AFullName: String; const AValue: Variant;
const ADataType: TFieldType = ftInteger;
const ACaseInsensitive: Boolean = False; const AOperation: String = '=');
var
p: Integer;
begin
inherited;
Assert(not AFullName.IsEmpty);
Assert(not VarIsNull(AValue));
FullName := AFullName;
p := FullName.IndexOf('.');
FieldName := IfThen(p > 0, AFullName.Substring(p + 1), AFullName);
Value := AValue;
DataType := ADataType;
CaseInsensitive := ACaseInsensitive;
Operation := AOperation;
if ACaseInsensitive then
Assert(ADataType = ftWideString);
end;
end.
|
unit Senl;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ParseMath, Func, Math, Matrices, Dialogs;
type
TSENL = class
private
MList: TList;
public
ECNL: array of string;
MP: array of real;
VX: array of string;
MParse: TParseMath;
n: integer;
MATJ: TMatriz;
constructor Create();
destructor Destroy(); override;
procedure SetVariable(nt: integer; _ECNL: VectString; _MP: VectReal);
function SF(ec: string; x: TMatriz): real;
function SFF(x: TMatriz): TMatriz;
function SDP(f,v: integer; x: TMatriz; h: real): real;
function Jacob(a: TMatriz; h: real): TMatriz;
function FX(a: TMatriz): TMatriz;
function NewtonGeneralizado(e: real): TBox;
function Distance(a,b: TMatriz): real;
function CreateBox(nt: integer): TBox;
end;
implementation
function MtoV(a: TMatriz): VectReal;
var
i: integer;
begin
SetLength(Result,a.x);
for i:=0 to a.x-1 do
Result[i] := a.m[i,0];
end;
function VtoM(a: VectReal): TMatriz;
var
i: integer;
begin
Result := TMatriz.Create(Length(a),1);
for i:=0 to Length(a)-1 do
Result.m[i,0] := a[i];
end;
function TSENL.SF(ec: string; x: TMatriz): real;
var i: integer;
begin
for i:=0 to x.x-1 do
MParse.NewValue(VX[i],x.m[i,0]);
MParse.Expression:= ec;
Result := MParse.Evaluate();
end;
function TSENL.SFF(x: TMatriz): TMatriz;
var i,nt: integer;
begin
nt:= x.x;
Result := TMatriz.Create(nt,1);
for i:=0 to nt-1 do begin
Result.m[i,0] := Self.SF(ECNL[i],x);
end;
end;
function TSENL.SDP(f,v: integer; x: TMatriz; h: real): real;
var
i: integer;
xi, xj: TMatriz;
begin
h:= h/10;
xi:= TMatriz.Create(x.x,1); xj:= TMatriz.Create(x.x,1);
for i:=0 to x.x-1 do begin
xi.m[i,0] := x.m[i,0];
xj.m[i,0] := x.m[i,0];
end;
xi.m[v,0]:= xi.m[v,0]+h; xj.m[v,0]:= xj.m[v,0]-h;
Result:= (Self.SF(ECNL[f],xi)-Self.SF(ECNL[f],xj))/(2*h);
end;
procedure TSENL.SetVariable(nt: integer; _ECNL: VectString; _MP: VectReal);
var
i: integer;
begin
MParse:= TParseMath.Create();
ECNL:= _ECNL;
MP:= _MP;
for i:= 0 to nt-1 do begin
MParse.AddVariable(VX[i],0.0);
end;
end;
constructor TSENL.Create();
begin
n:= 12;
SetLength(VX,n);
VX[0]:= 'a'; VX[1]:= 'b'; VX[2]:= 'c';
VX[3]:= 'd'; VX[4]:= 'e'; VX[5]:= 'f';
VX[6]:= 'g'; VX[7]:= 'h'; VX[8]:= 'i';
VX[9]:= 'j'; VX[10]:= 'k'; VX[11]:= 'l';
MList:= TList.Create();
end;
destructor TSENL.Destroy();
begin
end;
function TSENL.Jacob(a: TMatriz; h: real): TMatriz;
var
i,j,s: integer;
begin
s := a.x;
Result := TMatriz.Create(s,s);
for i:=0 to s-1 do
for j:=0 to s-1 do
Result.m[i,j] := SDP(i,j,a,h);
end;
function TSENL.FX(a: TMatriz): TMatriz;
var
i: integer;
begin
Result := TMatriz.Create(a.x,1);
for i:=0 to a.x-1 do
Result.m[i,0] := SF(ECNL[i],a);
end;
function TSENL.Distance(a,b: TMatriz): real;
var
i: integer;
begin
Result := 0;
for i:=0 to a.x-1 do begin
Result := Result+power(a.m[i,0]-b.m[i,0],2);
end;
Result := Sqrt(Result);
end;
function TSENL.CreateBox(nt: integer): TBox;
var
ntt,i,j,k: integer;
begin
ntt:= (MList.Count div nt);
Result:= TBox.Create(ntt+1,nt+1);
Result.M[0,0]:= 'n'; Result.M[0,nt]:= 'e';
for i:=0 to nt-2 do
Result.M[0,i+1]:= VX[i];
j:= 1; i:=0;
while(i<MList.Count) do begin
Result.M[j,0]:= IntToStr(j-1);
for k:=0 to nt-1 do
Result.M[j,k+1]:= FloatToStr(Real(MList.Items[i+k]));
i:= i+nt;
j:= j+1;
end;
end;
function TSENL.NewtonGeneralizado(e: real): TBox;
var
t: boolean;
Ea: real;
VM, PR, FT, TMP: TMatriz;
det: TRD;
i,j: integer;
begin
Ea:= e+1; j := 1;
t:= True;
MList.Clear;
VM:= VtoM(MP);
while(e<Ea) and (t=True) do begin
TMP:= VM;
MATJ:= Self.Jacob(VM,0.0001);
det:= MATJ.Determinante();
if(det.Value <> 0) then begin
PR:= MATJ.Inversa(det.Value);
FT:= SFF(VM);
VM:= VM-(PR*FT);
for i:=1 to VM.x do
MList.Add(Pointer(VM.M[i-1][0]));
Ea:= Self.Distance(TMP,VM);
MList.Add(Pointer(Ea));
j:= j+1;
end
else begin
t:= False;
ShowMessage('Determinante en la iteración '+IntToStr(j-1)+' es 0');
exit;
end;
end;
Result:= CreateBox(Length(MP)+1);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit TypeTrans;
interface
uses TypInfo, IntfInfo, SysUtils, InvokeRegistry;
type
TTypeTranslator = class
public
constructor Create;
destructor Destroy; override;
function CastSoapToNative(Info: PTypeInfo; const SoapData: WideString;
NatData: Pointer; IsNull: Boolean): Boolean;
procedure CastNativeToSoap(Info: PTypeInfo; var SoapData: WideString;
NatData: Pointer; var IsNull: Boolean);
procedure CastSoapToVariant(SoapInfo: PTypeInfo; const SoapData: WideString; NatData: Pointer); overload;
function CastSoapToVariant(SoapInfo: PTypeInfo; const SoapData: WideString): Variant; overload;
procedure Base64ToVar(NatData: Pointer; const SoapData: WideString); overload;
procedure Base64ToVar(var V: Variant; const SoapData: WideString); overload;
end;
ETypeTransException = class(Exception);
function FloatToStrEx(Value: Extended): string;
function StrToFloatEx(const S: string): Extended;
function GetEnumValueEx(TypInfo: PTypeInfo; const Name: string): Integer;
procedure SetEnumPropEx(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
TypeTranslator: TTypeTranslator;
implementation
uses Variants, SOAPConst, EncdDecd, Types, Math, XSBuiltIns;
constructor TTypeTranslator.Create;
begin
inherited Create;
end;
destructor TTypeTranslator.Destroy;
begin
inherited;
end;
type
PWideChar = ^WideChar;
function TTypeTranslator.CastSoapToVariant(SoapInfo: PTypeInfo; const SoapData: WideString): Variant;
var
I64: Int64;
begin
case SoapInfo.Kind of
tkString,
tkLString,
tkChar:
Result := SoapData;
tkInt64:
Result := StrToInt64(Trim(SoapData));
tkInteger:
begin
if GetTypeData(SoapInfo).OrdType = otULong then
begin
I64 := StrToInt64(Trim(SoapData));
Result := Cardinal(I64);
end else
Result := StrToInt(Trim(SoapData));
end;
tkFloat:
Result:= StrToFloatEx(Trim(SoapData));
tkWChar,
tkWString:
Result := WideString(Trim(SoapData));
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkEnumeration:
raise ETypeTransException.Create(SVariantCastNotSupported);
tkDynArray:
begin
if SameTypeInfo(TypeInfo(Types.TByteDynArray), SoapInfo) then
Base64ToVar(Result, SoapData)
else
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
end;
end;
procedure TTypeTranslator.CastSoapToVariant(SoapInfo: PTypeInfo; const SoapData: WideString; NatData: Pointer);
begin
case SoapInfo.Kind of
tkString,
tkLString,
tkChar:
Variant(PVarData(NatData)^) := SoapData;
tkInt64:
Variant(PVarData(NatData)^) := StrToInt64(Trim(SoapData));
tkInteger:
Variant(PVarData(NatData)^) := StrToInt(Trim(SoapData));
tkFloat:
Variant(PVarData(NatData)^) := StrToFloatEx(Trim(SoapData));
tkWChar,
tkWString:
Variant(PVarData(NatData)^) := WideString(SoapData);
tkDynArray:
begin
if SameTypeInfo(TypeInfo(Types.TByteDynArray), SoapInfo) then
Base64ToVar(NatData, SoapData)
else
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkEnumeration:
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
end;
{ Convert string to Enum value }
function GetEnumValueEx(TypInfo: PTypeInfo; const Name: string): Integer;
var
PName: string;
begin
PName := Name;
if SameTypeInfo(TypeInfo(System.Boolean), TypInfo) or
SameTypeInfo(TypeInfo(System.ByteBool), TypInfo) or
SameTypeInfo(TypeInfo(System.WordBool), TypInfo) or
SameTypeInfo(TypeInfo(System.LongBool), TypInfo) then
begin
if SameText(Name, 'true') or SameText(Name, '1') then { Do not localize }
PName := 'True' { Do not localize }
else if SameText(Name, 'false') or SameText(Name, '0') then { Do not localize }
PName := 'False'; { Do not localize }
Result := GetEnumValue(TypeInfo(System.Boolean), PName);
end else
begin
Result := GetEnumValue(TypInfo, PName);
end;
end;
{ Convert String to Float }
function StrToFloatEx(const S: string): Extended;
begin
if SameText(S, 'NaN') then
Result := Nan
else if SameText(S, 'INF') then
Result := Infinity
else if SameText(S, '-INF') then
Result := NegInfinity
else
Result := SoapStrToFloat(S);
end;
function IsNeg(const AValue: Double): Boolean;
begin
Result := ((PInt64(@AValue)^ and $8000000000000000) = $8000000000000000);
end;
{ Convert float to String }
function FloatToStrEx(Value: Extended): string;
begin
if IsNan(Value) then
Result := 'NaN'
else if IsInfinite(Value) then
begin
{ +|- ve }
if isNeg(Value) then
Result := '-INF'
else
Result := 'INF';
end
else
Result := SoapFloatToStr(Value);
end;
procedure SetEnumPropEx(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Val: string;
begin
Val := RemClassRegistry.GetInternalPropName(PropInfo.PropType^, Value);
SetEnumProp(Instance, PropInfo, Val);
end;
function TTypeTranslator.CastSoapToNative(Info: PTypeInfo; const SoapData: WideString; NatData: Pointer; IsNull: Boolean): Boolean;
var
ParamTypeData: PTypeData;
begin
DecimalSeparator := '.';
Result := True;
if IsNull and (Info.Kind = tkVariant) then
begin
Variant(PVarData(NatData)^) := NULL;
Exit;
end;
ParamTypeData := GetTypeData(Info);
case Info^.Kind of
tkInteger:
case ParamTypeData^.OrdType of
otSByte,
otUByte:
PByte(NatData)^ := StrToInt(Trim(SoapData));
otSWord,
otUWord:
PSmallInt(NatData)^ := StrToInt(Trim(SoapData));
otSLong,
otULong:
PInteger(NatData)^ := StrToInt(Trim(SoapData));
end;
tkFloat:
case ParamTypeData^.FloatType of
ftSingle:
PSingle(NatData)^ := StrToFloatEx(Trim(SoapData));
ftDouble:
begin
if Info = TypeInfo(TDateTime) then
PDateTime(NatData)^ := XMLTimeToDateTime(Trim(SoapData))
else
PDouble(NatData)^ := StrToFloatEx(Trim(SoapData));
end;
ftComp:
PComp(NatData)^ := StrToFloatEx(Trim(SoapData));
ftCurr:
PCurrency(NatData)^ := StrToFloatEx(Trim(SoapData));
ftExtended:
PExtended(NatData)^ := StrToFloatEx(Trim(SoapData));
end;
tkWString:
PWideString(NatData)^ := SoapData;
tkString:
PShortString(NatData)^ := SoapData;
tkLString:
PString(NatData)^ := SoapData;
tkChar:
if SoapData <> '' then
PChar(NatData)^ := Char(SoapData[1]);
tkWChar:
if SoapData <> '' then
PWideChar(NatData)^ := WideChar(SoapData[1]);
tkInt64:
PInt64(NatData)^ := StrToInt64(Trim(SoapData));
tkEnumeration:
{ NOTE: Here we assume enums to be byte-size; make sure (specially for C++)
that enums have generated with the proper size }
PByte(NatData)^ := GetEnumValueEx(Info, Trim(SoapData));
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkDynArray:
raise ETypeTransException.CreateFmt(SUnexpectedDataType, [ KindNameArray[Info.Kind]] );
tkVariant:
CastSoapToVariant(Info, SoapData, NatData);
end;
end;
procedure TTypeTranslator.CastNativeToSoap(Info: PTypeInfo;
var SoapData: WideString; NatData: Pointer; var IsNull: Boolean);
var
TypeData: PTypeData;
begin
TypeData := GetTypeData(Info);
case Info.Kind of
tkInteger:
case TypeData.OrdType of
otSByte,
otUByte:
SoapData := IntToStr(byte(NatData^) );
otSWord:
SoapData := IntToStr(SmallInt(NatData^));
otUWord:
SoapData := IntToStr(SmallInt(NatData^));
otSLong,
otULong:
SoapData := IntToStr(Integer(NatData^));
end;
tkFloat:
case TypeData.FloatType of
ftSingle:
SoapData := FloatToStrEx(Single(NatData^));
ftDouble:
begin
if Info = TypeInfo(TDateTime) then
SoapData := DateTimeToXMLTime(TDateTime(NatData^), True)
else
SoapData := FloatToStrEx(Double(NatData^));
end;
ftComp:
SoapData := FloatToStrEx(Comp(NatData^));
ftCurr:
SoapData := FloatToStrEx(Currency(NatData^));
ftExtended:
SoapData := FloatToStrEx(Extended(NatData^));
end;
tkInt64:
SoapData := IntToStr(Int64(NatData^));
tkChar:
SoapData := Char(NatData^);
tkWChar:
SoapData := WideChar(NatData^);
tkWString:
SoapData := PWideString(NatData)^;
tkString:
SoapData := PShortString(NatData)^;
tkLString:
SoapData := PAnsiString(NatData)^;
end;
end;
procedure TTypeTranslator.Base64ToVar(var V: Variant; const SoapData: WideString);
var
Base64Dec: String;
P: Pointer;
begin
Base64Dec := DecodeString(SoapData);
V := VarArrayCreate([0, Length(Base64Dec) - 1], varByte);
P := VarArrayLock(V);
try
Move(Base64Dec[1], P^, Length(Base64Dec));
finally
VarArrayUnLock(V);
end;
end;
procedure TTypeTranslator.Base64ToVar(NatData: Pointer; const SoapData: WideString);
begin
Base64ToVar(PVariant(PVarData(NatData))^, SoapData);
end;
initialization
TypeTranslator := TTypeTranslator.Create;
finalization
TypeTranslator.Free;
end.
|
unit lib_cadastros_iniciais;
interface
uses Windows, Messages, SysUtils;
type
TCadastrosIniciais = class(TObject)
private
FDataPadrao: TDateTime;
procedure AddEmpresa;
procedure AddPaises;
procedure AddEstados;
procedure AddCidade;
procedure AddAbairro;
procedure AddFuncionario;
procedure AddCaixa;
procedure AddAlmoxarifado;
procedure AddUnidade;
procedure AddParametrosSincronizacao;
public
FidEmpresa : Integer;
FidPais : Integer;
FidEstado : Integer;
FIdCidade : Integer;
FidBairro : Integer;
FidAlmoxarifado : Integer;
FidUnidade : Integer;
FIdFuncionario : Integer;
Fusuario : String;
FNomeEmpresa : String;
FNomeUnidade : String;
procedure Executar;
end;
implementation
uses lib_acesso, lib_db, Classes;
{ TCadastrosIniciais }
procedure TCadastrosIniciais.AddAbairro;
var
tbBairro : TObjetoDB;
begin
tbBairro := TObjetoDB.create('bairro');
try
// tbBairro.AddParametro('empresa_id', FidEmpresa);
tbBairro.AddParametro('cdbairro', '1');
tbBairro.Select(['id']);
if not tbBairro.IsEmpty then
begin
FidBairro := tbBairro.GetVal('id');
Exit;
end;
tbBairro.AddParametro('nmbairro', 'JARDIM VITÓRIA');
tbBairro.AddParametro('dtcadastro', FDataPadrao);
// tbBairro.AddParametro('pais_id', FidPais);
// tbBairro.AddParametro('estado_id', FidEstado);
tbBairro.AddParametro('cidade_id', FIdCidade);
tbBairro.Insert;
tbBairro.Select(['id']);
FidBairro := tbBairro.GetVal('id');
finally
FreeAndNil(tbBairro);
end
end;
procedure TCadastrosIniciais.AddAlmoxarifado;
var
tbAlmoxarifado : TObjetoDB;
begin
tbAlmoxarifado := TObjetoDB.create('Almoxarifado');
try
tbAlmoxarifado.AddParametro('nmalmoxa', 'Almoxarifado padrão');
tbAlmoxarifado.Select(['id']);
if tbAlmoxarifado.IsEmpty then
begin
tbAlmoxarifado.AddParametro('dtcadastro', FDataPadrao);
tbAlmoxarifado.Insert;
tbAlmoxarifado.Select(['id']);
FidAlmoxarifado := tbAlmoxarifado.GetVal('id');
Exit;
end;
FidAlmoxarifado := tbAlmoxarifado.GetVal('id');
finally
FreeAndNil(tbAlmoxarifado);
end;
end;
procedure TCadastrosIniciais.AddCaixa;
var
tbCaixa : TObjetoDB;
begin
tbCaixa := TObjetoDB.create('caixa');
try
tbCaixa.Select(['id']);
if tbCaixa.IsEmpty then
begin
tbCaixa.AddParametro('nmcaixa', 'CAIXA');
tbCaixa.Insert;
end;
finally
FreeAndNil(tbCaixa);
end;
end;
procedure TCadastrosIniciais.AddCidade;
var
tbCidade : TObjetoDB;
begin
tbCidade := TObjetoDB.create('cidade');
try
// tbCidade.AddParametro('empresa_id', FidEmpresa);
tbCidade.AddParametro('cdcidade', '1');
tbCidade.Select(['id']);
if not tbCidade.IsEmpty then
begin
FIdCidade := tbCidade.GetVal('id');
Exit;
end;
tbCidade.AddParametro('nmcidade', 'BELO HORIZONTE');
tbCidade.AddParametro('dtcadastro', FDataPadrao);
tbCidade.AddParametro('pais_id', FidPais);
tbCidade.AddParametro('estado_id', FidEstado);
tbCidade.Insert;
tbCidade.Select(['id']);
FIdCidade := tbCidade.GetVal('id');
finally
FreeAndNil(tbCidade);
end
end;
procedure TCadastrosIniciais.AddEmpresa;
var
tbEmpresa : TObjetoDB;
begin
tbEmpresa := TObjetoDB.create('empresa');
try
tbEmpresa.AddParametro('codigo', '01');
tbEmpresa.Select(['id', 'nmempresa']);
if not tbEmpresa.IsEmpty then
begin
FidEmpresa := tbEmpresa.GetVal('id');
FNomeEmpresa := tbEmpresa.GetVal('nmempresa');
Exit;
end;
tbEmpresa.AddParametro('nmempresa', 'Empresa Padrao');
tbEmpresa.AddParametro('dtcadastro', FDataPadrao);
tbEmpresa.Insert;
tbEmpresa.Select(['id']);
FidEmpresa := tbEmpresa.GetVal('id');
FNomeEmpresa := 'Empresa Padrão';
finally
FreeAndNil(tbEmpresa);
end
end;
procedure TCadastrosIniciais.AddEstados;
var
tbEstado : TObjetoDB;
begin
tbEstado := TObjetoDB.create('estado');
try
// tbEstado.AddParametro('empresa_id', FidEmpresa);
tbEstado.AddParametro('cdestado', '31');
tbEstado.Select(['id']);
if not tbEstado.IsEmpty then
begin
FidEstado := tbEstado.GetVal('id');
Exit;
end;
tbEstado.AddParametro('dtcadastro', FDataPadrao);
tbEstado.AddParametro('nmestado', 'MINAS GERAIS');
tbEstado.AddParametro('sgestado', 'MG');
tbEstado.AddParametro('pais_id', FidPais);
tbEstado.AddParametro('dsregiao', 'SUDESTE');
tbEstado.Insert;
tbEstado.Select(['id']);
FidEstado := tbEstado.GetVal('id');
finally
FreeAndNil(tbEstado);
end;
end;
procedure TCadastrosIniciais.AddFuncionario;
var
tbFunc : TobjetoDB;
begin
tbFunc := TObjetoDB.create('funcionario');
try
tbFunc.AddParametro('usuario', 'vmsismaster');
tbFunc.Select(['id', 'usuario']);
if not tbFunc.IsEmpty then
begin
FIdFuncionario := tbFunc.GetVal('id');
Fusuario := tbFunc.GetVal('usuario');
Exit;
end;
// tbFunc.AddParametro('empresa_id', FidEmpresa);
tbFunc.AddParametro('dtcadastro', FDataPadrao);
tbFunc.AddParametro('nome', 'vmsismaster');
tbFunc.AddParametro('sexo', 'M');
tbFunc.AddParametro('dtnascimento', FDataPadrao);
tbFunc.AddParametro('email', 'vmsis@vmsis.com.br');
tbFunc.AddParametro('senha', 'masterVMSIS123v');
tbFunc.AddParametro('confsenha', 'masterVMSIS123v');
// tbFunc.AddParametro('endereco', 'RUA 1');
// tbFunc.AddParametro('numero', '1');
// tbFunc.AddParametro('complemento', 'SEM COMPLEMENTO');
// tbFunc.AddParametro('cep', '31300000');
// tbFunc.AddParametro('pais_id', FidPais);
// tbFunc.AddParametro('estado_id', FidEstado);
// tbFunc.AddParametro('cidade_id', FIdCidade);
// tbFunc.AddParametro('bairro_id', FidBairro);
// tbFunc.AddParametro('dtadmissao', FDataPadrao);
tbFunc.AddParametro('pessoa', 'J');
tbFunc.Insert;
tbFunc.Select(['id', 'usuario']);
FIdFuncionario := tbFunc.GetVal('id');
Fusuario := tbFunc.GetVal('usuario');
finally
FreeAndNil(tbFunc);
end;
end;
procedure TCadastrosIniciais.AddPaises;
var
tbPais : TObjetoDB;
begin
tbPais := TObjetoDB.create('pais');
try
// tbPais.AddParametro('empresa_id', FidEmpresa);
tbPais.AddParametro('cdpais', '0055');
tbPais.Select(['id']);
if not tbPais.IsEmpty then
begin
FidPais := tbPais.GetVal('id');
Exit;
end;
tbPais.AddParametro('dtcadastro', FDataPadrao);
tbPais.AddParametro('nmpais', 'BRASIL');
tbPais.Insert;
tbPais.Select(['id']);
FidPais := tbPais.GetVal('id');
finally
FreeAndNil(tbPais);
end;
end;
procedure TCadastrosIniciais.AddParametrosSincronizacao;
var
tbParametrosSincronizacao: TObjetoDB;
begin
tbParametrosSincronizacao:= TObjetoDB.create('ParametrosSincronizacao');
try
tbParametrosSincronizacao.Select(['id']);
if tbParametrosSincronizacao.IsEmpty then
begin
//http://177.153.20.166
tbParametrosSincronizacao.AddParametro('IpSincronizacao', 'http://127.0.0.1:8000');
tbParametrosSincronizacao.Insert;
end;
finally
FreeAndNil(tbParametrosSincronizacao);
end;
end;
procedure TCadastrosIniciais.AddUnidade;
var
tbUnidade : TObjetoDB;
begin
tbUnidade := TObjetoDB.create('Unidade');
try
tbUnidade.AddParametro('nmrazao', 'UNIDADE PADRÃO');
tbUnidade.Select(['id', 'nmrazao']);
if tbUnidade.IsEmpty then
begin
tbUnidade.AddParametro('nmfantasia', 'UNIDADE PADRÃO');
tbUnidade.AddParametro('almoxpedido_id', FidAlmoxarifado);
tbUnidade.Insert;
tbUnidade.Select(['id', 'nmrazao']);
FidUnidade := tbUnidade.GetVal('id');
FNomeUnidade := tbUnidade.GetVal('nmrazao');
Exit;
end;
FidUnidade := tbUnidade.GetVal('id');
FNomeUnidade := tbUnidade.GetVal('nmrazao');
finally
FreeAndNil(tbUnidade);
end;
end;
procedure TCadastrosIniciais.Executar;
var
UsrAce : TAcessoUsuario;
begin
FDataPadrao:= Date;
AddEmpresa;
// AddPaises;
// AddEstados;
// AddCidade;
// AddAbairro;
// AddFuncionario;
AddAlmoxarifado;
AddUnidade;
AddCaixa;
AddParametrosSincronizacao;
TAcesso.AddRotinas;
{ UsrAce := TAcessoUsuario.create(Fusuario);
try
UsrAce.AddPermissao('gaveta', TpmProcessar);
finally
FreeAndNil(UsrAce);
end}
end;
end.
|
(****************************************************************************)
(* *)
(* REV97.PAS - The Relativity Emag (coded in Turbo Pascal 7.0) *)
(* *)
(* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *)
(* This source may not be copied, distributed or modified in any shape *)
(* or form. Some of the code has been derived from various sources and *)
(* units to help us produce a better quality electronic magazine to let *)
(* the scene know that we are THE BOSS. *)
(* *)
(* Program Notes : This program presents "The Relativity Emag" *)
(* *)
(* ASM/TP70 Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx *)
(* ------------------------------------------------------------------------ *)
(* TP70 Coder : xxxxx xxxxxxxxx (|MuadDib|) - xxxxxx@xxxxxxxxxx.xxx *)
(* *)
(****************************************************************************)
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - The Heading Specifies The Program Name And Parameters. *)
(****************************************************************************)
Program The_Relativity_Electronic_Magazine_issue2;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Compiler Directives - These Directives Are Not Meant To Be Modified. *)
(****************************************************************************)
{$A+}{$B+}{$D+}{$F+}{$G+}{$I+}{$K+}{$L+}{$N+}{$O-}{$P+}{$Q-}{$R-}{$S+}{$T+}
{$V-}{$W+}{$X+}{$Y+}
{$C MOVEABLE PRELOAD DISCARDABLE}
{$D The Relativity Emag (in Turbo Pascal 7.0)}
{$M 65000,0,655360}
{$S 602768}
{$IFNDEF __BPREAL__}
{$DEFINE NOEMS}
{$ENDIF}
{$DEFINE MSDOS}
{$DEFINE VER70}
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Each Identifier Names A Unit Used By The Program. *)
(****************************************************************************)
uses Crt,Dos,RevDat,RevGfx,RevMem,RevAnsi,revsmth,REVCOM,
REVSET,AdvHSC,revhelp,revconst,revhsc,revrad,revmus,
revinit,revmid,revspec,gifutil9,revnfo,revgif,revmenu,revint;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Statements To Be Executed When The Program Runs. *)
(****************************************************************************)
begin
checkbreak:=false;
cc:=1;
InitSubScreen;
RevCommand;
InitTag;
initavail;
InitradVol;
InitMusic;
{InitSubFiles;}
{CheckCFG;}
PhazePre;
StartMainMenuPhase;
end. |
unit DataPoint;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, msxml, DB, ADODB, StrUtils, FTPClient;
type
TDataPoint = class(TFrame)
ListBox1: TListBox;
ADOQuery1: TADOQuery;
ADOConnection1: TADOConnection;
Timer1: TTimer;
Panel1: TPanel;
Button1: TButton;
ADOQuery2: TADOQuery;
Label1: TLabel;
procedure log(str:String);
procedure fetchData(lastRecord:String);
procedure Timer1Timer(Sender: TObject);
procedure connectDB;
procedure Init;
procedure InitDB;
procedure InitFTP;
procedure GetFile(path:String;fileName:String);
function TestConnection:Boolean;
procedure Button1Click(Sender: TObject);
function WriteRecord:Boolean;
private
{ Private declarations }
FConfig:IXMLDOMNode;
inited:Boolean;
// dbInited:Boolean;
// ftpInited:Boolean;
fc: TFTPClient;
fileRoot: String;
public
{ Public declarations }
procedure Start;
procedure Stop;
property Config:IXMLDOMNode
read FConfig write FConfig;
end;
var
tableInf: IXMLDOMNode;
fieldsInf: IXMLDOMNodeList;
keyField: String;
ftpField: String;
limit: String;
interval: String;
ftp: String;
implementation
{$R *.dfm}
uses SDIMAIN;
procedure TDataPoint.Init;
begin
tableInf := config.selectSingleNode('Table');
fieldsInf := tableInf.selectNodes('Field');
ftp := config.attributes.getNamedItem('ftp').text;
keyField := tableInf.attributes.getNamedItem('keyField').text;
ftpField := tableInf.attributes.getNamedItem('ftpField').text;
limit := tableInf.attributes.getNamedItem('limit').text;
interval := tableInf.attributes.getNamedItem('interval').text;
InitDB;
if ftp = 'true' then
InitFTP;
Timer1.Interval := StrToInt(interval) * 1000;
inited := True;
end;
procedure TDataPoint.InitDB;
var
dbInfo:IXMLDOMNode;
begin
dbInfo := Config.selectSingleNode('dbserver');
ADOConnection1.ConnectionString := 'Provider=MSDASQL.1;Persist Security Info=True;'
+ 'Data Source=' + dbInfo.selectSingleNode('dsname').text + ';'
+ 'User ID=' + dbInfo.selectSingleNode('username').text + ';'
+ 'Password=' + dbInfo.selectSingleNode('passwd').text+ ';QTO=F';
// dbInited := True;
end;
procedure TDataPoint.Button1Click(Sender: TObject);
begin
if Button1.Caption = '开始' then
Start
else
Stop;
end;
procedure TDataPoint.connectDB;
begin
Timer1.Enabled := False;
log('正在连接' + config.selectSingleNode('name').text + '数据库');
try
ADOConnection1.Connected := True;
ADOConnection1.KeepConnection := True;
Timer1.Enabled := True;
log('成功连接数据库,开始读取数据...');
Except
on E:Exception do
begin
log('无法连接数据库:' + E.Message);
Stop;
end;
end;
end;
function TDataPoint.TestConnection;
begin
result := False;
if Not inited then
Init;
log('测试' + config.selectSingleNode('name').text + 'FTP服务连接');
if fc.Connect then
begin
fc.Disconnect;
log('FTP服务连接成功');
end
else
begin
log('无法连接FTP服务');
Exit;
end;
log('测试' + config.selectSingleNode('name').text + '数据库连接');
try
ADOConnection1.Connected := True;
ADOConnection1.KeepConnection := True;
log('数据库连接成功');
result := True;
Button1.Enabled := True;
Except
on E:Exception do
log('无法连接数据库:' + E.Message);
end;
end;
procedure TDataPoint.Start;
begin
if Not inited then
Init;
ADOQuery2.Connection := MainFrame.ADOConnection1;
Timer1.Enabled := True;
Button1.Caption := '停止';
end;
procedure TDataPoint.Stop;
begin
Timer1.Enabled := False;
ADOConnection1.Connected := False;
Button1.Caption := '开始';
end;
procedure TDataPoint.Timer1Timer(Sender: TObject);
begin
if ADOConnection1.Connected then
fetchData(config.attributes.getNamedItem('lastRecord').text)
else
ConnectDB();
end;
procedure TDataPoint.fetchData(lastRecord: string);
var
ftpInf: String;
fromNum: String;
tableName :String;
path: TStringList;
pathStr: String;
I:Integer;
begin
Timer1.Enabled := false;
tableName := tableInf.attributes.getNamedItem('from').text;
fromNum := '0';
if Trim(lastRecord) <> '' then
begin
ADOQuery1.SQL.Text := 'select * from (select rownum as rn,' + keyField + ',' + ftpField + ' from ' + tableName +
') where ' + keyField + ' = ''' + lastRecord + '''';
ADOQuery1.Open;
if not ADOQuery1.Eof then
begin
ADOQuery1.First;
fromNum := ADOQuery1.FieldByName('rn').Text;
end;
ADOQuery1.Close;
end;
ADOQuery1.SQL.Text := 'select * from (select rownum as rn, a.* from ' + tableName + ' a where rownum <= ' + IntToStr(StrToInt(fromNum) + StrToInt(limit)) + ') where rn > ' + fromNum;
ADOQuery1.Open;
path := TStringList.Create;
path.Delimiter := '/';
pathStr := '';
if Not ADOQuery1.Eof then
begin
log('本次将从第' + fromNum + '条记录开始读取' + IntToStr(ADOQuery1.RecordCount) + '条记录');
log('正在连接' + config.selectSingleNode('name').text + 'FTP服务');
if fc.Connect then
begin
log('成功连接FTP服务');
ADOQuery1.First;
while Not ADOQuery1.Eof do
begin
ftpInf := ADOQuery1.FieldByName(ftpField).Text;
ftpInf := StringReplace(ftpInf,'\','/',[rfReplaceAll]);
ftpInf := StringReplace(ftpInf,'//','/',[rfReplaceAll]);
path.DelimitedText := ftpInf;
for I := 2 to path.Count - 3 do
begin
pathStr := pathStr + path.Strings[I] + '/';
end;
pathStr := pathStr + path.Strings[path.Count - 2];
if WriteRecord then
begin
GetFile(pathStr, path.Strings[path.Count - 1])
end;
//log(path.Strings[3] + '/' + path.Strings[4] + '*' + path.Strings[5]);
config.attributes.getNamedItem('lastRecord').text := ADOQuery1.FieldByName(keyField).Text;
ADOQuery1.Next;
end;
log('本次数据读取完成');
fc.Disconnect;
Timer1.Enabled := True;
end
else
begin
log('无法连接FTP服务:' + fc.Host + ':' + IntToStr(fc.Port));
Stop;
end;
end
else
begin
log('没有发现新数据');
Timer1.Enabled := True;
end;
ADOQuery1.Close;
end;
procedure TDataPoint.InitFTP;
var
ftpInf: IXMLDOMNode;
begin
ftpInf := config.selectSingleNode('ftpserver');
fc := TFTPClient.Create;
fc.Host := ftpInf.selectSingleNode('address').text;
fc.Port := StrToInt(ftpInf.selectSingleNode('port').text);
fc.UserName := ftpInf.selectSingleNode('username').text;
fc.Password := ftpInf.selectSingleNode('passwd').text;
fileRoot := SDIMAIN.localInf.selectSingleNode('fileroot').text;
// ftpInited := True;
end;
procedure TDataPoint.GetFile(path:String;fileName: string);
begin
//if
fc.DownloadFile(PChar(path + '/' + fileName),PChar(fileRoot + '/' + path + '/' + fileName));
// then
//log('成功下载文件' + fileName)
//else
//log('无法下载文件' + fileName);
end;
procedure TDataPoint.log(str: string);
begin
if ListBox1.Items.Count = SDIMAIN.maxLog then
ListBox1.Items.Clear;
ListBox1.Items.Add(FormatDateTime('yyyy.mm.dd hh:mm:ss ', now()) + str);
ListBox1.Selected[ListBox1.Items.Count - 1] := true;
end;
function TDataPoint.WriteRecord;
var
I:Integer;
sql, fieldName, valueText:String;
blobField:String;
stream: TMemoryStream;
begin
if Not ADOQuery2.Connection.Connected then
begin
try
ADOQuery2.Connection.Connected := True;
except
on E:Exception do
begin
log('本地数据库连接失败');
result := False;
Exit;
end;
end;
end;
ADOQuery2.SQL.Clear;
ADOQuery2.SQL.Text := 'select ' + keyfield + ' from ' + tableInf.attributes.getNamedItem('to').text + ' where ' + keyfield + '=''' + ADOQuery1.FieldByName(keyField).Text + '''';
ADOQuery2.Open;
if not ADOQuery2.Eof then
begin
ADOQuery2.Close;
ADOQuery2.SQL.Clear;
Result := False;
end
else
begin
ADOQuery2.Close;
ADOQuery2.SQL.Clear;
sql := 'insert into ' + tableInf.attributes.getNamedItem('to').text + ' (';
for I := 0 to fieldsInf.length - 2 do
begin
sql := sql + fieldsInf.item[I].attributes.getNamedItem('to').text + ',';
end;
sql := sql + fieldsInf.item[I].attributes.getNamedItem('to').text + ')';
sql := sql + ' values (';
for I := 0 to fieldsInf.length - 1 do
begin
fieldName := fieldsInf.item[I].attributes.getNamedItem('from').text;
case MainFrame.DataType(fieldsInf.item[I].attributes.getNamedItem('type').text) of
0:
begin
if fieldsInf.item[I].attributes.getNamedItem('value') = Nil then
begin
if ADOQuery1.FieldByName(fieldName).Text = '' then
begin
valueText := 'null';
end
else
begin
valueText := ADOQuery1.FieldByName(fieldName).Text;
end;
end
else
begin
valueText := fieldsInf.item[I].attributes.getNamedItem('value').text;
end;
end;
1:
begin
valueText := 'TO_DATE(''' + ADOQuery1.FieldByName(fieldName).Text + ''', ''YYYY/MM/DD HH24:MI:SS'')';
end;
2:
begin
valueText := ':blob';
blobField := fieldName;
end;
else
begin
valueText := ':' + fieldName;
end;
end;
sql := sql + valueText + ',';
end;
sql := LeftStr(sql, length(sql) - 1);
Sql := sql + ')';
ADOQuery2.SQL.Add(sql);
Adoquery2.Prepared := true;
for I := 0 to fieldsInf.length - 1 do
begin
if MainFrame.DataType(fieldsInf.item[I].attributes.getNamedItem('type').text) = -1 then
begin
if fieldsInf.item[I].attributes.getNamedItem('value') = Nil then
ADOQuery2.Parameters.ParamByName(fieldsInf.item[I].attributes.getNamedItem('to').text).Value := ADOQuery1.FieldByName(fieldsInf.item[I].attributes.getNamedItem('from').text).Text
else
ADOQuery2.Parameters.ParamByName(fieldsInf.item[I].attributes.getNamedItem('to').text).Value := fieldsInf.item[I].attributes.getNamedItem('value').text;
end;
end;
stream := TMemoryStream.Create;
TBlobField(ADOQuery1.FieldByName(blobField)).SaveToStream(stream);
ADOQuery2.Parameters.ParamByName('blob').LoadFromStream(stream, ftBlob);
stream.Free;
try
ADOQuery2.ExecSQL;
Result := True;
except
on E:Exception do
begin
log('数据写入失败:' + E.Message);
Result := False;
//Stop;
end;
end;
end;
end;
end.
|
unit Security.Manage;
interface
uses
System.SysUtils, System.Classes, Vcl.ExtCtrls, System.UITypes, Vcl.StdCtrls, Vcl.Forms
, Security.Login
, Security.ChangePassword
, Security.Permission
, Security.Matrix
, Security.User
;
type
TSecurityManage = class(TComponent)
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
strict private
FLogin : TSecurityLogin;
FChangePassword: TSecurityChangePassword;
FPermission : TSecurityPermission;
FMatrix : TSecurityMatrix;
FUser : TSecurityUser;
{ Strict private declarations }
private
{ Private declarations }
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public declarations }
published
{ Published declarations }
property Login : TSecurityLogin read FLogin write FLogin;
property ChangePassword: TSecurityChangePassword read FChangePassword write FChangePassword;
property Permission : TSecurityPermission read FPermission write FPermission;
property Matrix : TSecurityMatrix read FMatrix write FMatrix;
property User : TSecurityUser read FUser write FUser;
end;
implementation
uses
Security.Internal;
{ TSecurityManage }
constructor TSecurityManage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// FView := TSecurityManageView.Create(Screen.FocusedForm);
end;
destructor TSecurityManage.Destroy;
begin
inherited;
end;
procedure TSecurityManage.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
end;
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is fAbout.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit fAbout;
{$I JcfGlobal.inc}
interface
uses
{ delphi }
Classes, Forms, Graphics, Controls, StdCtrls,
Buttons, ExtCtrls, ShellAPI, SysUtils,
{ JVCL }
JvLabel, JvExControls, JvComponent;
type
TfrmAboutBox = class(TForm)
bbOK: TBitBtn;
pnlClient: TPanel;
imgOpenSource: TImage;
mWarning: TLabel;
mWhat: TMemo;
lblMPL: TLabel;
hlHomePage: TLabel;
lblGnuLicence: TLabel;
procedure FormCreate(Sender: TObject);
procedure imgOpenSourceClick(Sender: TObject);
procedure lblMPLClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure hlHomePageClick(Sender: TObject);
procedure lblGnuLicenceClick(Sender: TObject);
private
procedure DoLayout;
procedure ControlFillWidthControl(const pcControl: TControl);
public
end;
implementation
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
uses
{ delphi }
Windows, URLMon,
{ jcl }
JcfStringUtils,
{ local }
JcfVersionConsts, JCFHelp, JcfFontSetFunctions;
procedure ShowURL(const ps: string);
var
lws: WideString;
begin
lws := ps;
HLinkNavigateString(nil, pWideChar(lws));
end;
function Below(Const pcControl: TControl): integer;
const
SPACING = 4;
begin
Result := pcControl.Top + pcControl.Height + SPACING;
end;
procedure TfrmAboutBox.imgOpenSourceClick(Sender: TObject);
begin
ShowURL('http://www.delphi-jedi.org');
end;
procedure TfrmAboutBox.lblGnuLicenceClick(Sender: TObject);
begin
ShowURL('http://www.gnu.org/licenses/gpl.html');
end;
procedure TfrmAboutBox.lblMPLClick(Sender: TObject);
begin
ShowURL('http://www.mozilla.org/MPL');
end;
procedure TfrmAboutBox.hlHomePageClick(Sender: TObject);
begin
ShowURL(PROGRAM_HOME_PAGE);
end;
procedure TfrmAboutBox.DoLayout;
begin
ControlFillWidthControl(mWarning);
ControlFillWidthControl(lblMPL);
ControlFillWidthControl(lblGnuLicence);
ControlFillWidthControl(hlHomePage);
mWarning.Top := Below(mWhat);
lblMPL.Top := Below(mWarning);
lblGnuLicence.Top := Below(lblMPL);
hlHomePage.Top := Below(lblGnuLicence);
end;
procedure TfrmAboutBox.FormCreate(Sender: TObject);
var
ls: string;
begin
inherited;
SetObjectFontToSystemFont(Self);
SetObjectFontToSystemFont(mWhat.Font);
SetObjectFontToSystemFont(mWarning.Font);
SetObjectFontToSystemFont(lblMPL);
SetObjectFontToSystemFont(lblGnuLicence);
SetObjectFontToSystemFont(hlHomePage);
// show the version from the program constant
ls := mWhat.Text;
StrReplace(ls, '%VERSION%', PROGRAM_VERSION);
StrReplace(ls, '%DATE%', PROGRAM_DATE);
mWhat.Text := string(ls);
hlHomePage.Caption := 'Find more information on the web at: ' + PROGRAM_HOME_PAGE;
DoLayout;
end;
procedure TfrmAboutBox.FormResize(Sender: TObject);
begin
DoLayout;
end;
procedure TfrmAboutBox.FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key = VK_F1 then
try
Application.HelpContext(HELP_MAIN);
except
if FileExists(Application.HelpFile) then
ShellExecute(Handle, 'open', PChar(Application.HelpFile), nil, nil, SW_SHOWNORMAL);
end;
end;
procedure TfrmAboutBox.ControlFillWidthControl(const pcControl: TControl);
const
SPACING = 8;
begin
pcControl.Left := SPACING;
pcControl.Width := pnlClient.ClientWidth - (2 * SPACING);
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Search Editor Panel }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Search;
interface
{
This form displays the UI necessary to work with TDataSearch.
TDataSearch is used to find free-text inside TDataItem values.
TBIGrid uses this form to allow searching text inside grid cells.
}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.Buttons, Vcl.StdCtrls,
BI.Search, BI.DataSet, BI.Arrays, BI.DataItem;
type
TGetDataSet=function:TBIDataSet of object;
TSearchEditor = class(TForm)
ESearch: TEdit;
SBMenu: TSpeedButton;
PopupMenu1: TPopupMenu;
Casesensitive1: TMenuItem;
Searchat1: TMenuItem;
Anywhere1: TMenuItem;
Start1: TMenuItem;
End1: TMenuItem;
Exact1: TMenuItem;
LHits: TLabel;
SBClose: TSpeedButton;
SBDown: TSpeedButton;
SBUp: TSpeedButton;
procedure ESearchChange(Sender: TObject);
procedure Casesensitive1Click(Sender: TObject);
procedure Exact1Click(Sender: TObject);
procedure SBMenuClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SBDownClick(Sender: TObject);
procedure SBUpClick(Sender: TObject);
private
{ Private declarations }
FOnChanged : TNotifyEvent;
FOnGetDataSet : TGetDataSet;
procedure SetCurrent(const Value:TInteger);
public
{ Public declarations }
CurrentColor,
HighLightColor : TColor;
Current,
Total : TInteger;
Search : TDataSearch;
procedure Clear;
class function Embed(const AOwner:TComponent; const AParent:TWinControl;
const AAlign:TAlign):TSearchEditor; static;
function HasHit(const ARow:Integer;
const AItem:TDataItem;
out AIndex:TInteger):Boolean;
function HasHits:Boolean;
function HitIndex(const ARow:Integer;
const AItem:TDataItem):TInteger;
procedure Reposition(const ALeft:Integer);
property OnChanged:TNotifyEvent read FOnChanged write FOnChanged;
property OnGetDataSet:TGetDataSet read FOnGetDataSet write FOnGetDataSet;
end;
implementation
|
unit Jet.Connection;
{
Database connection settings and connection procedures.
}
interface
uses UniStrUtils, AdoDb, OleDb, ADOX_TLB, DAO_TLB, Jet.CommandLine;
type
//Multiple database formats are supported by JET/ACE providers.
TDatabaseFormat = (
dbfDefault, //auto-select from file name, default to MDB4.0
dbfMdb10, //various older versions
dbfMdb11,
dbfMdb20,
dbfMdb3x,
dbfMdb4x, //latest MDB
dbfAccdb //ACCDB
);
//Application settings. Mostly configured via command line.
var
Providers: record
OleDbEng: UniString; //set by user or auto-detected
DaoEng: UniString; //set by user or auto-detected
end;
//Connection
ConnectionString: UniString;
DataSourceName: UniString;
Filename: UniString;
User, Password: UniString;
DatabasePassword: UniString;
NewDb: boolean;
ForceNewDb: boolean;
DatabaseFormat: TDatabaseFormat = dbfDefault;
var //Dynamic properties
CanUseDao: boolean; //sometimes there are other ways
type
TConnectionSettingsParser = class(TCommandLineParser)
public
procedure PrintUsage; override;
function HandleOption(ctx: PParsingContext; const s: UniString): boolean; override;
procedure Finalize; override;
end;
var
ConnectionSettings: TConnectionSettingsParser = nil;
function GetAdoConnection: _Connection;
function EstablishAdoConnection: _Connection;
function GetAdoxCatalog: Catalog;
function GetDaoConnection: Database;
function EstablishDaoConnection: Database;
procedure ClearOleObjects;
implementation
uses SysUtils, Windows, ActiveX, ComObj, AdoInt, Jet.IO;
procedure AutodetectOleDbProvider; forward;
procedure TConnectionSettingsParser.PrintUsage;
begin
err('Connection params:');
err(' -f [file.mdb] :: open a jet database file (preferred)');
err(' -dsn [data-source-name] :: use an ODBC data source name');
err(' -c [connection-string] :: use an ADO connection string (least preferred, overrides many settings)');
err(' -u [user]');
err(' -p [password]');
err(' -dp [database password]'); {Works fine with database creation too}
err(' -new :: create a new database (works only by file name)');
err(' -force :: overwrite existing database (requires -new)');
err('You cannot use -c with --comments when executing (dumping is fine).');
(* -dsn will probably not work with --comments too, as long as it really is MS Access DSN. They deny DAO DSN connections. *)
err('');
err('Database format:');
err(' --mdb :: use Jet 4.0 .mdb format (default)');
err(' --accdb :: use .accdb format');
err(' --db-format [jet10 / jet11 / jet20 / jet3x / jet4x (mdb) / ace12 (accdb)]');
err('By default the tool guesses by the file name (assumes jet4x MDBs unless the extension is accdb).');
err('');
err('Jet/ACE OLEDB and DAO have several versions which are available on different platforms.');
err('You can override the default selection (best compatible available):');
err(' --oledb-eng [ProgID] :: e.g. Microsoft.Jet.OLEDB.4.0');
err(' --dao-eng [ProgID] :: e.g. DAO.Engine.36');
err('');
end;
function TConnectionSettingsParser.HandleOption(ctx: PParsingContext; const s: UniString): boolean;
var s1: UniString;
begin
Result := true;
if WideSameText(s, '-c') then begin
Define(ConnectionString, 'Connection string', ctx.NextParam(s, 'connection string'));
end else
if WideSameText(s, '-dsn') then begin
Define(DataSourceName, 'Data source name', ctx.NextParam(s, 'data source name'));
end else
if WideSameText(s, '-f') then begin
Define(Filename, 'Filename', ctx.NextParam(s, 'filename'));
end else
if WideSameText(s, '-u') then begin
Define(User, 'Username', ctx.NextParam(s, 'username'));
end else
if WideSameText(s, '-p') then begin
Define(Password, 'Password', ctx.NextParam(s, 'password'));
end else
if WideSameText(s, '-dp') then begin
Define(DatabasePassword, 'Database password', ctx.NextParam(s, 'database password'));
end else
if WideSameText(s, '-new') then begin
NewDb := true;
end else
if WideSameText(s, '-force') then begin
ForceNewDb := true;
end else
//Database provider options
if WideSameText(s, '--oledb-eng') then begin
Define(Providers.OleDbEng, 'OLEDB Engine', ctx.NextParam(s, 'OLEDB Engine'));
end else
if WideSameText(s, '--dao-eng') then begin
Define(Providers.DaoEng, 'DAO Engine', ctx.NextParam(s, 'DAO Engine'));
end else
//Database format
if WideSameText(s, '--db-format')
or WideSameText(s, '--database-format') then begin
s1 := ctx.NextParam(s, 'format name');
if WideSameText(s1, 'jet10') then
DatabaseFormat := dbfMdb10
else
if WideSameText(s1, 'jet11') then
DatabaseFormat := dbfMdb11
else
if WideSameText(s1, 'jet20') then
DatabaseFormat := dbfMdb20
else
if WideSameText(s1, 'jet3x') then
DatabaseFormat := dbfMdb3x
else
if WideSameText(s1, 'jet4x') then
DatabaseFormat := dbfMdb4x
else
if WideSameText(s1, 'ace12') then
DatabaseFormat := dbfAccdb
else
BadUsage('Unsupported database format: '+s1);
end else
//Some shortcuts
if WideSameText(s, '--as-mdb')
or WideSameText(s, '--mdb') then
DatabaseFormat := dbfMdb4x
else
if WideSameText(s, '--as-accdb')
or WideSameText(s, '--accdb') then
DatabaseFormat := dbfAccdb
else
Result := false;
end;
procedure TConnectionSettingsParser.Finalize;
var i: integer;
begin
//Check params, only one is allowed: ConnectionString, ConnectionName, Filename
i := 0;
if ConnectionString<>'' then Inc(i);
if DataSourceName<>'' then Inc(i);
if Filename<>'' then Inc(i);
if i > 1 then BadUsage('Only one source (ConnectionString/DataSourceName/Filename) can be specified.');
if i < 1 then BadUsage('A source (ConnectionString/DataSourceName/Filename) needs to be specified.');
//With ConnectionString, additional params are disallowed: everything is in.
if (ConnectionString<>'') and (DatabasePassword<>'') then
BadUsage('ConnectionString conflicts with DatabasePassword: this should be included inside of the connection string.');
//If requested to create a db, allow only filename connection.
if NewDb and (Filename='') then
BadUsage('Database creation is supported only when connecting by Filename.');
if ForceNewDb and not NewDb then
BadUsage('-force requires -new');
if NewDb and not ForceNewDb and FileExists(Filename) then
raise Exception.Create('File '+Filename+' already exists. Use -force with -new to overwrite.');
//Whether we can use DAO. If not, prefer other options.
CanUseDao := (Filename<>'');
//Auto-enable accdb by file name (if not explicitly disable)
if (DatabaseFormat = dbfDefault) and (ExtractFileExt(Filename) = '.accdb') then
DatabaseFormat := dbfAccdb;
//We can't auto-enable Accdb in other cases (connection string / data source name),
//so force it with --accdb if it matters.
//To build a ConnectionString we need to select an OLEDB provider.
//We can't delay it until first use because ConnectionString is needed both by ADO and ADOX.
if Providers.OleDbEng = '' then
AutoDetectOleDbProvider();
//On the other hand, DAO detection can be safely delayed until first use.
//Convert all sources to ConnectionStrings
if Filename<>'' then
ConnectionString := 'Provider='+Providers.OleDbEng+';Data Source="'+Filename+'";'
else
if DataSourceName <> '' then
ConnectionString := 'Provider='+Providers.OleDbEng+';Data Source="'+DataSourceName+'";';
if DatabasePassword<>'' then
//Thankfully the parameter name has not been changed in ACE 12.0
ConnectionString := ConnectionString + 'Jet OLEDB:Database Password="'+DatabasePassword+'";';
end;
function CLSIDFromProgID(const ProgID: UniString; out clsid: TGUID): boolean;
var hr: HRESULT;
begin
hr := ActiveX.CLSIDFromProgID(PChar(ProgID), clsid);
Result := SUCCEEDED(hr);
if not Result then
verbose('Trying class '+ProgID+'... not found.');
end;
//Automatically detects which supported OLEDB Jet providers are available and chooses one.
//Called if the user has not specified a provider explicitly.
procedure AutodetectOleDbProvider;
var clsid: TGUID;
const
sOleDbProviderJet4: string = 'Microsoft.Jet.OLEDB.4.0';
sOleDbProviderAce12: string = 'Microsoft.ACE.OLEDB.12.0';
begin
(*
Different providers support different sets of database formats:
Jet 4.0 supports Jet11-Jet4x (MDB), but not Ace12 (ACCDB)
ACE 12 supports Ace12 (ACCDB)
ACE also supports Jet11-Jet4x, but it's complicated:
* some features reportedly work differently, notably some field types and user/password support.
* ACE14+ deprecates Jet11-Jet20
Jet 4.0 is almost universally available anyway, so we'll prefer it for older DB types,
and prefer ACE 12 for accdb.
Note that DAO preference needs not to follow ADO preference strictly.
*)
//For Accdb, try ACE12 first
if DatabaseFormat = dbfAccdb then
if CLSIDFromProgID(sOleDbProviderAce12, clsid) then begin
Providers.OleDbEng := sOleDbProviderAce12;
exit;
end;
//Try Jet 4.0
if CLSIDFromProgID(sOleDbProviderJet4, clsid) then begin
Providers.OleDbEng := sOleDbProviderJet4;
if DatabaseFormat = dbfAccdb then
//We have found something, but it's not ACE12
err('ERROR: ACCDB format requires Microsoft.ACE.OLEDB.12.0 provider which has not been found. The operations will likely fail.');
exit;
end;
//For MDBs try ACE12 as a last resort
if DatabaseFormat <> dbfAccdb then
if CLSIDFromProgID(sOleDbProviderAce12, clsid) then begin
Providers.OleDbEng := sOleDbProviderAce12;
log('NOTE: Fallback to ACE12 for older database access may introduce some inconsistencies.');
exit;
end;
err('ERROR: Jet/ACE OLEDB provider not found. The operations will likely fail.');
//Still set the most compatible provider just in case
Providers.OleDbEng := sOleDbProviderJet4;
end;
const
JetEngineType_Jet10 = 1;
JetEngineType_Jet11 = 2;
JetEngineType_Jet20 = 3;
JetEngineType_Jet3x = 4;
JetEngineType_Jet4x = 5;
JetEngineType_Ace12 = 6; //confirmed
//Some other known types:
// DBASE3 = 10;
// Xslx = 30 / 37 in some examples.
var
AdoxCatalog: Catalog;
//Creates a new database and resets a database-creation-required flag.
procedure CreateNewDatabase;
var engType: integer;
begin
if ForceNewDb and FileExists(Filename) then
DeleteFileW(PWideChar(Filename));
case DatabaseFormat of
dbfMdb10: engType := JetEngineType_Jet10;
dbfMdb11: engType := JetEngineType_Jet11;
dbfMdb20: engType := JetEngineType_Jet20;
dbfMdb3x: engType := JetEngineType_Jet3x;
dbfMdb4x: engType := JetEngineType_Jet4x;
dbfAccdb: engType := JetEngineType_Ace12;
else
//By default, create Jet4x MDB
engType := JetEngineType_Jet4x;
end;
AdoxCatalog := CoCatalog.Create;
AdoxCatalog.Create(ConnectionString
+ 'Jet OLEDB:Engine Type='+IntToStr(engType)+';');
verbose('Database created.');
NewDb := false; //works only once
end;
//Returns an ADOX Catalog. Caching is implemented.
function GetAdoxCatalog: Catalog;
begin
if AdoxCatalog=nil then begin
AdoxCatalog := CoCatalog.Create;
AdoxCatalog._Set_ActiveConnection(GetAdoConnection);
end;
Result := AdoxCatalog;
end;
var
AdoConnection: _Connection;
//Returns a NEW ADO connection.
function EstablishAdoConnection: _Connection;
begin
if NewDb then CreateNewDatabase;
Result := CoConnection.Create;
Result.Open(ConnectionString, User, Password, 0);
end;
//Returns an ADO connection. Caching is implemented
function GetAdoConnection: _Connection;
begin
if NewDb then CreateNewDatabase;
if AdoConnection=nil then begin
Result := EstablishAdoConnection;
AdoConnection := Result;
end else
Result := AdoConnection;
end;
var
DaoConnection: Database = nil;
Dao: record
SupportState: (
ssUntested,
ssDetected, //ProviderCLSID is valid
ssUnavailable //No DAO provider or DAO disabled by connection type
);
ProviderCLSID: TGUID;
end = (SupportState: ssUntested);
//These are not used and are provided only for information. We query the registry by ProgIDs.
const
CLASS_DAO36_DBEngine_x86 = '{00000100-0000-0010-8000-00AA006D2EA4}'; //no x64 version exists
CLASS_DAO120_DBEngine = '{CD7791B9-43FD-42C5-AE42-8DD2811F0419}'; //both x64 and x86
//Automatically detects which supported DAO providers are available and chooses one,
//or finds the provider the user has specified.
procedure AutodetectDao;
const
sDaoEngine36 = 'DAO.DBEngine.36';
sDaoEngine120 = 'DAO.DBEngine.120';
begin
//If explicit DAO provider is set, simply convert it to CLSID.
if Providers.DaoEng <> '' then begin
if not CLSIDFromProgID(Providers.DaoEng, Dao.ProviderCLSID) then
//Since its explicitly configured, we should raise
raise Exception.Create('Cannot find DAO provider with ProgID='+Providers.DaoEng);
Dao.SupportState := ssDetected;
exit;
end;
(*
As with ADO, prefer older DAO for older database types, and newer DAO for ACCDB.
DAO preference needs not to be strictly in sync with Jet preference:
OLEDB engine: Jet4.0, DAO engine: DAO120 <-- this is okay (if both can handle the file)
*)
//For ACCDB try DAO120 first
if DatabaseFormat = dbfAccdb then
if CLSIDFromProgID(sDaoEngine120, Dao.ProviderCLSID) then begin
Providers.DaoEng := sDaoEngine120;
Dao.SupportState := ssDetected;
exit;
end;
//DAO36
if CLSIDFromProgID(sDaoEngine36, Dao.ProviderCLSID) then begin
Providers.DaoEng := sDaoEngine36;
Dao.SupportState := ssDetected;
if DatabaseFormat = dbfAccdb then
err('WARNING: ACCDB format requires DAO.DBEngine.120 provider which is not found. DAO operations will probably fail.');
exit;
end;
if DatabaseFormat <> dbfAccdb then
if CLSIDFromProgID(sDaoEngine120, Dao.ProviderCLSID) then begin
Providers.DaoEng := sDaoEngine120;
Dao.SupportState := ssDetected;
log('NOTE: Fallback to DAO120 for older database access may introduce some inconsistencies.');
exit;
end;
err('WARNING: No compatible DAO provider found. DAO operations will be unavailable.');
{$IFDEF CPUX64}
err(' Note that this X64 build of jet-tool cannot use 32-bit only DAO.DBEngine.36 even if it''s installed. '
+'You need DAO.DBEngine.120 which is included in "Microsoft Office 12.0 Access Database Engine Objects Library" and later.');
{$ENDIF}
Dao.SupportState := ssUnavailable;
end;
resourcestring
sDaoUnavailable =
'The operation you''re trying to perform requires DAO. No supported DAO providers have been detected.'
+ 'This tool requires either DAO.DBEngine.120 or DAO.DBEngine.36.'#13
+ 'Install the required DAO providers, override DAO provider selection or disable the features that require DAO.';
sDaoConnectionTypeWrong =
'The operation you''re trying to perform requires DAO. DAO and DAO-dependent functions can only be '
+ 'accessed through Filename source.'#13
+ 'Somehow this condition was not properly verified during command-line parsing. '
+ 'Please file a bug to the developers.'#13
+ 'For the time being, disable the setting that required DAO (usually something obscure like importing '
+ 'comments) or switch to connecting through Filename.';
//Establishes a NEW DAO connection. Also refreshes the engine cache.
//Usually called every time DAO connection is needed by a DAO-dependent proc.
function EstablishDaoConnection: Database;
var DaoEngine: _DbEngine;
Params: OleVariant;
begin
if NewDb then CreateNewDatabase;
//Figure out supported DAO engine and its CLSID
if Dao.SupportState = ssUntested then
AutodetectDao();
if Dao.SupportState = ssUnavailable then
//Since we're here, someone tried to use Dao functions anyway. Raise!
raise Exception.Create(sDaoUnavailable);
//Doing the same as this would, only with variable CLSID:
// DaoEngine := CoDbEngine.Create;
DaoEngine := CreateComObject(Dao.ProviderCLSID) as DBEngine;
//Do not disable, or Dao refreshing will break too
DaoEngine.Idle(dbRefreshCache);
if Filename<>'' then begin
if DatabasePassword<>'' then
Params := UniString('MS Access;pwd=')+DatabasePassword
else
Params := '';
Result := DaoEngine.OpenDatabase(Filename, False, False, Params);
end else
if DataSourceName<>'' then begin
//Although this will probably not work
Params := 'ODBC;DSN='+DataSourceName+';UID='+User+';PWD='+Password+';';
Result := DaoEngine.OpenDatabase('', False, False, Params);
end else
raise Exception.Create(sDaoConnectionTypeWrong);
end;
//Returns a DAO connection. Caching is implemented.
function GetDaoConnection: Database;
begin
if Assigned(DaoConnection) then begin
Result := DaoConnection;
exit;
end;
Result := EstablishDaoConnection;
DaoConnection := Result;
end;
//This is needed before you CoUninitialize Ole. More notes where this is called.
procedure ClearOleObjects;
begin
AdoConnection := nil;
DaoConnection := nil;
AdoxCatalog := nil;
end;
initialization
ConnectionSettings := TConnectionSettingsParser.Create;
finalization
{$IFDEF DEBUG}
FreeAndNil(ConnectionSettings);
{$ENDIF}
end.
|
unit Devices.Modbus.ReqCreatorBase;
interface
uses Windows, GMGlobals, SysUtils, GMSqlQuery, GMConst, Devices.ReqCreatorBase, Devices.ModbusBase,
Generics.Collections, Math;
type
TModbusChannel = record
id_prm, userSrc, addr, resultType: int;
function addr2(): int;
end;
TModbusDevReqCreator = class(TDevReqCreator)
private
ChnList: TList<TModbusChannel>;
FPackSize: int;
procedure AddCurrents_OnePrm(q: TGMSqlQuery; obj: pointer);
function CheckOutputChannelType(ID_Src: int): bool;
function FncFromUserSrc(userSrc: int): int;
procedure CreateChannelList;
procedure ProcessFunction(userSrc: int);
protected
procedure AddModbusRequestToSendBuf(MemAddr, Cnt: int; rqtp: T485RequestType; ModbusFunction: byte = $03); virtual; abstract;
function GetDefaultReqPackSize(): int; virtual; abstract;
procedure DoSetChannelValue(DevNumber, ID_Src, N_Src, Val: int); virtual; abstract;
function PrepareCommand(var prmIds: TChannelIds; var Val: double): bool; override;
public
constructor Create(AddRequestToSendBuf: TGMAddRequestToSendBufProc; ReqDetails: TRequestDetails); override;
destructor Destroy; override;
procedure AddRequests; override;
function SetChannelValue(DevNumber, ID_Src, N_Src: int; Val: double; timeHold: int): bool; override;
end;
TModbusTCPDevReqCreator = class(TModbusDevReqCreator)
protected
procedure AddModbusRequestToSendBuf(MemAddr, Cnt: int; rqtp: T485RequestType; ModbusFunction: byte = $03); override;
function GetDefaultReqPackSize(): int; override;
procedure DoSetChannelValue(DevNumber, ID_Src, N_Src, Val: int); override;
end;
TModbusRTUDevReqCreator = class(TModbusDevReqCreator)
protected
procedure AddModbusRequestToSendBuf(MemAddr, Cnt: int; rqtp: T485RequestType; ModbusFunction: byte = $03); override;
function GetDefaultReqPackSize(): int; override;
procedure DoSetChannelValue(DevNumber, ID_Src, N_Src, Val: int); override;
end;
implementation
{ TModbusDevReqCreator }
function TModbusDevReqCreator.FncFromUserSrc(userSrc: int): int;
begin
Result := -1;
case userSrc of
SRC_DI: Result := 2; // Modbus Discrete Inputs
SRC_AI, SRC_CNT_MTR, SRC_CNT_DI: Result := 4; // Modbus input register
SRC_AO, SRC_AO_10, SRC_DO: Result := 3; // Modbus holding register
end;
end;
procedure TModbusDevReqCreator.AddCurrents_OnePrm(q: TGMSqlQuery; obj: pointer);
var addrBase: int;
chn: TModbusChannel;
begin
FPackSize := q.FieldByName('ReqPackSize').AsInteger;
if FPackSize <= 0 then
FPackSize := GetDefaultReqPackSize();
chn.id_prm := q.FieldByName('ID_Prm').AsInteger;
chn.userSrc := Max(q.FieldByName('UserSrc').AsInteger, SRC_AI);
// нюанс: приборы зачастую нумеруют каналы Modbus с 1, а физически они с 0
// поэтому все каналы со сдвигом на 1
// Но бывает и наоборот, поэтому введен поправочный сдвиг addrBase, по дефолту 1
addrBase := q.FieldByName('AddrBase').AsInteger;
chn.addr := q.FieldByName('CurrentsAddr').AsInteger - addrBase;
chn.resultType := q.FieldByName('ModbusResultType').AsInteger;
ChnList.Add(chn);
end;
procedure TModbusDevReqCreator.CreateChannelList();
var sql: string;
begin
sql := 'select * from DeviceSystem ' +
' where ID_Device = ' + IntToStr(FReqDetails.ID_Device) +
' and ID_Src = ' + IntToStr(SRC_USR) +
' and ID_PT > 0 ' +
' and N_Src >= 0 ' +
' order by UserSrc, CurrentsAddr';
ReadFromQuery(sql, AddCurrents_OnePrm);
end;
function TModbusDevReqCreator.PrepareCommand(var prmIds: TChannelIds; var Val: double): bool;
begin
Result := inherited;
if not Result then Exit;
prmIds.N_Src := prmIds.N_Src - prmIds.AddrBase;
Result := prmIds.N_Src >= 0;
end;
procedure TModbusDevReqCreator.ProcessFunction(userSrc: int);
var i, addr1, addr2, fnc, n: int;
procedure ClearReqDetails();
begin
addr1 := -1;
FReqDetails.ClearReqLink();
end;
procedure InitReqPack(chn: TModbusChannel);
begin
addr1 := chn.addr;
addr2 := chn.addr2();
FReqDetails.ID_Prm := chn.id_prm;
FReqDetails.ClearReqLink();
FReqDetails.ReqLinks[0].id := chn.id_prm;
FReqDetails.ReqLinks[0].ext := chn.resultType;
FReqDetails.ReqLinkCount := 1;
end;
procedure SendCurrentPack();
var count: int;
begin
if addr1 < 0 then Exit;
count := addr2 - addr1 + 1;
AddModbusRequestToSendBuf(addr1, count, rqtUSER_DEFINED, fnc);
end;
begin
ClearReqDetails();
fnc := FncFromUserSrc(userSrc);
if fnc < 0 then Exit;
for i := 0 to ChnList.Count - 1 do
begin
if ChnList[i].userSrc <> userSrc then
continue;
if addr1 < 0 then
begin
InitReqPack(ChnList[i]);
end
else
begin
if ChnList[i].addr > addr1 + FPackSize - 1 then
begin
SendCurrentPack();
InitReqPack(ChnList[i]);
end
else
begin
n := ChnList[i].addr - addr1;
addr2 := Max(addr2, ChnList[i].addr2());
FReqDetails.ReqLinks[n].id := ChnList[i].id_prm;
FReqDetails.ReqLinks[n].ext := ChnList[i].resultType;
FReqDetails.ReqLinkCount := n + 1;
end;
end;
end;
SendCurrentPack();
end;
function TModbusDevReqCreator.SetChannelValue(DevNumber, ID_Src, N_Src: int; Val: double; timeHold: int): bool;
begin
if not CheckOutputChannelType(ID_Src)
or not IsWord(Round(Val))
or not IsWord(N_Src)
or (N_Src < 0) then Exit(false);
DoSetChannelValue(DevNumber, ID_Src, N_Src, Round(Val));
Result := true;
end;
procedure TModbusDevReqCreator.AddRequests;
var i: int;
begin
CreateChannelList();
for i := SRC_AI to SRC_MAX do
ProcessFunction(i);
end;
function TModbusDevReqCreator.CheckOutputChannelType(ID_Src: int): bool;
begin
Result := ID_Src in [SRC_AO, SRC_AO_10];
end;
constructor TModbusDevReqCreator.Create(AddRequestToSendBuf: TGMAddRequestToSendBufProc; ReqDetails: TRequestDetails);
begin
inherited;
ChnList := TList<TModbusChannel>.Create();
end;
destructor TModbusDevReqCreator.Destroy;
begin
ChnList.Free();
inherited;
end;
function CreateModbusTCPRequest(DevNumber, MemAddr, Cnt: int; ModbusFunction: byte): ArrayOfByte;
begin
SetLength(Result, 12);
// Пример
// ? 00 FF 00 00 00 06 01 04 00 00 00 0A
// < 00 FF 00 00 00 17 01 04 14 00 00 00 01 00 02 00 03 27 10 FF FF FF FD 00 04 00 05 00 06
// Transaction Identifier 2 Bytes
Result[0] := 0;
Result[1] := 0;
// Protocol Identifier 2 Bytes 0 = MODBUS protocol
Result[2] := 0;
Result[3] := 0;
// Length 2 Bytes, max 2000
Result[4] := 0;
Result[5] := 6;
// Unit Identifier 1 Byte
Result[6] := DevNumber and $FF;
Result[7] := ModbusFunction;
// адрес первого слова данных
Result[8] := (MemAddr div 256) and $FF;
Result[9] := MemAddr mod 256;
// к-во слов
Result[10] := (Cnt div 256) and $FF;
Result[11] := Cnt mod 256;
end;
{ TModbusTCPDevReqCreator }
procedure TModbusTCPDevReqCreator.AddModbusRequestToSendBuf(MemAddr, Cnt: int; rqtp: T485RequestType; ModbusFunction: byte = $03);
begin
AddBufRequestToSendBuf(CreateModbusTCPRequest(FReqDetails.DevNumber, MemAddr, Cnt, ModbusFunction), 12, rqtp);
end;
function TModbusTCPDevReqCreator.GetDefaultReqPackSize: int;
begin
Result := 500;
end;
function CreateRequestSetChannelValueTCPFnc6(DevNumber, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 12);
// Transaction Identifier 2 Bytes
Result[0] := 0;
Result[1] := 0;
// Protocol Identifier 2 Bytes 0 = MODBUS protocol
Result[2] := 0;
Result[3] := 0;
// Length 2 Bytes
Result[4] := 0;
Result[5] := 6;
// Unit Identifier 1 Byte
Result[6] := DevNumber and $FF;
// Функция 6 - запись значения в один регистр хранения (Preset Single Register)
Result[7] := 6;
// адрес
Result[8] := HiByte(N_Src);
Result[9] := LoByte(N_Src);
// значение
Result[10] := HiByte(Val mod 65536);
Result[11] := LoByte(Val mod 65536);
end;
function CreateRequestSetChannelValueTCPFnc10(DevNumber, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 15);
// Transaction Identifier 2 Bytes
Result[0] := 0;
Result[1] := 0;
// Protocol Identifier 2 Bytes 0 = MODBUS protocol
Result[2] := 0;
Result[3] := 0;
// Length 2 Bytes
Result[4] := 0;
Result[5] := 9;
// Unit Identifier 1 Byte
Result[6] := DevNumber and $FF;
// Функция 6 - запись значения в несколько регистров хранения
Result[7] := $10;
// адрес
Result[8] := HiByte(N_Src);
Result[9] := LoByte(N_Src);
// пишем 1 значение
Result[10] := 0;
Result[11] := 1;
// Количество байт далее
Result[12] := 2;
// значение
Result[13] := HiByte(Val mod 65536);
Result[14] := LoByte(Val mod 65536);
end;
function CreateRequestSetChannelValueTCP(DevNumber, ID_Src, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 0);
case ID_Src of
SRC_AO:
Result := CreateRequestSetChannelValueTCPFnc6(DevNumber, N_Src, Val);
SRC_AO_10:
Result := CreateRequestSetChannelValueTCPFnc10(DevNumber, N_Src, Val);
end;
end;
procedure TModbusTCPDevReqCreator.DoSetChannelValue(DevNumber, ID_Src, N_Src, Val: int);
var buf: ArrayOfByte;
begin
buf := CreateRequestSetChannelValueTCP(DevNumber, ID_Src, N_Src, Round(Val));
AddBufRequestToSendBuf(buf, Length(buf), rqtCommand);
end;
function CreateModbusRTURequest(DevNumber, MemAddr, Cnt: int; ModbusFunction: byte): ArrayOfByte;
begin
SetLength(Result, 8);
// номер прибора на линии
Result[0] := DevNumber and $FF;
// код функции запроса данных
Result[1] := ModbusFunction;
// адрес первого слова данных
Result[2] := (MemAddr div 256) and $FF;
Result[3] := MemAddr mod 256;
// к-во слов, до 2000
Result[4] := (Cnt div 256) and $FF;
Result[5] := Cnt mod 256;
// CRC
Modbus_CRC(Result, 6);
end;
{ TModbusRTUDevReqCreator }
procedure TModbusRTUDevReqCreator.AddModbusRequestToSendBuf(MemAddr, Cnt: int; rqtp: T485RequestType; ModbusFunction: byte = $03);
var buf: ArrayOfByte;
begin
if FReqDetails.Converter = PROTOCOL_CONVETER_MODBUS_TCP_RTU then
buf := CreateModbusTCPRequest(FReqDetails.DevNumber, MemAddr, Cnt, ModbusFunction)
else
buf := CreateModbusRTURequest(FReqDetails.DevNumber, MemAddr, Cnt, ModbusFunction);
AddBufRequestToSendBuf(buf, Length(buf), rqtp);
end;
function TModbusRTUDevReqCreator.GetDefaultReqPackSize: int;
begin
Result := 100;
end;
function CreateRequestSetChannelValueRTUFnc6(DevNumber, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 8);
Result[0] := DevNumber and $FF;
Result[1] := 6; // запись значения в один регистр хранения (Preset Single Register)
Result[2] := HiByte(N_Src);
Result[3] := LoByte(N_Src);
Result[4] := HiByte(Val mod 65536);
Result[5] := LoByte(Val mod 65536);
Modbus_CRC(Result, 6);
end;
function CreateRequestSetChannelValueRTUFnc10(DevNumber, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 11);
Result[0] := DevNumber and $FF;
Result[1] := $10; // запись значения в несколько регистров хранения
Result[2] := HiByte(N_Src);
Result[3] := LoByte(N_Src);
Result[4] := 0;
Result[5] := 1; // 4, 5 - Количество регистров
Result[6] := 2; // Количество байт далее
Result[7] := HiByte(Val mod 65536);
Result[8] := LoByte(Val mod 65536);
Modbus_CRC(Result, 9);
end;
function CreateRequestSetChannelValueRTU(DevNumber, ID_Src, N_Src, Val: int): ArrayOfByte;
begin
SetLength(Result, 0);
case ID_Src of
SRC_AO: Result := CreateRequestSetChannelValueRTUFnc6(DevNumber, N_Src, Val);
SRC_AO_10: Result := CreateRequestSetChannelValueRTUFnc10(DevNumber, N_Src, Val);
end;
end;
procedure TModbusRTUDevReqCreator.DoSetChannelValue(DevNumber, ID_Src, N_Src, Val: int);
var buf: ArrayOfByte;
begin
if FReqDetails.Converter = PROTOCOL_CONVETER_MODBUS_TCP_RTU then
buf := CreateRequestSetChannelValueTCP(DevNumber, ID_Src, N_Src, Val)
else
buf := CreateRequestSetChannelValueRTU(DevNumber, ID_Src, N_Src, Val);
AddBufRequestToSendBuf(buf, Length(buf), rqtCommand);
end;
{ TModbusChannel }
function TModbusChannel.addr2: int;
begin
Result := addr + Modbus_ResultTypeLength(resultType) - 1;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
{$WARN IMPLICIT_STRING_CAST OFF}
unit Web.ApacheApp;
interface
uses System.SysUtils, System.Classes, Web.ApacheHTTP, Web.HTTPDMethods, Web.HTTPApp, Web.WebBroker;
type
TApacheTerminateProc = procedure;
{ TApacheApplication }
TApacheApplication = class(TWebApplication)
private
FTerminateProc: TApacheTerminateProc;
procedure ApacheHandleException(Sender: TObject);
protected
function NewRequest(const r: PHTTPDRequest): TApacheRequest;
function NewResponse(ApacheRequest: TApacheRequest): TApacheResponse;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ProcessRequest(const r: PHTTPDRequest): Integer;
function TerminateExtension(): integer;
property OnTerminate: TApacheTerminateProc read FTerminateProc write FTerminateProc;
end;
procedure InitApplication(const AModuleData: Pointer; const AHandlerName: UTF8String = '');
implementation
uses
Web.BrkrConst;
procedure HandleServerException(E: TObject; const r: PHTTPDRequest);
var
ErrorMessage, EMsg: string;
begin
if E is Exception then
EMsg := Exception(E).Message
else
EMsg := '';
ErrorMessage := Format(sInternalServerError, [E.ClassName, EMsg]);
THTTPDMethods.set_ContentType(r, 'text/html'); //r.content_type := 'text/html';
THTTPDMethods.set_headers_out_ContentLength(r, Length(ErrorMessage));
THTTPDMethods.write_string(r, UTF8String(ErrorMessage));
end;
function GetModuleFileName: string;
begin
Result := GetModuleName(hInstance);
// UNC issue in Vista.
if Result.IndexOf('\\?\') = 0 then
Result := Result.Substring(4);
end;
constructor TApacheApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Web.HTTPApp.FWebApplicationFileName := GetModuleFileName;
System.Classes.ApplicationHandleException := ApacheHandleException;
end;
destructor TApacheApplication.Destroy;
begin
System.Classes.ApplicationHandleException := nil;
inherited Destroy;
end;
function TApacheApplication.ProcessRequest(const r: PHTTPDRequest): Integer;
var
HTTPRequest: TApacheRequest;
HTTPResponse: TApacheResponse;
{$IFDEF LINUX}
PrevFMask: UInt32;
{$ENDIF}
begin
try
{$IFDEF LINUX}
PrevFMask := FGetExceptMask();
FSetExceptMask($32);
try
{$ENDIF}
HTTPRequest := NewRequest(r);
try
HTTPResponse := NewResponse(HTTPRequest);
try
HandleRequest(HTTPRequest, HTTPResponse);
Result := HTTPResponse.ReturnCode; { Typically will be AP_OK }
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
{$IFDEF LINUX}
finally
FSetExceptMask(PrevFMask);
end;
{$ENDIF}
except
HandleServerException(ExceptObject, r);
{ NOTE: Tell Apache we've handled this request; so there's no need to
pass this on to other modules. }
Result := THTTPDMethods.get_AP_OK; // AP_OKx;
end;
end;
function TApacheApplication.TerminateExtension(): integer;
begin
if Assigned(FTerminateProc) then
FTerminateProc;
Result:= THTTPDMethods.get_AP_OK;
end;
procedure TApacheApplication.ApacheHandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
E: TObject;
begin
Handled := False;
if (ExceptObject is Exception) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
begin
E := ExceptObject;
AcquireExceptionObject;
raise E;
end;
end;
function TApacheApplication.NewRequest(const r: PHTTPDRequest): TApacheRequest;
begin
Result := TApacheRequest.Create(r);
end;
function TApacheApplication.NewResponse(ApacheRequest: TApacheRequest): TApacheResponse;
begin
Result := TApacheResponse.Create(ApacheRequest);
end;
// Handle apache request
function DefaultHandler(const r: PHTTPDRequest): Integer; cdecl;
var
RequestedHandler: UTF8String;
begin
RequestedHandler := THTTPDMethods.get_handler(r); // r^.handler;
if (Application is TApacheApplication) and SameText(string(RequestedHandler), string(THTTPDInit.HandlerName)) then
Result := TApacheApplication(Application).ProcessRequest(r)
else
Result := THTTPDMethods.get_AP_DECLINED; // DECLINEDx;
end;
// Handle apache Termination
function TerminationHandler(const p: Pointer): Integer; cdecl;
begin
Result := TApacheApplication(Application).TerminateExtension;
//Result := THTTPDMethods.get_AP_OK;
end;
// Handle apache Initiation
procedure InitiationHandler(const p: PHTTPDPool; const s: PHTTPDServer_rec); cdecl;
begin
//register a cleanup function for when apache terminates the module.
THTTPDMethods.pool_cleanup_register(p, nil, TerminationHandler, nil);
end;
procedure DoRegisterHooks(const p: PHTTPDPool);
begin
THTTPDMethods.hook_handler(DefaultHandler, nil, nil, THTTPDMethods.get_APR_HOOK_MIDDLE);
THTTPDMethods.hook_child_init(InitiationHandler, nil, nil, THTTPDMethods.get_APR_HOOK_MIDDLE);
if Assigned(THTTPDInit.RegisterCustomHooksProc) then
begin
// Allow application to register custom hooks
THTTPDInit.RegisterCustomHooksProc(p);
end;
end;
procedure InitApplication(const AModuleData: Pointer; const AHandlerName: UTF8String);
begin
// Initialize internal data structures
THTTPDInit.InitModule(DoRegisterHooks, PByte(AModuleData), AHandlerName);
Application := TApacheApplication.Create(nil);
end;
end.
|
unit TreeViewExUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ComCtrls, Data.Db, Vcl.ExtCtrls,
plugin;
type
TTreeNodeEx = class(TTreeNode)
private
FDataSource: string;
public
property DataSource: string read FDataSource write FDataSource;
end;
TTreeViewEx = class(TCustomTreeView)
private
FBdType: TBdType;
procedure TreeViewCompare(Sender: TObject; Node1, Node2: TTreeNode;
Data: Integer; var Compare: Integer);
procedure WMRButtonDown(var Message: TWMLButtonDblClk); message WM_RBUTTONDOWN;
function Destroying: boolean;
procedure SetBdType(const Value: TBdType);
protected
function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; override;
function CustomDrawItem(Node: TTreeNode; State: TCustomDrawState;
Stage: TCustomDrawStage; var PaintImages: Boolean): Boolean; override;
procedure TreeViewExGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure TreeViewExGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure TreeViewCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
public
constructor Create(AOwner: TComponent); override;
function NodeFoundByDataSource(TreeView: TTreeViewEx; DataSource: string): TTreeNode;
procedure AddServer(const Data: string; Login: string; Bases: TDataset);
property BdType: TBdType read FBdType write SetBdType;
published
property Align;
property Anchors;
property AutoExpand;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind default bkNone;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property ChangeDelay;
property Color;
property Ctl3D;
property Constraints;
property DoubleBuffered;
property DragKind;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property HotTrack;
property Images;
property Indent;
property MultiSelect;
property MultiSelectStyle;
property ParentBiDiMode;
property ParentColor default False;
property ParentCtl3D;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property RightClickSelect;
property RowSelect;
property ShowButtons;
property ShowHint;
property ShowLines;
property ShowRoot;
property SortType;
property StateImages;
property TabOrder;
property TabStop default True;
property ToolTips;
property Touch;
property Visible;
property StyleElements;
property OnAddition;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnCancelEdit;
property OnChange;
property OnChanging;
property OnClick;
property OnCollapsed;
property OnCollapsing;
property OnCompare;
property OnContextPopup;
property OnCreateNodeClass;
property OnCustomDraw;
property OnCustomDrawItem;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnEdited;
property OnEditing;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnExpanding;
property OnExpanded;
property OnGesture;
property OnGetImageIndex;
property OnGetSelectedIndex;
property OnHint;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
{ Items must be published after OnGetImageIndex and OnGetSelectedIndex }
property Items;
end;
TTreeNodeHelper = class helper for TTreeNode
private
function GetItemType: TItemType;
procedure SetItemType(const Value: TItemType);
public
property ItemType: TItemType read GetItemType write SetItemType;
end;
implementation
{ TTreeNodeHelper }
function TTreeNodeHelper.GetItemType: TItemType;
begin
Result := TItemType(Self.Data);
end;
procedure TTreeNodeHelper.SetItemType(const Value: TItemType);
begin
Self.Data := Pointer(Integer(Value));
end;
{ TTreeViewEx }
constructor TTreeViewEx.Create(AOwner: TComponent);
begin
inherited;
OnCompare := TreeViewCompare;
ReadOnly := True;
SortType := stText;
Align := alClient;
HideSelection := False;
ShowRoot := False;
OnGetImageIndex := TreeViewExGetImageIndex;
OnGetSelectedIndex := TreeViewExGetSelectedIndex;
OnCreateNodeClass := TreeViewCreateNodeClass;
end;
function TTreeViewEx.CustomDrawItem(Node: TTreeNode; State: TCustomDrawState;
Stage: TCustomDrawStage; var PaintImages: Boolean): Boolean;
begin
Result := inherited CustomDrawItem(Node,State,Stage,PaintImages);
if (Stage = cdPrePaint) and PaintImages then
begin
if Node.ItemType = itLogin then
Canvas.Font.Style := Canvas.Font.Style + [fsBold]
else
Canvas.Font.Style := Canvas.Font.Style - [fsBold];
end;
end;
function TTreeViewEx.IsCustomDrawn(Target: TCustomDrawTarget;
Stage: TCustomDrawStage): Boolean;
begin
if (Stage = cdPrePaint) and (Target = dtItem) then
Result := True
else
Result := inherited IsCustomDrawn(Target, Stage);
end;
procedure TTreeViewEx.SetBdType(const Value: TBdType);
begin
FBdType := Value;
end;
procedure TTreeViewEx.TreeViewCompare(Sender: TObject; Node1, Node2: TTreeNode;
Data: Integer; var Compare: Integer);
begin
if TTreeView(Sender).Visible then
begin
if Node1.ItemType = itLogin then
begin
Compare := -1;
Exit;
end;
if Node2.ItemType = itLogin then
begin
Compare := 1;
Exit;
end;
Compare := lstrcmp(PChar(Node1.Text), PChar(Node2.Text))
end;
end;
procedure TTreeViewEx.TreeViewCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
begin
NodeClass := TTreeNodeEx;
end;
procedure TTreeViewEx.TreeViewExGetImageIndex(Sender: TObject; Node: TTreeNode);
begin
if Node.HasChildren then
Node.ImageIndex := 0
else
case Node.ItemType of
itBase : Node.ImageIndex := 2;
itBaseRTI : Node.ImageIndex := 3;
itLogin : Node.ImageIndex := 5;
end;
end;
procedure TTreeViewEx.TreeViewExGetSelectedIndex(Sender: TObject; Node: TTreeNode);
begin
Node.SelectedIndex := Node.ImageIndex;
end;
function TTreeViewEx.Destroying: boolean;
begin
Result := (csDestroying in ComponentState) or Application.Terminated;
end;
procedure TTreeViewEx.WMRButtonDown(var Message: TWMLButtonDblClk);
var
Node: TTreeNode;
begin
if Destroying then Exit;
Node := TTreeNode(GetNodeAt(TWMMouse(Message).XPos, TWMMouse(Message).YPos));
if Assigned(Node) then
begin
Self.Selected := Node;
end;
end;
procedure TTreeViewEx.AddServer(const Data: string; Login: string;
Bases: TDataset);
var
TreeNode,Node: TTreeNode;
begin
TreeNode := Items.AddChild(nil,Data.Substring(0,Data.IndexOf('|')));
TreeNode.Data := Pointer(Self.BdType); //Server type
TTreeNodeEx(TreeNode).DataSource := Data;
if not Login.IsEmpty then
begin
Node := Items.AddChild(TreeNode,Login);
Node.Data := Pointer(Integer(itLogin));
end;
if Assigned(Bases) and Bases.Active then
begin
Bases.First;
while not Bases.Eof do
begin
Node := Items.AddChild(TreeNode,Bases.Fields[0].AsString);
Node.Data := Pointer(Integer(itBase));
Bases.Next;
end;
Bases.Close;
end;
TreeNode.Expand(True);
end;
function TTreeViewEx.NodeFoundByDataSource(TreeView: TTreeViewEx;
DataSource: string): TTreeNode;
var
i: Integer;
begin
Result := nil;
for i := 0 to TreeView.Items.Count-1 do
if TreeView.Items[i].Parent = nil then
if TTreeNodeEx(TreeView.Items[i]).DataSource = DataSource then
begin
Result := TreeView.Items[i];
break;
end;
end;
end.
|
unit UnitPortScanner;
interface
uses
Windows, WinSock, ThreadUnit, UnitVariables, UnitConstants, UnitFunctions,
UnitConnection;
type
TScannerThread = class(TThread)
private
Host: string;
pBegin, pEnd: Word;
function hConnect(hHost: string; hPort: Word): Boolean;
function PortToService(Port: Word): string;
protected
procedure Execute; override;
public
StopScanning: Boolean;
constructor Create(CreateSuspended: Boolean = True);
procedure SetOptions(_Host: string; _pBegin, _pEnd: Word);
end;
var
ScannerThread: TScannerThread;
implementation
constructor TScannerThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
StopScanning := False;
end;
procedure TScannerThread.SetOptions(_Host: string; _pBegin, _pEnd: Word);
begin
Host := _Host;
pBegin := _pBegin;
pEnd := _pEnd;
end;
function TScannerThread.hConnect(hHost: string; hPort: Word): Boolean;
var
hSock: TSocket;
wsa: TWSAData;
Addr: TSockAddrIn;
begin
WSAStartup($0101, wsa);
try
hSock := socket(AF_INET, SOCK_STREAM, 0);
Addr.sin_family := AF_INET;
Addr.sin_addr.S_addr := inet_addr(PChar(ResolveIP(hHost)));
Addr.sin_port := htons(hPort);
if connect(hSock, Addr, SizeOf(Addr)) = 0 then Result := True else Result := False;
finally
closesocket(hSock);
WSACleanup();
end;
end;
function TScannerThread.PortToService(Port: Word): string;
begin
if Port = 20 then Result := IntToStr(Port) + ': FTP(File Transfer Protocol)' else
if Port = 21 then Result := IntToStr(Port) + ': FTP(File Transfer Protocol)'else
if Port = 22 then Result := IntToStr(Port) + ': SSH(Secure Shell)' else
if Port = 23 then Result := IntToStr(Port) + ': TELNET' else
if Port = 25 then Result := IntToStr(Port) + ': SMTP(Send Mail Transfer Protocol)' else
if Port = 43 then Result := IntToStr(Port) + ': WHOIS' else
if Port = 53 then Result := IntToStr(Port) + ': DNS(Domain name service)' else
if Port = 68 then Result := IntToStr(Port) + ': DHCP(Dynamic Host Control Protocol)' else
if (Port = 80) or (Port = 8080) then Result := IntToStr(Port) + ': HTTP(HyperText Transfer Protocol)' else
if Port = 110 then Result := IntToStr(Port) + ': POP3(Post Office Protocol 3)' else
if Port = 137 then Result := IntToStr(Port) + ': NETBIOS-ns' else
if Port = 138 then Result := IntToStr(Port) + ': NETBIOS-dgm' else
if Port = 139 then Result := IntToStr(Port) + ': NETBIOS' else
if Port = 143 then Result := IntToStr(Port) + ': IMAP(Internet Message Access Protocol)' else
if Port = 161 then Result := IntToStr(Port) + ': SNMP(Simple Network Management Protocol)' else
if Port = 194 then Result := IntToStr(Port) + ': IRC(Internet Relay Chat)' else
if Port = 220 then Result := IntToStr(Port) + ': IMAP(Internet Message Access Protocol 3)' else
if Port = 443 then Result := IntToStr(Port) + ': SSL(Secure Socket Layer)' else
if Port = 445 then Result := IntToStr(Port) + ': SMB(Netbios over TCP)' else
if Port = 1352 then Result := IntToStr(Port) + ': LOTUS NOTES' else
if Port = 1433 then Result := IntToStr(Port) + ': MICROSOFT SQL SERVER' else
if Port = 1521 then Result := IntToStr(Port) + ': ORACLE SQL' else
if Port = 2049 then Result := IntToStr(Port) + ': NFS(Network File System)' else
if Port = 3306 then Result := IntToStr(Port) + ': MySQL' else
if Port = 4000 then Result := IntToStr(Port) + ': ICQ' else
if (Port = 5800) or (Port = 5900) then Result := IntToStr(Port) + ': VNC' else
Result := IntToStr(Port) + ': Unknow service port.';
end;
procedure TScannerThread.Execute;
var
TmpStr: string;
begin
while (pBegin <> pEnd) and (StopScanning = False) do
begin
if hConnect(Host, pBegin) then
TmpStr := Host + '|' + PortToService(pBegin) + '|' + 'OPEN|'
else TmpStr := Host + '|' + PortToService(pBegin) + '|' + 'CLOSED|';
SendDatas(MainConnection, PORTSCANNERRESULTS + '|' + TmpStr);
Inc(pBegin);
end;
end;
end.
|
unit UIntComCargaEmAberto;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Buttons,
UDBCampoCodigo, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
MemDS, VirtualTable, Vcl.Menus, frxClass, frxDBSet;
type
TFIntComCargaEmAberto = class(TForm)
pnCampos: TPanel;
pnGrid: TPanel;
grDados: TDBGrid;
lbDuploClicObs: TLabel;
dsIntComCargaPesq: TDataSource;
btFechar: TBitBtn;
btConsultar: TBitBtn;
vtIntComCargaPesq: TVirtualTable;
vtIntComCargaPesqcdCarga: TIntegerField;
vtIntComCargaPesqdeCarga: TStringField;
vtIntComCargaPesqnupintura: TIntegerField;
vtIntComCargaPesqnmMotorista: TStringField;
vtIntComCargaPesqnmAjudante: TStringField;
vtIntComCargaPesqdePlaca: TStringField;
vtIntComCargaPesqdtSaida: TDateField;
vtIntComCargaPesqflTemObs: TStringField;
vtIntComCargaPesqnuQtdeCarga: TIntegerField;
vtIntComCargaPesqdeObsSistema: TStringField;
vtIntComCargaPesqcdPrioridade: TIntegerField;
relCargas: TfrxReport;
dbRelCargas: TfrxDBDataset;
btImprimir: TBitBtn;
vtIntComCargaPesqflSetorLixa: TStringField;
vtIntComCargaPesqflSetorFaturamento: TStringField;
vtIntComCargaPesqflSetorExpedicao: TStringField;
btAlertasCarga: TBitBtn;
vtIntComCargaPesqflTemAlerta: TStringField;
vtIntComCargaPesqdtIniCarreg: TDateField;
vtIntComCargaPesqhrIniCarreg: TStringField;
procedure FormCreate(Sender: TObject);
procedure btFecharClick(Sender: TObject);
procedure grDadosDblClick(Sender: TObject);
procedure btConsultarClick(Sender: TObject);
procedure grDadosDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
function relCargasUserFunction(const MethodName: string;
var Params: Variant): Variant;
procedure btImprimirClick(Sender: TObject);
procedure vtIntComCargaPesqflSetorLixaGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
procedure vtIntComCargaPesqflSetorFaturamentoGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
procedure vtIntComCargaPesqflSetorExpedicaoGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
procedure FormShow(Sender: TObject);
procedure btAlertasCargaClick(Sender: TObject);
private
procedure AplicarFiltro;
function UsuarioDataHoraImpressao : String;
public
{ Public declarations }
end;
var
FIntComCargaEmAberto: TFIntComCargaEmAberto;
implementation
uses
uDmERP, uDmIntegracao, UTelaInicial, uFuncoes;
{$R *.dfm}
function TFIntComCargaEmAberto.UsuarioDataHoraImpressao : String;
var
dthrAtual : TDateTime;
begin
dthrAtual := DataHoraAtual(DmERP.fdConnERP);
Result := 'Usuário impressão: ' + FTelaInicial.FnmUsuario + '. ' +
'Data/Hora: ' + FormatDateTime('dd/mm/yyyy', dthrAtual) + ' - ' + FormatDateTime('hh:mm', dthrAtual);
end;
procedure TFIntComCargaEmAberto.vtIntComCargaPesqflSetorExpedicaoGetText(
Sender: TField; var Text: string; DisplayText: Boolean);
begin
if SameText(Sender.FieldName, 'flSetorExpedicao') then
Text := '';
end;
procedure TFIntComCargaEmAberto.vtIntComCargaPesqflSetorFaturamentoGetText(
Sender: TField; var Text: string; DisplayText: Boolean);
begin
if SameText(Sender.FieldName, 'flSetorFaturamento') then
Text := '';
end;
procedure TFIntComCargaEmAberto.vtIntComCargaPesqflSetorLixaGetText(
Sender: TField; var Text: string; DisplayText: Boolean);
begin
if SameText(Sender.FieldName, 'flSetorLixa') then
Text := '';
end;
procedure TFIntComCargaEmAberto.btAlertasCargaClick(Sender: TObject);
var
stAux : TStringList;
begin
stAux := TStringList.Create;
if (vtIntComCargaPesq.Active) and (not vtIntComCargaPesq.IsEmpty)then
begin
if DmERP.qyIntComCargaAlertaPesq.Active then
DmERP.qyIntComCargaAlertaPesq.Close;
DmERP.qyIntComCargaAlertaPesq.MacroByName('filtro').Value := ' WHERE cdCarga = ' + vtIntComCargaPesq.FieldByName('cdCarga').AsString;
DmERP.qyIntComCargaAlertaPesq.Open();
DmERP.qyIntComCargaAlertaPesq.First;
while not DmERP.qyIntComCargaAlertaPesq.Eof do
begin
if Trim(DmERP.qyIntComCargaAlertaPesq.FieldByName('cdCargaAlerta').AsString) <> '' then
begin
if Trim(stAux.Text) = '' then
stAux.Text := 'Alerta ' + DmERP.qyIntComCargaAlertaPesq.FieldByName('cdCargaAlerta').AsString + ':' +
DmERP.qyIntComCargaAlertaPesq.FieldByName('deCargaAlerta').AsString
else
stAux.Text := stAux.Text + #13#13 +
'Alerta ' + DmERP.qyIntComCargaAlertaPesq.FieldByName('cdCargaAlerta').AsString + ':' +
DmERP.qyIntComCargaAlertaPesq.FieldByName('deCargaAlerta').AsString;
end;
DmERP.qyIntComCargaAlertaPesq.Next;
end;
if Trim(stAux.Text) <> '' then
MensagemAviso(stAux)
else
Aviso('Carga não possui alertas.');
end;
end;
procedure TFIntComCargaEmAberto.btConsultarClick(Sender: TObject);
begin
AplicarFiltro;
end;
procedure TFIntComCargaEmAberto.btFecharClick(Sender: TObject);
var
Tab : TTabSheet;
begin
dsIntComCargaPesq.DataSet.Close;
Tab := FTelaInicial.pcTelas.ActivePage;
if Assigned(Tab) then
begin
Tab.Parent := nil;
Tab.PageControl := nil;
FreeAndNil(Tab);
end;
FTelaInicial.pcTelas.Visible := FTelaInicial.pcTelas.PageCount > 0;
FTelaInicial.imLogoERP.Visible := not FTelaInicial.pcTelas.Visible;
end;
procedure TFIntComCargaEmAberto.btImprimirClick(Sender: TObject);
begin
try
vtIntComCargaPesq.DisableControls;
relCargas.PrepareReport();
if (FileExists(ExtractFilePath(Application.ExeName) + '\LogoLogin.jpg') and (relCargas.FindComponent('picLogoEmp') <> nil)) then
TfrxPictureView(relCargas.FindComponent('picLogoEmp')).Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + '\LogoLogin.jpg');
relCargas.ShowReport();
finally
vtIntComCargaPesq.EnableControls;
end;
end;
procedure TFIntComCargaEmAberto.AplicarFiltro;
var
sWhere : String;
stDados : TStringList;
begin
stDados := TStringList.Create;
vtIntComCargaPesq.Clear;
if (DmERP.qyIntComCargaPesq.Active) then
DmERP.qyIntComCargaPesq.Close;
DmERP.qyIntComCargaPesq.MacroByName('filtro').Clear;
sWhere := '';
if FTelaInicial.FcdSetorUsuario = 1 then
AdicionaCondSql(sWhere, ' cdSituacao IN(1, 2) ')
else
AdicionaCondSql(sWhere, ' cdSituacao = 2 ');
if Trim(sWhere) <> '' then
DmERP.qyIntComCargaPesq.MacroByName('filtro').Value := ' WHERE ' + sWhere;
DmERP.qyIntComCargaPesq.Open();
if DmERP.qyIntComCargaPesq.IsEmpty then
Aviso('Não existem cargas em aberto para mostrar.')
else
begin
try
vtIntComCargaPesq.DisableControls;
DmERP.qyIntComCargaPesq.DisableControls;
DmERP.qyIntComCargaPesq.First;
while not DmERP.qyIntComCargaPesq.Eof do
begin
vtIntComCargaPesq.Insert;
vtIntComCargaPesq.FieldByName('cdCarga').AsInteger := DmERP.qyIntComCargaPesq.FieldByName('cdCarga').AsInteger;
vtIntComCargaPesq.FieldByName('deCarga').AsString := DmERP.qyIntComCargaPesq.FieldByName('deCarga').AsString;
vtIntComCargaPesq.FieldByName('nuPintura').AsInteger := DmERP.qyIntComCargaPesq.FieldByName('nuPintura').AsInteger;
vtIntComCargaPesq.FieldByName('nmMotorista').AsString := DmERP.qyIntComCargaPesq.FieldByName('nmMotorista').AsString;
vtIntComCargaPesq.FieldByName('nmAjudante').AsString := DmERP.qyIntComCargaPesq.FieldByName('nmAjudante').AsString;
vtIntComCargaPesq.FieldByName('dePlaca').AsString := DmERP.qyIntComCargaPesq.FieldByName('dePlaca').AsString;
vtIntComCargaPesq.FieldByName('dtSaida').AsDateTime := DmERP.qyIntComCargaPesq.FieldByName('dtSaida').AsDateTime;
vtIntComCargaPesq.FieldByName('flTemObs').AsString := DmERP.qyIntComCargaPesq.FieldByName('flTemObsSis').AsString;
vtIntComCargaPesq.FieldByName('flSetorLixa').AsString := DmERP.qyIntComCargaPesq.FieldByName('flSetorLixa').AsString;
vtIntComCargaPesq.FieldByName('flSetorFaturamento').AsString := DmERP.qyIntComCargaPesq.FieldByName('flSetorFaturamento').AsString;
vtIntComCargaPesq.FieldByName('flSetorExpedicao').AsString := DmERP.qyIntComCargaPesq.FieldByName('flSetorExpedicao').AsString;
vtIntComCargaPesq.FieldByName('nuQtdeCarga').AsInteger := 0;
ExecuteSimplesSql(DmIntegracao.fdConnInteg,
'SELECT SUM(ip.qtde_solicitada) AS nuQtdeCarga ' +
' FROM pedido p ' +
' INNER JOIN itemPed ip ON (ip.nro_pedido = p.nro_pedido) ' +
' INNER JOIN grupoPed gp ON (gp.nro_pedido = p.nro_pedido) ' +
' WHERE COALESCE(gp.codigo_grupoPed, 0) = ' + DmERP.qyIntComCargaPesq.FieldByName('cdCarga').AsString +
' AND p.status_pedido <> ''C'' ',
'nuQtdeCarga',
stDados
);
if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then
vtIntComCargaPesq.FieldByName('nuQtdeCarga').AsInteger := StrToIntDef(stDados.Strings[0], 0);
vtIntComCargaPesq.FieldByName('deObsSistema').AsString := DmERP.qyIntComCargaPesq.FieldByName('deObsSistema').AsString;
vtIntComCargaPesq.FieldByName('cdPrioridade').AsInteger := DmERP.qyIntComCargaPesq.FieldByName('cdPrioridade').AsInteger;
if DmERP.qyIntComCargaAlertaPesq.Active then
DmERP.qyIntComCargaAlertaPesq.Close;
DmERP.qyIntComCargaAlertaPesq.MacroByName('filtro').Value := ' WHERE cdCarga = ' + vtIntComCargaPesq.FieldByName('cdCarga').AsString;
DmERP.qyIntComCargaAlertaPesq.Open();
if not DmERP.qyIntComCargaAlertaPesq.IsEmpty then
vtIntComCargaPesq.FieldByName('flTemAlerta').AsString := 'S'
else
vtIntComCargaPesq.FieldByName('flTemAlerta').AsString := 'N';
stDados.Clear;
ExecuteSimplesSql(DmERP.fdConnERP,
'SELECT dtBaixa, ' +
' CAST( ' +
' CASE ' +
' WHEN hrBaixa > 0 THEN ' +
' TRIM(TO_CHAR(TRUNC(hrBaixa/60), ''00'')) || '':'' || ' +
' TRIM(TO_CHAR(MOD(hrBaixa, 60), ''00'')) ' +
' END AS CHARACTER VARYING(5) ' +
' ) AS hrIniCarreg ' +
' FROM erp.intIndBaixaProducao ' +
' WHERE cdSetor = 9 ' +
' AND cdCarga = ' + vtIntComCargaPesq.FieldByName('cdCarga').AsString +
' ORDER BY dtBaixa, hrBaixa',
'dtBaixa,hrIniCarreg',
stDados
);
if (stDados.Count > 0) then
begin
if (Trim(stDados.Strings[0]) <> '') then
vtIntComCargaPesq.FieldByName('dtIniCarreg').AsDateTime := StrToDateTime(stDados.Strings[0])
else
vtIntComCargaPesq.FieldByName('dtIniCarreg').Clear;
if (Trim(stDados.Strings[1]) <> '') then
vtIntComCargaPesq.FieldByName('hrIniCarreg').AsString := Trim(stDados.Strings[1])
else
vtIntComCargaPesq.FieldByName('hrIniCarreg').Clear;
end;
vtIntComCargaPesq.Post;
DmERP.qyIntComCargaPesq.Next;
end;
finally
vtIntComCargaPesq.First;
vtIntComCargaPesq.EnableControls;
DmERP.qyIntComCargaPesq.EnableControls;
end;
end;
if Assigned(stDados) then
FreeAndNil(stDados);
end;
procedure TFIntComCargaEmAberto.FormCreate(Sender: TObject);
begin
vtIntComCargaPesq.Open;
btFechar.Glyph.LoadFromResourceName(HInstance, 'IMGBTFECHAR_32X32');
btConsultar.Glyph.LoadFromResourceName(HInstance, 'IMGBTCONSULTAR_32X32');
btImprimir.Glyph.LoadFromResourceName(HInstance, 'IMGBTIMPRIMIR_32X32');
btAlertasCarga.Glyph.LoadFromResourceName(HInstance, 'IMGBTALERTA_32X32');
AplicarFiltro;
relCargas.AddFunction('function UsuarioDataHoraImpressao : String', 'Sistema');
end;
procedure TFIntComCargaEmAberto.FormShow(Sender: TObject);
begin
{ grDados.Columns.Items[9].Visible := FTelaInicial.FcdSetorUsuario = 1;
grDados.Columns.Items[10].Visible := grDados.Columns.Items[9].Visible;
grDados.Columns.Items[11].Visible := grDados.Columns.Items[9].Visible;}
end;
procedure TFIntComCargaEmAberto.grDadosDblClick(Sender: TObject);
var
stAux : TStringList;
begin
stAux := TStringList.Create;
if (vtIntComCargaPesq.Active) and (not vtIntComCargaPesq.IsEmpty) then
begin
if (Trim(vtIntComCargaPesq.FieldByName('deObsSistema').AsString) <> '') then
begin
stAux.Text := vtIntComCargaPesq.FieldByName('deObsSistema').AsString;
MensagemAviso(stAux);
end
else
Aviso('Carga não possui observação.');
end;
if Assigned(stAux) then
FreeAndNil(stAux);
end;
procedure TFIntComCargaEmAberto.grDadosDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
Bitmap : TBitmap;
begin
if (gdSelected in State) or (gdFocused in State) then
grDados.Canvas.Brush.Color := clGradientInactiveCaption
else
grDados.Canvas.Brush.Color := clWindow;
if vtIntComCargaPesq.FieldByName('cdPrioridade').AsInteger = 2 then
begin
grDados.Canvas.Font.Color := clBlue;
grDados.Canvas.Font.Style := grDados.Canvas.Font.Style + [fsBold];
end
else if vtIntComCargaPesq.FieldByName('cdPrioridade').AsInteger = 3 then
begin
grDados.Canvas.Font.Color := clRed;
grDados.Canvas.Font.Style := grDados.Canvas.Font.Style + [fsBold];
end
else
begin
grDados.Canvas.Font.Color := clBlack;
grDados.Canvas.Font.Style := grDados.Canvas.Font.Style - [fsBold];
end;
grDados.Canvas.FillRect(Rect);
grDados.DefaultDrawColumnCell(Rect, DataCol, Column, State);
if (SameText(Column.FieldName, 'flSetorLixa')) then
begin
Bitmap := TBitmap.Create;
if UpperCase(vtIntComCargaPesq.FieldByName(Column.FieldName).AsString) = 'S' then
Bitmap.LoadFromResourceName(HInstance, 'IMGGRMARCAR_16X16')
else
Bitmap.LoadFromResourceName(HInstance, 'IMGGRDESMARCAR_16X16');
grDados.Canvas.Draw(Rect.Left+4, Rect.Top, Bitmap);
end
else if (SameText(Column.FieldName, 'flSetorFaturamento')) then
begin
Bitmap := TBitmap.Create;
if UpperCase(vtIntComCargaPesq.FieldByName(Column.FieldName).AsString) = 'S' then
Bitmap.LoadFromResourceName(HInstance, 'IMGGRMARCAR_16X16')
else
Bitmap.LoadFromResourceName(HInstance, 'IMGGRDESMARCAR_16X16');
grDados.Canvas.Draw(Rect.Left+4, Rect.Top, Bitmap);
end
else if (SameText(Column.FieldName, 'flSetorExpedicao')) then
begin
Bitmap := TBitmap.Create;
if UpperCase(vtIntComCargaPesq.FieldByName(Column.FieldName).AsString) = 'S' then
Bitmap.LoadFromResourceName(HInstance, 'IMGGRMARCAR_16X16')
else
Bitmap.LoadFromResourceName(HInstance, 'IMGGRDESMARCAR_16X16');
grDados.Canvas.Draw(Rect.Left+4, Rect.Top, Bitmap);
end;
end;
function TFIntComCargaEmAberto.relCargasUserFunction(const MethodName: string;
var Params: Variant): Variant;
begin
if SameText(MethodName, 'UsuarioDataHoraImpressao') then
Result := UsuarioDataHoraImpressao;
end;
initialization
RegisterClass(TFIntComCargaEmAberto);
finalization
UnRegisterClass(TFIntComCargaEmAberto);
end.
|
{
CoolProp Graphic Demo - Main form
Bruce Wernick, 13 December 2015
}
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
uMolChart;
type
TMainForm = class(TForm)
ListBox1: TListBox;
PaintBox1: TPaintBox;
StaticText1: TStaticText;
Button1: TButton;
procedure FormActivate(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure PaintBox1MouseLeave(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
private
fluid: AnsiString;
ref: PAnsiChar;
MolChart: TMolChart;
public
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
clipbrd,
cpIntf;
procedure TMainForm.FormCreate(Sender: TObject);
const
n = 80;
var
res: AnsiString;
begin
Caption := 'CoolProp Demo';
SetLength(res, n);
get_global_param_string('version', PAnsiChar(res), n);
Caption := Caption + ' ' + 'Version ' + string(res);
get_global_param_string('gitrevision', PAnsiChar(res), n);
Caption := Caption + ' ' + 'Revision ' + string(res);
MolChart := TMolChart.Create(PaintBox1.Canvas);
fluid := 'R22'; // initial fluid
ref := PAnsiChar(fluid)
end;
procedure TMainForm.FormActivate(Sender: TObject);
const
n = 2048;
var
res: AnsiString;
begin
SetLength(res, n);
get_global_param_string('FluidsList', PAnsiChar(res), n);
ListBox1.Items.CommaText := string(res);
ListBox1.ItemIndex := ListBox1.Items.IndexOf(string(ref))
end;
procedure TMainForm.ListBox1Click(Sender: TObject);
begin
fluid := AnsiString(ListBox1.Items[ListBox1.ItemIndex]);
ref := PAnsiChar(fluid);
PaintBox1.Refresh
end;
procedure TMainForm.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
h, p: Double;
begin
h := MolChart.P2X(X); p := MolChart.P2Y(Y);
Clipboard.AsText := format('h:%0.3f, p:%0.3f', [h, p]);
end;
procedure TMainForm.PaintBox1MouseLeave(Sender: TObject);
begin
StaticText1.Caption := string(fluid)
end;
procedure TMainForm.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
const
k0 = 273.15;
fmt = '%s: t=%0.2fC, p=%0.3f MPa, h=%0.3f kJ/kg, s=%0.4f kJ/kg-K';
var
h, p, t, s: Double;
begin
h := MolChart.P2X(X); p := MolChart.P2Y(Y);
t := PropsSI('T', 'P', 1e6*p, 'H', 1e3*h, ref);
s := 1e-3*PropsSI('S', 'P', 1e6*p, 'T', t+k0, ref);
StaticText1.Caption := format(fmt, [fluid, t-k0, p, h, s])
end;
procedure TMainForm.PaintBox1Paint(Sender: TObject);
begin
StaticText1.Caption := string(fluid);
MolChart.DrawChart(ref, PaintBox1.Width, PaintBox1.Height)
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
MyFormat: Word;
AData: THandle;
APalette: HPALETTE;
bmp: TBitmap;
begin
bmp := self.GetFormImage;
try
bmp.SaveToClipBoardFormat(MyFormat, AData, APalette);
ClipBoard.SetAsHandle(MyFormat,AData);
finally
bmp.Free;
end;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program HEAP1;
Const
maxN =20000;
Var
test,n,nHeap :LongInt;
ans :Int64;
Heap :Array[1..maxN] of Int64;
procedure UpHeap(i :LongInt);
var
key :Int64;
leaf,root :LongInt;
begin
key:=Heap[i]; leaf:=i;
while (leaf>=2) do
begin
root:=leaf div 2;
if (Heap[root]<=key) then Break;
Heap[leaf]:=Heap[root];
leaf:=root;
end;
Heap[leaf]:=key;
end;
procedure DownHeap(i :LongInt);
var
key :Int64;
leaf,root :LongInt;
begin
key:=Heap[i]; root:=i;
while (root*2<=nHeap) do
begin
leaf:=root*2;
if (leaf<nHeap) and (Heap[leaf]>Heap[leaf+1]) then Inc(leaf);
if (Heap[leaf]>=key) then Break;
Heap[root]:=Heap[leaf];
root:=leaf;
end;
Heap[root]:=key;
end;
procedure Push(x :Int64);
begin
Inc(nHeap);
Heap[nHeap]:=x;
UpHeap(nHeap);
end;
procedure Del(x :LongInt);
begin
Heap[x]:=Heap[nHeap];
Dec(nHeap);
DownHeap(x);
end;
procedure Enter;
var
i,x :LongInt;
begin
Read(n);
nHeap:=0;
for i:=1 to n do
begin
Read(x); Push(x);
end;
ans:=0;
end;
procedure Solve;
var
i :LongInt;
x,y :Int64;
begin
for i:=1 to n-1 do
begin
x:=Heap[1]; Inc(ans,x); Del(1);
y:=Heap[1]; Inc(ans,y); Del(1);
Push(x+y);
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Read(test);
repeat
Dec(test);
Enter;
Solve;
WriteLn(ans);
until (test=0);
Close(Input); Close(Output);
End. |
unit Test_FIToolkit.Config.Manager;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Config.Manager;
type
// Test methods for class TConfigManager
TestTConfigManager = class(TGenericTestCase)
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestCreate;
end;
implementation
uses
System.SysUtils, System.IniFiles,
TestUtils, TestConsts,
FIToolkit.Config.Consts, FIToolkit.Config.Types;
procedure TestTConfigManager.SetUp;
begin
DeleteFile(GetTestIniFileName)
end;
procedure TestTConfigManager.TearDown;
begin
DeleteFile(GetTestIniFileName)
end;
procedure TestTConfigManager.TestCreate;
var
sFileName : TFileName;
CfgMgr : TConfigManager;
begin
sFileName := GetTestIniFileName;
{ File name specified }
CfgMgr := TConfigManager.Create(sFileName, False, False);
try
CheckFalse(FileExists(sFileName), 'CheckFalse::FileExists<NonEmptyFileName,DoNotGenerateConfig>');
CheckTrue(String.IsNullOrEmpty(CfgMgr.ConfigFileName),
'CheckTrue::ConfigFileName.IsEmpty<NonEmptyFileName,DoNotGenerateConfig>');
CheckEquals<TFixInsightOutputFormat>(DEF_FIO_ENUM_OUTPUT_FORMAT, CfgMgr.ConfigData.FixInsightOptions.OutputFormat,
'(ConfigData.FixInsightOptions.OutputFormat = DEF_FIO_ENUM_OUTPUT_FORMAT)::<NonEmptyFileName,DoNotGenerateConfig>');
finally
CfgMgr.Free;
end;
CfgMgr := TConfigManager.Create(sFileName, True, False);
try
CheckTrue(FileExists(sFileName), 'CheckTrue::FileExists<NonEmptyFileName,GenerateConfig>');
CheckEquals(sFileName, CfgMgr.ConfigFileName, '(CfgMgr.ConfigFileName = sFileName)::<NonEmptyFileName,GenerateConfig>');
with TMemIniFile.Create(CloneFile(sFileName), TEncoding.UTF8) do
try
CheckEquals(
DEF_CD_STR_OUTPUT_FILENAME,
ReadString(CfgMgr.ConfigData.QualifiedClassName, 'OutputFileName', STR_INVALID_FILENAME),
'(ReadString = DEF_CD_STR_OUTPUT_FILENAME)::<NonEmptyFileName,GenerateConfig>'
);
finally
Free;
end;
finally
CfgMgr.Free;
end;
Assert(FileExists(sFileName));
CfgMgr := TConfigManager.Create(sFileName, False, False);
try
CheckFalse(String.IsNullOrEmpty(CfgMgr.ConfigFileName),
'CheckFalse::ConfigFileName.IsEmpty<NonEmptyFileName,DoNotGenerateConfig,FileExists>');
CheckEquals<TFixInsightOutputFormat>(DEF_FIO_ENUM_OUTPUT_FORMAT, CfgMgr.ConfigData.FixInsightOptions.OutputFormat,
'(ConfigData.FixInsightOptions.OutputFormat = DEF_FIO_ENUM_OUTPUT_FORMAT)::<NonEmptyFileName,DoNotGenerateConfig,FileExists>');
finally
CfgMgr.Free;
end;
{ File name NOT specified }
CfgMgr := TConfigManager.Create(String.Empty, False, False);
try
CheckTrue(String.IsNullOrEmpty(CfgMgr.ConfigFileName),
'CheckTrue::ConfigFileName.IsEmpty<EmptyFileName,DoNotGenerateConfig>');
CheckEquals<TFixInsightOutputFormat>(DEF_FIO_ENUM_OUTPUT_FORMAT, CfgMgr.ConfigData.FixInsightOptions.OutputFormat,
'(ConfigData.FixInsightOptions.OutputFormat = DEF_FIO_ENUM_OUTPUT_FORMAT)::<EmptyFileName,DoNotGenerateConfig>');
finally
CfgMgr.Free;
end;
CheckException(
procedure
begin
TConfigManager.Create(String.Empty, True, False);
end,
EArgumentException,
'CheckException::EArgumentException<EmptyFileName,GenerateConfig>'
);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTConfigManager.Suite);
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Registry;
const
SISTEMA = 'software\Microsoft\Windows\CurrentVersion\Policies\System';
EXPLORER = 'Software\Microsoft\Windows\CurrentVersion\Policies\Explorer';
NETWORK = 'Software\Microsoft\Windows\CurrentVersion\Policies\Network';
UNINSTALL = 'Software\Microsoft\Windows\CurrentVersion\Policies\Uninstall';
DOS = 'Software\Policies\Microsoft\Windows\System';
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure RestringirVideo(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(SISTEMA, TRUE);
//Desabilita página do papel de parede
key.WriteInteger('NoDispBackgroundPage', UmParaSimZeroParaNao);
//Desabilita página da aparência
key.WriteInteger('NoDispAppearancePage', UmParaSimZeroParaNao);
//Desabilita página da proteção de tela
key.WriteInteger('NoDispScrSavPage', UmParaSimZeroParaNao);
//Desabilita página Configurações
key.WriteInteger('NoDispSettingsPage', UmParaSimZeroParaNao);
//Deabilita toda propriedade do video
key.WriteInteger('NoDispCPL', UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirDesktop(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(EXPLORER, TRUE);
//Não mostrar ícones do Desktop
key.WriteInteger('NoDeskTop', UmParaSimZeroParaNao);
//Desabilita o active Desktop (essa eu não testei ainda)
key.WriteInteger('NoActiveDesktop', UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirIniciar(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(Explorer, true);
//Não mostrar o relógio da barra de tarefas
key.WriteInteger('HideClock', UmParaSimZeroParaNao);
//Desabilita o popup Propriedades da Barra de tarefas
key.WriteInteger('NoSetTaskbar', UmParaSimZeroParaNao);
//Desabilita o popup completo da barra de tarefas KEY.WriteInteger('NoTrayContextMenu',UmParaSimZeroParaNao);
//Oculta os icones vizinho ao relógio da barra de tarefas
kEY.WriteInteger('NoTrayItemsDisplay', UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirExplorer(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(EXPLORER, TRUE);
//Desabilita a exibição do Drive C
if UmParaSimZeroParaNao = 1 then
key.WriteInteger('NoDrives', 4)
else
key.WriteInteger('NoDrives', 0);
//Desabilita o menu Opções de pastas
key.WriteInteger('NoFolderOptions', UmParaSimZeroParaNao);
//Desabilita o menu Arquivo
key.WriteInteger('NoFileMenu', UmParaSimZeroParaNao);
//Desabilita o menu Favoritos
key.WriteInteger('NoFavoritesMenu', UmParaSimZeroParaNao);
//Limpa a lista de documentos recentes ao sair do windows
key.WriteInteger('ClearRecentDocsOnExit', UmParaSimZeroParaNao);
//Limpa o histórico da internet ao sair (Não testei ainda)
key.WriteInteger('NoRecentDocsHistory', UmParaSimZeroParaNao);
//Não mostra o ícone do Internet Explore no Desktop (Não testei ainda)
key.WriteInteger('NoInternetIcon', UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirSistema(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(DOS, TRUE);
//Desabilita o Prompt de Dos
key.WriteInteger('DisableCMD', UmParaSimZeroParaNao);
key.CloseKey;
key.OpenKey(EXPLORER, true);
//Desabilita o Executar (Tecla Win + R)
key.WriteInteger('NoRun', UmParaSimZeroParaNao);
//Desabilita o Localizar (Tecla Win + f)
key.WriteInteger('NoFind', UmParaSimZeroParaNao);
key.CloseKey;
key.OpenKey(SISTEMA, true);
//Desabilita o Regedit
key.WriteInteger('DisableRegistryTools', UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirPainel(UmParaSimZeroParaNao: integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(EXPLORER, true);
//Desabilita a propriedade de Sistema
key.WriteInteger('NoPropertiesMyComputer', UmParaSimZeroParaNao);
//Não tenho certeza mais parece que desabilita a propriedade de pastas
key.WriteInteger('NoSetFolders', UmParaSimZeroParaNao);
//Desabilita o painel de controle
Key.WriteInteger('NoControlPanel', UmParaSimZeroParaNao);
//Bloqueia a adição de novas impressoras
key.WriteInteger('NoAddPrinter', UmParaSimZeroParaNao);
//Bloqueia a exclusão de impressoras
key.WriteInteger('NoDeletePrinter', UmParaSimZeroParaNao);
key.CloseKey;
key.OpenKey(UNINSTALL, TRUE);
//Desabilita o Adicionar e Remover programas KEY.WriteInteger('NoAddRemovePrograms',UmParaSimZeroParaNao);
key.CloseKey;
end;
procedure RestringirOutros(UmParaSimZeroParaNao: Integer);
var
key: TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(EXPLORER, TRUE);
//Desabilita o botão Logoff do menu Iniciar
key.WriteInteger('StartMenuLogOff', UmParaSimZeroParaNao);
//Desabilita o botão desligar computador do MenuIniciar
key.WriteInteger('NoClose', UmParaSimZeroParaNao);
//Não testei ainda mais parece que não gravas as alterações feitas na sessão ao sair
key.WriteInteger('NoSaveSettings', UmParaSimZeroParaNao);
//Nâo testei ainda mais parece que desabilita as atualizações automáticas do windows
key.WriteInteger('NoDevMgrUpdate', UmParaSimZeroParaNao);
key.CloseKey;
end;
end.
{
Begin
RestringirVideo(1);//Para restringir
RestringirVideo(0);//Para desrestringir
end;
}
{
No programa que eu desenvolvi para LanHouse para cada restrição eu criei um campo no banco de dados referente a cada máquina, dai eu só restrinjo o que me interessa:
ex:
var
key:TRegistry;
begin
key := TRegistry.Create;
key.RootKey := HKEY_CURRENT_USER;
key.OpenKey(EXPLORER,TRUE);
With QrRestricoes do
Begin
//Desabilita o botão Logoff do menu Iniciar
key.WriteInteger('StartMenuLogOff',FieldByName('NoLogoff').AsInteger);
//Desabilita o botão desligar computador do MenuIniciar
key.WriteInteger('NoClose',FieldByName('NoDesligar').AsInteger);
//Não testei ainda mais parece que não gravas as alterações feitas na sessão ao sair
key.WriteInteger('NoSaveSettings',FieldByName('SalvarSessao').AsInteger);
//Nâo testei ainda mais parece que desabilita as atualizações automáticas do windows
key.WriteInteger('NoDevMgrUpdate',FieldByName('AtualizarWindows').AsInteger);
end;
key.CloseKey;
end;
}
|
unit frStation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, uCfgStorage;
type
{ TfraStation }
TfraStation = class(TFrame)
edtIOTA: TEdit;
edtCQZ: TEdit;
edtGrid: TEdit;
edtZipCode: TEdit;
edtStreet1: TEdit;
edtCall: TEdit;
edtState: TEdit;
edtName: TEdit;
edtCity: TEdit;
edtStreet2: TEdit;
edtITU: TEdit;
Label1: TLabel;
Label10: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
private
{ private declarations }
public
procedure LoadSettings(ini : TCfgStorage);
procedure SaveSettings(ini : TCfgStorage);
end;
implementation
{$R *.lfm}
procedure TfraStation.LoadSettings(ini : TCfgStorage);
begin
edtCall.Text := ini.ReadString('Station','Call','');
edtName.Text := ini.ReadString('Station','Name','');
edtStreet1.Text := ini.ReadString('Station','Street1','');
edtStreet2.Text := ini.ReadString('Station','Street2','');
edtCity.Text := ini.ReadString('Station','City','');
edtZipCode.Text := ini.ReadString('Station','ZIP','');
edtState.Text := ini.ReadString('Station','State','');
edtGrid.Text := ini.ReadString('Station','Grid','');
edtCQZ.Text := ini.ReadString('Station','CQZ','');
edtITU.Text := ini.ReadString('Station','ITU','');
edtIOTA.Text := ini.ReadString('Station','IOTA','')
end;
procedure TfraStation.SaveSettings(ini : TCfgStorage);
begin
ini.WriteString('Station','Call',edtCall.Text);
ini.WriteString('Station','Name',edtName.Text);
ini.WriteString('Station','Street1',edtStreet1.Text);
ini.WriteString('Station','Street2',edtStreet2.Text);
ini.WriteString('Station','City',edtCity.Text);
ini.WriteString('Station','ZIP',edtZipCode.Text);
ini.WriteString('Station','State',edtState.Text);
ini.WriteString('Station','Grid',edtGrid.Text);
ini.WriteString('Station','CQZ',edtCQZ.Text);
ini.WriteString('Station','ITU',edtITU.Text);
ini.WriteString('Station','IOTA',edtIOTA.Text)
end;
end.
|
unit gozgraph;
{$mode objfpc}{$H+}
{
Component to view a gozintograph structure
https://techpluscode.de/erzeugnisstruktur-visualisieren-als-gozintograph/
https://techpluscode.de/produktstruktur-analyse-im-gozintograph-viewer
https://github.com/tangielsky/tag/gozintograph
(C) 2021 Thomas Angielsky
}
interface
uses
Classes, SysUtils, Graphics, Controls, LMessages, LCLType, LCLIntf, Math,
Dialogs, ComCtrls, ComboEx;
type
TGozItemType = (gitUndefined,gitItem,gitModule,gitProduct);
TGozItemShape = (gisCircle,gisMixed);
TGozLinkInformation = record
Items : integer;
Quantity : extended;
end;
TGozProperty = class
private
FId : integer;
public
constructor Create;
published
property Id : integer read FId write FId;
end;
{ TGozFieldProperty }
TGozFieldProperty = class(TGozProperty)
private
FName : string;
public
constructor Create;
published
property Name : string read FName write FName;
end;
{ TGozValueProperty }
TGozValueProperty = class(TGozProperty)
private
FField : TGozFieldProperty;
FValue : string;
procedure SetValue(AValue: string);
public
constructor Create;
function GetFloatValue : float;
published
property Field : TGozFieldProperty read FField write FField;
property Value : string read FValue write SetValue;
end;
{ TGozPropertyList }
TGozPropertyList = class
private
IdCount : integer;
FList : TList;
function ExistsFieldId(Id: integer): TGozFieldProperty;
function GetId(Field: string): integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function AddField(Field: string): TGozFieldProperty;
function AddValue(FieldProperty : TGozFieldProperty; Value : string) : TGozValueProperty;
function ExistsValueId(Id: integer): TGozValueProperty;
function GetValue(Id : integer) : string;
function GetValueAsColor(Id : integer) : TColor;
function GetValueAsFloat(Id: integer): float;
procedure UpdateComboboxEx(ComboboxEx: TComboboxEx);
procedure UpdateListview(Listview: TListview);
published
property List : TList read FList write FList;
end;
{ TGozGraphConnection }
TGozGraphConnection = class
private
FDestination : string;
FHighlighted : boolean;
FQuantity : extended;
FSelected: boolean;
FShowText : boolean;
FSource : string;
Fx1 : longint;
Fx2 : longint;
Fy1 : longint;
Fy2 : longint;
public
constructor Create;
destructor Destroy; override;
published
property Destination : string read FDestination write FDestination;
property Quantity : extended read FQuantity write FQuantity;
property Selected : boolean read FSelected write FSelected;
property ShowText : boolean read FShowText write FShowText;
property Source : string read FSource write FSource;
property x1 : longint read Fx1 write Fx1;
property x2 : longint read Fx2 write Fx2;
property y1 : longint read Fy1 write Fy1;
property y2 : longint read Fy2 write Fy2;
end;
{ TGozGraphLink }
TGozGraphLink = class(TPersistent)
private
FDestination : string;
FQuantity : extended;
FSelected : boolean;
FShowText : boolean;
public
constructor Create;
destructor Destroy; override;
published
property Destination: string read FDestination write FDestination;
property Quantity: extended read FQuantity write FQuantity;
property Selected: boolean read FSelected write FSelected;
property ShowText: boolean read FShowText write FShowText;
end;
{ TGozGraphItem }
TGozGraphItem = class(TPersistent)
private
FCaption: string;
FColor2 : TColor;
FDescription : string;
FHeight : integer;
FItemType : TGozItemType;
FLevel : integer;
FLinks: TList;
FPainted : boolean;
FProperties : TGozPropertyList;
FSelected: boolean;
FWidth : integer;
Fx : longint;
Fy : longint;
public
IngoingInformation : TGozLinkInformation;
OutgoingInformation : TGozLinkInformation;
constructor Create;
destructor Destroy; override;
function ItemTypeColor : TColor;
function ItemTypeCaption : string;
procedure AddLink(Destination : string; Quantity : extended);
procedure Clear;
procedure SetSize(w,h : integer);
published
property Caption : string read FCaption write FCaption;
property Color2: TColor read FColor2 write FColor2;
property Description : string read FDescription write FDescription;
property Height : integer read FHeight write FHeight;
property ItemType : TGozItemType read FItemType write FItemType;
property Level : integer read FLevel write FLevel;
property Links : TList read FLinks write FLinks;
property Painted : boolean read FPainted write FPainted;
property Properties : TGozPropertyList read FProperties write FProperties;
property Selected : boolean read FSelected write FSelected;
property Width : integer read FWidth write FWidth;
property x : longint read Fx write Fx;
property y : longint read Fy write Fy;
end;
TOnGozGraphItemSelected = procedure(item : TGozGraphItem) of object;
{ TGozIntoGraph }
TGozIntoGraph = class(TCustomControl)
private
FColor : TColor;
FConnections : TList;
FDefaultItemHeight : integer;
FDefaultItemWidth : integer;
FDistanceX : integer;
FDistanceY : integer;
FFilename : string;
FFontSize : integer;
FHighlightColor : TColor;
FItems: TList;
FItemShape : TGozItemShape;
FLinkColor : TColor;
FLinkHighlightColor : TColor;
FLinkTextColor : TColor;
FOnItemSelected: TOnGozGraphItemSelected;
FProperties : TGozPropertyList;
FScaleFactor : double;
FSelectionAllDown : boolean;
FSelectionAllUp : boolean;
FShowCaptions : boolean;
FShowLinks : boolean;
FShowQuantities : boolean;
FTextColor : TColor;
xmax, ymax : longint;
MovedItem : TGozGraphItem;
MovedItemX, MovedItemY : longint;
Moving : boolean;
function ReScale(value: double): longint;
function Scale(value: double): longint;
function AddItem(ACaption: string): boolean;
procedure AddConnection(Source, Destination: string; Quantity: extended; x1,y1,x2,y2 : longint; Selected : boolean);
procedure ArrowTo(xa, ya, xe, ye, pb, pl: integer; Fill: boolean);
procedure CalcLinks(item: TGozGraphItem; x, y: longint; level: integer);
procedure ClearConnections;
procedure DrawItems;
procedure DrawLinks;
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 SelectLinksDown(searchitem: TGozGraphItem);
procedure SelectLinksUp(searchitem: TGozGraphItem);
procedure SetScaleFactor(AValue: double);
procedure SetSelectionAllDown(AValue: boolean);
procedure SetSelectionAllUp(AValue: boolean);
procedure SetShowCaptions(AValue: boolean);
procedure SetShowLinks(AValue: boolean);
procedure SetShowQuantities(AValue: boolean);
procedure UpdateItem(item: TGozGraphItem);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CountItemType(AItemType: TGozItemType; MultipleUse: boolean): integer;
function ExistsItem(ACaption: string): boolean;
function GetIngoingInformation(ACaption: string): TGozLinkInformation;
function GetOutgoingInformation(ACaption: string): TGozLinkInformation;
function GetItem(ACaption: string): TGozGraphItem;
function GetItemAt(X, Y: integer): TGozGraphItem;
function HasLinks(item: TGozGraphItem): boolean;
function ImportFromCsvFile(AFilename: string; Delimiter: string;
HasHeaders: boolean; PosSource, PosDestination, PosQuantity: integer
): boolean;
function ImportPropsFromCsvFile(AFilename: string; Delimiter: string;
HasHeaders: boolean; PosItem: integer; Listview : TListview ): boolean;
function MaxLevel : integer;
procedure AddLink(ParentItem, ChildItem : string; Quantity: extended);
procedure Autolayout;
procedure Clear;
procedure ClearSelections;
procedure Invalidate; override;
procedure SelectItems(startitem: TGozGraphItem);
procedure SetScaleFactorFromWidth(NewWidth: longint);
procedure UpdateConnections;
procedure UpdatePropertyListview(Listview: TListview; item: TGozGraphItem);
published
property Color : TColor read FColor write FColor;
property Connections : TList read FConnections write FConnections;
property DefaultItemHeight : integer read FDefaultItemHeight write FDefaultItemHeight;
property DefaultItemWidth : integer read FDefaultItemWidth write FDefaultItemWidth;
property DistanceX : integer read FDistanceX write FDistanceX;
property DistanceY : integer read FDistanceY write FDistanceY;
property Filename : string read FFilename write FFilename;
property FontSize : integer read FFontSize write FFontSize;
property HighlightColor : TColor read FHighlightColor write FHighlightColor;
property Items : TList read FItems write FItems;
property ItemShape : TGozItemShape read FItemShape write FItemShape;
property LinkColor : TColor read FLinkColor write FLinkColor;
property LinkHighlightColor : TColor read FLinkHighlightColor write FLinkHighlightColor;
property LinkTextColor : TColor read FLinkTextColor write FLinkTextColor;
property OnItemSelected: TOnGozGraphItemSelected read FOnItemSelected write FOnItemSelected;
property Properties : TGozPropertyList read FProperties write FProperties;
property ScaleFactor : double read FScaleFactor write SetScaleFactor;
property SelectionAllDown : boolean read FSelectionAllDown write SetSelectionAllDown;
property SelectionAllUp : boolean read FSelectionAllUp write SetSelectionAllUp;
property ShowCaptions : boolean read FShowCaptions write SetShowCaptions;
property ShowLinks : boolean read FShowLinks write SetShowLinks;
property ShowQuantities : boolean read FShowQuantities write SetShowQuantities;
property TextColor : TColor read FTextColor write FTextColor;
end;
var
gozProductColor : TColor;
gozModuleColor : TColor;
gozItemColor : TColor;
implementation
uses gozfunc;
{ TGozFieldProperty }
constructor TGozFieldProperty.Create;
begin
inherited Create;
FName:='';
end;
{ TGozValueProperty }
procedure TGozValueProperty.SetValue(AValue: string);
begin
if AValue<>FValue then FValue:=AValue;
end;
constructor TGozValueProperty.Create;
begin
inherited Create;
FField:=nil;
FValue:='';
end;
function TGozValueProperty.GetFloatValue: float;
begin
result:=StrToFloatDef(FValue,0);
end;
{ TGozPropertyList }
constructor TGozPropertyList.Create;
begin
inherited Create;
IdCount:=0;
FList:=TList.Create;
end;
destructor TGozPropertyList.Destroy;
begin
FList.Free;
inherited Destroy;
end;
procedure TGozPropertyList.Clear;
var
i : integer;
prop : TGozFieldProperty;
begin
for i:=0 to FList.Count-1 do
begin
prop:=TGozFieldProperty(FList[i]);
prop.Free;
end;
FList.Clear;
end;
function TGozPropertyList.GetId(Field : string) : integer;
var
i : integer;
prop : TGozFieldProperty;
begin
result:=-1;
for i:=0 to FList.Count-1 do
begin
prop:=TGozFieldProperty(FList[i]);
if Uppercase(Field)=UpperCase(prop.Name) then
begin
result:=prop.Id;
exit;
end;
end;
end;
function TGozPropertyList.ExistsFieldId(Id : integer) : TGozFieldProperty;
var
i : integer;
GozProperty : TGozFieldProperty;
begin
result:=nil;
for i:=0 to FList.Count-1 do
begin
GozProperty:=TGozFieldProperty(FList[i]);
if Id=GozProperty.Id then
begin
result:=GozProperty;
exit;
end;
end;
end;
function TGozPropertyList.ExistsValueId(Id : integer) : TGozValueProperty;
var
i : integer;
GozProperty : TGozValueProperty;
begin
result:=nil;
for i:=0 to FList.Count-1 do
begin
GozProperty:=TGozValueProperty(FList[i]);
if Id=GozProperty.Id then
begin
result:=GozProperty;
exit;
end;
end;
end;
function TGozPropertyList.AddField(Field: string): TGozFieldProperty;
var
GozProperty : TGozFieldProperty;
begin
IdCount:=IdCount+1;
GozProperty:=TGozFieldProperty.Create;
GozProperty.Id:=IdCount;
GozProperty.Name:=Field;
FList.Add(GozProperty);
result:=GozProperty;
end;
function TGozPropertyList.AddValue(FieldProperty: TGozFieldProperty;
Value: string): TGozValueProperty;
var
prop : TGozValueProperty;
begin
if FieldProperty<>nil then
begin
prop:=ExistsValueId(FieldProperty.Id);
if prop=nil then
begin
prop:=TGozValueProperty.Create;
prop.Id:=FieldProperty.Id;
prop.Value:=Value;
prop.Field:=FieldProperty;
FList.Add(prop);
end
else prop.Value:=Value;
result:=prop;
end else result:=nil;
end;
function TGozPropertyList.GetValue(Id: integer): string;
var
i : integer;
GozProperty : TGozValueProperty;
begin
result:='';
for i:=0 to FList.Count-1 do
begin
GozProperty:=TGozValueProperty(FList[i]);
if Id=GozProperty.Id then
begin
result:=GozProperty.Value;
exit;
end;
end;
end;
function TGozPropertyList.GetValueAsColor(Id: integer): TColor;
begin
result:=StringToColorDef(GetValue(Id),clNone);
end;
function TGozPropertyList.GetValueAsFloat(Id: integer): float;
begin
result:=StrToFloatDef(GetValue(Id),0);
end;
procedure TGozPropertyList.UpdateListview(Listview: TListview);
var
i : integer;
GozProperty : TGozFieldProperty;
item : TListitem;
begin
for i:=0 to FList.Count-1 do
begin
GozProperty:=TGozFieldProperty(FList[i]);
item:=Listview.Items.Add;
item.ImageIndex:=0;
item.Caption:=GozProperty.Name;
item.Data:=GozProperty;
end;
end;
procedure TGozPropertyList.UpdateComboboxEx(ComboboxEx: TComboboxEx);
var
i : integer;
GozProperty : TGozFieldProperty;
begin
for i:=0 to FList.Count-1 do
begin
GozProperty:=TGozFieldProperty(FList[i]);
ComboboxEx.ItemsEx.AddItem(GozProperty.Name,0,0,0,0,GozProperty);
end;
end;
{ TGozProperty }
constructor TGozProperty.Create;
begin
inherited Create;
FId:=-1;
end;
{ TGozGraphConnection }
constructor TGozGraphConnection.Create;
begin
end;
destructor TGozGraphConnection.Destroy;
begin
inherited Destroy;
end;
{ TGozIntoGraph }
constructor TGozIntoGraph.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItems:=TList.Create;
FConnections:=TList.Create;
FProperties:=TGozPropertyList.Create;
FProperties.AddField('Beschreibung');
FColor:=clWhite;
FTextColor:=clBlack;
FHighlightColor:=clYellow;
FLinkColor:=clSilver;
FLinkTextColor:=clSilver;
FLinkHighlightColor:=clBlack;
FDefaultItemHeight:=50;
FDefaultItemWidth:=50;
FDistanceX:=75;
FDistanceY:=150;
FScaleFactor:=1.0;
FSelectionAllUp:=false;
FSelectionAllDown:=false;
FShowCaptions:=true;
FShowLinks:=true;
FShowQuantities:=true;
FFontsize:=9;
Canvas.Font.Size:=Scale(FFontsize);
end;
destructor TGozIntoGraph.Destroy;
begin
ClearConnections;
FConnections.Free;
Clear;
FItems.Free;
FProperties.Free;
inherited Destroy;
end;
function TGozIntoGraph.HasLinks(item : TGozGraphItem) : boolean;
begin
result:=false;
if item<>nil then result:=item.Links.Count>0;
end;
procedure TGozIntoGraph.SelectLinksDown(searchitem : TGozGraphItem);
var
j : integer;
link : TGozGraphLink;
linkitem : TGozGraphItem;
begin
if searchitem=nil then exit;
if searchitem.Selected then exit;
searchitem.Selected:=true;
for j:=0 to searchitem.Links.Count-1 do
begin
link:=TGozGraphLink(searchitem.Links[j]);
linkitem:=GetItem(link.Destination);
SelectLinksDown(linkitem);
end;
end;
procedure TGozIntoGraph.SelectLinksUp(searchitem : TGozGraphItem);
var
i,j : integer;
link : TGozGraphLink;
item : TGozGraphItem;
begin
if searchitem=nil then exit;
if searchitem.Selected then exit;
searchitem.Selected:=true;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if (item<>nil) and (item.Caption<>searchitem.Caption) then
begin
for j:=0 to item.Links.Count-1 do
begin
link:=TGozGraphLink(item.Links[j]);
if link.Destination=searchitem.Caption then
SelectLinksUp(item);
end;
end;
end;
end;
procedure TGozIntoGraph.SelectItems(startitem : TGozGraphItem);
begin
if startitem=nil then exit;
if FSelectionAllDown then SelectLinksDown(startitem);
if FSelectionAllUp then
begin
startitem.Selected:=false;
SelectLinksUp(startitem);
end;
UpdateConnections;
startitem.Selected:=true;
end;
procedure TGozIntoGraph.CalcLinks(item : TGozGraphItem; x,y : longint; level : integer);
var
j,k : integer;
x0,y0 : longint;
link : TGozGraphLink;
linkitem : TGozGraphItem;
begin
item.Painted:=true;
if item.Level=-1 then item.Level:=level
else if item.Level<level then item.Level:=level;
x0:=x;
y0:=y+(item.Height+FDistanceY);
for j:=0 to item.Links.Count-1 do
begin
link:=TGozGraphLink(item.Links[j]);
linkitem:=GetItem(link.Destination);
if (linkitem<>nil) then
begin
if (linkitem.Painted=false) then
begin
CalcLinks(linkitem,x0,y0,level+1);
if linkitem.Height>item.Height then y0:=y+(linkitem.Height+FDistanceY);
x0:=xmax;
if j<item.Links.Count-1 then x0:=x0+(linkitem.Width+FDistanceX);
end
else
begin
//at multiuse always max of level
if linkitem.y<y0 then
begin
linkitem.y:=y0;
linkitem.Level:=level;
end;
end;
end;
end;
if x0>xmax then xmax:=x0;
if y0>ymax then ymax:=y0;
item.x:=x;
item.y:=y;
end;
procedure TGozIntoGraph.Autolayout;
var
i : integer;
x,y : longint;
item : TGozGraphItem;
begin
ClearConnections;
xmax:=0;
ymax:=0;
x:=FDistanceX;
y:=Canvas.TextHeight('Ag');
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
item.Painted:=false;
item.Level:=-1;
end;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if item.ItemType=gitProduct then
begin
CalcLinks(item,x,y,0);
if xmax>x then x:=xmax;
if i<FItems.Count-1 then x:=x+(item.Width+FDistanceX);
end;
end;
Width:=Scale(xmax+(FDistanceX+FDefaultItemWidth));
Height:=Scale(ymax+FDefaultItemHeight);
UpdateConnections;
Invalidate;
end;
procedure TGozIntoGraph.Paint;
var
TxtH : integer;
begin
inherited Paint;
Canvas.AntialiasingMode:=amOff;
Canvas.Brush.Style:=bsSolid;
Canvas.Brush.Color:=FColor;
Canvas.FillRect(ClientRect);
if FShowLinks then DrawLinks;
DrawItems;
end;
function TGozIntoGraph.Scale(value : double) : longint;
begin
result:=Round(value*FScaleFactor);
end;
function TGozIntoGraph.ReScale(value : double) : longint;
begin
result:=Round(value/FScaleFactor);
end;
procedure TGozIntoGraph.SetScaleFactor(AValue: double);
begin
if FScaleFactor=AValue then Exit;
FScaleFactor:=AValue;
Width:=Scale(xmax+(FDistanceX+FDefaultItemWidth));
Height:=Scale(ymax+FDefaultItemHeight);
Canvas.Font.Size:=Scale(FFontsize);
Invalidate;
end;
procedure TGozIntoGraph.SetScaleFactorFromWidth(NewWidth: longint);
var
f : double;
begin
f:=FScaleFactor/Width*NewWidth;
SetScaleFactor(f);
end;
procedure TGozIntoGraph.SetSelectionAllDown(AValue: boolean);
begin
if FSelectionAllDown=AValue then Exit;
FSelectionAllDown:=AValue;
Invalidate;
end;
procedure TGozIntoGraph.SetSelectionAllUp(AValue: boolean);
begin
if FSelectionAllUp=AValue then Exit;
FSelectionAllUp:=AValue;
Invalidate;
end;
procedure TGozIntoGraph.SetShowCaptions(AValue: boolean);
begin
if FShowCaptions=AValue then Exit;
FShowCaptions:=AValue;
Invalidate;
end;
procedure TGozIntoGraph.SetShowLinks(AValue: boolean);
begin
if FShowLinks=AValue then Exit;
FShowLinks:=AValue;
Invalidate;
end;
procedure TGozIntoGraph.SetShowQuantities(AValue: boolean);
begin
if FShowQuantities=AValue then Exit;
FShowQuantities:=AValue;
Invalidate;
end;
procedure TGozIntoGraph.ArrowTo(xa,ya,xe,ye,pb,pl:integer;Fill:boolean);
var
m,t,sqm : real;
x1,y1,x2,y2,xs,ys,la : real;
begin
la:=sqrt(sqr(xe-xa)+sqr(ye-ya));
if la<0.01 then exit;
t:=(la-pl)/la;
xs:=xa+t*(xe-xa);
if xe<>xa then
begin
m:=(ye-ya)/(xe-xa);
ys:=ya+t*m*(xe-xa);
if m<>0 then
begin
sqm:=sqrt(1+1/sqr(m));
x1:=xs+pb/sqm;
y1:=ys-(x1-xs)/m;
x2:=xs-pb/sqm;
y2:=ys-(x2-xs)/m;
end
else
begin
x1:=xs; x2:=xs;
y1:=ys+pb/1.0;
y2:=ys-pb/1.0;
end;
end
else
begin
xs:=xa;
ys:=ya+t*(ye-ya);
x1:=xs-pb/1.0;
x2:=xs+pb/1.0;
y1:=ys; y2:=ys;
end;
Canvas.MoveTo(xa,ya);
Canvas.LineTo(round(xs),round(ys));
if Fill then
begin
Canvas.Brush.Color:=Canvas.Pen.Color;
Canvas.Brush.Style:=bsSolid;
Canvas.Polygon([Point(xe,ye),Point(round(x1),round(y1)), Point(round(x2),round(y2)),Point(xe,ye)]);
end
else
Canvas.Polyline([Point(xe,ye),Point(round(x1),round(y1)), Point(round(x2),round(y2)),Point(xe,ye)]);
end;
procedure TGozIntoGraph.DrawLinks;
var
i,j : integer;
connection : TGozGraphConnection;
q : string;
begin
Canvas.Pen.Style:=psSolid;
for i:=0 to FConnections.Count-1 do
begin
connection:=TGozGraphConnection(FConnections[i]);
if connection.Selected=true then Canvas.Pen.Color:=FLinkHighlightColor
else Canvas.Pen.Color:=FLinkColor;
ArrowTo(Scale(connection.x2),Scale(connection.y2),
Scale(connection.x1),Scale(connection.y1),
Scale(4),Scale(10),false);
end;
if FShowQuantities then
begin
Canvas.Brush.Style:=bsClear;
Canvas.Brush.Color:=FColor;
Canvas.Font.Color:=FLinkTextColor;
for i:=0 to FConnections.Count-1 do
begin
connection:=TGozGraphConnection(FConnections[i]);
q:=FloatToStr(connection.Quantity);
Canvas.TextOut(Scale(((connection.x1)+((connection.x2)-(connection.x1)) div 2)-Canvas.TextWidth(q) div 2),
Scale(((connection.y1)+((connection.y2)-(connection.y1)) div 2)-Canvas.TextHeight(q) div 2),q);
end;
end;
end;
procedure TGozIntoGraph.DrawItems;
var
i,j : integer;
th,oy,maxwidth : integer;
s,s1,s2,itemcaption : string;
item : TGozGraphItem;
R : TRect;
begin
Canvas.Brush.Style:=bsSolid;
th:=Canvas.TextHeight('Ag');
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
Canvas.Brush.Color:=item.ItemTypeColor;
if item.Selected then Canvas.Brush.Color:=FHighlightColor;
if FItemShape=gisMixed then
begin
if (item.Color2<>clNone) and (item.Selected<>true) then
Canvas.Brush.Color:=item.Color2;
if item.ItemType=gitProduct then
Canvas.Rectangle(
Scale(item.x), Scale(item.y),
Scale(item.x+item.Width), Scale(item.y+item.Height))
else if item.ItemType=gitModule then
Canvas.Polygon([
Point(Scale(item.x+(item.width) div 2), Scale(item.y)),
Point(Scale(item.x+item.Width), Scale(item.y+item.Height)),
Point(Scale(item.x), Scale(item.y+item.Height))])
else
Canvas.Ellipse(
Scale(item.x), Scale(item.y),
Scale(item.x+item.Width), Scale(item.y+item.Height))
end
else
begin
if (item.Color2=clNone) or (item.Selected) then
Canvas.Ellipse(
Scale(item.x), Scale(item.y),
Scale(item.x+item.Width), Scale(item.y+item.Height))
else
begin
Canvas.Pie(
Scale(item.x), Scale(item.y),
Scale(item.x+item.Width), Scale(item.y+item.Height),
Scale(item.x+item.Width), Scale(item.y+(item.Height/2)),
Scale(item.x), Scale(item.y+(item.Height/2))
);
Canvas.Brush.Color:=item.Color2;
Canvas.Pie(
Scale(item.x), Scale(item.y),
Scale(item.x+item.Width), Scale(item.y+item.Height),
Scale(item.x), Scale(item.y+(item.Height/2)),
Scale(item.x+item.Width), Scale(item.y+(item.Height/2))
);
end;
end;
if item.Selected then Canvas.Brush.Color:=FHighlightColor
else Canvas.Brush.Color:=FColor;
//Text rechts
//Canvas.TextOut(item.x+FDefaultItemWidth,item.y+(item.Height-th) div 2,IntToStr(item.Level)+':'+item.Caption);
{
s:={IntToStr(item.Level)+':'+}item.Caption;
if Canvas.TextWidth(s)>Round(FDefaultItemWidth+FDistanceX/2) then
begin
j:=round(length(s)/2);
s1:=copy(s,1,j);
s2:=copy(s,j+1,length(s)-j);
end
else
begin
s1:='';
s2:=s;
end;
Canvas.Font.Color:=FTextColor;
Canvas.Brush.Style:=bsClear;
Canvas.TextOut(Scale(item.x+FDefaultItemWidth div 2 - Canvas.TextWidth(s1) div 2),Scale(item.y-th*2),s1);
Canvas.TextOut(Scale(item.x+FDefaultItemWidth div 2 - Canvas.TextWidth(s2) div 2),Scale(item.y-th),s2);
}
//R:=Rect(Scale(item.x),Scale(item.y),Scale(item.x+FDefaultItemWidth),Scale(item.y-2*th));
//Canvas.TextRect(R, R.Left, R.Top, s, Canvas.TextStyle);
//DrawText(Canvas.Handle, @sText[1], Length(sText), TextRect, DT_CALCRECT);
//Canvas.Font.Color:=clBlack;
//DrawText(Canvas.Handle, @s[1], Length(s), R, DT_WORDBREAK);
itemcaption:=item.caption;
if item.Description<>'' then itemcaption:=item.Description;
if FShowCaptions then
begin
Canvas.Font.Color:=FTextColor;
Canvas.Brush.Style:=bsClear;
maxwidth:=Round((item.Width+FDistanceX-Canvas.TextWidth('...'))*0.9);
s:='';
for j:=1 to length(itemcaption) do
if Canvas.TextWidth(s)<maxwidth then s:=s+copy(itemcaption,j,1)
else
begin
s:=trim(s)+'...';
break;
end;
//Canvas.TextOut(Scale(item.x+FDefaultItemWidth div 2 - Canvas.TextWidth(s) div 2),Scale(item.y-th),s);
Canvas.TextOut(Scale(item.x+item.Width div 2 - Canvas.TextWidth(s) div 2),
Scale(item.y-th),s);
end;
end;
end;
procedure TGozIntoGraph.Clear;
var
i : integer;
item : TGozGraphItem;
begin
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
item.Free;
end;
FItems.Clear;
end;
procedure TGozIntoGraph.ClearConnections;
var
i : integer;
item : TGozGraphConnection;
begin
for i:=0 to FConnections.Count-1 do
begin
item:=TGozGraphConnection(FConnections[i]);
item.Free;
end;
FConnections.Clear;
end;
procedure TGozIntoGraph.ClearSelections;
var
i : integer;
item : TGozGraphItem;
begin
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
item.Selected:=false;
end;
end;
procedure TGozIntoGraph.AddConnection(Source, Destination : string; Quantity : extended;
x1,y1,x2,y2 : longint; Selected : boolean);
var
i : integer;
connection : TGozGraphConnection;
begin
for i:=0 to FConnections.Count-1 do
begin
connection:=TGozGraphConnection(FConnections[i]);
if (connection.Source=Source) and (connection.Destination=Destination) then exit;
end;
connection:=TGozGraphConnection.Create;
connection.Source:=Source;
connection.Destination:=Destination;
connection.Quantity:=Quantity;
connection.Selected:=Selected;
connection.x1:=x1;
connection.y1:=y1;
connection.x2:=x2;
connection.y2:=y2;
FConnections.Add(connection);
end;
procedure TGozIntoGraph.UpdateConnections;
var
i,j : integer;
item,item2 : TGozGraphItem;
link : TGozGraphLink;
begin
ClearConnections;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
for j:=0 to item.Links.Count-1 do
begin
link:=TGozGraphLink(item.Links[j]);
item2:=GetItem(link.Destination);
AddConnection(item.Caption,link.Destination,link.Quantity,
item.x+item.Width div 2,item.y+item.Height,
item2.x+item2.Width div 2,item2.y+item2.Height div 2,
item.Selected and item2.Selected);
end;
end;
end;
procedure TGozIntoGraph.Invalidate;
begin
inherited Invalidate;
end;
function TGozIntoGraph.ImportFromCsvFile(AFilename: string; Delimiter: string;
HasHeaders: boolean; PosSource, PosDestination, PosQuantity: integer
): boolean;
var
sl : TStringList;
sr : TStringArray;
i,j,k : integer;
source,destination : string;
quantity : extended;
begin
result:=false;
FFilename:=AFilename;
Cursor:=crHourglass;
sl:=TStringList.Create;
sl.LoadFromFile(AFilename);
Clear;
try
if HasHeaders then j:=1
else j:=0;
for i:=j to sl.Count-1 do
begin
sr:=sl[i].Split(Delimiter);
source:=sr[PosSource-1];
destination:=sr[PosDestination-1];
if PosQuantity=-1 then quantity:=1
else Val(sr[PosQuantity-1],quantity,j);
if (source<>'') and (destination<>'') {and (quantity>0)} then
AddLink(source,destination,quantity);
end;
Autolayout;
result:=true;
except
end;
Cursor:=crDefault;
sl.Free;
end;
function TGozIntoGraph.ImportPropsFromCsvFile(
AFilename: string; Delimiter: string; HasHeaders: boolean;
PosItem: integer;
Listview : TListview
): boolean;
var
sl : TStringList;
sr : TStringArray;
i,j : integer;
item : TGozGraphItem;
Listitem : TListitem;
prop : TGozFieldProperty;
begin
result:=false;
Cursor:=crHourglass;
if FileExists(AFilename)=false then
begin
result:=false;
exit;
end;
sl:=TStringList.Create;
sl.LoadFromFile(AFilename);
//add new property fields
for i:=0 to Listview.Items.Count-2 do
begin
Listitem:=Listview.Items[i];
if Listitem.ImageIndex=2 then
begin
prop:=FProperties.AddField(Listitem.Caption);
listitem.Data:=prop;
end;
end;
try
if HasHeaders then j:=1
else j:=0;
for i:=j to sl.Count-1 do
begin
sr:=sl[i].Split(Delimiter);
item:=GetItem(sr[PosItem-1]);
if item<>nil then
begin
//add or update properties
for j:=0 to Listview.Items.Count-2 do
begin
Listitem:=Listview.Items[j];
if Listitem.ImageIndex>0 then item.Properties.AddValue(
TGozFieldProperty(Listitem.Data),
sr[StrInt(ListItem.SubItems[0])-1]);
end;
end;
end;
Autolayout;
result:=true;
except
end;
Cursor:=crDefault;
sl.Free;
end;
function TGozIntoGraph.MaxLevel: integer;
var
i : integer;
item : TGozGraphItem;
begin
result:=0;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if item<>nil then
if item.Level>result then result:=item.Level;
end;
end;
function TGozIntoGraph.GetItem(ACaption : string) : TGozGraphItem;
var
i : integer;
item : TGozGraphItem;
begin
result:=nil;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if item<>nil then
if ACaption=item.Caption then
begin
result:=item;
exit;
end;
end;
end;
function TGozIntoGraph.ExistsItem(ACaption : string) : boolean;
begin
result:=GetItem(ACaption)<>nil;
end;
function TGozIntoGraph.GetOutgoingInformation(ACaption : string) : TGozLinkInformation;
var
i,j : integer;
item : TGozGraphItem;
link : TGozGraphLink;
begin
result.Items:=0;
result.Quantity:=0;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if (item<>nil) and (item.Caption<>ACaption) then
begin
for j:=0 to item.Links.Count-1 do
begin
link:=TGozGraphLink(item.Links[j]);
if link.Destination=ACaption then
begin
result.Items:=result.Items+1;
result.Quantity:=result.Quantity+link.Quantity;
end;
end;
end;
end;
end;
function TGozIntoGraph.GetIngoingInformation(ACaption : string) : TGozLinkInformation;
var
i : integer;
item : TGozGraphItem;
link : TGozGraphLink;
begin
result.Items:=0;
result.Quantity:=0;
item:=GetItem(ACaption);
if item<>nil then
begin
result.Items:=item.Links.Count;
for i:=0 to item.Links.Count-1 do
begin
link:=TGozGraphLink(item.Links[i]);
result.Quantity:=result.Quantity+link.Quantity;
end;
end;
end;
procedure TGozIntoGraph.UpdateItem(item : TGozGraphItem);
begin
item.IngoingInformation:=GetIngoingInformation(item.Caption);
item.OutgoingInformation:=GetOutgoingInformation(item.Caption);
item.ItemType:=gitUndefined;
if (item.IngoingInformation.Items=0) and (item.OutgoingInformation.Items>0) then item.ItemType:=gitItem;
if (item.IngoingInformation.Items>0) and (item.OutgoingInformation.Items=0) then item.ItemType:=gitProduct;
if (item.IngoingInformation.Items>0) and (item.OutgoingInformation.Items>0) then item.ItemType:=gitModule;
end;
procedure TGozIntoGraph.UpdatePropertyListview(Listview: TListview; item : TGozGraphItem);
var
i : integer;
prop : TGozFieldProperty;
Listitem : TListitem;
begin
if (Listview=nil) or (item=nil) then exit;
for i:=0 to FProperties.List.Count-1 do
begin
prop:=TGozFieldProperty(FProperties.List[i]);
Listitem:=Listview.Items.Add();
Listitem.ImageIndex:=0;
Listitem.Caption:=prop.Name;
Listitem.SubItems.Add(item.Properties.GetValue(prop.Id));
Listitem.Data:=prop;
end;
end;
function TGozIntoGraph.AddItem(ACaption: string) : boolean;
var
item : TGozGraphItem;
begin
result:=false;
if ExistsItem(ACaption)=false then
begin
item:=TGozGraphItem.Create;
item.Caption:=ACaption;
item.Width:=FDefaultItemWidth;
item.Height:=FDefaultItemHeight;
FItems.Add(item);
result:=true;
end;
end;
function TGozIntoGraph.CountItemType(AItemType: TGozItemType; MultipleUse: boolean): integer;
var
item : TGozGraphItem;
i,j : integer;
begin
j:=0;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if item.ItemType=AItemType then
begin
if MultipleUse=true then
begin
if item.OutgoingInformation.Items>1 then j:=j+1;
end
else j:=j+1;
end;
end;
result:=j;
end;
procedure TGozIntoGraph.AddLink(ParentItem, ChildItem: string; Quantity: extended);
var
item : TGozGraphItem;
begin
AddItem(ParentItem);
AddItem(ChildItem);
//Add connection
item:=GetItem(ParentItem);
if item<>nil then
begin
item.AddLink(ChildItem,Quantity);
UpdateItem(item);
item:=GetItem(ChildItem);
if item<>nil then UpdateItem(item);
end;
end;
function TGozIntoGraph.GetItemAt(X, Y: integer): TGozGraphItem;
var
i : Integer;
item : TGozGraphItem;
begin
result:=nil;
for i:=0 to FItems.Count-1 do
begin
item:=TGozGraphItem(FItems[i]);
if (x>=Scale(item.x)) and (x<=Scale(item.x+item.Width))
and (y>=Scale(item.y)) and (y<=Scale(item.y+item.Height)) then exit(item);
end;
end;
procedure TGozIntoGraph.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited MouseMove(Shift, X, Y);
if (ssLeft in Shift) then
begin
if (MovedItem<>nil) and (Moving=true) then
begin
MovedItem.x:=ReScale(X)-MovedItemX;
MovedItem.y:=ReScale(Y)-MovedItemY;
Invalidate;
end;
end;
end;
procedure TGozIntoGraph.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
item : TGozGraphItem;
begin
inherited MouseDown(Button, Shift, X, Y);
MovedItem:=nil;
item:=GetItemAt(X,Y);
if Button=mbLeft then
begin
ClearSelections;
if item<>nil then
begin
SelectItems(item);
MovedItem:=item;
MovedItemX:=ReScale(X)-item.x;
MovedItemY:=ReScale(Y)-item.y;
Moving:=true;
end;
Invalidate;
if Assigned(FOnItemSelected) then FOnItemSelected(item);
end;
end;
procedure TGozIntoGraph.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
if (MovedItem<>nil) and (Moving=true) then
begin
Moving:=false;
MovedItem.x:=ReScale(X)-MovedItemX;
MovedItem.y:=ReScale(Y)-MovedItemY;
SelectItems(MovedItem);
Invalidate;
end;
end;
{ TGozGraphLink }
constructor TGozGraphLink.Create;
begin
inherited Create;
FDestination:='';
FQuantity:=0;
FSelected:=false;
FShowText:=true;
end;
destructor TGozGraphLink.Destroy;
begin
inherited Destroy;
end;
{ TGozGraphItem }
constructor TGozGraphItem.Create;
begin
inherited Create;
FLinks:=TList.Create;
FProperties:=TGozPropertyList.Create;
FCaption:='';
FColor2:=clNone;
FWidth:=50;
FHeight:=50;
Fx:=0;
Fy:=0;
FSelected:=false;
FPainted:=false;
end;
destructor TGozGraphItem.Destroy;
begin
Clear;
FLinks.Free;
FProperties.Free;
inherited Destroy;
end;
procedure TGozGraphItem.Clear;
var
i : integer;
link : TGozGraphLink;
begin
for i:=0 to FLinks.Count-1 do
begin
link:=TGozGraphLink(FLinks[i]);
link.Free;
end;
FLinks.Clear;
FProperties.Clear;
end;
procedure TGozGraphItem.SetSize(w, h: integer);
begin
FWidth:=w;
FHeight:=h;
end;
procedure TGozGraphItem.AddLink(Destination: string; Quantity: extended);
var
connection : TGozGraphLink;
begin
connection:=TGozGraphLink.Create;
connection.Destination:=Destination;
connection.Quantity:=Quantity;
FLinks.Add(connection);
end;
function TGozGraphItem.ItemTypeColor: TColor;
begin
if FItemType=gitItem then result:=gozItemColor
else if FItemType=gitModule then result:=gozModuleColor
else if FItemType=gitProduct then result:=gozProductColor
else result:=clGray;
end;
function TGozGraphItem.ItemTypeCaption: string;
begin
if FItemType=gitItem then result:='Einzelteil'
else if FItemType=gitModule then result:='Baugruppe'
else if FItemType=gitProduct then result:='Produkt'
else result:='undefiniert';
end;
end.
|
unit uImportacao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, JvExStdCtrls, JvGroupBox, ExtCtrls, IOUtils,
FMTBcd, DB, SqlExpr, DateUtils, xmldom, XMLIntf, msxmldom, XMLDoc,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, jpeg, StrUtils,
PngImage, ActiveX, DBXCommon, SyncObjs, DBClient, Provider, uFactoryImagem, GIFImg;
type
TRGBArray = array[Word] of TRGBTriple;
pRGBArray = ^TRGBArray;
type
TImportacao = class
protected
FIdAgendameto: integer;
FIdImobiliaria: Integer;
FIdBancoDados: Integer;
FPortal: string;
FUrlXml: string;
FPathXml: string;
FPathMarcaAgua: string;
FPathImagem: string;
FNomeMarcaAgua: string;
FQryInsertImg: TSQLQuery;
FConexaoPortal: TSQLConnection;
FConexaoAux: TSQLConnection;
procedure setConexaoAux(const Value: TSQLConnection);
function getConexaoAux: TSQLConnection;
procedure ConectarPortal();
procedure LoadConfig();
procedure AtualizaInfoTarefa(idAgendamento: integer; duracao, status, msg, nameXml: string);
procedure ProcessaImagem();
function CalculaDuracao(timeInicial, timeFinal: TDateTime): string;
procedure DownloadXML(url, pathXml, nameFile: string);
procedure ImportaXML(idImobiliaria:integer);
procedure ContaImoveisFotos(pathXML: string); virtual; abstract;
procedure InseriTempXML(pathXML: string); virtual; abstract;
function ValidaTagsXML(node: IXMLNode): boolean; virtual; abstract;
function AcertoAcento(texto: string): string;
procedure GravarLog(Conteudo, Path: string);
function Ternario(Condicao, Retorno1, Retorno2: string): string;
public
property ConexaoAux: TSQLConnection read getConexaoAux write setConexaoAux;
constructor Create(idAgendamento, idImobiliaria, idBancoDados: integer; var ConexaoAux: TSQLConnection);
end;
var
iContFoto, iContErroFoto, iContTotalItem, iContTotalFoto, iContInserido, iContAtualizado, iContExcluido: Integer;
tTimeInicial : TDateTime;
implementation
uses uPrincipal, uDM, uThreadImportacao;
{ TImportacao }
procedure TImportacao.GravarLog(Conteudo, Path: string);
var
arquivo : TextFile;
nameLog: string;
begin
nameLog := Path + 'LogImagem.txt';
if not FileExists(nameLog) then
begin
AssignFile(arquivo, nameLog);
ReWrite(arquivo);
WriteLn(arquivo, Conteudo);
end
else
begin
AssignFile(arquivo, nameLog);
Append(arquivo);
WriteLn(arquivo, Conteudo);
end;
WriteLn(arquivo, '------------------------------------------------------------------------------------------------------------');
CloseFile(arquivo);
end;
// Configura uma conexão com o banco de dados específico do portal
procedure TImportacao.ConectarPortal;
var
oQry: TSQLQuery;
begin
if not Assigned(FConexaoPortal) then
begin
try
try
oQry := TSQLQuery.Create(nil);
oQry.SQLConnection := Self.getConexaoAux;
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('SELECT id, host, usuario, senha, bancoDados, timeOut FROM TAB_BANCO_DADOS WHERE id = :id AND registro = :registro');
oQry.ParamByName('id').AsInteger := Self.FIdBancoDados;
oQry.ParamByName('registro').AsString := 'A';
oQry.Open;
if not oQry.IsEmpty then
begin
Self.FConexaoPortal := TSQLConnection.Create(nil);
Self.FConexaoPortal.Connected := False;
Self.FConexaoPortal.LoginPrompt := false;
Self.FConexaoPortal.ParamsLoaded := True;
Self.FConexaoPortal.DriverName := 'MSSQL';
Self.FConexaoPortal.GetDriverFunc := 'getSQLDriverMSSQL';
Self.FConexaoPortal.LibraryName := 'dbxmss.dll';
Self.FConexaoPortal.VendorLib := 'sqlncli10.dll';
Self.FConexaoPortal.Params.Clear;
Self.FConexaoPortal.Params.Add('hostname='+ oQry.FieldByName('host').AsString);
Self.FConexaoPortal.Params.Add('user_name='+ oQry.FieldByName('usuario').AsString);
Self.FConexaoPortal.Params.Add('password='+ oQry.FieldByName('senha').AsString);
Self.FConexaoPortal.Params.Add('Database='+ oQry.FieldByName('bancoDados').AsString);
Self.FConexaoPortal.Params.Add('connecttimeout='+ IntToStr(oQry.FieldByName('timeOut').AsInteger));
Self.FConexaoPortal.Params.Add('Mars_Connection=True');
Self.FConexaoPortal.Connected := True;
end;
except
on E:Exception do
MessageDlg('Erro ao carregar dados de conexão do portal: ' + E.Message, mtError, [mbOK], 0);
end;
finally
Self.ConexaoAux.Close;
FreeAndNil(oQry);
end;
end
else
Self.FConexaoPortal.Connected := True;
end;
procedure TImportacao.ImportaXML(idImobiliaria:integer);
var
iDuracaoHora, iDuracaoMinuto, iDuracaoSegundos, iNumeroXml: integer;
oQry, oQryTemp: TSQLQuery;
oCds: TClientDataSet;
oProvider: TDataSetProvider;
sNameImagem, sNomeXml: string;
begin
if not ThreadImportacao.CheckTerminated then
begin
try
try
// Inicializa as variáveis
iContInserido := 0;
iContAtualizado:= 0;
iContExcluido := 0;
iContFoto := 0;
iContTotalItem := 0;
iContTotalFoto := 0;
iContErroFoto := 0;
Self.LoadConfig;
// Atribui a hora de início do processo
tTimeInicial := Now;
// Chama a função para baixar o aquivo XML
Randomize;
iNumeroXml := Random(99999);
sNomeXml := IntToStr(iNumeroXml) + '_xml.xml';
Self.DownloadXML(FUrlXml, FPathXml, sNomeXml);
// Verifica se o arquivo XML NÃO existe, ser verdadeiro gera uma exception e finaliza a rotina
if not FileExists(FPathXml + sNomeXml) then
raise Exception.Create('Arquivo XML não encontrado!');
// Chama procedure para contar o total de imóveis e fotos no XML
Self.ContaImoveisFotos(FPathXml + sNomeXml);
// Chama procedure ler e gravar os dados do XML na tabela imoveis_xml
Self.InseriTempXML(FPathXml + sNomeXml);
// Chama a função para executar a conexão com o respectivo portal onde serão gravados os dados
Self.ConectarPortal;
oQryTemp := TSQLQuery.Create(nil);
oQryTemp.SQLConnection := Self.FConexaoPortal;
//////////////////////////// INÍCIO INSERT ////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Comparando registros de imóveis para inclusão', '');
// Filtra todos os registros que não existem na tabela imóveis2
oQryTemp.Close;
oQryTemp.SQL.Clear;
oQryTemp.SQL.Add('SELECT id_externo, cod_usuario FROM imoveis_xml a where cod_usuario = :idTemp ');
oQryTemp.SQL.Add('EXCEPT SELECT id_externo, cod_usuario FROM imoveis b WHERE cod_usuario = :idFixo ORDER BY id_externo');
oQryTemp.ParamByName('idTemp').AsInteger := idImobiliaria;
oQryTemp.ParamByName('idFixo').AsInteger := idImobiliaria;
oQryTemp.Open;
oQry := TSQLQuery.Create(nil);
oQry.SQLConnection := Self.FConexaoPortal;
if not oQryTemp.IsEmpty then
begin
oQryTemp.First;
while not oQryTemp.Eof and not ThreadImportacao.CheckTerminated do
begin
// Inseri os registros no banco de dados
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('INSERT INTO imoveis(id_externo, categoria, tipo, cidade, endereco, titulo, descricao, cond_pag, area, area_c, quartos, suites, tipo_construcao, salas, ambientes, cozinhas, ');
oQry.SQL.Add('wc, lavabo, piscina, garagem, telefone, data, cod_usuario, views, status, aprovado, valor, bairro) ');
oQry.SQL.Add('SELECT id_externo, categoria, tipo, cidade, endereco, titulo, descricao, cond_pag, area, area_c, quartos, suites, tipo_construcao, salas, ambientes, cozinhas, ');
oQry.SQL.Add('wc, lavabo, piscina, garagem, telefone, data, cod_usuario, views, status, aprovado, valor, bairro ');
oQry.SQL.Add('FROM imoveis_xml WHERE id_externo = :idExterno');
oQry.ParamByName('idExterno').AsInteger := oQryTemp.FieldByName('id_externo').AsInteger;
oQry.ExecSQL();
Inc(iContInserido);
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusão de novos imóveis - ' + IntToStr(iContInserido) + ' de ' + IntToStr(iContTotalItem) , '');
oQryTemp.Next;
end;
end;
//////////////////////////// FIM INSERT ////////////////////////////////////////////////////////////////////////////////
//////////////////////////// INÍCIO UPDATE ////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Comparando registro de imóveis para atualização', '');
// Filtra todos os registros que são diferentes da tabela imóveis2
dm.cdsAux.Close;
dm.qryAux.Close;
dm.qryAux.SQLConnection := Self.FConexaoPortal;
dm.qryAux.SQL.Clear;
dm.qryAux.SQL.Add('SELECT id_externo, categoria, tipo, cidade, endereco, titulo, descricao, cond_pag, area, area_c, quartos, suites, tipo_construcao, salas, ambientes, cozinhas, ');
dm.qryAux.SQL.Add('wc, lavabo, piscina, garagem, cod_usuario, valor, bairro FROM imoveis_xml A ');
dm.qryAux.SQL.Add('EXCEPT SELECT id_externo, categoria, tipo, cidade, endereco, titulo, descricao, cond_pag, area, area_c, quartos, suites, tipo_construcao, salas, ambientes, cozinhas, ');
dm.qryAux.SQL.Add('wc, lavabo, piscina, garagem, cod_usuario, valor, bairro FROM imoveis B ORDER BY id_externo');
dm.qryAux.Open;
// Abri o ClientDataSet
dm.cdsAux.Open;
if not dm.cdsAux.IsEmpty then
begin
dm.cdsAux.First;
dm.qryAux.Close;
while not dm.cdsAux.Eof and not ThreadImportacao.CheckTerminated do
begin
// Atualiza os registros no banco de dados
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('UPDATE imoveis SET categoria=:categoria, tipo=:tipo, cidade=:cidade, endereco=:endereco, titulo=:titulo, descricao=:descricao, cond_pag=:cond_pag, ');
oQry.SQL.Add('area=:area, area_c=:area_c, quartos=:quartos, suites=:suites, tipo_construcao=:tipo_construcao, salas=:salas, ambientes=:ambientes, cozinhas=:cozinhas, ');
oQry.SQL.Add('wc=:wc, lavabo=:lavabo, piscina=:piscina, garagem=:garagem, data=:data, cod_usuario=:cod_usuario, valor=:valor, bairro=:bairro ');
oQry.SQL.Add('WHERE id_externo = :id_externo');
oQry.ParamByName('categoria').AsString := dm.cdsAux.FieldByName('categoria').AsString;
oQry.ParamByName('tipo').AsString := dm.cdsAux.FieldByName('tipo').AsString;
oQry.ParamByName('cidade').AsString := dm.cdsAux.FieldByName('cidade').AsString;
oQry.ParamByName('endereco').AsString := dm.cdsAux.FieldByName('endereco').AsString;
oQry.ParamByName('titulo').AsString := dm.cdsAux.FieldByName('titulo').AsString;
oQry.ParamByName('descricao').AsString := dm.cdsAux.FieldByName('descricao').AsString;
oQry.ParamByName('cond_pag').AsString := dm.cdsAux.FieldByName('cond_pag').AsString;
oQry.ParamByName('area').AsString := dm.cdsAux.FieldByName('area').AsString;
oQry.ParamByName('area_c').AsString := dm.cdsAux.FieldByName('area_c').AsString;
oQry.ParamByName('quartos').AsString := dm.cdsAux.FieldByName('quartos').AsString;
oQry.ParamByName('suites').AsString := dm.cdsAux.FieldByName('suites').AsString;
oQry.ParamByName('tipo_construcao').AsString := dm.cdsAux.FieldByName('tipo_construcao').AsString;
oQry.ParamByName('salas').AsString := dm.cdsAux.FieldByName('salas').AsString;
oQry.ParamByName('ambientes').AsString := dm.cdsAux.FieldByName('ambientes').AsString;
oQry.ParamByName('cozinhas').AsString := dm.cdsAux.FieldByName('cozinhas').AsString;
oQry.ParamByName('wc').AsString := dm.cdsAux.FieldByName('wc').AsString;
oQry.ParamByName('lavabo').AsString := dm.cdsAux.FieldByName('lavabo').AsString;
oQry.ParamByName('piscina').AsString := dm.cdsAux.FieldByName('piscina').AsString;
oQry.ParamByName('garagem').AsString := dm.cdsAux.FieldByName('garagem').AsString;
oQry.ParamByName('data').AsString := FormatDateTime('dd/mm/yyyy', Date);
oQry.ParamByName('cod_usuario').AsString := IntToStr(FIdImobiliaria);
oQry.ParamByName('valor').AsFloat := StrToFloat(dm.cdsAux.FieldByName('valor').AsString);
oQry.ParamByName('bairro').AsString := dm.cdsAux.FieldByName('bairro').Text;
oQry.ParamByName('id_externo').AsInteger := StrToInt(dm.cdsAux.FieldByName('id_externo').AsString);
oQry.ExecSQL();
Inc(iContAtualizado);
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando atualização de imóveis - ' + IntToStr(iContAtualizado) + ' de ' + IntToStr(iContTotalItem) , '');
dm.cdsAux.Next;
end;
end;
dm.cdsAux.EmptyDataSet;
dm.cdsAux.Close;
//////////////////////////// FIM UPDATE ////////////////////////////////////////////////////////////////////////////////
//////////////////////////// INÍCIO DELETE ////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Comparando registro de imóveis para exclusão', '');
// Filtra todos os registros que não existem na tabela imóveis_xml
oQryTemp.Close;
oQryTemp.SQL.Clear;
oQryTemp.SQL.Add('SELECT id_externo, cod_usuario FROM imoveis a where a.cod_usuario = '+IntToStr(idImobiliaria)+' and (a.id_externo is not null OR a.id_externo <> '+QuotedStr('')+') ');
oQryTemp.SQL.Add('EXCEPT SELECT id_externo, cod_usuario FROM imoveis_xml b WHERE cod_usuario = '+IntToStr(idImobiliaria)+' ORDER BY id_externo');
oQryTemp.Open;
if not oQryTemp.IsEmpty then
begin
oQryTemp.First;
while not oQryTemp.Eof and not ThreadImportacao.CheckTerminated do
begin
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('DELETE FROM imoveis WHERE id_externo = :idTemp');
oQry.ParamByName('idTemp').AsInteger := oQryTemp.FieldByName('id_externo').AsInteger;
oQry.ExecSQL();
Inc(iContExcluido);
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando exclusão de imóveis - ' + IntToStr(iContExcluido) + ' de ' + IntToStr(iContTotalItem) , '');
oQryTemp.Next;
end;
end;
//////////////////////////// FIM DELETE ////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Limpando tabela temporária de imóveis', '');
// Limpa a tabela imoveis_xml
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('DELETE FROM imoveis_xml');
oQry.ExecSQL();
// Chama a procedure para ler e processar todas as imagens do XML
Self.ProcessaImagem();
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Atualizando id_externo das fotos', '');
// Atualiza o campo id_externo da tabela imoveis_foto
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('UPDATE imoveis_fotos SET id_imovel = i.id FROM imoveis_fotos f INNER JOIN imoveis i ON f.id_externo = i.id_externo');
oQry.ExecSQL();
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'F', 'Finalizado com Sucesso', sNomeXml);
// Fecha Conexão com banco de dados do portal
Self.FConexaoPortal.Close;
except
on E:Exception do
begin
MessageDlg('Erro ao importa XML padrão dogus: '#13 + 'Mensagem: ' + E.Message, mtError, [mbOK], 0);
self.AtualizaInfoTarefa(idImobiliaria, Self.CalculaDuracao(tTimeInicial, Now), 'C', 'Erro: ' + E.Message, sNomeXml);
Self.FConexaoPortal.Close;
end;
end;
finally
FreeAndNil(Self.FConexaoPortal);
FreeAndNil(oQry);
FreeAndNil(oQryTemp);
end;
end;
end;
// Método constutor da Classe
constructor TImportacao.Create(idAgendamento,idImobiliaria, idBancoDados: integer; var ConexaoAux: TSQLConnection);
begin
Self.FIdAgendameto := idAgendamento;
Self.FIdImobiliaria := idImobiliaria;
Self.FIdBancoDados := idBancoDados;
Self.setConexaoAux(ConexaoAux);
Self.ImportaXML(FIdImobiliaria);
end;
// Procedure para finalizar a tarefa inserindo os dados necessários na TAB_TAREFA
function TImportacao.AcertoAcento(texto: string): string;
begin
{def map = ["á":"á","Ã":"Á","â":"â","Ã":"Â","à ":"à","Ã":"À",
"ã":"ã","Ã":"Ã","ç":"ç","Ã":"Ç","é":"é","Ã":"É",
"ê":"ê","Ã":"Ê","Ã":"í","Ã":"Í","ó":"ó","Ã":"Ó",
"ô":"ô","Ã":"Ô","õ":"õ","Ã":"Õ","ú":"ú","Ã":"ÚA;" ]}
texto := StringReplace(texto, 'á', 'á', [rfReplaceAll]);
texto := StringReplace(texto, 'â', 'â', [rfReplaceAll]);
texto := StringReplace(texto, 'Ã ', 'à', [rfReplaceAll]);
texto := StringReplace(texto, 'ã', 'ã', [rfReplaceAll]);
texto := StringReplace(texto, 'é', 'é', [rfReplaceAll]);
texto := StringReplace(texto, 'ê', 'ê', [rfReplaceAll]);
texto := StringReplace(texto, 'Ã', 'í', [rfReplaceAll]);
texto := StringReplace(texto, 'ô', 'ô', [rfReplaceAll]);
texto := StringReplace(texto, 'õ', 'õ', [rfReplaceAll]);
texto := StringReplace(texto, 'ó', 'ó', [rfReplaceAll]);
texto := StringReplace(texto, 'ú', 'ú', [rfReplaceAll]);
texto := StringReplace(texto, 'ç', 'ç', [rfReplaceAll]);
texto := StringReplace(texto, 'Ã', 'Ç', [rfReplaceAll]);
Result := texto;
end;
procedure TImportacao.AtualizaInfoTarefa(idAgendamento: integer; duracao, status, msg, nameXml: string);
var
oQry: TSQLQuery;
sSqlFull, sSqlMin : string;
begin
try
sSqlFull := 'UPDATE TAB_TAREFA SET statusAtual = :status, qtdeRegistroI = :qRegistroI, qtdeImagem = :qImagem, qtdeErroImagem = :qErroImagem, duracao = :duracao, msg = :msg, xmlTotalImovel = :qTotalImovel, ';
sSqlFull := sSqlFull + 'xmlTotalFoto = :qTotalFoto, qtdeRegistroA = :qRegistroA, qtdeRegistroE = :qRegistroE ';
sSqlMin := 'UPDATE TAB_TAREFA SET xmlTotalImovel = :qTotalImovel, xmlTotalFoto = :qTotalFoto ';
try
oQry := TSQLQuery.Create(nil);
oQry.SQLConnection := Self.getConexaoAux();
oQry.Close;
oQry.SQL.Clear;
if status = EmptyStr then
oQry.SQL.Add(sSqlMin)
else
oQry.SQL.Add(sSqlFull);
oQry.SQL.Add('WHERE idAgendamento = :id AND statusAtual = :statusAtual AND dataCadastro = :data');
if status = EmptyStr then
begin
oQry.ParamByName('qTotalImovel').AsInteger := iContTotalItem;
oQry.ParamByName('qTotalFoto').AsInteger := iContTotalFoto;
end
else
begin
oQry.ParamByName('status').AsString := status;
oQry.ParamByName('qRegistroI').AsInteger := iContInserido;
oQry.ParamByName('qRegistroA').AsInteger := iContAtualizado;
oQry.ParamByName('qRegistroE').AsInteger := iContExcluido;
oQry.ParamByName('qImagem').AsInteger := iContFoto;
oQry.ParamByName('qErroImagem').AsInteger := iContErroFoto;
oQry.ParamByName('duracao').AsString := duracao;
oQry.ParamByName('msg').AsString := msg;
oQry.ParamByName('qTotalImovel').AsInteger := iContTotalItem;
oQry.ParamByName('qTotalFoto').AsInteger := iContTotalFoto;
end;
oQry.ParamByName('id').AsInteger := idAgendamento;
oQry.ParamByName('statusAtual').AsString := 'E';
oQry.ParamByName('data').AsDateTime := Date;
oQry.ExecSQL();
DeleteFile(FPathXml + nameXml);
except
on E:Exception do
MessageDlg('Erro ao atualizar status da tarefa: ' + E.Message, mtError, [mbOK], 0);
end;
finally
FreeAndNil(oQry);
end;
end;
function TImportacao.getConexaoAux: TSQLConnection;
begin
if not FConexaoAux.Connected then
begin
FConexaoAux.Open;
Sleep(2000);
end;
Result := FConexaoAux;
end;
procedure TImportacao.setConexaoAux(const Value: TSQLConnection);
begin
if Assigned(Value) then
FConexaoAux := Value;
end;
function TImportacao.Ternario(Condicao, Retorno1, Retorno2: string): string;
begin
if Retorno1 <> Condicao then
Result := Retorno1
else
Result := Retorno2;
end;
// Função que cálcula e retorna o tempo de duração da importação
function TImportacao.CalculaDuracao(timeInicial, timeFinal: TDateTime): string;
var
iDiff, iHora, iMinuto, iSegundo: Integer;
begin
iHora := 0;
iMinuto := 0;
iSegundo := 0;
iDiff := 0;
iDiff := SecondsBetween(timeFinal, timeInicial);
iMinuto := Trunc(iDiff /60);
iSegundo := iDiff mod 60;
while iMinuto > 60 do
begin
iMinuto := iMinuto - 60;
Inc(iHora);
end;
Result := FormatFloat('00', iHora)+ ':' + FormatFloat('00', iMinuto) + ':' + FormatFloat('00', iSegundo);
end;
// Função para baixar o arqivo XML do cliente
procedure TImportacao.DownloadXML(url, pathXml, nameFile: string);
var
oMs: TMemoryStream;
oHTTP: TIdHTTP;
begin
oMs := TMemoryStream.Create;
oHTTP := TIdHTTP.Create(nil);
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Baixando arquivo XML', '');
try
try
oMs.Clear;
try
url := StringReplace(url, ' ', '%20',[rfReplaceAll]);
oHTTP.Get(url, oMs);
except
on E: EIdHTTPProtocolException do
end;
oMs.Position := 0;
if not DirectoryExists(pathXml) then
ForceDirectories(pathXml);
oMs.SaveToFile(pathXml + nameFile);
Except
on E:Exception do
MessageDlg('Erro ao baixar XML: ' + E.Message, mtError, [mbOK], 0);
end;
finally
FreeAndNil(oMs);
FreeAndNil(oHTTP);
end;
end;
// Método para carregar os dados de conexão com o banco de dados do portal
procedure TImportacao.LoadConfig;
var
oQry: TSQLQuery;
begin
try
oQry := TSQLQuery.Create(nil);
oQry.SQLConnection := Self.getConexaoAux;
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('SELECT id, idImobiliaria, idUsuario, descricaoBancoDados, urlXml, pathXml, pathImagem, marcaAgua, pathMarcaAgua FROM TAB_IMOBILIARIA WHERE idImobiliaria = :id AND registro = :registro');
oQry.ParamByName('id').AsInteger := Self.FIdImobiliaria;
oQry.ParamByName('registro').AsString := 'A';
oQry.Open;
if not oQry.IsEmpty then
begin
FPortal := oQry.FieldByName('descricaoBancoDados').AsString;
FUrlXml := oQry.FieldByName('urlXml').AsString;
FPathXml := oQry.FieldByName('pathXml').AsString;
FPathImagem := oQry.FieldByName('pathImagem').AsString;
FPathMarcaAgua := oQry.FieldByName('pathMarcaAgua').AsString;
FNomeMarcaAgua := oQry.FieldByName('marcaAgua').AsString;
end;
finally
Self.ConexaoAux.Close;
FreeAndNil(oQry);
end;
end;
procedure TImportacao.ProcessaImagem();
var
oMs: TMemoryStream;
oHTTP: TIdHTTP;
oNodePai, oNodeItem, oNodeFotos, oNodeFoto: IXMLNode;
oXMLDoc: TXMLDocument;
sNameImagem, url, sTempName: string;
oQryTemp, oQry: TSQLQuery;
idExterno, iContIdFoto, iTempTotal, iContFotoExcluida: Integer;
oFactoryImg: TFactoryImagem;
begin
oMs := TMemoryStream.Create;
oHTTP := TIdHTTP.Create(nil);
try
// Processa as imagens do XML
try
// Chama a função para executar a conexão com o respectivo portal onde serão gravados os dados
Self.ConectarPortal;
oQryTemp := TSQLQuery.Create(nil);
oQryTemp.SQLConnection := Self.FConexaoPortal;
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Comparando registros de imagens para inclusão', '');
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// INÍCIO INSERT ////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Filtra todos os registros que não existem na tabela imoveis_fotos
dm.qryAux.Close;
dm.qryAux.SQLConnection := Self.FConexaoPortal;
dm.qryAux.SQL.Clear;
dm.qryAux.SQL.Add('SELECT id_externo, url_foto FROM imoveis_fotos_xml a where cod_imobiliaria = :idTemp ');
dm.qryAux.SQL.Add('EXCEPT SELECT id_externo, url_foto FROM imoveis_fotos b WHERE cod_imobiliaria = :idFixo ORDER BY id_externo');
dm.qryAux.ParamByName('idTemp').AsInteger := FIdImobiliaria;
dm.qryAux.ParamByName('idFixo').AsInteger := FIdImobiliaria;
dm.qryAux.Open;
dm.cdsAux.Open;
oQry := TSQLQuery.Create(nil);
oQry.SQLConnection := Self.FConexaoPortal;
if dm.cdsAux.RecordCount > 0 then
begin
// Atualiza o contador com total de fotos depois da comparação EXCEPT
iTempTotal := dm.cdsAux.RecordCount;
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusão de novas imagens', '');
Self.FQryInsertImg := TSQLQuery.Create(nil);
Self.FQryInsertImg.SQLConnection := FConexaoPortal;
// Instância o objeto para processar as imagens
oFactoryImg := TFactoryImagem.Create(FQryInsertImg, FIdImobiliaria);
oFactoryImg.MaxWdth := frmMonitoramento.FLAG_MAX_WIDTH;
oFactoryImg.Qualidade := frmMonitoramento.FLAG_QUALITY_SM;
oFactoryImg.MarcaAgua := FPathMarcaAgua + FNomeMarcaAgua;
iContIdFoto := 1;
iContErroFoto := 0;
dm.cdsAux.First;
while not dm.cdsAux.Eof and not ThreadImportacao.CheckTerminated do
begin
idExterno := dm.cdsAux.FieldByName('id_externo').AsInteger;
oMs.Clear;
try
url := Trim(StringReplace(dm.cdsAux.FieldByName('url_foto').AsString, ' ', '%20',[rfReplaceAll]));
oHTTP.Get(url, oMs);
except
on E:Exception do
begin
GravarLog('Erro: ' + E.Message + #13#10'Data/Hora: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' - URL: ' + url, FPathImagem);
Inc(iContErroFoto);
end;
end;
oMs.Position := 0;
// Verifica se a pasta para gravar as imagens não existe, se verdadeiro cria a pasta
if not DirectoryExists(FPathImagem) then
ForceDirectories(FPathImagem);
// Verifica se o MemoryStream possui conteúdo maior ou igual a 1Kb, devido ao retorno de imagens com link quebrado
if oMs.Size >= 1024 then
begin
sTempName := 'temp_' + IntToStr(Random(99999)) + '_' + FormatDateTime('yyyymmddhhmmss', Now) + '_' + IntToStr(iContIdFoto);
sNameImagem := IntToStr(Random(99999)) + '_' + FormatDateTime('yyyymmddhhmmss', Now) + '_' + IntToStr(iContIdFoto);
if oFactoryImg.TrataDownload(oMs, FPathImagem + sTempName, FPathImagem + sTempName + '.jpg') then
begin
// Redimensiona e grava novamente as imagens no diretório atual
oFactoryImg.ResizeImage(FPathImagem + sTempName + '.jpg', 'small_' + sNameImagem + '.jpg', url, 153, 115, idExterno, iContFoto);
oFactoryImg.ResizeImage(FPathImagem + sTempName + '.jpg', 'mobile_' + sNameImagem + '.jpg', url, 310, 180, idExterno, iContFoto);
oFactoryImg.ResizeImage(FPathImagem + sTempName + '.jpg', sNameImagem + '.jpg', url, 0, 0, idExterno, iContFoto);
DeleteFile(FPathImagem + sTempName + '.jpg');
// Inseri os dados para atualização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando inclusão de novas imagens - ' + IntToStr(iContFoto) + ' de ' + IntToStr((iTempTotal * 3) - (iContErroFoto * 3)) , '');
Inc(iContIdFoto);
end;
end
else
begin
GravarLog('Erro: MemoryStream menor que 1024 Bytes (' + IntToStr(oMs.Size) + ')' + #13#10'Data/Hora: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' - URL: ' + url, FPathImagem);
Inc(iContErroFoto);
end;
dm.cdsAux.Next;
end;
end;
dm.cdsAux.EmptyDataSet;
dm.cdsAux.Close;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// FIM INSERT ///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// INÍCIO DELETE ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Comparando registros de imagens para exclusão', '');
// Filtra todos os registros que não existem na tabela imóveis_fotos_xml
oQryTemp.Close;
oQryTemp.SQL.Clear;
oQryTemp.SQL.Add('SELECT url_foto, id_externo FROM imoveis_fotos a where a.cod_imobiliaria = '+IntToStr(FIdImobiliaria)+' and (a.id_externo is not null OR a.id_externo <> '+QuotedStr('')+') ');
oQryTemp.SQL.Add('EXCEPT SELECT url_foto, id_externo FROM imoveis_fotos_xml b WHERE cod_imobiliaria = '+IntToStr(FIdImobiliaria)+' ORDER BY id_externo');
oQryTemp.Open;
if not oQryTemp.IsEmpty then
begin
iContFotoExcluida := 0;
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Executando exclusão de imagens', '');
oQryTemp.First;
while not oQryTemp.Eof and not ThreadImportacao.CheckTerminated do
begin
dm.qryAux.Close;
dm.qryAux.SQLConnection := Self.FConexaoPortal;
dm.qryAux.SQL.Clear;
dm.qryAux.SQL.Add('SELECT id, foto FROM imoveis_fotos WHERE url_foto = :url');
dm.qryAux.ParamByName('url').AsString := oQryTemp.FieldByName('url_foto').AsString;
dm.qryAux.Open;
if not dm.qryAux.IsEmpty then
begin
DeleteFile(FPathImagem + dm.qryAux.FieldByName('foto').AsString);
DeleteFile(FPathImagem + 'small_' + dm.qryAux.FieldByName('foto').AsString);
DeleteFile(FPathImagem + 'mobile_' + dm.qryAux.FieldByName('foto').AsString);
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('DELETE FROM imoveis_fotos WHERE id = :id');
oQry.ParamByName('id').AsInteger := dm.qryAux.FieldByName('id').AsInteger;
oQry.ExecSQL();
Inc(iContFotoExcluida);
end;
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Imagens excluídas ('+IntToStr(iContFotoExcluida)+')', '');
oQryTemp.Next;
end;
Self.FConexaoPortal.Close;
end;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// FIM DELETE /////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inseri os dados para finalização da tarefa
self.AtualizaInfoTarefa(FIdAgendameto, Self.CalculaDuracao(tTimeInicial, Now), 'E', 'Limpando tabela temporária de imagens', '');
// Limpa a tabela imoveis_xml
oQry.Close;
oQry.SQL.Clear;
oQry.SQL.Add('DELETE FROM imoveis_fotos_xml');
oQry.ExecSQL();
Application.ProcessMessages;
except
on E:Exception do
begin
MessageDlg('Erro ao processar imagens: ' + E.Message, mtError, [mbOK], 0);
self.AtualizaInfoTarefa(FIdImobiliaria, Self.CalculaDuracao(tTimeInicial, Now), 'C', 'Erro: ' + E.Message, '');
end;
end;
finally
FreeAndNil(oXMLDoc);
FreeAndNil(oMs);
FreeAndNil(oHTTP);
FreeAndNil(oQry);
FreeAndNil(oQryTemp);
end;
end;
end.
|
namespace RemObjects.Elements.System;
uses
Foundation;
operator Add(aLeft, aRight: NSDecimalNumber): NSDecimalNumber; public;
begin
exit aLeft.decimalNumberByAdding(aRight);
end;
operator Subtract(aLeft, aRight: NSDecimalNumber): NSDecimalNumber; public;
begin
exit aLeft.decimalNumberBySubtracting(aRight);
end;
operator Multiply(aLeft, aRight: NSDecimalNumber): NSDecimalNumber; public;
begin
exit aLeft.decimalNumberByMultiplyingBy(aRight);
end;
operator Divide(aLeft, aRight: NSDecimalNumber): NSDecimalNumber; public;
begin
exit aLeft.decimalNumberByDividingBy(aRight);
end;
operator Pow(a, b: Double): Double; public;
begin
exit rtl.pow(a,b);
end;
operator Pow(a, b: Int64): Int64; public;
begin
result := 1;
if b < 0 then exit 0;
while b <> 0 do begin
if (b and 1) <> 0 then result := result * a;
a := a * a;
b := b shr 1;
end;
end;
operator Pow(a, b: Integer): Integer; public;
begin
result := 1;
if b < 0 then exit 0;
while b <> 0 do begin
if (b and 1) <> 0 then result := result * a;
a := a * a;
b := b shr 1;
end;
end;
end. |
(**
This module contains code for tokenizing object pascal code.
@Author David Hoyle
@Version 1.0
@Date 05 Jan 2018
**)
Unit ITHelper.PascalParsing;
Interface
{$INCLUDE 'CompilerDefinitions.inc'}
Uses
Classes;
Function Tokenize(Const strText: String): TStringList;
Implementation
Uses
SysUtils,
StrUtils;
(**
This function returns a string list contains the tokenized representation of the passed string with
respect to some basic object pascal grammer.
@precon strText si the line of text to be tokenised
@postcon Returns a new string list of the tokenized string
@note The string list returned must be destroyed be the calling method.
@param strText as a String as a constant
@return a TStringList
**)
Function Tokenize(Const strText: String): TStringList;
Type
TBADITokenType = (ttUnknown, ttWhiteSpace, ttNumber, ttIdentifier, ttLineEnd,
ttStringLiteral, ttSymbol);
(** State machine for block types. **)
TBlockType = (btNoBlock, btStringLiteral);
Const
(** Growth size of the token buffer. **)
iTokenCapacity = 25;
Var
(** Token buffer. **)
strToken: String;
CurToken: TBADITokenType;
LastToken: TBADITokenType;
BlockType: TBlockType;
(** Token size **)
iTokenLen: Integer;
i: Integer;
Begin
Result := TStringList.Create;
BlockType := btNoBlock;
strToken := '';
CurToken := ttUnknown;
strToken := '';
iTokenLen := 0;
SetLength(strToken, iTokenCapacity);
For i := 1 To Length(strText) Do
Begin
LastToken := CurToken;
{$IFNDEF D2009}
If strText[i] In [#32, #9] Then
{$ELSE}
If CharInSet(strText[i], [#32, #9]) Then
{$ENDIF}
CurToken := ttWhiteSpace
{$IFNDEF D2009}
Else If strText[i] In ['#', '_', 'a' .. 'z', 'A' .. 'Z', '.', '*'] Then
{$ELSE}
Else If CharInSet(strText[i], ['#', '_', 'a' .. 'z', 'A' .. 'Z', '.', '*']) Then
{$ENDIF}
Begin
{$IFNDEF D2009}
If (LastToken = ttNumber) And (strText[i] In ['A' .. 'F', 'a' .. 'f']) Then
{$ELSE}
If (LastToken = ttNumber) And
(CharInSet(strText[i], ['A' .. 'F', 'a' .. 'f'])) Then
{$ENDIF}
CurToken := ttNumber
Else
CurToken := ttIdentifier;
End
{$IFNDEF D2009}
Else If strText[i] In ['$', '0' .. '9'] Then
{$ELSE}
Else If CharInSet(strText[i], ['$', '0' .. '9']) Then
{$ENDIF}
Begin
CurToken := ttNumber;
If LastToken = ttIdentifier Then
CurToken := ttIdentifier;
End
{$IFNDEF D2009}
Else If strText[i] In [#10, #13] Then
{$ELSE}
Else If CharInSet(strText[i], [#10, #13]) Then
{$ENDIF}
CurToken := ttLineEnd
{$IFNDEF D2009}
Else If strText[i] In ['''', '"'] Then
{$ELSE}
Else If CharInSet(strText[i], ['''', '"']) Then
{$ENDIF}
CurToken := ttStringLiteral
{$IFNDEF D2009}
Else If strText[i] In [#0 .. #255] - ['#', '_', 'a' .. 'z', 'A' .. 'Z', '$',
'0' .. '9'] Then
{$ELSE}
Else If CharInSet(strText[i], [#0 .. #255] - ['#', '_', 'a' .. 'z', 'A' .. 'Z', '$',
'0' .. '9']) Then
{$ENDIF}
CurToken := ttSymbol
Else
CurToken := ttUnknown;
If (LastToken <> CurToken) Or (CurToken = ttSymbol) Then
Begin
If ((BlockType In [btStringLiteral]) And (CurToken <> ttLineEnd)) Then
Begin
Inc(iTokenLen);
If iTokenLen > Length(strToken) Then
SetLength(strToken, iTokenCapacity + Length(strToken));
strToken[iTokenLen] := strText[i];
End
Else
Begin
SetLength(strToken, iTokenLen);
If iTokenLen > 0 Then
If Not(LastToken In [ttLineEnd, ttWhiteSpace]) Then
Result.AddObject(strToken, TObject(LastToken));
BlockType := btNoBlock;
iTokenLen := 1;
SetLength(strToken, iTokenCapacity);
strToken[iTokenLen] := strText[i];
End;
End
Else
Begin
Inc(iTokenLen);
If iTokenLen > Length(strToken) Then
SetLength(strToken, iTokenCapacity + Length(strToken));
strToken[iTokenLen] := strText[i];
End;
// Check for string literals
If CurToken = ttStringLiteral Then
If BlockType = btStringLiteral Then
BlockType := btNoBlock
Else If BlockType = btNoBlock Then
BlockType := btStringLiteral;
End;
If iTokenLen > 0 Then
Begin
SetLength(strToken, iTokenLen);
If Not(CurToken In [ttLineEnd, ttWhiteSpace]) Then
Result.AddObject(strToken, TObject(CurToken));
End;
End;
End.
|
unit uBaseFrame;
interface
uses
System.Classes, System.SysUtils, FMX.Types,
UI.Base, UI.Frame;
type
TFrameView = class;
TBaseFrameEvent = reference to procedure (View: TFrameView);
TFrameViewClass = class of TFrameView;
TFrameView = class(UI.Frame.TFrameView)
protected
procedure DoShow; override;
procedure DoReStart; override;
procedure DoFinish; override;
function DoCanFinish(): Boolean; override;
function DoCanFree(): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Finish(Ani: TFrameAniType); override;
class function ShowMainFrame(const Title: string = ''; Ani: TFrameAniType = TFrameAniType.None;
SwitchFlag: Boolean = False): TFrameView;
class function ShowWithInit(AOnInit: TBaseFrameEvent; const Title: string = ''; Ani: TFrameAniType = TFrameAniType.None;
SwitchFlag: Boolean = False): TFrameView;
function StartFrame(FrameClass: TFrameViewClass; Ani: TFrameAniType = TFrameAniType.DefaultAni): TFrameView; overload;
function StartFrame(FrameClass: TFrameViewClass; const Title: string; Ani: TFrameAniType = TFrameAniType.DefaultAni): TFrameView; overload;
end;
TFrame = class(TFrameView);
TFrameClass = type of TFrame;
implementation
uses
FMX.Forms,
UI.Dialog;
{ TFrameView }
constructor TFrameView.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TFrameView.Destroy;
begin
inherited;
end;
function TFrameView.DoCanFinish: Boolean;
begin
Result := inherited;
end;
function TFrameView.DoCanFree: Boolean;
begin
Result := inherited;
end;
procedure TFrameView.DoFinish;
begin
inherited;
end;
procedure TFrameView.DoReStart;
begin
inherited;
end;
procedure TFrameView.DoShow;
begin
inherited;
end;
procedure TFrameView.Finish(Ani: TFrameAniType);
begin
inherited Finish(Ani);
end;
class function TFrameView.ShowWithInit(AOnInit: TBaseFrameEvent;
const Title: string; Ani: TFrameAniType; SwitchFlag: Boolean): TFrameView;
begin
Result := CreateFrame(Application.MainForm, Title) as TFrameView;
if Result <> nil then begin
Result.Show(Ani, nil, SwitchFlag);
if Assigned(AOnInit) then begin
Result.Hint('Callback from ShowWithInit');
AOnInit(Result);
end;
end;
end;
class function TFrameView.ShowMainFrame(const Title: string;
Ani: TFrameAniType; SwitchFlag: Boolean): TFrameView;
begin
Result := CreateFrame(Application.MainForm, Title) as TFrameView;
if Result <> nil then begin
Result.Show(Ani, nil, SwitchFlag);
end;
end;
function TFrameView.StartFrame(FrameClass: TFrameViewClass; const Title: string;
Ani: TFrameAniType): TFrameView;
begin
Result := MakeFrame(FrameClass) as TFrameView;
if Assigned(Result) then begin
Result.Title := Title;
Hide(Ani);
Result.Show(Ani, nil);
end;
end;
function TFrameView.StartFrame(FrameClass: TFrameViewClass; Ani: TFrameAniType): TFrameView;
begin
Result := MakeFrame(FrameClass) as TFrameView;
if Assigned(Result) then begin
Hide(Ani);
Result.Show(Ani, nil);
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConfig.NameValueFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, System.StrUtils,
FMX.DialogService,
RSConfig.ConfigDM;
type
TNameValueFrame = class(TFrame)
Layout: TLayout;
ValueEdit: TEdit;
ConfigButton: TButton;
CheckBox: TCheckBox;
NameEdit: TEdit;
LeftLayout: TLayout;
procedure ConfigButtonClick(Sender: TObject);
private
{ Private declarations }
FCallback: TNotifyEvent;
public
{ Public declarations }
procedure SetCallback(ACallback: TNotifyEvent);
end;
implementation
{$R *.fmx}
procedure TNameValueFrame.ConfigButtonClick(Sender: TObject);
begin
FCallback(Self);
end;
procedure TNameValueFrame.SetCallback(ACallback: TNotifyEvent);
begin
FCallback := ACallback;
end;
end.
|
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* *)
(* REVMEM.PAS - The Relativity E-Mag (coded in Turbo Pascal 7.0) *)
(* *)
(* "The Relativity E-Mag" was originally written by En|{rypt, |MuadDib|, *)
(* and IllumiTIE (for assembly routines). This source may not be copied, *)
(* distributed or modified in any shape or form. Some of the code has been *)
(* derived from various sources and units to help us produce a better *)
(* quality electronic magazine to let the scene know we're boss. *)
(* *)
(* Program Notes : This program presents "The Relativity E-Mag" *)
(* *)
(* ASM/TP70 Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx *)
(* ------------------------------------------------------------------------ *)
(* TP70 Coder : xxxxx xxxxxxxxx (|MuadDib|) - xxxxxx@xxxxxxxxxx.xxx *)
(* ------------------------------------------------------------------------ *)
(* MEMORY UNIT USED WITH REV97.PAS AND ABOVE. CODED IN TURBO PASCAL 7.0. *)
(****************************************************************************)
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Compiler Directives - These Directives Are Not Meant To Be Modified. *)
(****************************************************************************)
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Library Divides The Main Program Into Related Modules. *)
(****************************************************************************)
unit RevMem;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - What Is Visible And Accessible To Any Program Or Unit. *)
(****************************************************************************)
interface
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Each Identifier Names A Unit Used By This Single Unit. *)
(****************************************************************************)
uses Dos;
function GetMainMemory : Longint;
procedure CheckMainMemory;
procedure CheckXMSMemory(var installed : boolean);
procedure CheckEMSMemory(var installed : boolean);
procedure CheckXMSEMSMemory;
procedure Extend_Heap;
procedure ShrinkHeapMemory;
procedure ExpandHeapMemory;
procedure FlushDiskCaches;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Procedures And Functions Declared In The Interface. *)
(****************************************************************************)
implementation
const
Max_Blocks = 4;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Specifies An Identifier That Denotes A Type. (values) *)
(****************************************************************************)
TYPE
PFreeRec = ^TFreeRec;
TFreeRec = record
Next : PFreeRec;
Size : Pointer;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Associates And Stores An Identifier And Type In Memory. *)
(****************************************************************************)
var
XMS_Driver : Pointer;
Num_Blocks : Word;
Block_Address,
Block_Size : Array[1..Max_Blocks+1] of Pointer;
SaveExitProc : Pointer;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Specifies An Identifier That Denotes A Type. (values) *)
(****************************************************************************)
TYPE
MCBrec = record
location : Char;
ProcessID : WORD;
allocation : WORD;
reserved : array[1..11] of BYTE;
end;
PSPrec = record
int20h,
EndofMem : WORD;
Reserved1 : BYTE;
Dosdispatcher : array[1..5] of BYTE;
Int22h : Pointer;
Int23h : Pointer;
INT24h : Pointer;
ParentPSP : WORD;
HandleTable : array[1..20] of BYTE;
EnvSeg : WORD;
Reserved2 : Longint;
HandleTableSize : WORD;
HandleTableAddr : Pointer;
Reserved3 : array[1..23] of BYTE;
Int21 : WORD;
RetFar : BYTE;
Reserved4 : array[1..9] of BYTE;
DefFCB1 : array[1..36] of BYTE;
DefFCB2 : array[1..20] of BYTE;
Cmdlength : BYTE;
Cmdline : array[1..127] of BYTE;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Associates And Stores An Identifier And Type In Memory. *)
(****************************************************************************)
var
pmcb : ^MCBrec;
emcb : ^MCBrec;
psp : ^PSPrec;
dmem : Longint;
HaveXms,HaveEms : Boolean;
Reg : Registers;
UMB_Heap_Debug : Boolean;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Checks If XMS Is Installed, Allocates Memory To Heap. *)
(****************************************************************************)
procedure Pointer_Swap(var A,B : Pointer);
var
Temp : Pointer;
begin
Temp := A;
A := B;
B := Temp;
end;
function XMS_Driver_Present : Boolean;
var
Result : Boolean;
begin
Result := False;
asm
@Begin:
mov ax,4300h
int 2Fh
cmp al,80h
jne @Fail
mov ax,4310h
int 2Fh
mov word ptr XMS_Driver+2,es
mov word ptr XMS_Driver,bx
mov Result,1
jmp @End
@Fail:
mov Result,0
@End:
end;
XMS_Driver_Present := Result;
end;
procedure Allocate_UMB_Heap;
var
i,j : Word;
UMB_Strategy,
DOS_Strategy,
Segment,Size : Word;
Get_Direct : Boolean;
begin
Num_Blocks := 0;
for i := 1 to Max_Blocks do
begin
Block_Address[i] := nil;
Block_Size[i] := nil;
end;
asm
mov ax,5800h
int 21h
mov [DOS_Strategy],ax
mov ax,5802h
int 21h
mov [UMB_Strategy],ax
mov ax,5801h
mov bx,0000h
int 21h
mov ax,5803h
mov bx,0001h
int 21h
end;
Get_Direct := True;
for i := 1 to Max_Blocks do
begin
Segment := 0;
Size := 0;
if Get_Direct then
begin
asm
@Begin:
mov ax,01000h
mov dx,0FFFFh
push ds
mov cx,ds
mov es,cx
call es:[XMS_Driver]
cmp dx,100h
jl @End
mov ax,01000h
call es:[XMS_Driver]
cmp ax,1
jne @End
cmp bx,0A000h
jl @End
mov [Segment],bx
mov [Size],dx
@End:
pop ds
end;
if ((i = 1) and (Size = 0)) then
Get_Direct := False;
end;
if (not Get_Direct) then
begin
asm
@Begin:
mov ax,4800h
mov bx,0FFFFh
int 21h
cmp bx,100h
jl @End
mov ax,4800h
int 21h
jc @End
cmp ax,0A000h
jl @End
mov [Segment],ax
mov [Size],bx
@End:
end;
end;
if (Segment > 0) then
begin
Block_Address[i] := Ptr(Segment,0);
Inc(Num_Blocks);
end;
Block_Size[i] := Ptr(Size,0);
end;
if (Num_Blocks > 0) then
begin
for i := 1 to Num_Blocks-1 do
for j := i+1 to Num_Blocks do
if (Seg(Block_Address[i]^) > Seg(Block_Address[j]^)) then
begin
Pointer_Swap(Block_Address[i],Block_Address[j]);
Pointer_Swap(Block_Size[i],Block_Size[j]);
end;
end;
asm
mov ax,5803h
mov bx,[UMB_Strategy]
int 21h
mov ax,5801h
mov bx,[DOS_Strategy]
int 21h
end;
end;
procedure Release_UMB; far;
var
i : Word;
Segment : Word;
begin
ExitProc := SaveExitProc;
if (Num_Blocks > 0) then
begin
asm
mov ax,5803h
mov bx,0000h
int 21h
end;
for i := 1 to Num_Blocks do
begin
Segment := Seg(Block_Address[i]^);
if (Segment > 0) then
asm
mov ax,$4901
mov bx,[Segment]
mov es,bx
int 21h
end;
end;
end;
end;
procedure Extend_Heap;
var
i : Word;
Temp : PFreeRec;
begin
if XMS_Driver_Present then
begin
Allocate_UMB_Heap;
if UMB_Heap_Debug then
Release_UMB;
if (Num_Blocks > 0) then
begin
for i := 1 to Num_Blocks do
PFreeRec(Block_Address[i])^.Size := Block_Size[i];
for i := 1 to Num_Blocks do
PFreeRec(Block_Address[i])^.Next := Block_Address[i+1];
PFreeRec(Block_Address[Num_Blocks])^.Next := nil;
if (FreeList = HeapPtr) then
with PFreeRec(FreeList)^ do
begin
Next := Block_Address[1];
Size := Ptr(Seg(HeapEnd^)-Seg(HeapPtr^),0);
end
else
with PFreeRec(HeapPtr)^ do
begin
Next := Block_Address[1];
Size := Ptr(Seg(HeapEnd^)-Seg(HeapPtr^),0);
end;
HeapPtr := Block_Address[Num_Blocks];
HeapEnd := Ptr(Seg(Block_Address[Num_Blocks]^)+Seg(Block_Size[Num_Blocks]^),0);
end;
end;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Detects The Amount Of Main Memory Available. (640K) *)
(****************************************************************************)
function GetMainMemory : Longint;
begin
psp:=PTR(PrefixSeg,0);
pmcb:=Ptr(PrefixSeg-1,0);
emcb:=Ptr(psp^.envseg-1,0);
GetMainMemory:=Longint(pmcb^.allocation+emcb^.allocation+1)*16;
end;
procedure CheckMainMemory;
begin
Writeln('Memory Used: ',GetMainMemory,' bytes');
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Detects If Expanded And Extended Memory Are Available. *)
(****************************************************************************)
procedure CheckXMSMemory(var installed : boolean);
begin
reg.ax := $4300;
intr($2F, reg);
installed := reg.al = $80;
end;
procedure CheckEMSMemory(var installed : boolean);
begin
reg.ah := $46;
intr($67, reg);
installed := reg.ah = $00;
end;
procedure CheckXMSEMSMemory;
begin
CheckXMSMemory(HaveXms);
CheckEMSMemory(HaveEms);
writeln('XMS: ',HaveXms,' EMS: ',HaveEms,'');
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Gives A Larger Heap Size Temporarily Until heap_expand. *)
(****************************************************************************)
procedure ShrinkHeapMemory;
begin
reg.bx := memw[seg(heapptr) : ofs(heapptr) + 2] - prefixseg;
reg.es := prefixseg;
reg.ah := $4a;
msdos(reg);
end;
procedure ExpandHeapMemory;
begin
reg.bx := memw[seg(heapend) : ofs(heapend) + 2] - prefixseg;
reg.es := prefixseg;
reg.ah := $4a;
msdos(reg);
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Flushes Disk Caches SmartDrive 4.00+ and PC-Cache 8.0+. *)
(****************************************************************************)
procedure FlushDiskCaches;
begin
Reg.AX:=$4A10;
Reg.BX:=$0001;
Intr($2F,Reg);
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
(****************************************************************************)
(* Reserved Words - Statements To Be Executed When The Unit Is Loaded. *)
(****************************************************************************)
end.
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
Attachment Converted: "c:\eudora\attach\rev.dat"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.