text stringlengths 14 6.51M |
|---|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.10 2004.10.29 8:49:00 PM czhower
Fixed a constructor.
Rev 1.9 2004.10.27 9:20:04 AM czhower
For TIdStrings
Rev 1.8 10/26/2004 8:43:02 PM JPMugaas
Should be more portable with new references to TIdStrings and TIdStringList.
Rev 1.7 4/12/2004 4:50:36 PM JPMugaas
TIdThreadSafeInt64 created for some internal work but I figured it would help
with other stuff.
Rev 1.6 3/26/2004 1:09:28 PM JPMugaas
New ThreadSafe objects that I needed for some other work I'm doing.
Rev 1.5 3/17/2004 8:57:32 PM JPMugaas
Increment and decrement overloads added for quick math in the
TIdThreadSafeCardinal and TIdThreadSafeInteger. I need this for personal
work.
Rev 1.4 2004.02.25 8:23:20 AM czhower
Small changes
Rev 1.3 2004.02.03 4:17:00 PM czhower
For unit name changes.
Rev 1.2 2004.01.22 5:59:12 PM czhower
IdCriticalSection
Rev 1.1 3/27/2003 12:29:46 AM BGooijen
Added TIdThreadSafeList.Assign
Rev 1.0 11/13/2002 09:01:54 AM JPMugaas
}
unit IdThreadSafe;
interface
{$I IdCompilerDefines.inc}
//we need to put this in Delphi mode to work
uses
Classes,
IdGlobal;
type
TIdThreadSafe = class
protected
FCriticalSection: TIdCriticalSection;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
end;
// Yes we know that integer operations are "atomic". However we do not like to rely on
// internal compiler implementation. This is a safe and proper way to keep our code independent
TIdThreadSafeInteger = class(TIdThreadSafe)
protected
FValue: Integer;
//
function GetValue: Integer;
procedure SetValue(const AValue: Integer);
public
function Decrement: Integer; overload;
function Decrement(const AValue : Integer) : Integer; overload;
function Increment: Integer; overload;
function Increment(const AValue : Integer) : Integer; overload;
//
property Value: Integer read GetValue write SetValue;
end;
TIdThreadSafeBoolean = class(TIdThreadSafe)
protected
FValue: Boolean;
//
function GetValue: Boolean;
procedure SetValue(const AValue: Boolean);
public
function Toggle: Boolean;
//
property Value: Boolean read GetValue write SetValue;
end;
TIdThreadSafeCardinal = class(TIdThreadSafe)
protected
FValue: Cardinal;
//
function GetValue: Cardinal;
procedure SetValue(const AValue: Cardinal);
public
function Decrement: Cardinal; overload;
function Decrement(const AValue : Cardinal) : Cardinal; overload;
function Increment: Cardinal; overload;
function Increment(const AValue : Cardinal) : Cardinal; overload;
//
property Value: Cardinal read GetValue write SetValue;
end;
TIdThreadSafeInt64 = class(TIdThreadSafe)
protected
FValue: Int64;
//
function GetValue: Int64;
procedure SetValue(const AValue: Int64);
public
function Decrement: Int64; overload;
function Decrement(const AValue : Int64) : Int64; overload;
function Increment: Int64; overload;
function Increment(const AValue : Int64) : Int64; overload;
//
property Value: Int64 read GetValue write SetValue;
end;
TIdThreadSafeString = class(TIdThreadSafe)
protected
FValue: string;
//
function GetValue: string;
procedure SetValue(const AValue: string);
public
procedure Append(const AValue: string);
procedure Prepend(const AValue: string);
//
property Value: string read GetValue write SetValue;
end;
TIdThreadSafeStringList = class(TIdThreadSafe)
protected
FValue: TStringList;
//
function GetValue(const AName: string): string;
procedure SetValue(const AName, AValue: string);
public
constructor Create; override;
destructor Destroy; override;
procedure Add(const AItem: string);
procedure AddObject(const AItem: string; AObject: TObject);
procedure Clear;
function Empty: Boolean;
function Lock: TStringList; reintroduce;
function ObjectByItem(const AItem: string): TObject;
procedure Remove(const AItem: string);
procedure Unlock; reintroduce;
property Values[const AName: string]: string read GetValue write SetValue;
end;
TIdThreadSafeDateTime = class(TIdThreadSafe)
protected
FValue : TDateTime;
function GetValue: TDateTime;
procedure SetValue(const AValue: TDateTime);
public
procedure Add(const AValue : TDateTime);
procedure Subtract(const AValue : TDateTime);
property Value: TDateTime read GetValue write SetValue;
end;
//In D7, a double is the same as a TDateTime. In DotNET, it is not.
TIdThreadSafeDouble = class(TIdThreadSafe)
protected
FValue : Double;
function GetValue: Double;
procedure SetValue(const AValue: Double);
public
procedure Add(const AValue : Double);
procedure Subtract(const AValue : Double);
property Value: Double read GetValue write SetValue;
end;
//TODO: Later make this descend from TIdThreadSafe instead
TIdThreadSafeList = class(TThreadList)
private
FOwnsObjects: Boolean;
public
procedure Assign(AThreadList: TThreadList);overload;
procedure Assign(AList: TList);overload;
// Here to make it virtual
constructor Create; virtual;
destructor Destroy; override;
function IsCountLessThan(const AValue: Cardinal): Boolean;
function Count:Integer;
function IsEmpty: Boolean;
function Pop: TObject;
function Pull: TObject;
procedure ClearAndFree;
property OwnsObjects:Boolean read FOwnsObjects write FOwnsObjects;
End;
implementation
uses
{$IFDEF VCL_2010_OR_ABOVE}
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
{$ENDIF}
{$IFDEF VCL_XE3_OR_ABOVE}
System.SyncObjs,
{$ENDIF}
SysUtils;
{ TIdThreadSafe }
constructor TIdThreadSafe.Create;
begin
inherited Create;
FCriticalSection := TIdCriticalSection.Create;
end;
destructor TIdThreadSafe.Destroy;
begin
FreeAndNil(FCriticalSection);
inherited Destroy;
end;
procedure TIdThreadSafe.Lock;
begin
FCriticalSection.Enter;
end;
procedure TIdThreadSafe.Unlock;
begin
FCriticalSection.Leave;
end;
{ TIdThreadSafeInteger }
function TIdThreadSafeInteger.Decrement: Integer;
begin
Lock; try
Result := FValue;
Dec(FValue);
finally Unlock; end;
end;
function TIdThreadSafeInteger.Decrement(const AValue: Integer): Integer;
begin
Lock; try
Result := FValue;
Dec(FValue,AValue);
finally Unlock; end;
end;
function TIdThreadSafeInteger.GetValue: Integer;
begin
Lock; try
Result := FValue;
finally Unlock; end;
end;
function TIdThreadSafeInteger.Increment: Integer;
begin
Lock; try
Result := FValue;
Inc(FValue);
finally Unlock; end;
end;
function TIdThreadSafeInteger.Increment(const AValue: Integer): Integer;
begin
Lock; try
Result := FValue;
Inc(FValue,AValue);
finally Unlock; end;
end;
procedure TIdThreadSafeInteger.SetValue(const AValue: Integer);
begin
Lock; try
FValue := AValue;
finally Unlock; end;
end;
{ TIdThreadSafeString }
procedure TIdThreadSafeString.Append(const AValue: string);
begin
Lock; try
FValue := FValue + AValue;
finally Unlock; end;
end;
function TIdThreadSafeString.GetValue: string;
begin
Lock; try
Result := FValue;
finally Unlock; end;
end;
procedure TIdThreadSafeString.Prepend(const AValue: string);
begin
Lock; try
FValue := AValue + FValue;
finally Unlock; end;
end;
procedure TIdThreadSafeString.SetValue(const AValue: string);
begin
Lock; try
FValue := AValue;
finally Unlock; end;
end;
{ TIdThreadSafeStringList }
procedure TIdThreadSafeStringList.Add(const AItem: string);
begin
with Lock do try
Add(AItem);
finally Unlock; end;
end;
procedure TIdThreadSafeStringList.AddObject(const AItem: string; AObject: TObject);
begin
with Lock do try
AddObject(AItem, AObject);
finally Unlock; end;
end;
procedure TIdThreadSafeStringList.Clear;
begin
with Lock do try
Clear;
finally Unlock; end;
end;
constructor TIdThreadSafeStringList.Create;
begin
inherited Create;
FValue := TStringList.Create;
end;
destructor TIdThreadSafeStringList.Destroy;
begin
inherited Lock; try
FreeAndNil(FValue);
finally inherited Unlock; end;
inherited Destroy;
end;
function TIdThreadSafeStringList.Empty: Boolean;
begin
with Lock do try
Result := Count = 0;
finally Unlock; end;
end;
function TIdThreadSafeStringList.GetValue(const AName: string): string;
begin
with Lock do try
Result := Values[AName];
finally Unlock; end;
end;
function TIdThreadSafeStringList.Lock: TStringList;
begin
inherited Lock;
Result := FValue;
end;
function TIdThreadSafeStringList.ObjectByItem(const AItem: string): TObject;
var
i: Integer;
begin
Result := nil;
with Lock do try
i := IndexOf(AItem);
if i > -1 then begin
Result := Objects[i];
end;
finally Unlock; end;
end;
procedure TIdThreadSafeStringList.Remove(const AItem: string);
var
i: Integer;
begin
with Lock do try
i := IndexOf(AItem);
if i > -1 then begin
Delete(i);
end;
finally Unlock; end;
end;
procedure TIdThreadSafeStringList.SetValue(const AName, AValue: string);
begin
with Lock do try
Values[AName] := AValue;
finally Unlock; end;
end;
procedure TIdThreadSafeStringList.Unlock;
begin
inherited Unlock;
end;
{ TIdThreadSafeCardinal }
function TIdThreadSafeCardinal.Decrement: Cardinal;
begin
Lock; try
Result := FValue;
Dec(FValue);
finally Unlock; end;
end;
function TIdThreadSafeCardinal.Decrement(const AValue: Cardinal): Cardinal;
begin
Lock; try
Result := FValue;
Dec(FValue,AValue);
finally Unlock; end;
end;
function TIdThreadSafeCardinal.GetValue: Cardinal;
begin
Lock; try
Result := FValue;
finally Unlock; end;
end;
function TIdThreadSafeCardinal.Increment: Cardinal;
begin
Lock; try
Result := FValue;
Inc(FValue);
finally Unlock; end;
end;
function TIdThreadSafeCardinal.Increment(const AValue: Cardinal): Cardinal;
begin
Lock; try
Result := FValue;
Inc(FValue,AValue);
finally Unlock; end;
end;
procedure TIdThreadSafeCardinal.SetValue(const AValue: Cardinal);
begin
Lock; try
FValue := AValue;
finally Unlock; end;
end;
{ TIdThreadSafeList }
function TIdThreadSafeList.IsCountLessThan(const AValue: Cardinal): Boolean;
begin
if Assigned(Self) then begin
Result := Cardinal(Count) < AValue;
end else begin
Result := True; // none always <
end;
end;
function TIdThreadSafeList.IsEmpty: Boolean;
begin
Result := IsCountLessThan(1);
end;
function TIdThreadSafeList.Pop: TObject;
begin
with LockList do try
if Count > 0 then begin
Result := Items[Count - 1];
Delete(Count - 1);
end else begin
Result := nil;
end;
finally UnlockList; end;
end;
function TIdThreadSafeList.Pull: TObject;
begin
with LockList do try
if Count > 0 then begin
Result := Items[0];
Delete(0);
end else begin
Result := nil;
end;
finally UnlockList; end;
end;
procedure TIdThreadSafeList.Assign(AList: TList);
var
i: integer;
begin
with LockList do try
Clear;
Capacity := AList.Capacity;
for i := 0 to AList.Count - 1 do begin
Add(AList.Items[i]);
end;
finally UnlockList; end;
end;
procedure TIdThreadSafeList.Assign(AThreadList: TThreadList);
var
LList:TList;
begin
LList := AThreadList.LockList; try
Assign(LList);
finally AThreadList.UnlockList; end;
end;
constructor TIdThreadSafeList.Create;
begin
inherited Create;
OwnsObjects:=False;
end;
procedure TIdThreadSafeList.ClearAndFree;
var
LList:TList;
i:Integer;
begin
LList := LockList; try
for i := 0 to LList.Count-1 do
begin
TObject(LList[i]).Free;
end;
LList.Clear;
finally UnlockList; end;
end;
destructor TIdThreadSafeList.Destroy;
begin
if OwnsObjects then ClearAndFree;
inherited;
end;
function TIdThreadSafeList.Count: Integer;
var
aList: TList;
begin
aList := LockList;
try
Result := aList.Count;
finally
UnlockList;
end;
end;
{ TIdThreadSafeBoolean }
function TIdThreadSafeBoolean.GetValue: Boolean;
begin
Lock; try
Result := FValue;
finally Unlock; end;
end;
procedure TIdThreadSafeBoolean.SetValue(const AValue: Boolean);
begin
Lock; try
FValue := AValue;
finally Unlock; end;
end;
function TIdThreadSafeBoolean.Toggle: Boolean;
begin
Lock; try
FValue := not FValue;
Result := FValue;
finally Unlock; end;
end;
{ TIdThreadSafeDateTime }
procedure TIdThreadSafeDateTime.Add(const AValue: TDateTime);
begin
Lock;
try
FValue := FValue + AValue;
finally
Unlock;
end;
end;
function TIdThreadSafeDateTime.GetValue: TDateTime;
begin
Lock;
try
Result := FValue;
finally
Unlock;
end;
end;
procedure TIdThreadSafeDateTime.SetValue(const AValue: TDateTime);
begin
Lock;
try
FValue := AValue;
finally
Unlock;
end;
end;
procedure TIdThreadSafeDateTime.Subtract(const AValue: TDateTime);
begin
Lock;
try
FValue := FValue - AValue;
finally
Unlock;
end;
end;
{ TIdThreadSafeDouble }
procedure TIdThreadSafeDouble.Add(const AValue: Double);
begin
Lock;
try
FValue := FValue + AValue;
finally
Unlock;
end;
end;
function TIdThreadSafeDouble.GetValue: Double;
begin
Lock;
try
Result := FValue;
finally
Unlock;
end;
end;
procedure TIdThreadSafeDouble.SetValue(const AValue: Double);
begin
Lock;
try
FValue := AValue;
finally
Unlock;
end;
end;
procedure TIdThreadSafeDouble.Subtract(const AValue: Double);
begin
Lock;
try
FValue := FValue - AValue;
finally
Unlock;
end;
end;
{ TIdThreadSafeInt64 }
function TIdThreadSafeInt64.Decrement(const AValue: Int64): Int64;
begin
Lock; try
Result := FValue;
Dec(FValue,AValue);
finally Unlock; end;
end;
function TIdThreadSafeInt64.Decrement: Int64;
begin
Lock; try
Result := FValue;
Dec(FValue);
finally Unlock; end;
end;
function TIdThreadSafeInt64.GetValue: Int64;
begin
Lock; try
Result := FValue;
finally Unlock; end;
end;
function TIdThreadSafeInt64.Increment(const AValue: Int64): Int64;
begin
Lock; try
Result := FValue;
Inc(FValue,AValue);
finally Unlock; end;
end;
function TIdThreadSafeInt64.Increment: Int64;
begin
Lock; try
Result := FValue;
Inc(FValue);
finally Unlock; end;
end;
procedure TIdThreadSafeInt64.SetValue(const AValue: Int64);
begin
Lock;
try
FValue := AValue;
finally
Unlock;
end;
end;
end.
|
Unit DebugStr;
// Контейнер всех отладочных строковых констант (Assert и пр.) во ВСЕМ пректе
interface
const
// Unit - dsUserList
caUnknownUserNodeType = 'Неизвестный тип ноды пользователей';
// Unit - bsConvert
caAdapterLanguageCHanged = 'Стал приходить другой идентификатор языка из адаптера';
// Unit - sdsDocInfo
caRespCorrestUnsupported = 'Этим объектом СКР к части не поддерживается';
caAnnotationNotFound = 'У документа должна быть аннотация, но адаптер ее не нашел';
// Unit - sdsDocument
capDocumentEnter = 'Вход ОТКРЫТИЕ_ДОКУМЕНТА';
// Unit - dsDocumentList
caINodeIndexPathToINodeBaseFailed = 'INodeBase по INodeIndexPath не была получена.';
caUnknownElementType = 'Не известный тип элемента списка.';
// Unit - sdsAttributeSelect
caUninitializedFormsetData = 'Не были установленны данные для инициализации сборки.';
// Unit - cfStyleEditor
caSettingsWithoutContainer = 'Нет контейнера для настроек';
// Unit - moSearch
caUnknownFilterType = 'Не известный тип фильтра';
// Unit - nsConfiguration
caNoActiveConfig = 'Нет активной конфигурации';
caNoSettings = 'Нет настроек';
// Unit - DataAdapter
caWrongDllVersion = 'Продолжение работы невозможно! Версия библиотеки отличается от требуемойя оболочкой';
// Unit - Document
c_prDocument = 'Открытие документа';
c_prQueryCard = 'Карточка запроса 6.х';
c_prListAfterSearch = 'Список после поиска';
c_prMainMenu = 'Открытие основного меню';
// Unit - nsStreamDocument
capDocumentExit = 'Выход ОТКРЫТИЕ_ДОКУМЕНТА';
capDocumentReadTimeWOPipe = 'Время чтения без трубы (desktop)';
capDocumentBeforeReadTime = 'Время от начала pm_GetDocument до собственно чтения из полученной трубы';
capDocumentReadWPipeTime = '%d Время чтения из трубы';
capDocumentAfterReadTime = '%d Время завершения чтения - переход на Sub и т.п.';
// Unit - SynchroViewContainer
caUnsupported = 'Не поддерживается';
// Unit - TextForm
caTextFormUpdateAdditionalFormsEnter = 'Вход в TTextForm.UpdateAditionalForms';
caTextFormUpdateAdditionalFormsExit = 'Выход из TTextForm.UpdateAditionalForms';
caTextFormRelatedDocsUpdateEnter = 'Вход в RelatedDocsUpdate';
caTextFormRelatedDocsUpdateExit = 'Выход из RelatedDocsUpdate';
// Unit - nsApplication
caWrongQueryParameters = 'Неправильный список параметров для открытия запроса.';
caUnknownQueryType = 'Неизвестный тип запроса %s';
// Unit - nsQueryAttribute;
caUnsuppotedAttributeType = 'Не поддерживаемый тип атрибутов! ';
caFieldNotAdded = 'Не было добавлено поле! ';
caFieldNotInitialized = 'Не инициализировано поле! ';
caUnknownControlType = 'Неизвестный тип контрола!';
// Unit - Common
caDataNotDefined = 'Для создания прецедента необходимо подать IdeConsultation';
// Unit - sdsConsultation
caConsultationNotReceived = 'Консультация не получена';
caConsultationAnswerNotSet = 'Ответ консультации не определен';
// Unit - nsQueryUtils
caQueryTypeIsNotDefined = 'Тип запроса не определен';
// Unit - dsConsultationMark
caConsultationIsNotDefined = 'Консультация не определена, продолжение ' +
'работы не возможно.';
// Unit - usUtils
caUnknownUseCaseType = 'Не известный тип прецедента.';
// Unit - bsConvert
caUnknownConsultationMark = 'Не известный тип оценки';
caUnknownWordPosition = 'Не известный тип Tl3WordPosition';
// Unit - nsQueryUtils
type
TnsNumberSufixes = (
ns_nsTenth, // *10, *11, ... , *19,
ns_nsSingle, // *1
ns_nsFew, // *2, *3, *4
ns_nsSome); // *5, *6, *7, *8, *9, *0
TnsNumberSufixesArray = array [TnsNumberSufixes] of string;
const
cseDocument: TnsNumberSufixesArray = (
'документов',
'документ',
'документа',
'документов');
cseEdition: TnsNumberSufixesArray = (
'редакций',
'редакция',
'редакции',
'редакций');
cseEntry: TnsNumberSufixesArray = (
'вхождений',
'вхождение',
'вхождения',
'вхождений');
cseSinglePrefix = 'Найден'; // все *1, кроме *11
cseOtherPrefix = 'Найдено';
cseSingleFilterFound = '%s %d %s с использованием фильтра "%s".'#13'Построить список?';
cseManyFilterFound = '%s %d %s с использованием %d фильтров.'#13'Построить список?';
cseBuildList = 'Найдено: %d %s, %d %s (%d %s в документы и редакции).'#13'Построить список?';
cseBuildListWOEdition = 'Найдено: %d %s (%d %s в документы).'#13'Построить список?';
cseBuildListWOEntry = 'Найдено: %d %s, %d %s.'#13'Построить список?';
cseBuildListWOEditionWOEntry = 'Найдено: %d %s.'#13'Построить список?';
cseBuildAutoReferat = 'Найдено: %d %s, %d %s (%d %s в документы и редакции).'#13'Построить обзор изменений законодательства?';
cseBuildAutoReferatWOEdition = 'Найдено: %d %s (%d %s в документы).'#13'Построить обзор изменений законодательства?';
cseBuildAutoReferatWOEntry = 'Найдено: %d %s, %d %s.'#13'Построить обзор изменений законодательства?';
cseBuildAutoReferatWOEditionWOEntry = 'Найдено: %d %s.'#13'Построить обзор изменений законодательства?';
cseSingleFilterNotFound = 'Ни один найденный документ не соответствует фильтру "%s".'#13'Построить список без учета фильтра (%d %s, %d %s (%d %s в документы и редакции))?';
cseSingleFilterNotFoundWOEdition = 'Ни один найденный документ не соответствует фильтру "%s".'#13'Построить список без учета фильтра (%d %s (%d %s в документы))?';
cseSingleFilterNotFoundWOEntry = 'Ни один найденный документ не соответствует фильтру "%s".'#13'Построить список без учета фильтра (%d %s, %d %s)?';
cseSingleFilterNotFoundWOEditionWOEntry = 'Ни один найденный документ не соответствует фильтру "%s".'#13'Построить список без учета фильтра (%d %s)?';
cseManyFilterNotFound = 'Ни один найденный документ не соответствует заданным фильтрам.'#13'Построить список без учета фильтров (%d %s, %d %s (%d %s в документы и редакции))?';
cseManyFilterNotFoundWOEdition = 'Ни один найденный документ не соответствует заданным фильтрам.'#13'Построить список без учета фильтров (%d %s (%d %s в документы))?';
cseManyFilterNotFoundWOEntry = 'Ни один найденный документ не соответствует заданным фильтрам.'#13'Построить список без учета фильтров (%d %s, %d %s)?';
cseManyFilterNotFoundWOEditionWOEntry = 'Ни один найденный документ не соответствует заданным фильтрам.'#13'Построить список без учета фильтров (%d %s)?';
implementation
end.
|
unit presentation_time_protocol;
{$mode objfpc} {$H+}
{$interfaces corba}
interface
uses
Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol;
type
Pwp_presentation = Pointer;
Pwp_presentation_feedback = Pointer;
const
WP_PRESENTATION_ERROR_INVALID_TIMESTAMP = 0; // invalid value in tv_nsec
WP_PRESENTATION_ERROR_INVALID_FLAG = 1; // invalid flag
type
Pwp_presentation_listener = ^Twp_presentation_listener;
Twp_presentation_listener = record
clock_id : procedure(data: Pointer; AWpPresentation: Pwp_presentation; AClkId: DWord); cdecl;
end;
const
WP_PRESENTATION_FEEDBACK_KIND_VSYNC = $1; // presentation was vsync'd
WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK = $2; // hardware provided the presentation timestamp
WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION = $4; // hardware signalled the start of the presentation
WP_PRESENTATION_FEEDBACK_KIND_ZERO_COPY = $8; // presentation was done zero-copy
type
Pwp_presentation_feedback_listener = ^Twp_presentation_feedback_listener;
Twp_presentation_feedback_listener = record
sync_output : procedure(data: Pointer; AWpPresentationFeedback: Pwp_presentation_feedback; AOutput: Pwl_output); cdecl;
presented : procedure(data: Pointer; AWpPresentationFeedback: Pwp_presentation_feedback; ATvSecHi: DWord; ATvSecLo: DWord; ATvNsec: DWord; ARefresh: DWord; ASeqHi: DWord; ASeqLo: DWord; AFlags: DWord); cdecl;
discarded : procedure(data: Pointer; AWpPresentationFeedback: Pwp_presentation_feedback); cdecl;
end;
TWpPresentation = class;
TWpPresentationFeedback = class;
IWpPresentationListener = interface
['IWpPresentationListener']
procedure wp_presentation_clock_id(AWpPresentation: TWpPresentation; AClkId: DWord);
end;
IWpPresentationFeedbackListener = interface
['IWpPresentationFeedbackListener']
procedure wp_presentation_feedback_sync_output(AWpPresentationFeedback: TWpPresentationFeedback; AOutput: TWlOutput);
procedure wp_presentation_feedback_presented(AWpPresentationFeedback: TWpPresentationFeedback; ATvSecHi: DWord; ATvSecLo: DWord; ATvNsec: DWord; ARefresh: DWord; ASeqHi: DWord; ASeqLo: DWord; AFlags: DWord);
procedure wp_presentation_feedback_discarded(AWpPresentationFeedback: TWpPresentationFeedback);
end;
TWpPresentation = class(TWLProxyObject)
private
const _DESTROY = 0;
const _FEEDBACK = 1;
public
destructor Destroy; override;
function Feedback(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TWpPresentationFeedback}): TWpPresentationFeedback;
function AddListener(AIntf: IWpPresentationListener): LongInt;
end;
TWpPresentationFeedback = class(TWLProxyObject)
function AddListener(AIntf: IWpPresentationFeedbackListener): LongInt;
end;
var
wp_presentation_interface: Twl_interface;
wp_presentation_feedback_interface: Twl_interface;
implementation
var
vIntf_wp_presentation_Listener: Twp_presentation_listener;
vIntf_wp_presentation_feedback_Listener: Twp_presentation_feedback_listener;
destructor TWpPresentation.Destroy;
begin
wl_proxy_marshal(FProxy, _DESTROY);
inherited Destroy;
end;
function TWpPresentation.Feedback(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TWpPresentationFeedback}): TWpPresentationFeedback;
var
callback: Pwl_proxy;
begin
callback := wl_proxy_marshal_constructor(FProxy,
_FEEDBACK, @wp_presentation_feedback_interface, nil, ASurface.Proxy);
if AProxyClass = nil then
AProxyClass := TWpPresentationFeedback;
Result := TWpPresentationFeedback(AProxyClass.Create(callback));
if not AProxyClass.InheritsFrom(TWpPresentationFeedback) then
Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TWpPresentationFeedback]);
end;
function TWpPresentation.AddListener(AIntf: IWpPresentationListener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_wp_presentation_Listener, @FUserDataRec);
end;
function TWpPresentationFeedback.AddListener(AIntf: IWpPresentationFeedbackListener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_wp_presentation_feedback_Listener, @FUserDataRec);
end;
procedure wp_presentation_clock_id_Intf(AData: PWLUserData; Awp_presentation: Pwp_presentation; AClkId: DWord); cdecl;
var
AIntf: IWpPresentationListener;
begin
if AData = nil then Exit;
AIntf := IWpPresentationListener(AData^.ListenerUserData);
AIntf.wp_presentation_clock_id(TWpPresentation(AData^.PascalObject), AClkId);
end;
procedure wp_presentation_feedback_sync_output_Intf(AData: PWLUserData; Awp_presentation_feedback: Pwp_presentation_feedback; AOutput: Pwl_output); cdecl;
var
AIntf: IWpPresentationFeedbackListener;
begin
if AData = nil then Exit;
AIntf := IWpPresentationFeedbackListener(AData^.ListenerUserData);
AIntf.wp_presentation_feedback_sync_output(TWpPresentationFeedback(AData^.PascalObject), TWlOutput(TWLProxyObject.WLToObj(AOutput)));
end;
procedure wp_presentation_feedback_presented_Intf(AData: PWLUserData; Awp_presentation_feedback: Pwp_presentation_feedback; ATvSecHi: DWord; ATvSecLo: DWord; ATvNsec: DWord; ARefresh: DWord; ASeqHi: DWord; ASeqLo: DWord; AFlags: DWord); cdecl;
var
AIntf: IWpPresentationFeedbackListener;
begin
if AData = nil then Exit;
AIntf := IWpPresentationFeedbackListener(AData^.ListenerUserData);
AIntf.wp_presentation_feedback_presented(TWpPresentationFeedback(AData^.PascalObject), ATvSecHi, ATvSecLo, ATvNsec, ARefresh, ASeqHi, ASeqLo, AFlags);
end;
procedure wp_presentation_feedback_discarded_Intf(AData: PWLUserData; Awp_presentation_feedback: Pwp_presentation_feedback); cdecl;
var
AIntf: IWpPresentationFeedbackListener;
begin
if AData = nil then Exit;
AIntf := IWpPresentationFeedbackListener(AData^.ListenerUserData);
AIntf.wp_presentation_feedback_discarded(TWpPresentationFeedback(AData^.PascalObject));
end;
const
pInterfaces: array[0..10] of Pwl_interface = (
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(@wl_surface_interface),
(@wp_presentation_feedback_interface),
(@wl_output_interface)
);
wp_presentation_requests: array[0..1] of Twl_message = (
(name: 'destroy'; signature: ''; types: @pInterfaces[0]),
(name: 'feedback'; signature: 'on'; types: @pInterfaces[8])
);
wp_presentation_events: array[0..0] of Twl_message = (
(name: 'clock_id'; signature: 'u'; types: @pInterfaces[0])
);
wp_presentation_feedback_events: array[0..2] of Twl_message = (
(name: 'sync_output'; signature: 'o'; types: @pInterfaces[10]),
(name: 'presented'; signature: 'uuuuuuu'; types: @pInterfaces[0]),
(name: 'discarded'; signature: ''; types: @pInterfaces[0])
);
initialization
Pointer(vIntf_wp_presentation_Listener.clock_id) := @wp_presentation_clock_id_Intf;
Pointer(vIntf_wp_presentation_feedback_Listener.sync_output) := @wp_presentation_feedback_sync_output_Intf;
Pointer(vIntf_wp_presentation_feedback_Listener.presented) := @wp_presentation_feedback_presented_Intf;
Pointer(vIntf_wp_presentation_feedback_Listener.discarded) := @wp_presentation_feedback_discarded_Intf;
wp_presentation_interface.name := 'wp_presentation';
wp_presentation_interface.version := 1;
wp_presentation_interface.method_count := 2;
wp_presentation_interface.methods := @wp_presentation_requests;
wp_presentation_interface.event_count := 1;
wp_presentation_interface.events := @wp_presentation_events;
wp_presentation_feedback_interface.name := 'wp_presentation_feedback';
wp_presentation_feedback_interface.version := 1;
wp_presentation_feedback_interface.method_count := 0;
wp_presentation_feedback_interface.methods := nil;
wp_presentation_feedback_interface.event_count := 3;
wp_presentation_feedback_interface.events := @wp_presentation_feedback_events;
end.
|
unit flLabel;
interface
uses
SysUtils, Classes, Controls, StdCtrls, flImageList, Graphics, ExtCtrls,
Messages;
type
TflLabel = class(TLabel)
private
FImageList: TflImageList;
FSmartTruncate: Boolean;
FLetterDelay: Integer;
FDelayDraw: Boolean;
procedure SetImageList(const Value: TflImageList);
procedure SetSmartTruncate(const Value: Boolean);
procedure SetLetterDelay(const Value: Integer);
procedure CMTextChanged(var M: TMessage); message CM_TEXTCHANGED;
procedure SetDelayDraw(const Value: Boolean);
{ Private declarations }
protected
FTimer: TTimer;
FTmpCaption: string;
FTmpIndex: Integer;
procedure Paint; override;
function GetHoldString(const AText: string; AWidth: Integer): string;
procedure DoTimer(Sender: TObject); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CalcTextWidth(const AText: string): Integer;
procedure StartDelayDraw;
published
property DelayDraw: Boolean read FDelayDraw write SetDelayDraw
default True;
property ImageList: TflImageList read FImageList write SetImageList;
property LetterDelay: Integer read FLetterDelay write SetLetterDelay
default 100;
property SmartTruncate: Boolean read FSmartTruncate write SetSmartTruncate
default True;
end;
Var
Imgs: array[' '..'~'] of Integer =
(88,62,63,64,65,66,93,82,67,68,69,70,71,72,73,74,61,52,53,54,55,
56,57,58,59,60,75,76,77,78,79,80,81,26,27,28,29,30,31,32,33,
34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,83,84,
85,94,86,87, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,91,90,92,89);
implementation
{ TflLabel }
function TflLabel.CalcTextWidth(const AText: string): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(AText) do
Result := Result + StrToInt(ImageList.Widths[Imgs[AText[i]]]);
end;
procedure TflLabel.CMTextChanged(var M: TMessage);
begin
inherited;
if FDelayDraw then StartDelayDraw;
end;
constructor TflLabel.Create(AOwner: TComponent);
begin
inherited;
FTimer := TTimer.Create(nil);
with FTimer do begin
Interval := FLetterDelay;
OnTimer := DoTimer;
Enabled := False;
end;
AutoSize := False;
FLetterDelay := 100;
FSmartTruncate := True;
FDelayDraw := True;
end;
destructor TflLabel.Destroy;
begin
FTimer.Free;
inherited;
end;
procedure TflLabel.DoTimer(Sender: TObject);
var
S: string;
begin
S := Caption;
if FTmpIndex = Length(S) then begin
FTimer.Enabled := False;
Exit;
end;
Inc(FTmpIndex);
FTmpCaption := FTmpCaption + S[FTmpIndex];
Invalidate;
end;
function TflLabel.GetHoldString(const AText: string;
AWidth: Integer): string;
var
i, W: Integer;
begin
Result := '';
W := 0;
for i := 1 to Length(AText) do begin
if W + StrToInt(ImageList.Widths[Imgs[AText[i]]]) <= AWidth then begin
Result := Result + AText[i];
W := W + StrToInt(ImageList.Widths[Imgs[AText[i]]]);
end
else Break;
end;
end;
procedure TflLabel.Paint;
var
i, X, W: Integer;
S: string;
Bmp: TBitmap;
NeedTrunc: Boolean;
begin
if FTimer.Enabled
then S := FTmpCaption
else S := Caption;
W := CalcTextWidth(S);
NeedTrunc := W > Self.Width;
if FSmartTruncate and NeedTrunc then begin
S := GetHoldString(S, Self.Width - CalcTextWidth('...')) + '...';
end;
Bmp := TBitmap.Create;
Bmp.Transparent := True;
X := 0;
with Canvas do begin
Brush.Color := Self.Color;
if not FTimer.Enabled or (FTmpIndex = 1) or (FSmartTruncate and NeedTrunc) then
FillRect(ClientRect);
for i := 1 to Length(S) do begin
Bmp.Width := 0;
Bmp.Height := 0;
FImageList.GetBitmap(Imgs[S[i]], Bmp);
Draw(X, 0, Bmp);
Inc(X, StrToInt(FImageList.Widths[Imgs[S[i]]]));
// FImageList.Draw(Canvas, FImageList.Width*i, 0, Imgs[S[i]]);
end;
end;
Bmp.Free;
end;
procedure TflLabel.SetDelayDraw(const Value: Boolean);
begin
FDelayDraw := Value;
end;
procedure TflLabel.SetImageList(const Value: TflImageList);
begin
FImageList := Value;
end;
procedure TflLabel.SetLetterDelay(const Value: Integer);
begin
FLetterDelay := Value;
FTimer.Interval := Value;
end;
procedure TflLabel.SetSmartTruncate(const Value: Boolean);
begin
FSmartTruncate := Value;
Invalidate;
end;
procedure TflLabel.StartDelayDraw;
begin
if not FDelayDraw then Exit;
FTmpCaption := '';
FTmpIndex := 0;
FTimer.Enabled := True;
end;
end.
|
unit FiveWebUtils_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ FiveWebUtils Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_FiveWebUtils: TGUID = '{73C41814-C0DD-11D1-ABE2-008029EC1811}';
const
{ Component class GUIDs }
Class_TURLTrigger: TGUID = '{73C41816-C0DD-11D1-ABE2-008029EC1811}';
type
{ Forward declarations: Interfaces }
ITURLTrigger = interface;
ITURLTriggerDisp = dispinterface;
{ Forward declarations: CoClasses }
TURLTrigger = ITURLTrigger;
{ Dispatch interface for TURLTrigger Object }
ITURLTrigger = interface(IDispatch)
['{73C41815-C0DD-11D1-ABE2-008029EC1811}']
function Trig(const URL: WideString): WordBool; safecall;
end;
{ DispInterface declaration for Dual Interface ITURLTrigger }
ITURLTriggerDisp = dispinterface
['{73C41815-C0DD-11D1-ABE2-008029EC1811}']
function Trig(const URL: WideString): WordBool; dispid 1;
end;
{ TURLTriggerObject }
CoTURLTrigger = class
class function Create: ITURLTrigger;
class function CreateRemote(const MachineName: string): ITURLTrigger;
end;
implementation
uses ComObj;
class function CoTURLTrigger.Create: ITURLTrigger;
begin
Result := CreateComObject(Class_TURLTrigger) as ITURLTrigger;
end;
class function CoTURLTrigger.CreateRemote(const MachineName: string): ITURLTrigger;
begin
Result := CreateRemoteComObject(MachineName, Class_TURLTrigger) as ITURLTrigger;
end;
end.
|
unit GameData;
{$mode objfpc}{$H+}
interface
+
+uses
+ Classes, Forms, SysUtils, process, SynRegExpr, LCLPRoc, tappywords, util
+ {$IFDEF Linux}
+ ,oldlinux
+ {$ENDIF}
+ ;
+
+Type
+ TTappyGameData = object
+ SndFX : Boolean;
+ SndMusic: Boolean;
+ ModuleName : String;
+ Option : String;
+ Level : Integer;
+ NextLevel : Integer;
+ NextLife : Integer;
+ Speed : Integer;
+ Score : Integer;
+ Lives : Integer;
+ SongList : TStringList;
+ QuestionList :TStringList;
+ Procedure Create;
+ Function GetQuestion:String;
+ Function CheckAnswer(Question,Answer:String):Integer;
+ Procedure ScoreUp(ScorInc:Integer);
+ Procedure LevelUp;
+ Procedure LoseLife;
+ Function NextSong: String;
+ BGS : TStringList;
+ BG : Integer;
+ Function NextBG:String;
+ end;
+
+Type HammerQue = Object
+ Target : Array [1..10] of Integer;
+ Function addTarget(newTarget : Integer):Boolean;
+ Procedure delTarget;
+ Count : Integer;
+ end;
+
+
+ TSong = class(TThread)
+ protected
+ procedure Execute; override;
+ public
+ Constructor Create(isSuspended : boolean);
+ end;
+
+ TQuestion = class(TThread)
+ private
+ S : TStringList;
+ protected
+ procedure Execute; override;
+ public
+ Constructor Create(isSuspended : boolean);
+ published
+ property terminated;
+ end;
+
+Var
+ ThisGame: TTappyGameData;
+ Question : TQuestion;
+ Scale : Integer;
+ TPTDIR: string;
+
+implementation
+
+constructor TQuestion.Create(isSuspended : boolean);
+ begin
+ S := TSTringlist.Create;
+ FreeOnTerminate := True;
+ inherited Create(isSuspended);
+ end;
+
+Procedure TQuestion.Execute;
+Var CMD : String;
+ PS : TProcess;
+ TheWord : String;
+Begin
+repeat
+If (Not Terminated) and
+(ThisGame.QuestionList.Count < 20) and
+(length(ThisGame.ModuleName) > 0) and
+(Length(ThisGame.Option) > 0) then
+Begin
+if pos('tappywords',ThisGame.ModuleName) <> 0 then
+Begin
+ TheWord :=GetQuestion(ThisGame.Level);
+ If ThisGame.QuestionList.IndexOf(TheWord) = -1 then
+ ThisGame.QuestionList.Add(TheWord);
+end else
+Begin
+ S.Clear;
+ Ps := TProcess.create(nil);;
+ CMD := ThisGame.ModuleName+' "'+ThisGAme.Option+'" '+intToStr(ThisGame.Level)+' --getquestion';
+ PS.CommandLine := cmd;
+ Ps.Options := [poNoConsole,poUsePipes,poWaitOnExit];
+ Ps.Execute;
+ S.LoadFromStream(PS.OutPut);
+ PS.Free;
+ If ThisGame.QuestionList.IndexOf(S[0]) = -1 then
+ ThisGame.QuestionList.Add(S[0]);
+end;
+end;
+ until Terminated;
+S.Free;
+end;
+
+constructor TSong.Create(isSuspended : boolean);
+begin
+ FreeOnTerminate := True;
+ inherited Create(isSuspended);
+end;
+
+Procedure TSong.Execute;
+var
+ Process: TProcess;
+begin
+ {To prevent ESD clashes - we slow this down on first run}
+ sleep(5000);
+ with ThisGame do
+ begin
+ Process := TProcess.create(nil);
+ while (NextSong <> 'NONE') and (not Terminated) do
+ begin
+{$IFDEF Linux}
+ Process.CommandLine := 'ogg123 -d esd "'+NextSong+'"' ;
+ Process.Options := [poNoConsole,poWaitOnExit];
+ Process.Execute;
+{$ENDIF}
+{$IFDEF Win32}
+ sleep(5000);
+{$ENDIF}
+ end;
+
+ Process.Free;
+ SNDMusic := False;
+ end;
+end;
+
+procedure TTappyGameData.Create;
+begin
+ BG := 0;
+
+ if not (NextLevel > 0) then NextLevel := 100;
+
+ if not (NextLife > 0) then NextLife := 325;
+
+ if not(Score > 0) then Score := 0;
+
+ Lives := 5;
+ SearchFiles(SongList,TPTDir+pathdelim+'music'+pathdelim,'*.ogg','');
+
+ If Scale = 640 then
+ SearchFiles(BGS,TPTDir+pathdelim+'levels','*.jpg','');
+
+ If Scale = 800 then
+ SearchFiles(BGS,TPTDir+pathdelim+'levels'+pathdelim+'800'+pathdelim,'*.jpg','');
+
+ If scale = 1024 then
+ SearchFiles(BGS,TPTDir+pathdelim+'levels'+pathdelim+'1024'+pathdelim,'*.jpg','');
+end;
+
+Function TTappyGameData.GetQuestion:String;
+Var
+TheQ:String;
+Begin
+While QuestionList.Count < 1 do
+ sleep (100);
+ TheQ := QuestionList[0];
+ GetQuestion := TheQ;
+ QuestionList.Delete(0);
+end;
+
+
+
+Function TTappyGameData.CheckAnswer(Question,Answer:String):Integer;
+Var S: TStringList;
+Begin
+if (length(Question) <> 0) and (length(Answer) <> 0) then
+begin
+If ThisGame.ModuleName <> 'tappywords' then
+begin
+try
+ execute(ModuleName+' "'+Option+'" '+intToStr(Level)+' --checkquestion "'+Question+'" "'+answer+'"',S);
+ CheckAnswer := StrToInt(S[0]);
+except
+ CheckAnswer := 0;
+end;
+end else
+ CheckAnswer := CheckQuestion(Question,Answer)
+end else
+ CheckAnswer := -1;
+end;
+
+
+Procedure TTappyGameData.LevelUp;
+Var I : Integer;
+Begin
+For I := (QuestionList.Count - 1) downto 5 do
+ QuestionList.Delete(I);
+SchroedingersCat := True;
+Inc(Level);
+NextLevel := NextLevel + 100;
+End;
+
+
+Procedure TTappyGameData.ScoreUp(ScorInc:Integer);
+Begin
+ If (Score + ScorInc > NextLevel) and (Score > NextLevel) then
+ LevelUp;
+ Score := Score + ScorInc;
+End;
+
+
+Procedure TTappyGameData.LoseLife;
+Begin
+Dec(Lives);
+End;
+
+Function TTappyGameData.NextSong: String;
+Var SongNum : Integer;
+Begin
+if SongList.Count > 0 then
+begin
+ SongNum := Random(songList.Count -1);
+ NextSong:=SongList[SongNum];
+end else
+ NextSong := 'NONE';
+end;
+
+Function TTappyGameData.NextBG: String;
+Begin
+ If BG + 1 = BGS.Count then BG := 0 else
+ inc(BG);
+ NextBG:=BGS[BG];
+end;
+
+
+
+
+Function HammerQue.addTarget(newTarget : Integer):Boolean;
+Var I : Integer;
+ New : Boolean;
+
+begin
+New := True;
+for I := 1 to Count do
+begin
+if (Target[I] = NewTarget) then
+ New := False;
+end;
+If New then
+begin
+ Inc(Count);
+ Target[Count] := NewTarget;
+ AddTarget := True;
+end else
+ AddTarget := False;
+end;
+
+Procedure HammerQue.delTarget;
+Var X : Integer;
+Begin
+ For X := 1 to Count do
+ Target[X] := Target[X + 1];
+ Dec(Count);
+
+end;
+
+initialization
+
+{$IFDEF Linux}
+ TPTDIR := '/usr/share/tappytux';
+{$ELSE}
+ TPTDIR := ExtractFileDir(Application.EXEName);
+{$ENDIF}
+
+end.
+
Index: tappytux.lpr
===================================================================
--- tappytux.lpr (revision 67)
+++ tappytux.lpr (working copy)
@@ -3,8 +3,8 @@
{$mode objfpc}{$H+}
uses
-{$IFDEF Linux}
-cthreads,
+{$IFDEF UNIX}
+ cthreads,
{$ENDIF}
Interfaces, // this includes the LCL widgetset
Forms
@@ -14,9 +14,9 @@
Application.Title:='TappyTux';
Application.Initialize;
Application.CreateForm(TForm1, Form1);
- Application.CreateForm(TForm2, Form2);
- Application.CreateForm(TForm3, Form3);
- Application.CreateForm(TForm4, Form4);
- Application.Run;
+ Application.CreateForm(TForm2, Form2);
+ Application.CreateForm(TForm3, Form3);
+ Application.CreateForm(TForm4, Form4);
+ Application.Run;
end.
Index: unit1.pas
===================================================================
--- unit1.pas (revision 67)
+++ unit1.pas (working copy)
@@ -1,892 +1,854 @@
-unit unit1;
-
-{$mode objfpc}{$H+}
-
-interface
-
-uses
- Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,unit2,
- doublebuffer, StdCtrls, ExtCtrls, Buttons,Sprite,GameData
- ,unit3,unit4, screensize,util
- {$IFDEF Linux}
- ,oldlinux, esdsound
- {$ENDIF}
- {$IFDEF Win32}
- ,Windows,ShellAPI
- {$ENDIF}
- ;
-
-type
-
- { TForm1 }
-
- TForm1 = class(TForm)
- BitBtn1: TBitBtn;
- BG: TDoubleBuffer;
- Button1: TButton;
- Edit1: TEdit;
- Edit2: TEdit;
- Edit3: TEdit;
- Edit4: TEdit;
- {$IFDEF Linux}
- ESDSound1: TESDSound;
- {$ENDIF}
- Image1: TImage;
- DanceTimer: TTimer;
- Label1: TLabel;
- ScreenSize1: TScreenSize;
- SnowManTimer: TTimer;
- ScreenUpdateTimer: TTimer;
- HammerTimer: TTimer;
- BoomTimer: TTimer;
- SplashTimer: TTimer;
- ThrowTimer: TTimer;
- procedure BitBtn1Click(Sender: TObject);
- procedure BoomTimerStartTimer(Sender: TObject);
- procedure BoomTimerTimer(Sender: TObject);
- procedure Button1Click(Sender: TObject);
- procedure DanceTimerTimer(Sender: TObject);
- procedure Edit1KeyPress(Sender: TObject; var Key: char);
- procedure Edit2Enter(Sender: TObject);
- procedure FormActivate(Sender: TObject);
- procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
- procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
- procedure FormCreate(Sender: TObject);
- procedure FormResize(Sender: TObject);
- procedure FormShow(Sender: TObject);
- procedure FormWindowStateChange(Sender: TObject);
- procedure HammerTimerTimer(Sender: TObject);
- procedure ScreenUpdateTimerTimer(Sender: TObject);
- procedure SnowManTimerTimer(Sender: TObject);
- procedure SplashTimerTimer(Sender: TObject);
- procedure ThrowTimerStartTimer(Sender: TObject);
- procedure ThrowTimerTimer(Sender: TObject);
- private
- { private declarations }
- public
- { public declarations }
- end;
-
-
-
-var
-
- Music : TSong;
- Form1: TForm1;
- SnowMan : Array[1..5] of TSprite;
- NextQuestion : Array[1..5] Of String;
- Hammer : HammerQue;
- HammerPic : Tsprite;
- Boom : TSprite;
- Splash:TSprite;
- DancingTux : TSprite;
- HurtTux: TSprite;
- ThrowTux: TSprite;
- GameOver : Boolean;
-
-implementation
-
-{ TForm1 }
-
-
-Procedure Play(Name : String);
-Begin
-{$IFDEF Linux}
-If ThisGame.SNDFX then
- Form1.esdSound1.Play(Name);
-{$ENDIF}
-end;
-
-
-Procedure ThrowHammer(GoLeft:Boolean);
-Begin
-With Form1 do
-begin
-If GoLeft then
-begin
- ThrowTux.Frame := 0;
- HammerPic.X := ThrowTux.X - HammerPic.FrameWidth;
- HammerPic.Y := ThrowTux.Y;
-end else
-begin
- ThrowTux.Frame := 1;
- HammerPic.X := ThrowTux.X + ThrowTux.FrameWidth;
- HammerPic.Y := ThrowTux.Y;
-end;
-ThrowTimer.Enabled := True;
-end;
-end;
-
-Function textY(I:Integer):Integer;
-Begin
-TextY := SnowMan[I].Y - 35;
-end;
-
-//Why larry why is this different between platforms ?
-{$IFDEF Win32}
-function MyRect(X,Y,A,B:Integer):Rect;
-Var Z : Rect;
-Begin
- Z.Top := Y;
- Z.Left := X;
- Z.Right := A;
- Z.Bottom := B;
- MyRect := Z;
-end;
-{$ENDIF}
-
-procedure textMask(I :Integer);
-Begin
-With Form1 do
-begin
-{$IFDEF Win32}
-BG.MemBuff.Canvas.CopyRect(MyRect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35),
- BG.BackGround.BitMap.Canvas,MyRect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35));
-{$ENDIF}
-{$IFDEF Linux}
-BG.MemBuff.Canvas.CopyRect(Rect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35),
- BG.BackGround.BitMap.Canvas,Rect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35));
-{$ENDIF}
-
-end;
-end;
-
-
-procedure updateScoreboard;
-Begin
-With Form1 do
-Begin
- Edit2.Text := intToStr(ThisGame.Level);
- Edit3.Text := intToStr(ThisGame.Score);
- Edit4.Text := IntToStr(ThisGame.Lives);
- If ThisGame.Lives <=2 then
- Form1.Caption := 'TappyTux - Warning: '+IntToStr(ThisGame.Lives)+' Left';
-
-end;
-end;
-
-procedure SnowQuestion(I:Integer);
-Var X : Integer;
-Unique : Boolean;
-begin
- repeat
- NextQuestion[I] := ThisGame.GetQuestion;
- Unique := True;
- for X := 1 to 5 do
- if (length(NextQuestion[X]) <> 0) and (X <> I) then
- if (thisgame.CheckAnswer(NextQuestion[X],NextQuestion[I]) <> 0) then
- Unique := False;
- until Unique;
-end;
-
-Procedure InitSnowMen;
-Var I,X : integer;
- Unique: Boolean;
-Begin
-
- For I := 1 to 5 do
- SnowQuestion(I);
-
- for I := 1 to 5 do
- repeat
- Unique := True;
- for X := 1 to 5 do
- SnowMan[I].Y := 50 - (random(3000) div 10);
- if (SnowMan[I].Y = SnowMan[X].Y) And (I <> X) then
- Unique := False;
- until Unique;
-end;
-
-Procedure LoadSnowMen;
-Var I,X,Y : integer;
-Begin
-Case Scale of
-640:Y := 100;
-800:Y := 130;
-1024:Y := 180;
-end;
-For I := 1 to random(30) do
- X := random(100);
- For I := 5 downto 1 do
- begin
- SnowMan[I] := TSprite.Create(nil);
- {$IFDEF Linux}
- SnowMan[I].loadFromFile('/usr/share/tappytux/sprites/snowmen.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- SnowMan[I].loadFromFile('c:\program files\tappytux\sprites\snowmen.xpm');
- {$ENDIF}
-
- SnowMan[I].FrameWidth := 94;
- SnowMan[I].Frame := I -1;
- SnowMan[I].X := 10+((I -1) * Y);
-
- end;
-InitSnowMen;
-end;
-
-Procedure BlitSnowMen;
-Var I : Integer;
-Begin
- For I := 5 downto 1 do
- With form1 do
- begin
- BG.Mask(SnowMan[I]);
- BG.Blit(SnowMan[I]);
- end;
-end;
-
-
-procedure TForm1.BitBtn1Click(Sender: TObject);
-Var
- Browser : String;
-begin
-{$IFDEF Linux}
-Browser := 'none';
-if shell('if which mozilla ; then exit 0 ; else exit 1 ; fi') = 0 then
- Browser := 'mozilla';
-if shell('if which konqueror ; then exit 0 ; else exit 1 ; fi') = 0 then
- Browser := 'konqueror';
-if shell('if which opera ; then exit 0 ; else exit 1 ; fi') = 0 then
- Browser := 'opera';
-if shell('if which firefox ; then exit 0 ; else exit 1 ; fi') = 0 then
- Browser := 'firefox';
-Writeln(browser);
-if browser <> 'none' then
- shell(browser+' "http://www.getopenlab.com"&');
-{$ENDIF}
-{$IFDEF Win32}
- ShellExecute(Handle,'open','http://www.getopenlab.com', nil, nil, SW_SHOWNORMAL);
-{$ENDIF}
-
-end;
-
-procedure TForm1.BoomTimerStartTimer(Sender: TObject);
-begin
-HammerTimer.Enabled := False;
- SnowManTimer.Enabled := True;
- Play('hit');
- Boom.X := SnowMan[Hammer.Target[1]].X - 20;
- Boom.Y := SnowMan[Hammer.Target[1]].Y - 20;
- BG.Mask(SnowMan[Hammer.Target[1]]);
- BG.Mask(HammerPic);
-
- SnowMan[Hammer.Target[1]].Y := -150;
- BG.Blit(Boom);
- // BG.Flip;
-
-end;
-
-procedure TForm1.BoomTimerTimer(Sender: TObject);
-
-begin
-
- BG.Mask(Boom);
- SnowQuestion(Hammer.Target[1]);
- BoomTimer.Enabled := False;
- Hammer.DelTarget;
- If Hammer.Count <> 0 then
- begin
- If SnowMan[Hammer.Target[1]].X <= DancingTux.X then
- ThrowHammer(True) else
- ThrowHammer(False);
- end;
- BG.Mask(HammerPic);
-SnowManTimer.Enabled := True;
- BG.Mask(HammerPic);
- HammerTimer.Enabled := True;
-end;
-
-Procedure PauseGame;
-Begin
-With Form1 do
-begin
- HammerTimer.Enabled := False;
- SnowManTimer.Enabled := False;
- Button1.Caption := 'Play';
- Form1.Caption := 'TappyTux - PAUSED';
-end;
-end;
-
-Procedure UnPauseGame;
-Begin
-With Form1 do
-begin
- Edit1.SetFocus;
- HammerTimer.Enabled := True;
- SnowManTimer.Enabled := True;
- Button1.Caption := 'Pause';
- Form1.Caption := 'TappyTux';
-end;
-end;
-
-
-procedure TForm1.Button1Click(Sender: TObject);
-begin
-If Button1.Caption = 'Pause' then
-PauseGame
-else
-UnPauseGame;
-end;
-
-
-
-procedure TForm1.DanceTimerTimer(Sender: TObject);
-begin
- if DancingTux.Frame = 0 then
- DancingTux.Frame := 1 else
- DancingTux.Frame := 0;
-
-BG.Mask(DancingTux);
-BG.Blit(Dancingtux);
-{BG.Flip; }
-end;
-
-
-
-procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: char);
-Var I,Y : Integer;
- Gotcha : Boolean;
-begin
- Edit1.Font.Color := ClBlack;
- If Key = #13 then
- begin
- Gotcha := False;
- For I := 1 to 5 do
- begin
- Y := ThisGame.CheckAnswer(NextQuestion[I],Edit1.Text);
- If (Y > 0) and (Hammer.AddTarget(I)) then
- begin
- Gotcha := True;
- If (ThisGame.Score + Y > ThisGame.NextLevel) and
- (ThisGame.Score > ThisGame.NextLevel)
- then
- Begin
- Play('levelup');
- BG.LoadFromFile(ThisGame.NextBG);
- For I := 1 to 5 do
- begin
- BG.Mask(SnowMan[I]);
- BG.Blit(SnowMan[I]);
- BG.Mask(ThrowTux);
- end;
- BG.Blit(DancingTux);
- end;
- ThisGame.ScoreUp(Y);
- If thisgame.Score > ThisGame.NextLife then
- begin
- play ('life');
- ThisGame.NextLife := ThisGame.NextLife + 300;
- inc(ThisGame.Lives);
- end else
- play ('match');
- updateScoreBoard;
- Edit1.Text := '';
- If Hammer.Count = 1 then
- begin
- If SnowMan[I].X <= DancingTux.X then
- ThrowHammer(True) else
- ThrowHammer(False);
- end;
- end;
- end;
- if Not Gotcha then
- begin
- play('error');
- edit1.Font.Color := ClRed;
- end;
- end;
-end;
-
-
-
-
-
-procedure TForm1.Edit2Enter(Sender: TObject);
-begin
- Edit1.SetFocus;
-end;
-
-procedure TForm1.FormActivate(Sender: TObject);
-begin
- Edit1.SetFocus;
-end;
-
-procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
-Var
-I : Integer;
-begin
- ThisGame.Level := 1;
- ThisGame.Score := 0;
- ThisGame.Lives := 5;
- SnowManTimer.Enabled := False;
- ScreenUpdateTimer.Enabled := False;
- HammerTimer.Enabled := FAlse;
- BoomTimer.Enabled := False;
- SplashTimer.Enabled := FAlse;
- ThrowTimer.Enabled := False;
-If Music <> Nil then
-begin
- Music.Terminate;
- execute ('killall -9 ogg123');
-end;
-
- DanceTimer.Enabled := False;
- if ThisGame.SndMusic then
- For I := 5 downto 1 do
- SnowMan[I].Free;
-try
-If Music <> Nil then
-begin
- Music.Free;
- BG.Free;
-end;
- ThisGame.QuestionList.Free;
-except
- writeln ('Exiting');
-for I := 1 to 5 do
- SnowMan[I].free;
- DancingTux.free;
- HurtTux.free;
- ThrowTux.free;
- HammerPic.free;
- Boom.free;
- Splash.free;
- BG.Free;
-Application.Terminate;
-end;
-end;
-
-procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
-begin
-If Not GameOver then
-begin
-PauseGame;
- Form3.ShowModal;
- If Form3.ModalResult = MrYes then
- CanClose := True
- else
- Begin
- CanClose := False;
- UnPauseGame;
- end;
-end;
-end;
-
-Procedure InitSprites;
-Begin
-With form1 do
-begin
- DancingTux := TSprite.Create(nil);
- {$IFDEF Linux}
- DancingTux.LoadFromFile('/usr/share/tappytux/sprites/tuxfront.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- DancingTux.loadFromFile('c:\program files\tappytux\sprites\tuxfront.xpm');
- {$ENDIF}
- DancingTux.X := (BG.Width div 2) - (DancingTux.Width div 2);
- DancingTux.Y := BG.Height - DancingTux.Height;
- DancingTux.Visible := True;
- DancingTux.Frame := 0;
- DancingTux.FrameWidth := 54;
-
- HurtTux := TSprite.Create(nil);
- {$IFDEF Linux}
- HurtTux.LoadFromFile('/usr/share/tappytux/sprites/hurt.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- HurtTux.loadFromFile('c:\program files\tappytux\sprites\hurt.xpm');
- {$ENDIF}
-
- HurtTux.X := (BG.Width div 2) - (HurtTux.Width div 2);
- HurtTux.Y := Edit1.Top - DancingTux.Height;
- HurtTux.Visible := True;
- HurtTux.Frame := 0;
- HurtTux.FrameWidth := 45;
-
- ThrowTux := TSprite.Create(nil);
- {$IFDEF Linux}
- ThrowTux.LoadFromFile('/usr/share/tappytux/sprites/tuxside.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- ThrowTux.loadFromFile('c:\program files\tappytux\sprites\tuxside.xpm');
- {$ENDIF}
- ThrowTux.X := (BG.Width div 2) - (ThrowTux.Width div 2);
- ThrowTux.Y := Edit1.Top - DancingTux.Height;
- ThrowTux.Visible := True;
- ThrowTux.Frame := 0;
- ThrowTux.FrameWidth := 58;
-
-
- HammerPic := TSprite.Create(nil);
- {$IFDEF Linux}
- HammerPic.LoadFromFile('/usr/share/tappytux/sprites/hammer.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- HammerPic.loadFromFile('c:\program files\tappytux\sprites\hammer.xpm');
- {$ENDIF}
- HammerPic.X := DancingTux.X - 30;
- HammerPic.Y := DancingTux.Y;
- HammerPic.Visible := False;
- HammerPic.Frame := 0;
- HammerPic.FrameWidth := 41;
-
- Boom := TSprite.Create(nil);
- {$IFDEF Linux}
- Boom.LoadFromFile('/usr/share/tappytux/sprites/crash.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- Boom.loadFromFile('c:\program files\tappytux\sprites\crash.xpm');
- {$ENDIF}
- Boom.X := DancingTux.X - 30;
- Boom.Y := DancingTux.Y;
- Boom.Visible := True;
- Boom.Frame := 0;
- Boom.FrameWidth := 208;
-
- Splash := TSprite.Create(nil);
- {$IFDEF Linux}
- Splash.LoadFromFile('/usr/share/tappytux/sprites/splash.xpm');
- {$ENDIF}
- {$IFDEF Win32}
- Splash.loadFromFile('c:\program files\tappytux\sprites\splash.xpm');
- {$ENDIF}
- Splash.X := DancingTux.X - 30;
- Splash.Y := BG.Height - DancingTux.Height;
- Splash.Visible := True;
- Splash.Frame := 0;
- Splash.FrameWidth := 198;
-
-end;
-end;
-
-procedure startGame;
-Begin
-With Form1 Do
-begin
- ThisGame.Create;
- LoadSnowMen;
- SnowManTimer.Enabled := True;
- HammerTimer.Enabled := True;
- BlitSnowMen;
- UpdateScoreBoard;
-End;
-end;
-
-
-procedure TForm1.FormCreate(Sender: TObject);
-
-begin
-{$IFDEF Linux}
-// EsdSound1.Enabled := True;
-{$ENDIF}
-ThisGame.QuestionList := TStringList.Create;
-randomize;
- SchroedingersCat := False;
-ScreenSize1.GetScreenSize;
-If (ScreenSize1.X = 640) or (paramcount <> 0) then
-begin
- {$IFDEF Linux}
- BG.LoadFromFile('/usr/share/tappytux/levels/levelp.jpg');
- {$ENDIF}
- {$IFDEF Win32}
- BG.LoadFromFile('c:\program files\tappytux\levels\levelp.jpg');
- {$ENDIF}
- Scale := 640;
- Form1.Width := BG.Width + Image1.Width;
- Form1.Height := BG.Height + Edit1.Height;
- SnowManTimer.Interval := 200;
- HammerTimer.Interval := 180;
-end;
-if paramcount = 0 then
-begin
-If ScreenSize1.X = 800 then
-Begin
- Scale := 800;
- {$IFDEF Linux}
- BG.LoadFromFile('/usr/share/tappytux/levels/800/levelp.jpg');
- {$ENDIF}
- {$IFDEF Win32}
- BG.LoadFromFile('c:\program files\tappytux\levels\800\levelp.jpg');
- {$ENDIF}
- Form1.Width := BG.Width + Image1.Width;
- Form1.Height := BG.Height + Edit1.Height;
- SnowManTimer.Interval := 150;
- HammerTimer.Interval := 100;
-end;
-If ScreenSize1.X >= 1024 then
-Begin
- Scale := 1024;
- {$IFDEF Linux}
- BG.LoadFromFile('/usr/share/tappytux/levels/1024/levelp.jpg');
- {$ENDIF}
- {$IFDEF Win32}
- BG.LoadFromFile('c:\program files\tappytux\levels\1024\levelp.jpg');
- {$ENDIF}
- Form1.Width := BG.Width + Image1.Width;
- Form1.Height := BG.Height + Edit1.Height;
- SnowManTimer.Interval := 100;
- HammerTimer.Interval := 80;
-End;
-end;
- Hammer.Count := 0;
- InitSprites;
-end;
-
-procedure TForm1.FormResize(Sender: TObject);
-begin
- Form1.Width := BG.Width + Image1.Width;
- Form1.Height := BG.Height + Edit1.Height;
-
-end;
-
-procedure TForm1.FormShow(Sender: TObject);
-Var
- BTNFont : TFont;
-begin
- BTNFont := TFont.Create;
- BTNFont.Color := ClPurple;
- BTNFont.Size := 47;
- BTNFont.Name := 'TeachersPet';
- BTNFont.Style := [FSBold];
- Edit1.Font.Assign(BTNFont);
-
-GameOver := False;
-edit1.SetFocus;
- Form2.ShowModal;
- if not DoLoad then
- Application.Terminate
- else
- Begin
- {$IFDEF Linux}
- Play('/usr/share/tappytux/sounds/startup.wav');
- {$ENDIF}
- if ThisGame.SndMusic then
- begin
- Music := TSong.Create(false);
- if Assigned(Music.FatalException) then
- raise Music.FatalException;
- Music.Resume;
- end;
- {$IFDEF Linux}
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/gameover.wav','gameover');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/level_up.wav','levelup');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/missed_word.wav','missed');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/ready.wav','ready');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_hit.wav','hit');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_error.wav','error');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_match.wav','match');
- ESDSound1.CacheSample('/usr/share/tappytux/sounds/life.wav','life');
- {$ENDIF}
- Edit1.SetFocus;
- StartGame;
- end;
-end;
-
-procedure TForm1.FormWindowStateChange(Sender: TObject);
-begin
- Edit1.SetFocus;
-end;
-
-
-procedure TForm1.HammerTimerTimer(Sender: TObject);
-Var xdif,ydif : Integer;
- GoLeft: Boolean;
-
-Procedure HammerLeft;
-Begin
- if HammerPic.Frame <> 0 then
- HammerPic.Frame := 0 else
- HammerPic.Frame := 1;
-end;
-
-Procedure HammerRight;
-Begin
- if HammerPic.Frame <> 2 then
- HammerPic.Frame := 2 else
- HammerPic.Frame := 3;
-end;
-
-begin
- If Hammer.Count <> 0 then
- begin
- HammerPic.VIsible := True;
-
- BG.Mask(HammerPic);
- if HammerPic.X > SnowMan[Hammer.Target[1]].X + 30 then
- begin
- GoLeft := True;
- HammerPic.X := HammerPic.X - 20;
- end;
- if HammerPic.X < SnowMan[Hammer.Target[1]].X + 30 then
- begin
- GoLeft := False;
- HammerPic.X := HammerPic.X + 20;
-
- end;
- If GoLeft then HammerLeft else HammerRight;
-
- if HammerPic.Y < SnowMan[Hammer.Target[1]].Y + 50 then
- HammerPic.Y := HammerPic.Y + 20;
- if HammerPic.Y > SnowMan[Hammer.Target[1]].Y + 50 then
- HammerPic.Y := HammerPic.Y -20;
- BG.Blit(HammerPic);
-
- xdif := abs(SnowMan[Hammer.Target[1]].X +30 - HammerPic.X);
- ydif := abs(SnowMan[Hammer.Target[1]].Y +50- HammerPic.Y);
- If (xdif < 20) and (ydif < 50)
- then
- begin
- snowManTimer.Enabled := False;
- BoomTimer.Enabled := True;
- end;
-
- end else
- HammerPic.Visible := False;
-end;
-
-procedure TForm1.ScreenUpdateTimerTimer(Sender: TObject);
-Var I : Integer;
-begin
- bg.flip;
-end;
-
-Function SnowColor(X : Integer):Integer;
-Begin
- Case X of
- 1: SnowColor := ClRed;
- 2: SnowColor := ClBlue;
- 3: SnowColor := ClPurple;
- 4: SnowColor := ClGreen;
- 5: SnowColor := ClOlive;
- end;
-end;
-
-procedure TForm1.SnowManTimerTimer(Sender: TObject);
-Var I,J : Integer;
- Hit : Boolean;
-begin
- for I := 5 downto 1 do
- begin
- TextMask(I);
- BG.Mask(SnowMan[I]);
- Hit := False;
- for J := 0 to Hammer.Count do
- If I = Hammer.Target[J] then Hit := True;
-
- if Not Hit then
- begin
- SnowMan[I].Y := SnowMan[I].Y + (thisgame.Level div 4) +1;
-
- With BG.MemBuff.Canvas do
- begin
- Brush.Style := BsSolid;
- Brush.color := clWhite;
- Font.Size := 28;
- Font.Color := SnowColor(I);
- Font.Name := 'TeachersPet';
- {$IFDEF Win32}
- FillRect(MyRect(SnowMan[I].X +1,TextY(I),SnowMan[I].X + 99,textY(I)+ 35));
- {$ENDIF}
- {$IFDEF Linux}
- FillRect(Rect(SnowMan[I].X +1,TextY(I),SnowMan[I].X + 99,textY(I)+ 35));
- {$ENDIF}
- if Scale = 1024 then
- TextOut(SnowMan[I].X +2,TextY(I),NextQuestion[I]) else
- TextOut(SnowMan[I].X +2,TextY(I) + 3,NextQuestion[I]);
- end;
- end;
- If SnowMan[I].Y >= BG.Height then
- begin
- DanceTimer.Enabled := False;
- HammerTimer.Enabled:= false;
- SnowManTimer.Enabled := False;
- Play('missed');
-
- If SnowMan[I].X <= DancingTux.X then
- HurtTux.Frame := 0 else
- HurtTux.Frame := 1;
- DanceTimer.Enabled := False;
- BG.Mask(DancingTux);
- textMask(I);
- BG.Mask(SnowMan[I]);
- SnowMan[I].Y := -150;
- BG.Blit(HurtTux);
-
- Splash.X := SnowMan[I].X - 50;
- Splash.Y := BG.Height - Splash.Height;
- If Splash.Frame = 0 then
- Splash.Frame := 1 else
- Splash.Frame := 0;
- BG.Blit(Splash);
- // BG.Flip;
- SplashTimer.Enabled := True;
- end;
- end;
-
- BlitSnowMen;
-
-end;
-
-
-
-procedure TForm1.SplashTimerTimer(Sender: TObject);
-begin
- ThisGame.LoseLife;
- BG.Load;
- BG.Mask(Splash);
- BG.Mask(HurtTux);
- BG.Blit(DancingTux);
- //BG.Flip;
- DanceTimer.Enabled := True;
- SnowManTimer.Enabled := True;
- HammerTimer.Enabled := True;
- SplashTimer.Enabled := False;
- UpdateScoreBoard;
- if StrToInt(Edit4.Text) <> ThisGame.Lives then
- begin
- Edit4.Text := IntToStr(ThisGame.Lives);
- play ('life');
- end;
- If ThisGame.Lives = 0 then
- begin
- GameOver := True;
- PauseGame;
- Form4.ShowModal;
- If Form4.ModalResult = MrYes then
- begin
- GameOver := False;
- ThisGame.Create;
- Edit3.Text := '0';
- ThisGame.Score := 0;
- ThisGame.Level := 1;
- Edit2.Text := '1';
- Form2.ShowModal;
- InitSnowMen;
- UnPauseGame;
- end else
- Form1.Close;
- end;
-end;
-
-procedure TForm1.ThrowTimerStartTimer(Sender: TObject);
-begin
- DanceTimer.Enabled := False;
- BG.Mask(DancingTux);
- BG.Blit(ThrowTux);
- // BG.Flip;
-end;
-
-procedure TForm1.ThrowTimerTimer(Sender: TObject);
-begin
- BG.Mask(ThrowTux);
- BG.Blit(DancingTux);
- DanceTimer.Enabled := True;
- ThrowTimer.Enabled := False;
-end;
-
-initialization
- {$I unit1.lrs}
-
-end.
-
+unit unit1;
+
+{$mode objfpc}{$H+}
+
+interface
+
+uses
+ Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,unit2,
+ doublebuffer, StdCtrls, ExtCtrls, Buttons, Sprite, GameData,
+ unit3, unit4, screensize, util, esdsound
+ {$IFDEF UNIX}
+ ,oldlinux
+ {$ENDIF}
+ {$IFDEF Win32}
+ ,Windows,ShellAPI
+ {$ENDIF}
+ ;
+
+type
+
+ { TForm1 }
+
+ TForm1 = class(TForm)
+ BitBtn1: TBitBtn;
+ BG: TDoubleBuffer;
+ Button1: TButton;
+ Edit1: TEdit;
+ Edit2: TEdit;
+ Edit3: TEdit;
+ Edit4: TEdit;
+ ESDSound1: TESDSound;
+ Image1: TImage;
+ DanceTimer: TTimer;
+ Label1: TLabel;
+ ScreenSize1: TScreenSize;
+ SnowManTimer: TTimer;
+ ScreenUpdateTimer: TTimer;
+ HammerTimer: TTimer;
+ BoomTimer: TTimer;
+ SplashTimer: TTimer;
+ ThrowTimer: TTimer;
+ procedure BitBtn1Click(Sender: TObject);
+ procedure BoomTimerStartTimer(Sender: TObject);
+ procedure BoomTimerTimer(Sender: TObject);
+ procedure Button1Click(Sender: TObject);
+ procedure DanceTimerTimer(Sender: TObject);
+ procedure Edit1KeyPress(Sender: TObject; var Key: char);
+ procedure Edit2Enter(Sender: TObject);
+ procedure FormActivate(Sender: TObject);
+ procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
+ procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
+ procedure FormCreate(Sender: TObject);
+ procedure FormResize(Sender: TObject);
+ procedure FormShow(Sender: TObject);
+ procedure FormWindowStateChange(Sender: TObject);
+ procedure HammerTimerTimer(Sender: TObject);
+ procedure ScreenUpdateTimerTimer(Sender: TObject);
+ procedure SnowManTimerTimer(Sender: TObject);
+ procedure SplashTimerTimer(Sender: TObject);
+ procedure ThrowTimerStartTimer(Sender: TObject);
+ procedure ThrowTimerTimer(Sender: TObject);
+ private
+ { private declarations }
+ public
+ { public declarations }
+ end;
+
+
+
+var
+ Music: TSong;
+ Form1: TForm1;
+ SnowMan: Array[1..5] of TSprite;
+ NextQuestion: Array[1..5] Of String;
+ Hammer: HammerQue;
+ HammerPic: Tsprite;
+ Boom: TSprite;
+ Splash: TSprite;
+ DancingTux: TSprite;
+ HurtTux: TSprite;
+ ThrowTux: TSprite;
+ GameOver: Boolean;
+
+implementation
+
+{ TForm1 }
+
+
+Procedure Play(Name : String);
+Begin
+ If ThisGame.SNDFX then Form1.esdSound1.Play(Name);
+end;
+
+
+Procedure ThrowHammer(GoLeft:Boolean);
+Begin
+ With Form1 do
+ begin
+ If GoLeft then
+ begin
+ ThrowTux.Frame := 0;
+ HammerPic.X := ThrowTux.X - HammerPic.FrameWidth;
+ HammerPic.Y := ThrowTux.Y;
+ end else
+ begin
+ ThrowTux.Frame := 1;
+ HammerPic.X := ThrowTux.X + ThrowTux.FrameWidth;
+ HammerPic.Y := ThrowTux.Y;
+ end;
+ ThrowTimer.Enabled := True;
+ end;
+end;
+
+Function textY(I:Integer):Integer;
+Begin
+ TextY := SnowMan[I].Y - 35;
+end;
+
+//Why larry why is this different between platforms ?
+{$IFDEF Win32}
+function MyRect(X,Y,A,B:Integer):Rect;
+Var
+ Z : Rect;
+Begin
+ Z.Top := Y;
+ Z.Left := X;
+ Z.Right := A;
+ Z.Bottom := B;
+ MyRect := Z;
+end;
+{$ENDIF}
+
+procedure textMask(I :Integer);
+Begin
+ With Form1 do
+ begin
+{$IFDEF Win32}
+ BG.MemBuff.Canvas.CopyRect(MyRect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35),
+ BG.BackGround.BitMap.Canvas,MyRect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35));
+{$ENDIF}
+{$IFDEF Linux}
+ BG.MemBuff.Canvas.CopyRect(Rect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35),
+ BG.BackGround.BitMap.Canvas,Rect(SnowMan[I].X +1,textY(I),SnowMan[I].X + 99,textY(I)+35));
+{$ENDIF}
+ end;
+end;
+
+
+procedure updateScoreboard;
+Begin
+With Form1 do
+Begin
+ Edit2.Text := intToStr(ThisGame.Level);
+ Edit3.Text := intToStr(ThisGame.Score);
+ Edit4.Text := IntToStr(ThisGame.Lives);
+ If ThisGame.Lives <=2 then
+ Form1.Caption := 'TappyTux - Warning: '+IntToStr(ThisGame.Lives)+' Left';
+
+end;
+end;
+
+procedure SnowQuestion(I:Integer);
+Var X : Integer;
+Unique : Boolean;
+begin
+ repeat
+ NextQuestion[I] := ThisGame.GetQuestion;
+ Unique := True;
+ for X := 1 to 5 do
+ if (length(NextQuestion[X]) <> 0) and (X <> I) then
+ if (thisgame.CheckAnswer(NextQuestion[X],NextQuestion[I]) <> 0) then
+ Unique := False;
+ until Unique;
+end;
+
+Procedure InitSnowMen;
+Var I,X : integer;
+ Unique: Boolean;
+Begin
+
+ For I := 1 to 5 do
+ SnowQuestion(I);
+
+ for I := 1 to 5 do
+ repeat
+ Unique := True;
+ for X := 1 to 5 do
+ SnowMan[I].Y := 50 - (random(3000) div 10);
+ if (SnowMan[I].Y = SnowMan[X].Y) And (I <> X) then
+ Unique := False;
+ until Unique;
+end;
+
+procedure LoadSnowMen;
+var
+ I, X, Y: integer;
+begin
+ case Scale of
+ 640: Y := 100;
+ 800: Y := 130;
+ 1024:Y := 180;
+ end;
+
+ For I := 1 to random(30) do X := random(100);
+
+ for I := 5 downto 1 do
+ begin
+ SnowMan[I] := TSprite.Create(nil);
+
+ SnowMan[I].loadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'snowmen.xpm');
+
+ SnowMan[I].FrameWidth := 94;
+ SnowMan[I].Frame := I -1;
+ SnowMan[I].X := 10+((I -1) * Y);
+ end;
+
+ InitSnowMen;
+end;
+
+Procedure BlitSnowMen;
+Var I : Integer;
+Begin
+ For I := 5 downto 1 do
+ With form1 do
+ begin
+ BG.Mask(SnowMan[I]);
+ BG.Blit(SnowMan[I]);
+ end;
+end;
+
+
+procedure TForm1.BitBtn1Click(Sender: TObject);
+Var
+ Browser : String;
+begin
+{$IFDEF Linux}
+Browser := 'none';
+if shell('if which mozilla ; then exit 0 ; else exit 1 ; fi') = 0 then
+ Browser := 'mozilla';
+if shell('if which konqueror ; then exit 0 ; else exit 1 ; fi') = 0 then
+ Browser := 'konqueror';
+if shell('if which opera ; then exit 0 ; else exit 1 ; fi') = 0 then
+ Browser := 'opera';
+if shell('if which firefox ; then exit 0 ; else exit 1 ; fi') = 0 then
+ Browser := 'firefox';
+Writeln(browser);
+if browser <> 'none' then
+ shell(browser+' "http://www.getopenlab.com"&');
+{$ENDIF}
+{$IFDEF Win32}
+ ShellExecute(Handle,'open','http://www.getopenlab.com', nil, nil, SW_SHOWNORMAL);
+{$ENDIF}
+
+end;
+
+procedure TForm1.BoomTimerStartTimer(Sender: TObject);
+begin
+HammerTimer.Enabled := False;
+ SnowManTimer.Enabled := True;
+ Play('hit');
+ Boom.X := SnowMan[Hammer.Target[1]].X - 20;
+ Boom.Y := SnowMan[Hammer.Target[1]].Y - 20;
+ BG.Mask(SnowMan[Hammer.Target[1]]);
+ BG.Mask(HammerPic);
+
+ SnowMan[Hammer.Target[1]].Y := -150;
+ BG.Blit(Boom);
+ // BG.Flip;
+
+end;
+
+procedure TForm1.BoomTimerTimer(Sender: TObject);
+
+begin
+
+ BG.Mask(Boom);
+ SnowQuestion(Hammer.Target[1]);
+ BoomTimer.Enabled := False;
+ Hammer.DelTarget;
+ If Hammer.Count <> 0 then
+ begin
+ If SnowMan[Hammer.Target[1]].X <= DancingTux.X then
+ ThrowHammer(True) else
+ ThrowHammer(False);
+ end;
+ BG.Mask(HammerPic);
+SnowManTimer.Enabled := True;
+ BG.Mask(HammerPic);
+ HammerTimer.Enabled := True;
+end;
+
+Procedure PauseGame;
+Begin
+With Form1 do
+begin
+ HammerTimer.Enabled := False;
+ SnowManTimer.Enabled := False;
+ Button1.Caption := 'Play';
+ Form1.Caption := 'TappyTux - PAUSED';
+end;
+end;
+
+Procedure UnPauseGame;
+Begin
+With Form1 do
+begin
+ Edit1.SetFocus;
+ HammerTimer.Enabled := True;
+ SnowManTimer.Enabled := True;
+ Button1.Caption := 'Pause';
+ Form1.Caption := 'TappyTux';
+end;
+end;
+
+
+procedure TForm1.Button1Click(Sender: TObject);
+begin
+If Button1.Caption = 'Pause' then
+PauseGame
+else
+UnPauseGame;
+end;
+
+
+
+procedure TForm1.DanceTimerTimer(Sender: TObject);
+begin
+ if DancingTux.Frame = 0 then
+ DancingTux.Frame := 1 else
+ DancingTux.Frame := 0;
+
+BG.Mask(DancingTux);
+BG.Blit(Dancingtux);
+{BG.Flip; }
+end;
+
+
+
+procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: char);
+Var I,Y : Integer;
+ Gotcha : Boolean;
+begin
+ Edit1.Font.Color := ClBlack;
+ If Key = #13 then
+ begin
+ Gotcha := False;
+ For I := 1 to 5 do
+ begin
+ Y := ThisGame.CheckAnswer(NextQuestion[I],Edit1.Text);
+ If (Y > 0) and (Hammer.AddTarget(I)) then
+ begin
+ Gotcha := True;
+ If (ThisGame.Score + Y > ThisGame.NextLevel) and
+ (ThisGame.Score > ThisGame.NextLevel)
+ then
+ Begin
+ Play('levelup');
+ BG.LoadFromFile(ThisGame.NextBG);
+ For I := 1 to 5 do
+ begin
+ BG.Mask(SnowMan[I]);
+ BG.Blit(SnowMan[I]);
+ BG.Mask(ThrowTux);
+ end;
+ BG.Blit(DancingTux);
+ end;
+ ThisGame.ScoreUp(Y);
+ If thisgame.Score > ThisGame.NextLife then
+ begin
+ play ('life');
+ ThisGame.NextLife := ThisGame.NextLife + 300;
+ inc(ThisGame.Lives);
+ end else
+ play ('match');
+ updateScoreBoard;
+ Edit1.Text := '';
+ If Hammer.Count = 1 then
+ begin
+ If SnowMan[I].X <= DancingTux.X then
+ ThrowHammer(True) else
+ ThrowHammer(False);
+ end;
+ end;
+ end;
+ if Not Gotcha then
+ begin
+ play('error');
+ edit1.Font.Color := ClRed;
+ end;
+ end;
+end;
+
+
+
+
+
+procedure TForm1.Edit2Enter(Sender: TObject);
+begin
+ Edit1.SetFocus;
+end;
+
+procedure TForm1.FormActivate(Sender: TObject);
+begin
+ Edit1.SetFocus;
+end;
+
+procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
+Var
+I : Integer;
+begin
+ ThisGame.Level := 1;
+ ThisGame.Score := 0;
+ ThisGame.Lives := 5;
+ SnowManTimer.Enabled := False;
+ ScreenUpdateTimer.Enabled := False;
+ HammerTimer.Enabled := FAlse;
+ BoomTimer.Enabled := False;
+ SplashTimer.Enabled := FAlse;
+ ThrowTimer.Enabled := False;
+If Music <> Nil then
+begin
+ Music.Terminate;
+ execute ('killall -9 ogg123');
+end;
+
+ DanceTimer.Enabled := False;
+ if ThisGame.SndMusic then
+ For I := 5 downto 1 do
+ SnowMan[I].Free;
+try
+If Music <> Nil then
+begin
+ Music.Free;
+ BG.Free;
+end;
+ ThisGame.QuestionList.Free;
+except
+ writeln ('Exiting');
+for I := 1 to 5 do
+ SnowMan[I].free;
+ DancingTux.free;
+ HurtTux.free;
+ ThrowTux.free;
+ HammerPic.free;
+ Boom.free;
+ Splash.free;
+ BG.Free;
+Application.Terminate;
+end;
+end;
+
+procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
+begin
+If Not GameOver then
+begin
+PauseGame;
+ Form3.ShowModal;
+ If Form3.ModalResult = MrYes then
+ CanClose := True
+ else
+ Begin
+ CanClose := False;
+ UnPauseGame;
+ end;
+end;
+end;
+
+Procedure InitSprites;
+Begin
+ With form1 do
+ begin
+ DancingTux := TSprite.Create(nil);
+
+ DancingTux.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'tuxfront.xpm');
+
+ DancingTux.X := (BG.Width div 2) - (DancingTux.Width div 2);
+ DancingTux.Y := BG.Height - DancingTux.Height;
+ DancingTux.Visible := True;
+ DancingTux.Frame := 0;
+ DancingTux.FrameWidth := 54;
+
+ HurtTux := TSprite.Create(nil);
+
+ HurtTux.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'hurt.xpm');
+
+ HurtTux.X := (BG.Width div 2) - (HurtTux.Width div 2);
+ HurtTux.Y := Edit1.Top - DancingTux.Height;
+ HurtTux.Visible := True;
+ HurtTux.Frame := 0;
+ HurtTux.FrameWidth := 45;
+
+ ThrowTux := TSprite.Create(nil);
+
+ ThrowTux.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'tuxside.xpm');
+
+ ThrowTux.X := (BG.Width div 2) - (ThrowTux.Width div 2);
+ ThrowTux.Y := Edit1.Top - DancingTux.Height;
+ ThrowTux.Visible := True;
+ ThrowTux.Frame := 0;
+ ThrowTux.FrameWidth := 58;
+
+
+ HammerPic := TSprite.Create(nil);
+
+ HammerPic.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'hammer.xpm');
+
+ HammerPic.X := DancingTux.X - 30;
+ HammerPic.Y := DancingTux.Y;
+ HammerPic.Visible := False;
+ HammerPic.Frame := 0;
+ HammerPic.FrameWidth := 41;
+
+ Boom := TSprite.Create(nil);
+
+ Boom.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'crash.xpm');
+
+ Boom.X := DancingTux.X - 30;
+ Boom.Y := DancingTux.Y;
+ Boom.Visible := True;
+ Boom.Frame := 0;
+ Boom.FrameWidth := 208;
+
+ Splash := TSprite.Create(nil);
+
+ Splash.LoadFromFile(TPTDir+pathdelim+'sprites'+pathdelim+'splash.xpm');
+
+ Splash.X := DancingTux.X - 30;
+ Splash.Y := BG.Height - DancingTux.Height;
+ Splash.Visible := True;
+ Splash.Frame := 0;
+ Splash.FrameWidth := 198;
+ end;
+end;
+
+procedure startGame;
+Begin
+With Form1 Do
+begin
+ ThisGame.Create;
+ LoadSnowMen;
+ SnowManTimer.Enabled := True;
+ HammerTimer.Enabled := True;
+ BlitSnowMen;
+ UpdateScoreBoard;
+End;
+end;
+
+
+procedure TForm1.FormCreate(Sender: TObject);
+begin
+ // EsdSound1.Enabled := True;
+
+ ThisGame.QuestionList := TStringList.Create;
+ Randomize;
+
+ SchroedingersCat := False;
+ ScreenSize1.GetScreenSize;
+
+ if (ScreenSize1.X = 640) or (paramcount <> 0) then
+ begin
+ BG.LoadFromFile(TPTDir + pathdelim + 'levels' + pathdelim + 'levelp.jpg');
+
+ Scale := 640;
+ Form1.Width := BG.Width + Image1.Width;
+ Form1.Height := BG.Height + Edit1.Height;
+ SnowManTimer.Interval := 200;
+ HammerTimer.Interval := 180;
+ end;
+
+ if paramcount = 0 then
+ begin
+ If ScreenSize1.X = 800 then
+ Begin
+ Scale := 800;
+
+ BG.LoadFromFile(TPTDir + pathdelim + 'levels' + pathdelim + '800' + pathdelim + 'levelp.jpg');
+
+ Form1.Width := BG.Width + Image1.Width;
+ Form1.Height := BG.Height + Edit1.Height;
+ SnowManTimer.Interval := 150;
+ HammerTimer.Interval := 100;
+ end;
+ if ScreenSize1.X >= 1024 then
+ begin
+ Scale := 1024;
+ BG.LoadFromFile(TPTDir + pathdelim + 'levels' + pathdelim + '1024' + pathdelim + 'levelp.jpg');
+
+ Form1.Width := BG.Width + Image1.Width;
+ Form1.Height := BG.Height + Edit1.Height;
+ SnowManTimer.Interval := 100;
+ HammerTimer.Interval := 80;
+ end;
+ end;
+ Hammer.Count := 0;
+ InitSprites;
+end;
+
+procedure TForm1.FormResize(Sender: TObject);
+begin
+ Form1.Width := BG.Width + Image1.Width;
+ Form1.Height := BG.Height + Edit1.Height;
+
+end;
+
+procedure TForm1.FormShow(Sender: TObject);
+Var
+ BTNFont : TFont;
+begin
+ BTNFont := TFont.Create;
+ BTNFont.Color := ClPurple;
+ BTNFont.Size := 47;
+ BTNFont.Name := 'TeachersPet';
+ BTNFont.Style := [FSBold];
+ Edit1.Font.Assign(BTNFont);
+
+ GameOver := False;
+ edit1.SetFocus;
+ Form2.ShowModal;
+
+ if not DoLoad then
+ Application.Terminate
+ else
+ begin
+ Play('/usr/share/tappytux/sounds/startup.wav');
+
+ if ThisGame.SndMusic then
+ begin
+ Music := TSong.Create(false);
+ if Assigned(Music.FatalException) then
+ raise Music.FatalException;
+ Music.Resume;
+ end;
+
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/gameover.wav','gameover');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/level_up.wav','levelup');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/missed_word.wav','missed');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/ready.wav','ready');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_hit.wav','hit');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_error.wav','error');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/word_match.wav','match');
+ ESDSound1.CacheSample('/usr/share/tappytux/sounds/life.wav','life');
+
+ Edit1.SetFocus;
+ StartGame;
+ end;
+end;
+
+procedure TForm1.FormWindowStateChange(Sender: TObject);
+begin
+ Edit1.SetFocus;
+end;
+
+
+procedure TForm1.HammerTimerTimer(Sender: TObject);
+var xdif,ydif : Integer;
+ GoLeft: Boolean;
+
+Procedure HammerLeft;
+Begin
+ if HammerPic.Frame <> 0 then
+ HammerPic.Frame := 0 else
+ HammerPic.Frame := 1;
+end;
+
+Procedure HammerRight;
+Begin
+ if HammerPic.Frame <> 2 then
+ HammerPic.Frame := 2 else
+ HammerPic.Frame := 3;
+end;
+
+begin
+ If Hammer.Count <> 0 then
+ begin
+ HammerPic.VIsible := True;
+
+ BG.Mask(HammerPic);
+ if HammerPic.X > SnowMan[Hammer.Target[1]].X + 30 then
+ begin
+ GoLeft := True;
+ HammerPic.X := HammerPic.X - 20;
+ end;
+ if HammerPic.X < SnowMan[Hammer.Target[1]].X + 30 then
+ begin
+ GoLeft := False;
+ HammerPic.X := HammerPic.X + 20;
+
+ end;
+ If GoLeft then HammerLeft else HammerRight;
+
+ if HammerPic.Y < SnowMan[Hammer.Target[1]].Y + 50 then
+ HammerPic.Y := HammerPic.Y + 20;
+ if HammerPic.Y > SnowMan[Hammer.Target[1]].Y + 50 then
+ HammerPic.Y := HammerPic.Y -20;
+ BG.Blit(HammerPic);
+
+ xdif := abs(SnowMan[Hammer.Target[1]].X +30 - HammerPic.X);
+ ydif := abs(SnowMan[Hammer.Target[1]].Y +50- HammerPic.Y);
+ If (xdif < 20) and (ydif < 50)
+ then
+ begin
+ snowManTimer.Enabled := False;
+ BoomTimer.Enabled := True;
+ end;
+
+ end else
+ HammerPic.Visible := False;
+end;
+
+procedure TForm1.ScreenUpdateTimerTimer(Sender: TObject);
+Var I : Integer;
+begin
+ bg.flip;
+end;
+
+Function SnowColor(X : Integer):Integer;
+Begin
+ Case X of
+ 1: SnowColor := ClRed;
+ 2: SnowColor := ClBlue;
+ 3: SnowColor := ClPurple;
+ 4: SnowColor := ClGreen;
+ 5: SnowColor := ClOlive;
+ end;
+end;
+
+procedure TForm1.SnowManTimerTimer(Sender: TObject);
+Var I,J : Integer;
+ Hit : Boolean;
+begin
+ for I := 5 downto 1 do
+ begin
+ TextMask(I);
+ BG.Mask(SnowMan[I]);
+ Hit := False;
+ for J := 0 to Hammer.Count do
+ If I = Hammer.Target[J] then Hit := True;
+
+ if Not Hit then
+ begin
+ SnowMan[I].Y := SnowMan[I].Y + (thisgame.Level div 4) +1;
+
+ With BG.MemBuff.Canvas do
+ begin
+ Brush.Style := BsSolid;
+ Brush.color := clWhite;
+ Font.Size := 28;
+ Font.Color := SnowColor(I);
+ Font.Name := 'TeachersPet';
+ {$IFDEF Win32}
+ FillRect(MyRect(SnowMan[I].X +1,TextY(I),SnowMan[I].X + 99,textY(I)+ 35));
+ {$ENDIF}
+ {$IFDEF Linux}
+ FillRect(Rect(SnowMan[I].X +1,TextY(I),SnowMan[I].X + 99,textY(I)+ 35));
+ {$ENDIF}
+ if Scale = 1024 then
+ TextOut(SnowMan[I].X +2,TextY(I),NextQuestion[I]) else
+ TextOut(SnowMan[I].X +2,TextY(I) + 3,NextQuestion[I]);
+ end;
+ end;
+ If SnowMan[I].Y >= BG.Height then
+ begin
+ DanceTimer.Enabled := False;
+ HammerTimer.Enabled:= false;
+ SnowManTimer.Enabled := False;
+ Play('missed');
+
+ If SnowMan[I].X <= DancingTux.X then
+ HurtTux.Frame := 0 else
+ HurtTux.Frame := 1;
+ DanceTimer.Enabled := False;
+ BG.Mask(DancingTux);
+ textMask(I);
+ BG.Mask(SnowMan[I]);
+ SnowMan[I].Y := -150;
+ BG.Blit(HurtTux);
+
+ Splash.X := SnowMan[I].X - 50;
+ Splash.Y := BG.Height - Splash.Height;
+ If Splash.Frame = 0 then
+ Splash.Frame := 1 else
+ Splash.Frame := 0;
+ BG.Blit(Splash);
+ // BG.Flip;
+ SplashTimer.Enabled := True;
+ end;
+ end;
+
+ BlitSnowMen;
+
+end;
+
+
+
+procedure TForm1.SplashTimerTimer(Sender: TObject);
+begin
+ ThisGame.LoseLife;
+ BG.Load;
+ BG.Mask(Splash);
+ BG.Mask(HurtTux);
+ BG.Blit(DancingTux);
+ //BG.Flip;
+ DanceTimer.Enabled := True;
+ SnowManTimer.Enabled := True;
+ HammerTimer.Enabled := True;
+ SplashTimer.Enabled := False;
+ UpdateScoreBoard;
+ if StrToInt(Edit4.Text) <> ThisGame.Lives then
+ begin
+ Edit4.Text := IntToStr(ThisGame.Lives);
+ play ('life');
+ end;
+ If ThisGame.Lives = 0 then
+ begin
+ GameOver := True;
+ PauseGame;
+ Form4.ShowModal;
+ If Form4.ModalResult = MrYes then
+ begin
+ GameOver := False;
+ ThisGame.Create;
+ Edit3.Text := '0';
+ ThisGame.Score := 0;
+ ThisGame.Level := 1;
+ Edit2.Text := '1';
+ Form2.ShowModal;
+ InitSnowMen;
+ UnPauseGame;
+ end else
+ Form1.Close;
+ end;
+end;
+
+procedure TForm1.ThrowTimerStartTimer(Sender: TObject);
+begin
+ DanceTimer.Enabled := False;
+ BG.Mask(DancingTux);
+ BG.Blit(ThrowTux);
+ // BG.Flip;
+end;
+
+procedure TForm1.ThrowTimerTimer(Sender: TObject);
+begin
+ BG.Mask(ThrowTux);
+ BG.Blit(DancingTux);
+ DanceTimer.Enabled := True;
+ ThrowTimer.Enabled := False;
+end;
+
+initialization
+ {$I unit1.lrs}
+
+end.
+
Index: unit2.pas
===================================================================
--- unit2.pas (revision 67)
+++ unit2.pas (working copy)
@@ -1,328 +1,334 @@
-unit Unit2;
-
-{$mode objfpc}{$H+}
-
-interface
-
-uses
- Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons,gamedata,
- StdCtrls, ExtCtrls,util,tappywords
- {$IFDEF Linux}
- ,oldlinux
- {$ENDIF}
- ;
-
-type
-
- { TForm2 }
-
- TForm2 = class(TForm)
- Button1: TButton;
- Button2: TButton;
- ComboBox1: TComboBox;
- ComboBox2: TComboBox;
- ComboBox3: TComboBox;
- GroupBox5: TGroupBox;
- Image1: TImage;
- ListBox1: TListBox;
- Memo1: TMemo;
- Memo2: TMemo;
- sndfx: TComboBox;
- GroupBox1: TGroupBox;
- GroupBox2: TGroupBox;
- GroupBox3: TGroupBox;
- GroupBox4: TGroupBox;
- Label1: TLabel;
- Label2: TLabel;
- Label3: TLabel;
- procedure Button1Click(Sender: TObject);
- procedure Button2Click(Sender: TObject);
- procedure ComboBox1Select(Sender: TObject);
- procedure ComboBox2Change(Sender: TObject);
- procedure ComboBox3Change(Sender: TObject);
- procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
- procedure FormCreate(Sender: TObject);
- procedure FormResize(Sender: TObject);
- procedure FormShow(Sender: TObject);
- procedure ListBox1SelectionChange(Sender: TObject; User: boolean);
- procedure sndfxChange(Sender: TObject);
- private
- { private declarations }
- public
- { public declarations }
- end;
-
-var
- Form2: TForm2;
- Extra : String;
- Config : TStringList;
- DoLoad,IsLoaded : Boolean;
-implementation
-
-{ TForm2 }
-
-procedure TForm2.Button1Click(Sender: TObject);
-var
-E : STring;
-begin
-ThisGame.Level := StrToInt(ComboBox3.Text);
-DoLoad := True;
-Config.Clear;
-If ThisGame.SNDMusic then
- Config.Add('MUSIC=1') else
- Config.Add('MUSIC=0');
-If ThisGame.SNDFX then
- Config.Add('SOUNDFX=1') else
- Config.Add('SOUNDFX=0');
-{$IFDEF Linux}
-Config.SaveToFile(getEnv('HOME')+'/.tappytux');
-{$ENDIF}
-{$IFDEF Win32}
-Config.SaveToFile('c:\program files\tappytux\tappytux.conf');
-{$ENDIF}
- IsLoaded := True;
- Form2.CLose;
-end;
-
-procedure TForm2.Button2Click(Sender: TObject);
-begin
- execute(extra+' "'+ThisGame.Option+'"');
-end;
-
-
-procedure TForm2.ComboBox1Select(Sender: TObject);
-Var Op,Ex : TStringList;
- Path : String;
-begin
-ThisGame.QuestionList.Clear;
- If Length(ComboBox1.Text) > 0 then
- try
- {$IFDEF Linux}
- Path := '/usr/share/tappytux/modules/'+ComboBox1.text;
- {$ENDIF}
- {$IFDEF Win32}
- Path := 'c:\program files\tappytux\modules\'+ComboBox1.text;
- {$ENDIF}
- Memo1.Lines.LoadFromFile(Path+PathDelim+'description.txt');
-
- If ComboBox1.text <> 'tappywords' then
- begin
- execute (PAth+PathDelim+ComboBox1.text+' --options',Op);
- execute (PAth+PathDelim+ComboBox1.text+' --extra',Ex);
- end else
- begin
- options(op);
- tappyextra(ex);
- end;
-
- If Ex.Count = 2 then
- begin
- Button2.Visible := True;
- Button2.Caption := Ex[0];
- Extra := Ex[1];
- end else
- begin
- Button2.Visible := False;
- Button2.Caption := 'Add/Edit';
- end;
-
- GroupBox2.Caption := Op[0];
- Op.Delete(0);
- ListBox1.Items.Assign(Op);
- If ListBox1.ItemIndex = -1 then
- Button1.Enabled := False;
- If ComboBox1.text <> 'tappywords' then
- {$IFDEF Linux}
- ThisGame.ModuleName := '/usr/share/tappytux/modules/'+ComboBox1.Text+'/'+ComboBox1.Text
- {$ENDIF}
- {$IFDEF Win32}
- ThisGame.ModuleName := 'c:\program files\tappytux\modules\'+ComboBox1.Text+'\'+ComboBox1.Text+'.exe'
- {$ENDIF}
- else
- ThisGame.ModuleName := 'tappywords';
- except
- writeln ('except');
- end;
-end;
-
-procedure TForm2.ComboBox2Change(Sender: TObject);
-begin
- If ComboBox2.Text = 'On' then
- ThisGame.SNDMusic := True
- else
- ThisGame.SNDMusic := False;
-end;
-
-procedure TForm2.ComboBox3Change(Sender: TObject);
-begin
-ThisGame.QuestionList.Clear;
-If length(ComboBox3.Text) > 0 then
-Begin
- ThisGame.Level := StrToInt(ComboBox3.Text);
- ThisGame.Score := StrToInt(ComboBox3.Text) * 100;
- ThisGame.NextLevel := ThisGame.Score + 100;
- ThisGame.NextLife := ThisGame.Score + 325;
-end;
-end;
-
-
-
-
-procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: boolean);
-begin
- If not IsLoaded then Application.Terminate;
-end;
-
-
-
-
-procedure TForm2.FormCreate(Sender: TObject);
-Var S : TSTringList;
- St,Sa:String;
- I,V : Integer;
-begin
- DoLoad := False;
- {$IFDEF Linux}
- if not SearchFiles(S,'/usr/share/tappytux/modules/','*','') then
- {$ENDIF}
- {$IFDEF Win32}
- if not SearchFiles(S,'c:\program files\tappytux\modules\','*','') then
- {$ENDIF}
- begin
- ShowMessage('Installation Error - no modules found');
- application.Terminate;
- end;
- For I := 0 to S.Count -1 do
- begin
- St := ExtractFilePath(S[I]);
- Delete(St,Length(St),Length(St));
- While (pos('\',ST) <>0) do
- Delete(ST,1,pos('\',ST));
- While (pos('/',ST) <>0) do
- Delete(ST,1,pos('/',ST));
- If Combobox1.Items.IndexOf(St) = -1 then
- ComboBox1.Items.Add(St);
- end;
- ThisGame.SNDFX := True;
- ThisGame.SNDMusic := True;
- ThisGame.Option := '';
- ThisGame.Level := 1;
- ComboBox3.Text := '1';
- ThisGame.QuestionList := TStringList.Create;
- Config := TStringList.Create;
-{$IFDEF Linux}
-If FileExists(getEnv('HOME')+'/.tappytux') then
-{$ENDIF}
-{$IFDEF Win32}
-If FileExists('c:\program files\tappytux\tappytux.conf') then
-{$ENDIF}
- Begin
-{$IFDEF Linux}
-Config.LoadFromFile(getEnv('HOME')+'/.tappytux');
-{$ENDIF}
-{$IFDEF Win32}
-Config.LoadFromFile('c:\program files\tappytux\tappytux.conf');
-{$ENDIF}
- For I := 0 to Config.Count -1 do
- begin
- if pos('MUSIC',Config[I]) <> 0 then
- begin
- V := strToInt(Copy(Config[I],pos('=',Config[I])+1,length(Config[I])));
- if V <> 0 then
- Begin
- ComboBox2.Text := 'On';
- ThisGame.SNDMusic := True;
- end else
- begin
- ComboBox2.Text := 'Off';
- ThisGame.SNDMusic := False;
- end;
- end;
- if pos('SOUNDFX',Config[I]) <> 0 then
- begin
- V := strToInt(Copy(Config[I],pos('=',Config[I])+1,length(Config[I])));
- if V <> 0 then
- Begin
- SNDFX.Text := 'On';
- ThisGame.SndFX := True;
- end else
- begin
- SNDFX.Text := 'Off';
- ThisGame.SndFX := False;
- end;
- end;
- end;
-end;
-end;
-
-
-
-procedure TForm2.FormResize(Sender: TObject);
-begin
- Form2.Width := 583;
- Form2.Height := 400;
-end;
-
-procedure TForm2.FormShow(Sender: TObject);
-Var
- BTNFont : TFont;
-begin
- Memo2.Left := 6;
- Memo2.Top := 0;
- Memo2.Width := 172;
- Memo2.Height := 160;
- {$IFDEF Linux}
- Memo2.Lines.LoadFromFile('/usr/share/tappytux/CREDITS');
- {$ENDIF}
- {$IFDEF Win32}
- Memo2.Lines.LoadFromFile('c:\program files\tappytux\CREDITS');
- {$ENDIF}
-
- BTNFont := TFont.Create;
- BTNFont.Color := ClPurple;
- BTNFont.Size := 20;
- BTNFont.Name := 'TeachersPet';
- BTNFont.Style := [FSBold];
- Button1.Font.Assign(BTNFont);
- BTNFont.FRee;
- ComboBox3.Text := '1';
- ComboBox1.Text := Combobox1.Items[0];
- ComboBox1Select(Form2);
- Button1.Invalidate;
- IsLoaded := False;
- Memo1.Top := 9;
- Memo1.Left := 6;
- Memo1.Width := 360;
- Memo1.Height := 136;
-end;
-
-procedure TForm2.ListBox1SelectionChange(Sender: TObject; User: boolean);
-begin
-ThisGame.QuestionList.Clear;
-If (ListBox1.ItemIndex <> -1) AND (length(combobox1.Text) > 0 ) then
-begin
- ThisGame.Option := ListBox1.Items[Listbox1.ItemIndex];
- Button1.Enabled := True;
-if Combobox1.Text = 'tappywords' then
- SetOption(ListBox1.Items[Listbox1.ItemIndex]);
- Question := TQuestion.Create(false);
- if Assigned(Question.FatalException) then
- raise Question.FatalException;
- Question.Resume;
-end else
- Button1.Enabled := False;
-end;
-
-procedure TForm2.sndfxChange(Sender: TObject);
-begin
- If SndFX.Text = 'On' then
- ThisGame.SndFX := True
- else
- ThisGame.SndFX := False;
-end;
-
-initialization
- {$I unit2.lrs}
-
-end.
-
+unit Unit2;
+
+{$mode objfpc}{$H+}
+
+interface
+
+uses
+ Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons,gamedata,
+ StdCtrls, ExtCtrls,util,tappywords
+ {$IFDEF Linux}
+ ,oldlinux
+ {$ENDIF}
+ ;
+
+type
+
+ { TForm2 }
+
+ TForm2 = class(TForm)
+ Button1: TButton;
+ Button2: TButton;
+ ComboBox1: TComboBox;
+ ComboBox2: TComboBox;
+ ComboBox3: TComboBox;
+ GroupBox5: TGroupBox;
+ Image1: TImage;
+ ListBox1: TListBox;
+ Memo1: TMemo;
+ Memo2: TMemo;
+ sndfx: TComboBox;
+ GroupBox1: TGroupBox;
+ GroupBox2: TGroupBox;
+ GroupBox3: TGroupBox;
+ GroupBox4: TGroupBox;
+ Label1: TLabel;
+ Label2: TLabel;
+ Label3: TLabel;
+ procedure Button1Click(Sender: TObject);
+ procedure Button2Click(Sender: TObject);
+ procedure ComboBox1Select(Sender: TObject);
+ procedure ComboBox2Change(Sender: TObject);
+ procedure ComboBox3Change(Sender: TObject);
+ procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
+ procedure FormCreate(Sender: TObject);
+ procedure FormResize(Sender: TObject);
+ procedure FormShow(Sender: TObject);
+ procedure ListBox1SelectionChange(Sender: TObject; User: boolean);
+ procedure sndfxChange(Sender: TObject);
+ private
+ { private declarations }
+ public
+ { public declarations }
+ end;
+
+var
+ Form2: TForm2;
+ Extra : String;
+ Config : TStringList;
+ DoLoad,IsLoaded : Boolean;
+implementation
+
+{ TForm2 }
+
+procedure TForm2.Button1Click(Sender: TObject);
+var
+ E: STring;
+begin
+ ThisGame.Level := StrToInt(ComboBox3.Text);
+ DoLoad := True;
+ Config.Clear;
+ If ThisGame.SNDMusic then Config.Add('MUSIC=1')
+ else Config.Add('MUSIC=0');
+
+ If ThisGame.SNDFX then Config.Add('SOUNDFX=1')
+ else Config.Add('SOUNDFX=0');
+
+ {$IFDEF Linux}
+ Config.SaveToFile(getEnv('HOME')+'/.tappytux');
+ {$ENDIF}
+ {$IFDEF Win32}
+ Config.SaveToFile(TPTDir + pathdelim + 'tappytux.conf');
+ {$ENDIF}
+
+ IsLoaded := True;
+ Form2.CLose;
+end;
+
+procedure TForm2.Button2Click(Sender: TObject);
+begin
+ execute(extra+' "'+ThisGame.Option+'"');
+end;
+
+
+procedure TForm2.ComboBox1Select(Sender: TObject);
+Var
+ Op, Ex: TStringList;
+ Path: String;
+begin
+ ThisGame.QuestionList.Clear;
+
+ If Length(ComboBox1.Text) > 0 then
+ try
+
+ Path := TPTDir + pathdelim + 'modules'+pathdelim+ComboBox1.text;
+
+ Memo1.Lines.LoadFromFile(Path+PathDelim+'description.txt');
+
+ If ComboBox1.text <> 'tappywords' then
+ begin
+ execute(Path + PathDelim + ComboBox1.text
+ {$IFDEF Win32}
+ + '.exe'
+ {$ENDIF}
+ + ' --options', Op);
+
+ execute(Path + PathDelim + ComboBox1.text
+ {$IFDEF Win32}
+ + '.exe'
+ {$ENDIF}
+ + ' --extra', Ex);
+ end
+ else
+ begin
+ options(op);
+ tappyextra(ex);
+ end;
+
+ If Ex.Count = 2 then
+ begin
+ Button2.Visible := True;
+ Button2.Caption := Ex[0];
+ Extra := Ex[1];
+ end else
+ begin
+ Button2.Visible := False;
+ Button2.Caption := 'Add/Edit';
+ end;
+
+ GroupBox2.Caption := Op[0];
+ Op.Delete(0);
+ ListBox1.Items.Assign(Op);
+ If ListBox1.ItemIndex = -1 then
+ Button1.Enabled := False;
+
+ If ComboBox1.text <> 'tappywords' then
+ begin
+ ThisGame.ModuleName := TPTDir + pathdelim + 'modules'+
+ pathdelim + ComboBox1.text + pathdelim + ComboBox1.Text;
+
+ {$IFDEF Win32}
+ ThisGame.ModuleName := ThisGame.ModuleName + '.exe';
+ {$ENDIF}
+ end
+ else ThisGame.ModuleName := 'tappywords';
+
+ except
+ writeln('except');
+ end;
+end;
+
+procedure TForm2.ComboBox2Change(Sender: TObject);
+begin
+ If ComboBox2.Text = 'On' then
+ ThisGame.SNDMusic := True
+ else
+ ThisGame.SNDMusic := False;
+end;
+
+procedure TForm2.ComboBox3Change(Sender: TObject);
+begin
+ThisGame.QuestionList.Clear;
+If length(ComboBox3.Text) > 0 then
+Begin
+ ThisGame.Level := StrToInt(ComboBox3.Text);
+ ThisGame.Score := StrToInt(ComboBox3.Text) * 100;
+ ThisGame.NextLevel := ThisGame.Score + 100;
+ ThisGame.NextLife := ThisGame.Score + 325;
+end;
+end;
+
+
+
+
+procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: boolean);
+begin
+ If not IsLoaded then Application.Terminate;
+end;
+
+
+
+
+procedure TForm2.FormCreate(Sender: TObject);
+var
+ S: TSTringList;
+ St, Sa: String;
+ I, V: Integer;
+begin
+ DoLoad := False;
+
+ if not SearchFiles(S, TPTDir + pathdelim + 'modules'+pathdelim,'*','') then
+ begin
+ ShowMessage('Installation Error - no modules found');
+ application.Terminate;
+ end;
+ For I := 0 to S.Count -1 do
+ begin
+ St := ExtractFilePath(S[I]);
+ Delete(St,Length(St),Length(St));
+ While (pos('\',ST) <>0) do
+ Delete(ST,1,pos('\',ST));
+ While (pos('/',ST) <>0) do
+ Delete(ST,1,pos('/',ST));
+ If Combobox1.Items.IndexOf(St) = -1 then
+ ComboBox1.Items.Add(St);
+ end;
+ ThisGame.SNDFX := True;
+ ThisGame.SNDMusic := True;
+ ThisGame.Option := '';
+ ThisGame.Level := 1;
+ ComboBox3.Text := '1';
+ ThisGame.QuestionList := TStringList.Create;
+ Config := TStringList.Create;
+{$IFDEF Linux}
+If FileExists(getEnv('HOME')+'/.tappytux') then
+{$ENDIF}
+{$IFDEF Win32}
+If FileExists(TPTDir + pathdelim + 'tappytux.conf') then
+{$ENDIF}
+ Begin
+{$IFDEF Linux}
+Config.LoadFromFile(getEnv('HOME')+'/.tappytux');
+{$ENDIF}
+{$IFDEF Win32}
+Config.LoadFromFile(TPTDir + pathdelim + 'tappytux.conf');
+{$ENDIF}
+ For I := 0 to Config.Count -1 do
+ begin
+ if pos('MUSIC',Config[I]) <> 0 then
+ begin
+ V := strToInt(Copy(Config[I],pos('=',Config[I])+1,length(Config[I])));
+ if V <> 0 then
+ Begin
+ ComboBox2.Text := 'On';
+ ThisGame.SNDMusic := True;
+ end else
+ begin
+ ComboBox2.Text := 'Off';
+ ThisGame.SNDMusic := False;
+ end;
+ end;
+ if pos('SOUNDFX',Config[I]) <> 0 then
+ begin
+ V := strToInt(Copy(Config[I],pos('=',Config[I])+1,length(Config[I])));
+ if V <> 0 then
+ Begin
+ SNDFX.Text := 'On';
+ ThisGame.SndFX := True;
+ end else
+ begin
+ SNDFX.Text := 'Off';
+ ThisGame.SndFX := False;
+ end;
+ end;
+ end;
+end;
+end;
+
+
+
+procedure TForm2.FormResize(Sender: TObject);
+begin
+ Form2.Width := 583;
+ Form2.Height := 400;
+end;
+
+procedure TForm2.FormShow(Sender: TObject);
+var
+ BTNFont : TFont;
+begin
+ Memo2.Left := 6;
+ Memo2.Top := 0;
+ Memo2.Width := 172;
+ Memo2.Height := 160;
+
+ Memo2.Lines.LoadFromFile(TPTDir + pathdelim + 'CREDITS');
+
+ BTNFont := TFont.Create;
+ BTNFont.Color := ClPurple;
+ BTNFont.Size := 20;
+ BTNFont.Name := 'TeachersPet';
+ BTNFont.Style := [FSBold];
+ Button1.Font.Assign(BTNFont);
+ BTNFont.FRee;
+ ComboBox3.Text := '1';
+// ComboBox1.Text := Combobox1.Items[0]; // Crashes on win32
+ ComboBox1Select(Form2);
+ Button1.Invalidate;
+ IsLoaded := False;
+ Memo1.Top := 9;
+ Memo1.Left := 6;
+ Memo1.Width := 360;
+ Memo1.Height := 136;
+end;
+
+procedure TForm2.ListBox1SelectionChange(Sender: TObject; User: boolean);
+begin
+ThisGame.QuestionList.Clear;
+If (ListBox1.ItemIndex <> -1) AND (length(combobox1.Text) > 0 ) then
+begin
+ ThisGame.Option := ListBox1.Items[Listbox1.ItemIndex];
+ Button1.Enabled := True;
+if Combobox1.Text = 'tappywords' then
+ SetOption(ListBox1.Items[Listbox1.ItemIndex]);
+ Question := TQuestion.Create(false);
+ if Assigned(Question.FatalException) then
+ raise Question.FatalException;
+ Question.Resume;
+end else
+ Button1.Enabled := False;
+end;
+
+procedure TForm2.sndfxChange(Sender: TObject);
+begin
+ If SndFX.Text = 'On' then
+ ThisGame.SndFX := True
+ else
+ ThisGame.SndFX := False;
+end;
initialization
{$I unit2.lrs}
end.
|
{$MODE OBJFPC}
{$INLINE ON}
program IndependentSet;
const
InputFile = 'INDEP.INP';
OutputFile = 'INDEP.OUT';
maxN = Round(1E6);
neginf = -maxN - 1;
type
TGraph = record
f, fi, fo, fio: Integer;
end;
var
s: AnsiString;
stack: array[1..maxN] of Integer;
graph: array[1..maxN] of TGraph;
unitg: TGraph;
top: Integer;
res: Integer;
procedure Enter;
var
f: TextFile;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, s);
finally
CloseFile(f);
end;
end;
procedure Init;
begin
top := 0;
with unitg do
begin
f := 0;
fi := 1;
fo := 1;
fio := neginf;
end;
end;
function Max(x, y: Integer): Integer; inline;
begin
if x > y then Result := x else Result := y;
end;
function OS(const x, y: TGraph): TGraph;
begin
with Result do
begin
f := Max(x.f + y.f, x.fo + y.fi - 1);
fi := Max(x.fi + y.f, x.fio + y.fi - 1);
fo := Max(x.f + y.fo, x.fo + y.fio - 1);
fio := Max(x.fi + y.fo, x.fio + y.fio - 1);
end;
end;
function OP(const x, y: TGraph): TGraph;
begin
with Result do
begin
f := x.f + y.f;
fi := x.fi + y.fi - 1;
fo := x.fo + y.fo - 1;
fio := x.fio + y.fio - 2;
if fio < neginf then fio := neginf;
end;
end;
procedure Push(i: Integer); inline;
begin
Inc(top);
stack[top] := i;
end;
function Pop: Integer; inline;
begin
Result := stack[top];
Dec(top);
end;
procedure Solve;
var
i: Integer;
begin
for i := Length(s) downto 1 do
begin
case s[i] of
'g': graph[i] := unitg;
'S': graph[i] := OS(graph[pop], graph[pop]);
'P': graph[i] := OP(graph[pop], graph[pop]);
end;
Push(i);
end;
with graph[1] do
begin
res := f;
if fi > res then res := fi;
if fo > res then res := fo;
if fio > res then res := fio;
end;
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
Write(f, res);
finally
CloseFile(f);
end;
end;
begin
Enter;
Init;
Solve;
PrintResult;
end.
SPSgggPgg
|
//** Сцена выбора количества золотых монет.
unit uSceneGold;
interface
uses uScene, Graphics, uGraph, uResFont;
type
//** Сцена выбора количества золотых монет.
TSceneGold = class(TSceneCustom)
private
FBG, FF, FOkBtn, FCancelBtn: TBitmap;
FLogo: TBitmap;
FGraph: TGraph;
FFont: TResFont;
FGold: Integer;
FMsg: string;
FLeft, FTop: Integer;
procedure SetGold(const Value: Integer);
procedure SetMsg(const Value: string);
procedure KeysNum(var Key: Char);
procedure AddChar(C: string);
public
Inv: Boolean;
Num: string;
//** Конструктор.
constructor Create;
destructor Destroy; override;
procedure Ok();
procedure Cancel();
procedure Draw(); override;
function Click(Button: TMouseBtn): Boolean; override;
function KeyPress(var Key: Char): Boolean; override;
function Keys(var Key: Word): Boolean; override;
function Enum(): TSceneEnum; override;
procedure MakeBG;
property Gold: Integer read FGold write SetGold;
property Msg: string read FMsg write SetMsg;
procedure Added(); override;
procedure Removed(); override;
procedure OnTimer(Sender: TObject);
end;
var
//** Сцена выбора количества золотых монет.
SceneGold: TSceneGold;
//** Показывать или прятать курсор на сцене.
IsCursor: Boolean = False;
implementation
uses SysUtils, Types, uSCR, uUtils, uIni, uSceneMenu, uGUIBorder, uSounds, uMain,
uSceneTrade, uVars, uSaveLoad, uCommon;
{ TGoldScene }
function TSceneGold.Click(Button: TMouseBtn): Boolean;
begin
Result := True;
if IsMouseInRect(FLeft + 330, FTop + 80, FLeft + 354, FTop + 104) then Ok();
if IsMouseInRect(FLeft + 360, FTop + 80, FLeft + 384, FTop + 104) then Cancel();
end;
procedure TSceneGold.Draw;
begin
FF.Assign(FLogo);
with FF.Canvas do
begin
TextOut(FLeft + 200 - (TextWidth(Msg) div 2), FTop + 10, Msg);
if IsCursor then TextOut(FLeft + 150, FTop + 40, Num + '_') else TextOut(FLeft + 150, FTop + 40, Num);
end;
SCR.BG.Canvas.Draw(0, 0, FF);
end;
constructor TSceneGold.Create;
begin
FTop := 204;
FLeft := 200;
FGraph := TGraph.Create(Path + 'Data\Images\GUI\');
FFont := TResFont.Create;
FFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName);
FLogo := TBitmap.Create;
FBG := TBitmap.Create;
FGraph.LoadImage('BG.bmp', FBG);
FBG.Width := 400;
FBG.Height := 120;
GUIBorder.Make(FBG);
FOkBtn := TBitmap.Create;
FGraph.LoadImage('Ok.png', FOkBtn);
FCancelBtn := TBitmap.Create;
FGraph.LoadImage('Close.png', FCancelBtn);
FF := TBitmap.Create;
FF.Canvas.Font.Name := FFont.FontName;
FF.Canvas.Brush.Style := bsClear;
FF.Canvas.Font.Size := 22;
FF.Canvas.Font.Color := $006CB1C5;
end;
function TSceneGold.Keys(var Key: Word): Boolean;
begin
Result := True;
case Key of
13: Ok();
27: Cancel();
8:
begin
if (Length(Num) > 0) then
begin
Delete(Num, Length(Num), 1);
Sound.PlayClick(1);
// SCR.Display;
SceneManager.Draw();
end;
end;
end;
end;
destructor TSceneGold.Destroy;
begin
FOkBtn.Free;
FCancelBtn.Free;
FGraph.Free;
FLogo.Free;
FFont.Free;
FBG.Free;
FF.Free;
inherited;
end;
function TSceneGold.Enum: TSceneEnum;
begin
Result := scGold;
end;
procedure TSceneGold.MakeBG;
begin
FLogo.Assign(SCR.BG);
FLogo.Canvas.Draw(FLeft + 0, FTop + 0, FBG);
FLogo.Canvas.Draw(FLeft + 330, FTop + 80, FOkBtn);
FLogo.Canvas.Draw(FLeft + 360, FTop + 80, FCancelBtn);
Sound.PlayClick();
end;
procedure TSceneGold.SetGold(const Value: Integer);
begin
FGold := Value;
end;
procedure TSceneGold.SetMsg(const Value: string);
begin
FMsg := Value;
end;
procedure TSceneGold.Cancel;
begin
Gold := 0;
SceneTrade.OpenStash;
Sound.PlayClick();
end;
procedure TSceneGold.Ok;
begin
Num := Trim(Num);
if (Num = '') then
begin
Cancel();
Exit;
end;
Gold := StrToInt(Num);
case Inv of
True:
if (Gold > 0) and (Gold <= VM.GetInt('Hero.Gold')) then
begin
Sound.Play(1);
VM.Inc('Hero.Stash.Gold', Gold);
VM.Dec('Hero.Gold', Gold);
end else Sound.PlayClick();
False:
if (Gold > 0) and (Gold <= VM.GetInt('Hero.Stash.Gold')) then
begin
Sound.Play(1);
VM.Inc('Hero.Gold', Gold);
VM.Dec('Hero.Stash.Gold', Gold);
end else Sound.PlayClick();
end;
SceneTrade.OpenStash;
end;
procedure TSceneGold.AddChar(C: string);
begin
if (Length(Num) < 6) then
begin
Num := Num + C;
Sound.PlayClick(1);
end;
end;
procedure TSceneGold.KeysNum(var Key: Char);
const
Nums = '0123456789';
begin
if (Pos(Key, Nums) > 0) then AddChar(Key);
end;
function TSceneGold.KeyPress(var Key: Char): Boolean;
begin
Result := True;
KeysNum(Key);
Draw();
end;
procedure TSceneGold.Added;
begin
inherited;
fMain.AddTimerEvent(OnTimer);
end;
procedure TSceneGold.OnTimer(Sender: TObject);
begin
IsCursor := not IsCursor;
SceneManager.Draw();
end;
procedure TSceneGold.Removed;
begin
inherited;
fMain.DeleteTimerEvent(OnTimer);
end;
initialization
SceneGold := TSceneGold.Create;
finalization
SceneGold.Free;
end.
|
unit spells;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, JvExControls, JvFormWallpaper, net, ExtCtrls, JvTabBar;
type
TSkill = record
id: integer;
max: integer;
now: integer;
name: string;
descr: string;
group: integer;
end;
type
Tf_skills = class(TForm)
lb_skills: TListBox;
descr: TMemo;
cooldown: TTimer;
Tabs: TJvTabBar;
JvModernTabBarPainter1: TJvModernTabBarPainter;
procedure lb_skillsDblClick(Sender: TObject);
procedure CreateParams(var Params: TCreateParams); override;
procedure lb_skillsClick(Sender: TObject);
procedure SkillList(wrd: wrd_arr; str:str_arr);
procedure SkillTime(wrd: wrd_arr; str:str_arr);
procedure cooldownTimer(Sender: TObject);
procedure lb_skillsDrawItem(Control: TWinControl; Index: Integer;
XRect: TRect; State: TOwnerDrawState);
procedure TabsTabSelected(Sender: TObject; Item: TJvTabBarItem);
function GetCurrentSkill:TSkill;
private
skills: array of TSkill;
function GetSkill(id:integer):integer;
public
{ Public declarations }
end;
var
f_skills: Tf_skills;
implementation
uses main;
{$R *.dfm}
procedure Tf_skills.SkillList(wrd: wrd_arr; str:str_arr);
var i:integer; t:TJvTabBarItem;
begin
SetLength(skills,wrd[1]);
tabs.Tabs.BeginUpdate;
tabs.Tabs.Clear;
for i:=0 to wrd[1]-1 do
begin
skills[i].id:=wrd[i+2];
t:=tabs.FindTab(str[i*3]);
if (t=nil) then
begin
t:=TJvTabBarItem(tabs.Tabs.Add);
t.Caption:=str[i*3];
end;
skills[i].group:=t.Index;
skills[i].name:=str[i*3+1];
skills[i].descr:=str[i*3+2];
end;
lb_skills.Clear;
if (tabs.Tabs.Count>0) then
TabsTabSelected(self,tabs.SelectedTab);
tabs.Tabs.EndUpdate;
end;
function Tf_skills.GetCurrentSkill:TSkill;
var i:integer;
begin
i:=lb_skills.ItemIndex;
if (i=-1) then
exit;
result:=skills[Integer(lb_skills.Items.Objects[i])];
end;
function Tf_skills.GetSkill(id:integer):integer;
begin
for result:=0 to High(skills) do
if (skills[result].id=id) then
exit;
result:=-1;
end;
procedure Tf_skills.SkillTime(wrd: wrd_arr; str:str_arr);
var i,id:integer;
begin
for i:=0 to wrd[1] do
begin
id:=GetSkill(wrd[i*3+2]);
if (id<>-1) then
begin
skills[id].now:=wrd[i*3+3]*10;
skills[id].max:=wrd[i*3+4]*10;
end;
end;
cooldown.Enabled:=true;
lb_skills.Repaint;
end;
procedure Tf_skills.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
end;
procedure Tf_skills.lb_skillsDblClick(Sender: TObject);
begin
if (f_main.lb_guests.Count=0) then exit;
if (f_main.lb_guests.ItemIndex=-1) then
f_main.lb_guests.ItemIndex:=0;
stdsend('/skill '+inttostr(skills[Integer(lb_skills.Items.Objects[lb_skills.ItemIndex])].id));
end;
procedure Tf_skills.lb_skillsClick(Sender: TObject);
begin
descr.text:=skills[Integer(lb_skills.Items.Objects[lb_skills.ItemIndex])].descr;
end;
procedure Tf_skills.cooldownTimer(Sender: TObject);
var i:integer; b:boolean;
begin
if (Length(skills)=0) then
begin
cooldown.Enabled:=false;
end;
b:=false;
for i:=0 to High(skills) do
if (skills[i].now>0) then
begin
b:=true;
dec(skills[i].now);
end;
if (not b) then
cooldown.Enabled:=false
else
lb_skills.Refresh;
end;
procedure Tf_skills.lb_skillsDrawItem(Control: TWinControl; Index: Integer;
XRect: TRect; State: TOwnerDrawState);
var percent:integer; s:TSkill;
begin
s:=skills[Integer(lb_skills.Items.Objects[Index])];
with (Control as TListBox).Canvas do
begin
Pen.Color:=$00000000;
if (State=[odSelected]) or (State=[odSelected,odFocused]) then
Brush.Color:=$007E5950
else
Brush.Color:=$00221C1D;
FillRect(XRect);
Font.Color:=clWhite;
TextOut(XRect.Left+2,XRect.Top+2,s.name);
Rectangle(Xrect.Right-105,Xrect.Top+2,Xrect.Right-2,Xrect.Top+20);
Brush.Color:=$0000FF80;
percent:=Round((s.now/s.max)*100);
FillRect(Rect(Xrect.Right-104,Xrect.Top+3,Xrect.Right-3-percent,Xrect.Top+19));
end;
end;
procedure Tf_skills.TabsTabSelected(Sender: TObject; Item: TJvTabBarItem);
var i:integer;
begin
lb_skills.Clear;
if (Item=nil) then exit;
for i:=0 to high(skills) do
if (skills[i].group=Item.Index) then
lb_skills.AddItem(skills[i].name,TObject(i));
lb_skills.Refresh;
end;
end.
|
unit nsErrorReport;
// $Id: nsErrorReport.pas,v 1.2 2008/08/12 14:08:15 lulin Exp $
// $Log: nsErrorReport.pas,v $
// Revision 1.2 2008/08/12 14:08:15 lulin
// - не падаем в режиме отладки.
//
// Revision 1.1 2007/09/20 13:00:59 oman
// - new: Поддержка WER для Vista (cq26750)
//
interface
uses
SysUtils
;
function nsReportError(anException: Exception): Boolean;
implementation
uses
Windows
;
type
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = packed record
NextRaise: PRaiseFrame;
ExceptAddr: Pointer;
ExceptObject: TObject;
ExceptionRecord: PExceptionRecord;
end;
PExceptionPointers = ^TExceptionPointers;
EFaultRepRetVal = (
frrvOk,
frrvOkManifest,
frrvOkQueued,
frrvErr,
frrvErrNoDW,
frrvErrTimeout,
frrvLaunchDebugger,
frrvOkHeadless
);
TReportFaultFunc = function (pep: PExceptionPointers; dwMode: DWord): EFaultRepRetVal; stdcall;
function nsReportError(anException: Exception): Boolean;
var
l_DLL: THandle;
l_Func: TReportFaultFunc;
l_ExceptionPointers: TExceptionPointers;
l_Context: TContext;
begin
Result := False;
{$IfOpt D-}
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 6) and (ExceptObject = anException) then
begin
l_DLL := LoadLibrary('Faultrep.dll');
if l_DLL <> 0 then
try
l_Func := TReportFaultFunc(GetProcAddress(l_DLL, 'ReportFault'));
if Assigned(l_Func) then
begin
GetThreadContext(GetCurrentThreadId,l_Context);
l_ExceptionPointers.ContextRecord := @l_Context;
l_ExceptionPointers.ExceptionRecord := Windows.PExceptionRecord(Pointer(PRaiseFrame(RaiseList)^.ExceptionRecord));
l_Func(@l_ExceptionPointers, 0);
Result := True;
end;//Assigned(l_Func
finally
FreeLibrary(l_DLL);
end;//try..finally
end;//Win32Platform = VER_PLATFORM_WIN32_NT
{$EndIf}
end;
end.
|
{ <protocol_generator.pas>
Copyright (C) <2018> <Andrew Haines> <andrewd207@aol.com>
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1335, USA.
}
unit protocol_generator;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, wayland_xml, fgl;
type
{ TGenerator }
TSection = (sPrivateConst, sClassForward, sClasses, sTypes, sFuncs, sVars, sImplementation, sInterfacePointers, sPrivateVar, sListenerDecl, sListenerImpl, sListenerBind, sClassImpl ,sRequestandEvents, sInit, sFinalize);
TNodeList = specialize TFPGObjectList <TBaseNode>;
TGenerator = class
private
FProtocol: TProtocol;
Sections: array[TSection] of TStrings;
FImplementInterfaceVars: Boolean;
function Pascalify(AName: String): String;
function ArgToArg(AArg: TArg; APascalify: Boolean; var ANeedsWrapper: Boolean
): String;
function ArgTypeToPascalType(AType: String; AInterface: String;
APascalify: Boolean; var ANeedsWrapper: Boolean): String;
procedure ArgsToSig(Element: TBaseNode; AData: Pointer{PString});
procedure ArgTypesToInterfacePointer(Element: TBaseNode; AData: Pointer);
procedure CollectArgs(Element: TBaseNode; AData: Pointer{TArgList});
procedure CollectEntries(Element: TBaseNode; AData: Pointer);
procedure CollectEnums(Element: TBaseNode; AData: Pointer);
procedure CollectEventsForListener(Element: TBaseNode; AData: Pointer{TNodeList});
procedure DeclareInterfaceTypes(Element: TBaseNode; AData: Pointer);
procedure DeclareInterfaceVars(Element: TBaseNode; AData: Pointer);
procedure HandleInterface(Element: TInterface);
procedure GenerateListener(Element: TInterface);
procedure WriteRequestConsts(Element: TBaseNode; AData: Pointer{TInterface});
procedure WriteRequestImplmentation(Element: TBaseNode; Adata: Pointer{TInterface});
procedure WriteRequestImplmentationObjects(Element: TBaseNode; Adata: Pointer{TInterface});
procedure WriteListenerObjectMethod(Element: TInterface);
procedure WriteWaylandRequestorEventInterface(Element: TBaseNode; AData: Pointer);
public
constructor Create(AFileName: String);
procedure Generate(AUnitName: String; Strings: TStrings; ImplementInterfaceVars: Boolean = True);
end;
implementation
procedure TrimLastChar(AStrings: TStrings);
var
lLine: String;
begin
// trim the extra comma ","
lLine:=AStrings[AStrings.Count-1];
lLine:=Copy(lLine, 1, Length(lLine)-1);
AStrings[AStrings.Count-1] := lLine;
end;
{ TGenerator }
procedure TGenerator.HandleInterface(Element: TInterface);
var
lLine: String;
lInterfaceVar: String;
lRequestCount, lEventCount, lIndex: Integer;
lEventConstName: String = 'nil';
lRequestConstName: String = 'nil';
lParentClass: String;
begin
// global vars :(
DeclareInterfaceVars(Element, nil);
lInterfaceVar := Element.Name+'_interface';
case Element.Name of
'wl_display' : lParentClass:='TWlDisplayBase';
'wl_shm' : lParentClass:='TWlShmBase';
'wl_shm_pool' : lParentClass:='TWlShmPoolBase';
else
lParentClass:='TWLProxyObject';
end;
//Sections[sClassForward].Add(' T'+Pascalify(Element.Name)+'Class = class of T'+Pascalify(Element.Name)+';');
Sections[sClassForward].Add(' T'+Pascalify(Element.Name)+' = class;');
Sections[sClasses].Add('');
Sections[sClasses].Add(' T'+Pascalify(Element.Name)+' = class('+lParentClass+')');
if Element.HasRequests then
begin
Sections[sClasses].Add(' private');
Element.ForEachRequest(@WriteRequestConsts, Element);
Sections[sClasses].Add(' public');
// disable flat api and use objects instead
//Element.ForEachRequest(@WriteRequestImplmentation, Element);
Element.ForEachRequest(@WriteRequestImplmentationObjects, Element);
end;
WriteListenerObjectMethod(Element);
Sections[sClasses].Add(' end;');
// handles events
GenerateListener(Element);
if FImplementInterfaceVars then
begin
// requests
lIndex := Sections[sRequestandEvents].Count;
lRequestCount := Element.ForEachRequest(@WriteWaylandRequestorEventInterface, Element);
if lRequestCount > 0 then
begin
// get rid of comma
TrimLastChar(Sections[sRequestandEvents]);
lRequestConstName := Element.Name+'_requests';
Sections[sRequestandEvents].Insert(lIndex,
Format(' %s: array[0..%d] of Twl_message = (', [lRequestConstName, lRequestCount-1]));
Sections[sRequestandEvents].Add(' );');
lRequestConstName := '@'+lRequestConstName;
end;
//events
lIndex := Sections[sRequestandEvents].Count;
lEventCount := Element.ForEachEvent (@WriteWaylandRequestorEventInterface, Element);
if lEventCount > 0 then
begin
// get rid of comma
TrimLastChar(Sections[sRequestandEvents]);
lEventConstName:=Element.Name+'_events';
Sections[sRequestandEvents].Insert(lIndex,
Format(' %s: array[0..%d] of Twl_message = (', [lEventConstName, lEventCount-1]));
Sections[sRequestandEvents].Add(' );');
lEventConstName := '@'+lEventConstName;
end;
Sections[sInit].Add(Format(' %s.name := ''%s'';', [lInterfaceVar, Element.Name]));
Sections[sInit].Add(Format(' %s.version := %s;', [lInterfaceVar, Element.Version]));
Sections[sInit].Add(Format(' %s.method_count := %d;', [lInterfaceVar, lRequestCount]));
Sections[sInit].Add(Format(' %s.methods := %s;', [lInterfaceVar, lRequestConstName]));
Sections[sInit].Add(Format(' %s.event_count := %d;', [lInterfaceVar, lEventCount]));
Sections[sInit].Add(Format(' %s.events := %s;', [lInterfaceVar, lEventConstName]));
Sections[sInit].Add('');
end;
if Element.HasEvents then
begin
WriteLn('Interface with events: ', Element.Name);
end
else
begin
WriteLn('Interface NO events: ', Element.Name);
end;
end;
procedure TGenerator.CollectEventsForListener(Element: TBaseNode; AData: Pointer
);
var
lList: TNodeList absolute AData;
lEvent: TEvent;
begin
lEvent := TEvent.Create(nil);
lEvent.Assign(Element);
lList.Add(lEvent);
Tevent(Element).ForEachArg(@CollectArgs, AData);
end;
procedure TGenerator.DeclareInterfaceTypes(Element: TBaseNode; AData: Pointer);
begin
Sections[sTypes].Add(' P'+Element.Name+' = Pointer;');
//Sections[sTypes].Add(' P'+Element.Name+' = ^T'+Element.Name+';');
//Sections[sTypes].Add(' T'+Element.Name+' = record end;');
end;
procedure TGenerator.DeclareInterfaceVars(Element: TBaseNode; AData: Pointer);
var
lInterfaceVar, lLine: String;
begin
// global vars :(
lInterfaceVar := Element.Name+'_interface';
lLine := ' '+lInterfaceVar+': Twl_interface;';
if not FImplementInterfaceVars then
lLine+=' cvar; external;';
Sections[sVars].Add(lLine);
end;
procedure TGenerator.CollectEnums(Element: TBaseNode; AData: Pointer);
var
lList: TNodeList absolute AData;
lEnum: TEnum;
begin
lEnum := TEnum.Create(nil);
lEnum.Assign(Element);
lList.Add(lEnum);
TEnum(Element).ForEachEntry(@CollectEntries, lList);
end;
procedure TGenerator.CollectEntries(Element: TBaseNode; AData: Pointer);
var
lList: TNodeList absolute AData;
lEntry: TEntry;
begin
lEntry := TEntry.Create(nil);
lEntry.Assign(Element);
lList.Add(lEntry);
end;
procedure TGenerator.GenerateListener(Element: TInterface);
var
lTypeName, lArgs, lIntf, lValue, lName: String;
lList: TNodeList;
lNode: TBaseNode;
lEnum: TEnum;
lEntry : TEntry;
lEvent: TEvent;
lEventName: String;
lInterfaceName: String;
//lGUID: TGUID;
lInterfaceLine: String;
lWrapperLine: String;
lWrapperDecl: String;
lWrapperBind, lWrapperVar, lWrapperVarAssign, lArg, lInterface,
lInterfaceArg: String;
lNeedsWrapper: Boolean;
procedure WriteEvent;
begin
Sections[sTypes].Add(lArgs+'); cdecl;');
Sections[sListenerDecl].Add(lInterfaceLine+');');
Sections[sListenerImpl].Add(lWrapperDecl+'); cdecl;');
Sections[sListenerImpl].Add('var');
Sections[sListenerImpl].Add(lWrapperVar);
Sections[sListenerImpl].Add('begin');
Sections[sListenerImpl].Add(' if AData = nil then Exit;');
Sections[sListenerImpl].Add(lWrapperVarAssign);
//Sections[sListenerImpl].Add(' WriteLn('''+Element.Name+'.'+lEvent.Name+''');');
Sections[sListenerImpl].Add(lWrapperLine+');');
Sections[sListenerImpl].Add('end;');
Sections[sListenerImpl].Add('');
Sections[sListenerBind].Add(lWrapperBind);
lArgs:='';
end;
begin
// create type
if Element.HasEnums then
begin
Sections[sTypes].Add('const');
lList := TNodeList.Create(True);
Element.ForEachEnum(@CollectEnums, lList);
for lNode in lList do
begin
if lNode is TEnum then
lEnum := TEnum(lNode)
else
begin
lEntry := TEntry(lNode);
lValue := lEntry.Value;
if Pos('0x', lValue) = 1 then
begin
Delete(lValue, 1, 2);
lValue:='$'+ lValue;
end;
Sections[sTypes].Add(' '+UpperCase(Element.Name+'_'+lEnum.Name+'_'+lEntry.Name)+' = '+lValue +'; // '+ lEntry.Summary);
end;
end;
lList.Free;
Sections[sTypes].Add('');
Sections[sTypes].Add('type');
end;
lTypeName := Element.Name+'_listener';
//CreateGUID(lGUID);
lInterfaceName:='I'+Pascalify(Element.Name)+'Listener';
Sections[sListenerDecl].Add(' '+lInterfaceName+' = interface');
//Sections[sListenerDecl].Add(' ['''+GUIDToString(lGUID)+''']');
Sections[sListenerDecl].Add(' ['''+lInterfaceName+''']');
Sections[sPrivateVar].Add(' vIntf_'+Element.Name+'_Listener: T'+ Element.Name+'_listener;');
Sections[sTypes].Add(' P'+lTypeName+' = ^T'+lTypeName+';');
Sections[sTypes].Add(' T'+lTypeName+' = record');
lList := TNodeList.Create(True);
Element.ForEachEvent(@CollectEventsForListener, lList);
lArgs := '';
for lNode in lList do
begin
if lNode is TEvent then
begin
if lArgs <> '' then
begin
WriteEvent;
end;
lEvent := TEvent(lNode);
lEventName := lEvent.Name;
if (lEventName = 'begin')
or (lEventName = 'end')
or (lEventName = 'type') then
lEventName+= '_';
lArgs :=' '+ lEventName+' : procedure(data: Pointer; A'+Pascalify(Element.Name)+': P'+Element.Name;
// for IxxxListener
lInterfaceLine := ' procedure '+Element.Name+'_'+lEvent.Name+'(A'+Pascalify(Element.Name)+': T'+Pascalify(Element.Name);
lWrapperVar := ' AIntf: ' + lInterfaceName+';';
lWrapperVarAssign := ' AIntf := '+lInterfaceName+'(AData^.ListenerUserData);';
lWrapperDecl := 'procedure '+Element.Name+'_'+lEvent.Name+'_Intf(AData: PWLUserData; A'+Element.Name+': P'+Element.Name;
lWrapperLine:= ' AIntf.'+Element.Name+'_'+lEvent.Name+'(T'+Pascalify(Element.Name)+'(AData^.PascalObject)';
// setting the listener variable
lWrapperBind := ' Pointer(vIntf_'+Element.Name+'_Listener.'+lEventName+') := @'+Element.Name+'_'+lEvent.Name+'_Intf;';
end
else
begin
lArg := ArgToArg(TArg(lNode), False, lNeedsWrapper);
lInterfaceArg := ArgToArg(TArg(lNode), True, lNeedsWrapper);
lTypeName:=ArgTypeToPascalType(TArg(lNode).&Type, TArg(lNode).&Interface, True, lNeedsWrapper);
lName := 'A'+Pascalify(lNode.Name);
if lTypeName = 'String' then
lTypeName:='Pchar';
lArgs+='; '+ lArg;
lInterfaceLine+='; '+lInterfaceArg;
lWrapperDecl+='; '+lArg;
if lNeedsWrapper then
begin
if TArg(lNode).&Type = 'new_id' then
lWrapperLine+=', '+lTypeName+'.Create('+lName+')'
else
lWrapperLine+=', '+lTypeName+'(TWLProxyObject.WLToObj('+lName+'))'
end
else
lWrapperLine+=', '+lName;
end;
end;
if lArgs <> '' then
begin
WriteEvent;
end;
Sections[sListenerDecl].Add(' end;');
Sections[sListenerDecl].Add('');
lList.Free;
Sections[sTypes].Add(' end;');
Sections[sTypes].Add('');
{
// add listener
lIntf := 'function '+Element.Name+'_add_listener('+Element.Name+': P'+Element.Name+'; listener: P'+Element.Name+'_listener; data: Pointer): cint;';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' Result := wl_proxy_add_listener(Pwl_proxy('+Element.Name+'), listener, data);');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
// add interface listener
lIntf := 'procedure '+Element.Name+'_add_listener('+Element.Name+': P'+Element.Name+'; AIntf: '+lInterfaceName+');';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' '+Element.Name+'_add_listener('+Element.Name+', @vIntf_'+Element.Name+'_Listener, AIntf);');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
// set user data
lIntf := 'procedure '+Element.Name+'_set_user_data('+Element.Name+': P'+Element.Name+'; user_data: Pointer);';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' wl_proxy_set_user_data(Pwl_proxy('+Element.Name+'), user_data);');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
// get user data
lIntf := 'function '+Element.Name+'_get_user_data('+Element.Name+': P'+Element.Name+'): Pointer;';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' Result := wl_proxy_get_user_data(Pwl_proxy('+Element.Name+'));');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
// get version
lIntf := 'function '+Element.Name+'_get_version('+Element.Name+': P'+Element.Name+'): cuint32;';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' Result := wl_proxy_get_version(Pwl_proxy('+Element.Name+'));');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
// destroy
if not Element.DestructorDefined then
begin
lIntf := 'procedure '+Element.Name+'_destroy('+Element.Name+': P'+Element.Name+');';
Sections[sFuncs].Add(lIntf);
Sections[sImplementation].Add(lIntf);
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' wl_proxy_destroy(Pwl_proxy('+Element.Name+'));');
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
end;
}
end;
procedure TGenerator.CollectArgs(Element: TBaseNode; AData: Pointer);
var
lArgList: TNodeList absolute AData;
lArg: TArg;
begin
lArg := TArg.Create(nil);
lArg.Assign(Element);
lArgList.Add(lArg);
end;
function TGenerator.Pascalify(AName: String): String;
var
lPos: SizeInt;
begin
Result := AName;
if Result = '' then
Exit;
// capitalize the first char if not yet
Result[1] := UpperCase(Result[1])[1];
Repeat
lPos := Pos('_', Result);
if lPos > 0 then
begin
// delete char and capitalize the following one
Delete(Result, lPos, 1);
Result[lPos] := UpperCase(Result[lPos])[1];
end;
until lPos < 1;
end;
function TGenerator.ArgToArg(AArg: TArg; APascalify: Boolean; var ANeedsWrapper: Boolean): String;
var
lName, lType: String;
begin
lName := 'A'+Pascalify(AArg.Name);
lType := ArgTypeToPascalType(AArg.&Type, AArg.&Interface, APascalify, ANeedsWrapper);
Result := Format('%s: %s', [lName, lType]);
end;
function TGenerator.ArgTypeToPascalType(AType: String; AInterface: String;
APascalify: Boolean; var ANeedsWrapper: Boolean): String;
begin
ANeedsWrapper:=False;
case AType of
'new_id':
begin
if AInterface = '' then // bind
Result :='Pwl_proxy'
else
begin
if APascalify then
Result:='T'+ Pascalify(AInterface)
else
Result := 'P'+AInterface;
end;
ANeedsWrapper:=True;
end;
'object':
begin
if APascalify then
Result:='T'+ Pascalify(AInterface)
else
Result := 'P'+AInterface;
if Length(Result) = 1 then
Result := 'Pointer';
ANeedsWrapper:=True;
end;
'int': Result := 'LongInt';
'uint': Result := 'DWord';
'fixed': Result := 'Longint{24.8}';
'string':
begin
if APascalify then
Result := 'String'
else
Result := 'Pchar';
end;
'array':
begin
{if APascalify then
Result := 'TWlArray'
else
Result := 'Pwl_array';
ANeedsWrapper:=True;}
Result := 'Pwl_array';
end;
'fd': Result := 'LongInt{fd}';
else
raise Exception.CreateFmt('Unknown argument type : %s', [AType]);
end; {case}
end;
procedure TGenerator.ArgsToSig(Element: TBaseNode; AData: Pointer);
var
lArg: TArg absolute Element;
Str: PString absolute AData;
begin
if lArg.AllowNull='true' then
Str^+='?';
if lArg.&Type = 'fd' then
Str^+='h' // handle?
else if lArg.&Type <> '' then
Str^+=lArg.&Type[1]
else
Str^+='?';
end;
procedure TGenerator.ArgTypesToInterfacePointer(Element: TBaseNode; AData: Pointer);
var
lArg: TArg absolute Element;
lInterfaceType: String;
begin
lInterfaceType := larg.&Interface;
if lInterfaceType <> '' then
Sections[sInterfacePointers].Add(Format(' (@%s_interface),', [lInterfaceType]))
else
Sections[sInterfacePointers].Add(' (nil),');
end;
procedure TGenerator.WriteRequestConsts(Element: TBaseNode; AData: Pointer);
var
lInterface: TInterface absolute AData;
begin
Sections[sClasses].Add(' const _'+UpperCase(Element.Name) + ' = ' + IntToStr(Element.ElementIndex)+';');
//Sections[sPrivateConst].Add('_'+UpperCase(lInterface.Name+'_'+Element.Name + ' = ' + IntToStr(Element.ElementIndex)+';'));
end;
procedure TGenerator.WriteRequestImplmentation(Element: TBaseNode;
Adata: Pointer);
var
lInterface: TInterface absolute Adata;
lFuncType : String;
lFuncName: String;
lFuncReturn: String;
lReq: TRequest absolute Element;
lArgList: TNodeList;
lArg: TArg;
lArgs: String;
lIntf, lTypeName, lTypeCast: String;
lReturnVar: TArg;
lParams: TNodeList;
begin
lFuncType:='procedure';
lFuncName := LowerCase(lInterface.Name+'_'+Element.Name);
lArgs := lInterface.Name + ': P'+lInterface.Name;
lArgList := TNodeList.Create(True);
lReq.ForEachArg(@CollectArgs, lArgList);
lReturnVar := nil;
lParams := TNodeList.Create(False);
for TBaseNode(lArg) in lArgList do
begin
if lArg.&Type = 'new_id' then // the return type
begin
lFuncType:='function ';
if lArg.&Interface = '' then
lFuncReturn:=': Pointer'
else
lFuncReturn:=': P'+larg.&Interface;
lReturnVar := lArg;
end
else if lArg.&Type = 'object' then
begin
lArgs += '; ' + lArg.Name+': P'+lArg.&Interface;
lParams.Add(lArg);
end
else begin
lTypeName := 'c'+lArg.&Type;
if lTypeName = 'cstring' then
lTypeName:='pchar';
if lTypeName = 'cfd' then
lTypeName:='cint';
if lTypeName = 'carray' then
lTypeName:='Pwl_array';
if lTypeName = 'cfixed' then
lTypeName:='cint32';
lArgs += '; ' + lArg.Name+': '+lTypeName;
lParams.Add(lArg);
end;
end;
// interface
if Assigned(lReturnVar) and (lReq.Name = 'bind') then
begin
// wl_registry_bind doesn't quite follow the same rules and has some extra vars that are not declared
lArgs+='; interface_: Pwl_interface; version: cuint32';
end;
lIntf:=Format('%s %s(%s)%s;', [lFuncType, lFuncName, lArgs, lFuncReturn]);
Sections[TSection.sFuncs].Add(lIntf);
// for later
lArgs := '';
for TBaseNode(lArg) in lParams do
begin
lArgs+=', '+lArg.Name;
end;
lArgs+=');';
// implementation
WriteLn(Element.Name);
Sections[sImplementation].Add(lIntf);
if Assigned(lReturnVar) and (lReturnVar.&Interface = '') and (lReq.Name = 'bind')then
begin
// wl_registry_bind doesn't quite follow the same rules
lTypeCast := lReturnVar.&Interface;
if lTypeCast = '' then
lTypeCast:=lInterface.Name;
Sections[sImplementation].Add('var');
Sections[sImplementation].Add(' '+lReturnVar.Name+': Pwl_proxy;');
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' '+lReturnVar.Name+' := wl_proxy_marshal_constructor_versioned(Pwl_proxy('+lInterface.Name+'),' );
Sections[sImplementation].Add(' _'+UpperCase(lInterface.Name+'_'+Element.Name)+', interface_, version, name, interface_^.name, version, nil);');
Sections[sImplementation].Add(' Result := Pointer('+lReturnVar.Name+');');
end
else if Assigned(lReturnVar) then
begin
lTypeCast := lReturnVar.&Interface;
if lTypeCast = '' then
lTypeCast:=lInterface.Name;
Sections[sImplementation].Add('var');
Sections[sImplementation].Add(' '+lReturnVar.Name+': Pwl_proxy;');
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' '+lReturnVar.Name+' := wl_proxy_marshal_constructor(Pwl_proxy('+lInterface.Name+'),' );
Sections[sImplementation].Add(' _'+UpperCase(lInterface.Name+'_'+Element.Name)+', @'+ lReturnVar.&Interface+'_interface, nil'+lArgs);
Sections[sImplementation].Add(' Result := P'+lTypeCast+'('+lReturnVar.Name+');');
end
else if lReq.&Type <> 'destructor' then
begin
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' wl_proxy_marshal(Pwl_proxy('+lInterface.Name+'),' );
Sections[sImplementation].Add(' _'+UpperCase(lInterface.Name+'_'+Element.Name)+lArgs);
end;
if lReq.&Type = 'destructor' then
begin
lInterface.DestructorDefined := True;
Sections[sImplementation].Add('begin');
Sections[sImplementation].Add(' wl_proxy_marshal(Pwl_proxy('+lInterface.Name+'), _'+UpperCase(lInterface.Name+'_'+Element.Name)+');');
Sections[sImplementation].Add(' wl_proxy_destroy(Pwl_proxy('+lInterface.Name+'));');
end;
Sections[sImplementation].Add('end;');
Sections[sImplementation].Add('');
lArgList.Free;
lParams.Free;
end;
procedure TGenerator.WriteRequestImplmentationObjects(Element: TBaseNode; Adata: Pointer);
var
lInterface: TInterface absolute Adata;
lRequest: TRequest absolute Element;
lFuncType, lFuncName, lIntf, lArgs, lImpl, lTypeCast, lFuncReturn,
lOverride, lTmp, lWrapperArgs: String;
lArg, lReturnVar: TArg;
lParams: TNodeList;
lArgList: TNodeList;
lNeedsWrapper: Boolean;
lWrapperCode: TStrings;
begin
lWrapperCode := TStringList.Create;
lFuncType:='procedure';
lFuncName := Pascalify(LowerCase(Element.Name));
// collect declared args
lArgList := TNodeList.Create(True);
lRequest.ForEachArg(@CollectArgs, lArgList);
lReturnVar:=nil;
lParams := TNodeList.Create(False);
lArgs := '';
lWrapperArgs := '';
for TBaseNode(lArg) in lArgList do
begin
case lArg.&Type of
'new_id':
begin
lFuncType:='function';
lFuncReturn:= ': '+ArgTypeToPascalType(lArg.&Type, larg.&Interface, True, lNeedsWrapper);
lReturnVar := lArg;
end;
else
lArgs += '; '+ArgToArg(lArg, False, lNeedsWrapper);
lWrapperArgs += '; '+ArgToArg(lArg, True, lNeedsWrapper);
lParams.Add(lArg);
if lNeedsWrapper then
larg.NeedsWrapper:=True;
end;
end;
if Assigned(lReturnVar) and (lRequest.Name = 'bind') then
begin
// wl_registry_bind doesn't quite follow the same rules and has some extra vars that are not declared
lArgs+='; AInterface: Pwl_interface; AVersion: LongInt';
lWrapperArgs+='; AInterface: Pwl_interface; AVersion: LongInt';
end
else
if Assigned(lReturnVar) then
begin
lArgs+='; AProxyClass: TWLProxyObjectClass = nil {T'+Pascalify(lReturnVar.&Interface+'}');
lWrapperArgs+='; AProxyClass: TWLProxyObjectClass = nil {T'+Pascalify(lReturnVar.&Interface+'}');
end;
if lRequest.&Type = 'destructor' then
begin
lFuncType:='destructor';
lFuncName:='Destroy';
lOverride:='; override';
end;
if Length(lArgs) > 0 then
Delete(lArgs, 1, 2); // delete from the start '; '
if Length(lWrapperArgs) > 0 then
Delete(lWrapperArgs, 1, 2); // delete from the start '; '
lArgs := '('+lArgs+')';
if lArgs = '()' then
lArgs := '';
lWrapperArgs := '('+lWrapperArgs+')';
if lWrapperArgs = '()' then
lWrapperArgs := '';
lIntf:=Format(' %s %s%s%s%s;', [lFuncType, lFuncName, lOverride, lWrapperArgs, lFuncReturn]);
lImpl:=Format('%s T%s.%s%s%s;', [lFuncType, Pascalify(lInterface.Name), lFuncName, lWrapperArgs, lFuncReturn]);
// add interface line of request
Sections[sClasses].Add(lIntf);
// for later
lArgs := '';
for TBaseNode(lArg) in lParams do
begin
if lArg.&Type = 'object' then
lTmp:='.Proxy'
else
lTmp := '';
if lArg.&Type = 'string' then
lArgs+=', PChar(A'+Pascalify(lArg.Name)+lTmp+')'
else
lArgs+=', A'+Pascalify(lArg.Name)+lTmp;
end;
lArgs+=');';
// add implementation function line
Sections[sClassImpl].Add(lImpl);
if Assigned(lReturnVar) and (lReturnVar.&Interface = '') and (lRequest.Name = 'bind')then
begin
// wl_registry_bind doesn't quite follow the same rules
Sections[sClassImpl].Add('begin');
Sections[sClassImpl].Add(' Result := wl_proxy_marshal_constructor_versioned(FProxy,' );
Sections[sClassImpl].Add(' _'+UpperCase(Element.Name)+', AInterface, AVersion, AName, AInterface^.name, AVersion, nil);');
end
else if Assigned(lReturnVar) then
begin
lTypeCast := lReturnVar.&Interface;
if lTypeCast = '' then
lTypeCast:=lInterface.Name;
lTypeCast:=Pascalify(lTypeCast);
Sections[sClassImpl].Add('var');
Sections[sClassImpl].Add(' '+lReturnVar.Name+': Pwl_proxy;');
Sections[sClassImpl].Add('begin');
Sections[sClassImpl].Add(' '+lReturnVar.Name+' := wl_proxy_marshal_constructor(FProxy,' );
Sections[sClassImpl].Add(' '+UpperCase('_'+Element.Name)+', @'+ lReturnVar.&Interface+'_interface, nil'+lArgs);
Sections[sClassImpl].Add(' if AProxyClass = nil then');
Sections[sClassImpl].Add(' AProxyClass := T'+lTypeCast+';');
Sections[sClassImpl].Add(' Result := T'+lTypeCast+'(AProxyClass.Create('+lReturnVar.Name+'));');
Sections[sClassImpl].Add(' if not AProxyClass.InheritsFrom(T'+lTypeCast+') then');
Sections[sClassImpl].Add(' Raise Exception.CreateFmt(''%s does not inherit from %s'', [AProxyClass.ClassName, T'+lTypeCast+']);');
end
else if lRequest.&Type <> 'destructor' then
begin
Sections[sClassImpl].Add('begin');
Sections[sClassImpl].Add(' wl_proxy_marshal(FProxy, '+UpperCase('_'+Element.Name)+lArgs);
end;
if lRequest.&Type = 'destructor' then
begin
lInterface.DestructorDefined := True;
Sections[sClassImpl].Add('begin');
Sections[sClassImpl].Add(' wl_proxy_marshal(FProxy, '+UpperCase('_'+Element.Name)+');');
//Sections[sClassImpl].Add(' wl_proxy_destroy(FProxy);'); // inherited will call this
Sections[sClassImpl].Add(' inherited Destroy;');
end;
Sections[sClassImpl].Add('end;');
Sections[sClassImpl].Add('');
end;
procedure TGenerator.WriteListenerObjectMethod(Element: TInterface);
var
lIntf, lClassname: String;
begin
lIntf:='I'+Pascalify(Element.Name)+'Listener';
lClassname := 'T'+Pascalify(Element.Name);
Sections[sClasses].Add(' function AddListener(AIntf: '+lIntf+'): LongInt;');
Sections[sClassImpl].Add('function '+lClassname+'.AddListener(AIntf: '+lIntf+'): LongInt;');
Sections[sClassImpl].Add('begin');
Sections[sClassImpl].Add(' FUserDataRec.ListenerUserData := Pointer(AIntf);');
Sections[sClassImpl].Add(' Result := wl_proxy_add_listener(FProxy, @vIntf_'+Element.Name+'_Listener, @FUserDataRec);');
Sections[sClassImpl].Add('end;');
end;
procedure TGenerator.WriteWaylandRequestorEventInterface(Element: TBaseNode; AData: Pointer);
var
lInterface: TInterface absolute AData;
lElement: TBaseWithArg absolute Element;
lSig: String = '';
lInterfacePointer,
lInterfaceVar, lName, lSince: String;
lIndex: Integer;
begin
lName := lElement.Name;
lElement.ForEachArg(@ArgsToSig, @lSig);
if lElement is TRequest then
begin
lSince := TRequest(lElement).Since;
lInterfaceVar := TRequest(lElement).GetNewIdInterface;
if lInterfaceVar <> '' then
begin
lInterfaceVar+='_interface';
end;
end
else
begin
lSince := TEvent(lElement).Since;
lInterfaceVar := TEvent(lElement).GetObjectIdInterface;
if lInterfaceVar <> '' then
begin
lInterfaceVar+='_interface';
end;
end;
// wl_registry_bind doesn't quite follow the same rules and has some extra vars that are not declared
if (lInterface.Name = 'wl_registry') and (Element.Name = 'bind') then
lSig:='us'+lSig;
lSig:=lSince+lSig;
if lInterfaceVar <> '' then
begin
lIndex:= Sections[sInterfacePointers].Count;
lElement.ForEachArg(@ArgTypesToInterfacePointer, lInterface);
end
else
lIndex := 0;
{
lIndex:= Sections[sInterfacePointers].IndexOf(' (@'+lInterfaceVar+'),')+1;
if lIndex < 1 then
begin
lIndex:=0;
if lInterfaceVar <> '' then
lIndex := Sections[sInterfacePointers].Add(Format(' (@%s),', [lInterfaceVar]))+1;
end;}
lInterfacePointer := Format('pInterfaces[%d]', [lIndex]);
Sections[sRequestandEvents].Add(Format(' (name: ''%s''; signature: ''%s''; types: @%s),', [lName, lSig, lInterfacePointer]));
end;
constructor TGenerator.Create(AFileName: String);
var
lStream: TFileStream;
s: TSection;
begin
lStream := TFileStream.Create(AFileName, fmOpenRead);
try
FProtocol := TProtocol.Create(lStream, False);
finally
lStream.Free;
end;
for s in TSection do
Sections[s] := TStringList.Create;
end;
procedure TGenerator.Generate(AUnitName: String; Strings: TStrings;
ImplementInterfaceVars: Boolean);
var
lUses: String;
i: Integer;
begin
FImplementInterfaceVars:=ImplementInterfaceVars;
for i := 0 to 7 do
Sections[sInterfacePointers].Add(' (nil),');
// this sets up pointer types for each interface name.
FProtocol.ForEachInterface(@DeclareInterfaceTypes, nil);
FProtocol.ForEachInterface(TForEachHandler(@HandleInterface), nil);
//WriteLn(Sections[sConst].Text);
WriteLn(Sections[sFuncs].Text);
WriteLn(Sections[sTypes].Text);
WriteLn(Sections[sImplementation].Text);
if Assigned(Strings) then
begin
Strings.Add('unit '+AUnitName+';');
Strings.Add('');
Strings.Add('{$mode objfpc} {$H+}');
Strings.Add('{$interfaces corba}');
Strings.Add('');
Strings.Add('interface');
Strings.Add('');
Strings.Add('uses');
if AUnitName = 'wayland_protocol' then
lUses := ' Classes, Sysutils, ctypes, wayland_util, wayland_client_core'
else
lUses := ' Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol';
Strings.Add(lUses +';');
Strings.Add('');
Strings.Add('');
Strings.Add('type');
Strings.AddStrings(Sections[sTypes].Text);
Strings.Add('');
Strings.AddStrings(Sections[sClassForward].Text);
Strings.Add('');
Strings.AddStrings(Sections[sListenerDecl].Text);
Strings.Add('');
Strings.AddStrings(Sections[sClasses].Text);
Strings.Add('');
Strings.Add('');
Strings.AddStrings(Sections[sFuncs].Text);
Strings.Add('');
Strings.Add('');
Strings.Add('var');
Strings.AddStrings(Sections[sVars].Text);
Strings.Add('');
Strings.Add('');
Strings.Add('implementation');
Strings.Add('');
if Sections[sPrivateConst].Count > 0 then
begin
Strings.Add('const');
Strings.AddStrings(Sections[sPrivateConst].Text);
Strings.Add('');
end;
if Sections[sPrivateVar].Count > 0 then
begin
Strings.Add('var');
Strings.AddStrings(Sections[sPrivateVar].Text);
Strings.Add('');
Strings.Add('');
end;
Strings.AddStrings(Sections[sClassImpl].Text);
Strings.Add('');
Strings.Add('');
Strings.AddStrings(Sections[sImplementation].Text);
Strings.AddStrings(Sections[sListenerImpl].Text);
Strings.Add('');
if FImplementInterfaceVars then
begin
// get rid of comma
TrimLastChar(Sections[sInterfacePointers]);
Strings.Add('const');
Strings.Add(Format(' pInterfaces: array[0..%d] of Pwl_interface = (', [Sections[sInterfacePointers].Count-1]));
Strings.AddStrings(Sections[sInterfacePointers]);
Strings.Add(' );');
Strings.Add('');
Strings.AddStrings(Sections[sRequestandEvents]);
Strings.Add('');
end;
Strings.Add('initialization');
Strings.AddStrings(Sections[sListenerBind].Text);
Strings.Add('');
Strings.AddStrings(Sections[sInit]);
Strings.Add('end.');
end;
end;
end.
|
{ Subroutine SST_R_PAS_SMENT_TYPE
*
* Process TYPE_STATEMENT syntax. This will also involve processing any
* number of TYPE_SUBSTATEMENT syntaxes. These will be invoked explicitly
* with the syntax subroutine SST_R_PAS_SYN_TYPE.
}
module sst_r_pas_SMENT_TYPE;
define sst_r_pas_sment_type;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_sment_type; {process TYPE_STATMENT construction}
const
max_msg_parms = 3; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {syntax tag from .syn file}
str_h: syo_string_t; {handle to string for a tag}
chain_p: sst_symbol_p_t; {points to symbols declared here}
symbol_p: sst_symbol_p_t; {points to current symbol definition}
dtype_p: sst_dtype_p_t; {pointer to new data type definition}
dt_p: sst_dtype_p_t; {scratch data type block pointer}
fnam: string_treename_t; {file name passed to a message}
lnum: sys_int_machine_t; {line number passed to a message}
mflag: syo_mflag_k_t; {syntaxed matched yes/no flag}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
label
loop_statement, loop_tag;
begin
fnam.max := sizeof(fnam.str);
chain_p := nil; {init chain of new symbols to empty}
loop_statement: {back here each new TYPE_SUBSTATEMENT syntax}
syo_tree_clear; {set up for parsing}
sst_r_pas_syn_type (mflag); {try to parse next TYPE_SUBSTATEMENT syntax}
if mflag = syo_mflag_yes_k
then begin {syntax matched}
error_syo_found := false; {indicate no syntax error}
end
else begin {syntax did not match}
return; {no more TYPE_SUBSTATMENTS here}
end
;
syo_tree_setup; {set up syntax tree for getting tags}
syo_level_down; {down into TYPE_SUBSTATEMENT syntax level}
loop_tag: {back here for each new TYPE_SUBSTATEMENT tag}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'type_sment_bad', nil, 0); {get next tag}
case tag of {what kind of tag is it ?}
{
* End of this TYPE statement.
}
syo_tag_end_k: begin
goto loop_statement; {back for next TYPE_SUBSTATEMENT syntax}
end;
{
* Tag is name of new symbol being declared as a data type.
}
1: begin
sst_symbol_new ( {add new symbol to current scope}
str_h, syo_charcase_down_k, symbol_p, stat);
if sys_stat_match (sst_subsys_k, sst_stat_sym_prev_def_k, stat)
then begin {symbol already exists}
if (symbol_p^.symtype <> sst_symtype_dtype_k) or else
(symbol_p^.dtype_dtype_p^.dtype <> sst_dtype_undef_k)
then begin {existing symbol is not undefined data type ?}
sst_charh_info (symbol_p^.char_h, fnam, lnum);
sys_msg_parm_vstr (msg_parm[1], symbol_p^.name_in_p^);
sys_msg_parm_int (msg_parm[2], lnum);
sys_msg_parm_vstr (msg_parm[3], fnam);
syo_error (str_h, 'sst_pas_read', 'symbol_already_def', msg_parm, 3);
end;
end
else begin {symbol did not already exist}
syo_error_abort (stat, str_h, '', '', nil, 0); {check for error}
symbol_p^.symtype := sst_symtype_dtype_k; {new symbol is a data type}
sst_dtype_new (symbol_p^.dtype_dtype_p); {create dtype block for this symbol}
symbol_p^.dtype_dtype_p^.symbol_p := symbol_p; {point dtype block to symbol}
end
;
symbol_p^.flags := symbol_p^.flags + {this symbol will be defined here}
[sst_symflag_def_k];
symbol_p^.next_p := chain_p; {link with other symbols defined together}
chain_p := symbol_p; {update pointer to start of chain}
end;
{
* Tag is the data type definition for the previous symbol names.
* All the symbols have empty data type blocks linked to them. Set the first
* one from the data type definition and then copy the information to the
* others.
}
2: begin
dtype_p := chain_p^.dtype_dtype_p; {get pointer to dtype block of first symbol}
sst_r_pas_data_type (dtype_p); {fill in dtype block of first symbol}
chain_p := chain_p^.next_p; {start looping at second symbol in chain}
while chain_p <> nil do begin {once for each symbol of this data type}
dt_p := chain_p^.dtype_dtype_p; {get pointer to symbols data type block}
dt_p^ := dtype_p^; {init our dtype to exact copy of base}
if sst_symflag_intrinsic_out_k in dtype_p^.symbol_p^.flags
then begin {base data type is intrinsic to output}
dt_p^.dtype := sst_dtype_copy_k; {make new data type soft copy of old}
dt_p^.copy_symbol_p := dtype_p^.symbol_p;
dt_p^.copy_dtype_p := dtype_p;
end;
dt_p^.symbol_p := chain_p; {point data type block to this symbol}
chain_p := chain_p^.next_p; {point to next symbol in chain}
end; {back and process next symbol in chain}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of TAG cases}
goto loop_tag; {back and process next tag}
end;
|
(*
libltc - en+decode linear timecode
Copyright (C) 2006-2012 Robin Gareus <robin@gareus.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
If not, see <http://www.gnu.org/licenses/>.
Conversion to Pascal Copyright 2014 (c) Oleksandr Nazaruk <support@freehand.com.ua>
based on libltc-1.1.3
*)
unit FH.LIBLTC.LTC;
interface
(**
* default audio sample type: 8bit unsigned (mono)
*)
type
size_t = NativeUInt;
ltcsnd_sample_t = byte;
pltcsnd_sample_t = ^ltcsnd_sample_t;
(*
* sample-count offset - 64bit wide
*)
type
ltc_off_t = int64;
Const
LTC_FRAME_BIT_COUNT = 80;
SAMPLE_CENTER = 128;
(* Little Endian version -- and doxygen doc *)
type
TLTCFrame = packed record
frame_units : byte; ///< SMPTE framenumber BCD unit 0..9
user1 : byte;
frame_tens : byte; ///< SMPTE framenumber BCD tens 0..3
dfbit : byte; ///< indicated drop-frame timecode
col_frame : byte;///< colour-frame: timecode intentionally synchronized to a colour TV field sequence
user2 : byte;
secs_units : byte; ///< SMPTE seconds BCD unit 0..9
user3 : byte;
secs_tens : byte; ///< SMPTE seconds BCD tens 0..6
biphase_mark_phase_correction : byte; ///< see note on Bit 27 in description and \ref ltc_frame_set_parity .
user4 : byte;
mins_units : byte; ///< SMPTE minutes BCD unit 0..9
user5 : byte;
mins_tens : byte; ///< SMPTE minutes BCD tens 0..6
binary_group_flag_bit0 : byte; ///< indicate user-data char encoding, see table above - bit 43
user6 : byte;
hours_units : byte; ///< SMPTE hours BCD unit 0..9
user7 : byte;
hours_tens : byte; ///< SMPTE hours BCD tens 0..2
binary_group_flag_bit1 : byte; ///< indicate timecode is local time wall-clock, see table above - bit 58
binary_group_flag_bit2 : byte; ///< indicate user-data char encoding (or parity with 25fps), see table above - bit 59
user8 : byte;
sync_word: word;
end;
type
TLTCFrameRAW = packed record
b1 : byte;
b2 : byte;
b3 : byte;
b4 : byte;
b5 : byte;
b6 : byte;
b7 : byte;
b8 : byte;
sync_word: word;
end;
PLTCFrameRAW = ^TLTCFrameRAW;
(* the standard defines the assignment of the binary-group-flag bits
* basically only 25fps is different, but other standards defined in
* the SMPTE spec have been included for completeness.
*)
Type
LTC_TV_STANDARD = (
LTC_TV_525_60, ///< 30fps
LTC_TV_625_50, ///< 25fps
LTC_TV_1125_60,///< 30fps
LTC_TV_FILM_24 ///< 24fps
);
(** encoder and LTCframe <> timecode operation flags *)
type
LTC_BG_FLAGS = (
LTC_USE_DATE = 1, ///< LTCFrame <> SMPTETimecode converter and LTCFrame increment/decrement use date, also set BGF2 to '1' when encoder is initialized or re-initialized (unless LTC_BGF_DONT_TOUCH is given)
LTC_TC_CLOCK = 2,///< the Timecode is wall-clock aka freerun. This also sets BGF1 (unless LTC_BGF_DONT_TOUCH is given)
LTC_BGF_DONT_TOUCH = 4, ///< encoder init or re-init does not touch the BGF bits (initial values after initialization is zero)
LTC_NO_PARITY = 8 ///< parity bit is left untouched when setting or in/decrementing the encoder frame-number
);
(**
* Extended LTC frame - includes audio-sample position offsets, volume, etc
*
* Note: For TV systems, the sample in the LTC audio data stream where the LTC Frame starts is not neccesarily at the same time
* as the video-frame which is described by the LTC Frame.
*
* \ref off_start denotes the time of the first transition of bit 0 in the LTC frame.
*
* For 525/60 Television systems, the first transition shall occur at the beginning of line 5 of the frame with which it is
* associated. The tolerance is ± 1.5 lines.
*
* For 625/50 systems, the first transition shall occur at the beginning of line 2 ± 1.5 lines of the frame with which it is associated.
*
* Only for 1125/60 systems, the first transition occurs exactly at the vertical sync timing reference of the frame. ± 1 line.
*
*)
type
TLTCFrameExt = packed record
ltc : TLTCFrameRAW; ///< the actual LTC frame. see \ref LTCFrame
off_start : ltc_off_t; ///< \anchor off_start the approximate sample in the stream corresponding to the start of the LTC frame.
off_end : ltc_off_t; ///< \anchor off_end the sample in the stream corresponding to the end of the LTC frame.
reverse : integer; ///< if non-zero, a reverse played LTC frame was detected. Since the frame was reversed, it started at off_end and finishes as off_start (off_end > off_start). (Note: in reverse playback the (reversed) sync-word of the next/previous frame is detected, this offset is corrected).
biphase_tics : array[0..LTC_FRAME_BIT_COUNT-1] of Single; ///< detailed timing info: phase of the LTC signal; the time between each bit in the LTC-frame in audio-frames. Summing all 80 values in the array will yield audio-frames/LTC-frame = (\ref off_end - \ref off_start + 1).
sample_min : ltcsnd_sample_t; ///< the minimum input sample signal for this frame (0..255)
sample_max : ltcsnd_sample_t; ///< the maximum input sample signal for this frame (0..255)
volume : Single; ///< the volume of the input signal in dbFS
end;
PLTCFrameExt = ^TLTCFrameExt;
type
TSMPTETimecode = packed record
// these are only set when compiled with ENABLE_DATE
timezone : array[0..5] of char;
years : byte;
months : byte;
days : byte;
//
hours : byte;
mins : byte;
secs : byte;
frame : byte;
end;
PSMPTETimecode = ^TSMPTETimecode;
implementation
end. |
unit Unt_Principal;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.ExtDlgs,
Vcl.CheckLst,
Data.DB,
Data.SqlExpr,
Data.DBXFirebird;
type
/// <summary>
/// Especializada em apagar os dados da tabela
/// </summary>
TThreadEsvaziarTabela = class(TThread)
public
/// <summary>
/// Rotina que ser� executado pelo thread
/// </summary>
procedure Execute; override;
end;
/// <summary>
/// Efetiva importa��o dos dados
/// </summary>
TThreadImportacao = class(TThread)
private
FNomeArquivo : string;
FTempoSegundos : NativeUInt;
FQuantidadeLinhas: NativeUInt;
public
/// <summary>
/// Recebe o nome do arquivo alvo
/// </summary>
constructor Create(const ANomeArquivo: string); reintroduce;
/// <summary>
/// Define corretamente a m�scara de afinidade
/// </summary>
procedure Execute; override;
/// <summary>
/// Tempo total de execu��o
/// </summary>
property TempoSegundos: NativeUInt read FTempoSegundos;
/// <summary>
/// Quantidade de linhas processadas
/// </summary>
property QuantidadeLinhas: NativeUInt read FQuantidadeLinhas;
end;
/// <summary>
/// Thread de gerenciamento das m�ltiplas threads
/// </summary>
TThreadGerente = class(TThread)
private
FNomeArquivo : string;
FTempoSegundos : NativeUInt;
FQuantidadeLinhas: NativeUInt;
FEsvaziador : TThreadEsvaziarTabela;
FImportadores : array of TThreadImportacao;
/// <summary>
/// Divide o arquivo em partes e os distribui aos threads
/// </summary>
procedure DividirArquivo;
protected
/// <summary>
/// Utilizado para terminar os threads de importa��o
/// </summary>
procedure TerminatedSet; override;
public
/// <summary>
/// Recebe o nome do arquivo alvo
/// </summary>
constructor Create(const ANomeArquivo: string); reintroduce;
/// <summary>
/// Rotina a ser executado pelo thread
/// </summary>
procedure Execute; override;
/// <summary>
/// Tempo total de execu��o
/// </summary>
property TempoSegundos: NativeUInt read FTempoSegundos;
/// <summary>
/// Quantidade de linhas processadas
/// </summary>
property QuantidadeLinhas: NativeUInt read FQuantidadeLinhas;
end;
TfImportacao = class(TForm)
Button1: TButton;
Button2: TButton;
OpenTextFileDialog1: TOpenTextFileDialog;
lTempo: TLabel;
lQuantidade: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FThreadUnica : TThreadImportacao;
FThreadGerente: TThreadGerente;
procedure QuandoTerminarThread(Sender: TObject);
function EscolherArquivo: string;
public
{ Public declarations }
end;
var
fImportacao: TfImportacao;
implementation
uses
System.StrUtils,
System.Diagnostics,
System.TypInfo;
{$R *.dfm}
{ TThreadImportacao }
constructor TThreadImportacao.Create(const ANomeArquivo: string);
begin
inherited Create(True);
Self.FNomeArquivo := ANomeArquivo;
end;
procedure TThreadImportacao.Execute;
const
C_INSTRUCAO_SQL = 'INSERT INTO TBCONTATOS ' + ' (ID, NOME_CLIENTE, CNPJ, ENDERECO, TELEFONE_1, TELEFONE_2, EMAIL)' + 'VALUES ' + ' (%s, ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'');';
var
_csv : TextFile;
sLinha : string;
slAuxiliar : TStringList;
sInstrucaoSQL: string;
rTempo : TStopwatch;
oDatabase : TSQLConnection;
begin
inherited;
rTempo := TStopwatch.StartNew;
// Efetua a conex�o com o banco de dados
oDatabase := TSQLConnection.Create(nil);
with oDatabase do
begin
LoginPrompt := False;
DriverName := 'Firebird';
Params.Values['Database'] := '192.168.0.132:MARIO';
Params.Values['User_Name'] := 'sysdba';
Params.Values['Password'] := 'masterkey';
Open;
end;
// Instancia o StringList
slAuxiliar := TStringList.Create;
// Associa o maniopulador ao arquivo alvo
AssignFile(_csv, Self.FNomeArquivo);
try
// Abre o arquivo para leitura
Reset(_csv);
// Enquanto n�o for o fim do arquivo ...
while not Eof(_csv) do
begin
// Incrementa a quantidade de linhas processadas
Inc(Self.FQuantidadeLinhas);
// Se o thread foi sinalizado para terminar,
// interrompe o ciclo
if Self.Terminated then
begin
Break;
end;
// L� a pr�xima linha
Readln(_csv, sLinha);
// Quebra os campos CSV
slAuxiliar.CommaText := sLinha;
// Monta a instru��o SQL
sInstrucaoSQL := Format(C_INSTRUCAO_SQL, [slAuxiliar[0], slAuxiliar[1], slAuxiliar[2], slAuxiliar[3], slAuxiliar[4], slAuxiliar[5], slAuxiliar[6]]);
// Executa a instru��o SQL
oDatabase.ExecuteDirect(sInstrucaoSQL);
end;
finally
rTempo.Stop;
Self.FTempoSegundos := rTempo.ElapsedMilliseconds div 1000;
oDatabase.Close;
oDatabase.Free;
slAuxiliar.Free;
CloseFile(_csv);
end;
end;
procedure TfImportacao.Button1Click(Sender: TObject);
var
sNomeArquivo: string;
oEsvaziador : TThreadEsvaziarTabela;
begin
// Seleciona o arquivo
sNomeArquivo := Self.EscolherArquivo;
// Desabilita os bot�es
Self.Button1.Enabled := False;
Self.Button2.Enabled := False;
// Esvazia a tabela
oEsvaziador := TThreadEsvaziarTabela.Create(True);
oEsvaziador.FreeOnTerminate := True;
oEsvaziador.Start;
WaitForSingleObject(oEsvaziador.Handle, INFINITE);
// Configura e inicializa o thread, definindo a prioridade
Self.FThreadUnica := TThreadImportacao.Create(sNomeArquivo);
Self.FThreadUnica.FreeOnTerminate := True;
Self.FThreadUnica.OnTerminate := Self.QuandoTerminarThread;
Self.FThreadUnica.Start;
end;
procedure TfImportacao.Button2Click(Sender: TObject);
var
sNomeArquivo: string;
begin
// Seleciona o arquivo
sNomeArquivo := Self.EscolherArquivo;
// Desabilita os bot�es
Self.Button1.Enabled := False;
Self.Button2.Enabled := False;
// Configura e inicializa o thread
Self.FThreadGerente := TThreadGerente.Create(sNomeArquivo);
Self.FThreadGerente.FreeOnTerminate := True;
Self.FThreadGerente.OnTerminate := Self.QuandoTerminarThread;
Self.FThreadGerente.Start;
end;
function TfImportacao.EscolherArquivo: string;
var
bRet: Boolean;
begin
// Abre a caixa de di�logo para selecionar o arquivo
Self.OpenTextFileDialog1.Title := 'Selecionar arquivo ...';
Self.OpenTextFileDialog1.Filter := 'Arquivo CSV|*.csv';
bRet := Self.OpenTextFileDialog1.Execute(Self.Handle);
// Se o usu�rio cancelar a opera��o, gera erro
if not bRet then
begin
raise Exception.Create('Opera��o cancelada pelo usu�rio');
end;
// Retorno do nome do arquivo escolhido
Result := Self.OpenTextFileDialog1.FileName;
end;
procedure TfImportacao.FormClose(Sender: TObject; var Action: TCloseAction);
var
oThread: TThread;
begin
// Inicializa a variavel
oThread := nil;
// Se a thread �nica estiver sinalizada, assume
if Assigned(Self.FThreadUnica) then
begin
oThread := Self.FThreadUnica;
end;
// Se a thread gerente estiver sinalizada, assume
if Assigned(Self.FThreadGerente) then
begin
oThread := Self.FThreadGerente;
end;
// Se sinalizado ...
if Assigned(oThread) then
begin
// "Desliga" o OnTerminate
oThread.OnTerminate := nil;
// "Desliga" o FreeOnTerminate
oThread.FreeOnTerminate := False;
// Indica o t�rmino
oThread.Terminate;
// Aguarda o t�rmino
oThread.WaitFor;
// Libera as inst�ncias
oThread.Free;
end;
end;
procedure TfImportacao.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
end;
procedure TfImportacao.QuandoTerminarThread(Sender: TObject);
const
C_TEMPO = 'Tempo: [%s] - [%d]';
var
sTexto : string;
iLinhas: NativeUInt;
begin
// Se for um thread de importa��o ...
if Sender is TThreadImportacao then
begin
sTexto := Format(C_TEMPO, ['Um thread!', Self.FThreadUnica.TempoSegundos]);
iLinhas := Self.FThreadUnica.QuantidadeLinhas;
Self.FThreadUnica := nil;
end;
// Se for a thread gerenciadora ...
if Sender is TThreadGerente then
begin
sTexto := Format(C_TEMPO, ['V�rios threads!', Self.FThreadGerente.TempoSegundos]);
iLinhas := Self.FThreadGerente.QuantidadeLinhas;
Self.FThreadGerente := nil;
end;
// Elementos de tela
Self.lTempo.Caption := sTexto;
Self.lQuantidade.Caption := FormatFloat('#,###,##0', iLinhas);
Self.Button1.Enabled := True;
Self.Button2.Enabled := True;
end;
{ TThreadGerente }
constructor TThreadGerente.Create(const ANomeArquivo: string);
begin
inherited Create(True);
Self.FNomeArquivo := ANomeArquivo;
end;
procedure TThreadGerente.DividirArquivo;
const
C_ASCII_10 = 10;
var
_arq_entrada : file;
_arq_saida : file;
aBuffer : array [1 .. MAXWORD] of Byte;
iQuantProcessador: Byte;
iTamEntrada : NativeUInt;
iTamPorArquivo : NativeUInt;
iNumProcessador : NativeUInt;
iTamBuffer : NativeUInt;
iTotalLido : NativeUInt;
sNomeArquivoSaida: string;
iPosArray : Byte;
begin
// Associa o arquivo de entrada a um manipulador
AssignFile(_arq_entrada, Self.FNomeArquivo);
try
// Vai para o in�cio do arquivo
Reset(_arq_entrada, 1);
// Quantidade de processadores
iQuantProcessador := TThread.ProcessorCount;
SetLength(Self.FImportadores, iQuantProcessador);
// Tamanho do arquivo em bytes
iTamEntrada := FileSize(_arq_entrada);
// Tamanho aproximando para cada arquivo
iTamPorArquivo := iTamEntrada div iQuantProcessador;
// Varre-se de tras p�ra frente para definir a afinidade do
// �ltimo n�cleo ao primeiro
for iNumProcessador := 1 to iQuantProcessador do
begin
// Zera a quantidade lida
iTotalLido := 0;
// Nome do arquivo de sa�da
sNomeArquivoSaida := Format('.\arquivo_%d.csv', [iNumProcessador]);
// Associa o arquivo de sa�da a um manipulador
AssignFile(_arq_saida, sNomeArquivoSaida);
// Coloca o arquivo em modo de escrita
Rewrite(_arq_saida, 1);
try
while True do
begin
// L� um bloco do arquivo de entrada
BlockRead(_arq_entrada, aBuffer, MAXWORD, iTamBuffer);
// Escreve este bloco no arquivo de sa�da
BlockWrite(_arq_saida, aBuffer, iTamBuffer);
// Finaliza se chegou ao fim do arquivo de entrada
if Eof(_arq_entrada) then
begin
Exit;
end;
// Se estiver no �ltimo arquivo n�o precisa
// mais verifica��es
if (iNumProcessador = iQuantProcessador) then
begin
Continue;
end;
// Se j� atingiu o tamanho proposto ...
Inc(iTotalLido, iTamBuffer);
if (iTotalLido >= iTamPorArquivo) then
begin
// Se o �ltimo caracter n�o for #10 continua lendo
// byte a byte para finalizar um arquivo �ntegro
if (aBuffer[iTamBuffer] <> C_ASCII_10) then
begin
// L� o arquivo continuamente at� encontrar um #10
repeat
BlockRead(_arq_entrada, aBuffer, 1, iTamBuffer);
BlockWrite(_arq_saida, aBuffer, iTamBuffer);
until (aBuffer[1] = C_ASCII_10);
end;
// Finaliza o [while True do]
Break;
end;
end;
finally
// Encerra o manipulador do arquivo de sa�da
CloseFile(_arq_saida);
// Determina a posi��o no array
iPosArray := iNumProcessador - 1;
// Cria um thread de importa��o passando o arquivo de sa�da
Self.FImportadores[iPosArray] := TThreadImportacao.Create(sNomeArquivoSaida);
// Inicia o thread
Self.FImportadores[iPosArray].Start;
end;
end;
finally
// Encerra o manipulador do arquivo de entrada
CloseFile(_arq_entrada);
end;
end;
procedure TThreadGerente.Execute;
var
aHandles : array [1 .. MAXBYTE] of THandle;
_crono : TStopwatch;
iNumThread: Integer;
begin
inherited;
_crono := TStopwatch.StartNew;
try
// Esvazia a tabela
Self.FEsvaziador := TThreadEsvaziarTabela.Create(True);
Self.FEsvaziador.Start;
WaitForSingleObject(Self.FEsvaziador.Handle, INFINITE);
// Divide o arquivo gigante em partes e inicia o thread
// de importa��o correspondente
Self.DividirArquivo;
// Anota os manipuladores dos threads
for iNumThread := 0 to High(Self.FImportadores) do
begin
aHandles[Succ(iNumThread)] := Self.FImportadores[iNumThread].Handle;
end;
// Aguarda o t�rminos dos threads de importa��o
WaitForMultipleObjects(Length(Self.FImportadores), @aHandles, True, INFINITE);
// Determina a quantidade de linhas processadas
for iNumThread := 0 to High(Self.FImportadores) do
begin
Inc(Self.FQuantidadeLinhas, Self.FImportadores[iNumThread].QuantidadeLinhas);
end;
// For�a a libera��o dos threads de importa��o
Self.Terminate;
finally
_crono.Stop;
Self.FTempoSegundos := _crono.ElapsedMilliseconds div 1000;
end;
end;
procedure TThreadGerente.TerminatedSet;
var
i: Integer;
begin
inherited;
// Libera o array de esvaziamento da tabela
if Assigned(Self.FEsvaziador) then
begin
// Se N�O estiver finalizada, indica o t�rmino
if not(Self.FEsvaziador.Finished) then
begin
Self.FEsvaziador.Terminate;
Self.FEsvaziador.WaitFor;
end;
// Libera a inst�ncia
Self.FEsvaziador.Free;
end;
// Libera os arrays de importa��o
for i := 0 to High(Self.FImportadores) do
begin
// Se estiver sinalizada ...
if Assigned(Self.FImportadores[i]) then
begin
// Se N�O estiver finalizada, indica o t�rmino
if not(Self.FImportadores[i].Finished) then
begin
Self.FImportadores[i].Terminate;
Self.FImportadores[i].WaitFor;
end;
// Libera a inst�ncia
Self.FImportadores[i].Free;
end;
end;
end;
{ TThreadEsvaziarTabela }
procedure TThreadEsvaziarTabela.Execute;
var
oDatabase: TSQLConnection;
begin
inherited;
// Conex�o com o banco de dados
oDatabase := TSQLConnection.Create(nil);
try
with oDatabase do
begin
LoginPrompt := False;
DriverName := 'Firebird';
Params.Values['Database'] := '192.168.0.132:MARIO';
Params.Values['User_Name'] := 'sysdba';
Params.Values['Password'] := 'masterkey';
Open;
end;
// Instru��o SQL de dele��o
oDatabase.ExecuteDirect('DELETE FROM TBCONTATOS');
finally
oDatabase.Close;
oDatabase.Free;
end;
end;
end.
|
unit uDepartamentoEmailVO;
interface
uses
System.SysUtils, uTableName, uKeyField, System.Generics.Collections;
type
[TableName('Departamento_Email')]
TDepartamentoEmailVO = class
private
FIdDepartamento: Integer;
FEmail: string;
FId: Integer;
procedure SetEmail(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdDepartamento(const Value: Integer);
public
[KeyField('DepEm_Id')]
property Id: Integer read FId write SetId;
[FieldName('DepEm_Departamento')]
Property IdDepartamento: Integer read FIdDepartamento write SetIdDepartamento;
[FieldName('DepEm_Email')]
property Email: string read FEmail write SetEmail;
end;
TListaDepartamentoEmail = TObjectList<TDepartamentoEmailVO>;
implementation
{ TDepartamentoEmailVO }
procedure TDepartamentoEmailVO.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TDepartamentoEmailVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TDepartamentoEmailVO.SetIdDepartamento(const Value: Integer);
begin
FIdDepartamento := Value;
end;
end.
|
unit MakeGraph;
{$MODE OBJFPC}
uses
Classes, SysUtils, StrUtils, uMinPrioQueue;
type
TCity = (NY = 0, LONDON = 1, PARIS = 2, MOSCOW = 3);
TNode = record
Index: Integer;
Edges: Array of TNode;
end;
TSetOfNode = Set of Integer;
TIntegerArray = Array of Integer;
const
TCities: Array[0..3] of TCity = (NY, LONDON, MOSCU, OTHER);
CityNames: Array[0..3] of String = ('new york','london','moscu','other city');
Destinations: Array[0..3] of String = ('london,moscu',
'moscu',
'"new york","other city"',
''); // 'other city' doesn''t have destinations
function AnsiIndexStr(const AText: string; const AValues: array of string): Integer;
var
i : longint;
begin
Result := -1;
if (High(AValues) = -1) or (High(AValues) > MaxInt) Then
Exit;
for i := Low(AValues) to High(Avalues) do
if (avalues[i] = AText) Then
exit(i); // make sure it is the first val.
end;
function MakeGraph: TGraph;
var
i, j: Integer;
Edge: Array of Integer;
DestList: TStringList;
Graph: TGraph;
begin
SetLength(Graph, Length(TCities));
for i := 0 to Length(TCities) - 1 do
begin
DestList := TStringList.Create;
DestList.Delimiter := ',';
DestList.DelimitedText := Destinations[i];
WriteLn('Destinations from ' + CityNames[ord(TCities[i])] + ': ');
Graph[i].Index := i;
SetLength(Edge, DestList.Count);
for j := 0 to pred(DestList.Count) do
begin
WriteLn(DestList[j] + ' ' + IntToStr(AnsiIndexStr(DestList[j], CityNames)));
Edge[j] := AnsiIndexStr(DestList[j], CityNames);
end;
WriteLN();
end;
Result := Graph;
end;
var
Graph: TGraph;
Queue: TMinPrioQueue;
Prev: Array of Integer;
procedure Main;
begin
Graph := MakeGraph();
Queue := TMinPrioQueue.Create;
Queue.Insert
//Prev := DijkstraAlgorithm(Graph, 1);
//BacktrackDijkstra(Prev, 0);
end;
begin
end.
|
unit UIWrapper_LogSearchUnit;
interface
uses
FMX.ListBox, FMX.Edit, FMX.Controls, DB, System.UITypes, Classes, DCL_intf,
DBManager, StrUtils, SearchOption_Intf;
type
TUIWrapper_LogSearch = class(TObject)
private
FComboBox_LogTableName: TComboBox;
FEdit_SearchKeyword: TClearingEdit;
FButton_SearchLog: TButton;
FListBox_LogData: TListBox;
FLogDataSet: IStrMap;
FDBManager: TAbsDBManager;
FLogDataStrList: TStringList;
FOnLogDataSelected: TLogDataEvent;
protected
procedure SetDataByTableName(tableName: String);
function HasLogDataSet(tableName: String): Boolean;
procedure SetLogTables(dbmsName: String);
function GetFilterStr(keyword: String): String;
procedure ListBox_LogDataMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure ListBox_LogDataDragEnd(Sender: TObject);
procedure ComboBox_LogTableNameChange(Sender: TObject);
procedure ClearingEdit_KeywordKeyUp(Sender: TObject;
var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure Button_LogSearchClick(Sender: TObject);
procedure ListBox_LogDataDblClick(Sender: TObject);
procedure OnLogDataSelected_Proc(Sender: TObject; logData: ILogData);
public
constructor Create(logTableName: TComboBox; searchKeyword: TClearingEdit;
searchLog: TButton; logData: TListBox);
destructor Destroy; override;
procedure SetData(data: TDataSet);
procedure Clear;
procedure SearchLog(tableName, keyword: String);
procedure SetEnabled(val: Boolean);
procedure SetDBManager(dbm: TAbsDBManager);
published
property OnLogDataSelected: TLogDataEvent read FOnLogDataSelected write FOnLogDataSelected;
end;
implementation
uses
SysUtils, HashMap, QueryReader, Windows;
{ TEvent_SchOpt_LogSearch }
constructor TUIWrapper_LogSearch.Create(logTableName: TComboBox;
searchKeyword: TClearingEdit; searchLog: TButton; logData: TListBox);
begin
FComboBox_LogTableName := logTableName;
FEdit_SearchKeyword := searchKeyword;
FButton_SearchLog := searchLog;
FListBox_LogData := logData;
FLogDataSet := TStrHashMap.Create;
//SetLogTableToComboBox( dbm.GetDBMSName );
FListBox_LogData.OnMouseDown := ListBox_LogDataMouseDown;
FListBox_LogData.OnDragEnd := ListBox_LogDataDragEnd;
FListBox_LogData.OnDblClick := ListBox_LogDataDblClick;
FComboBox_LogTableName.OnChange := ComboBox_LogTableNameChange;
FEdit_SearchKeyword.OnKeyUp := ClearingEdit_KeywordKeyUp;
FButton_SearchLog.OnClick := Button_LogSearchClick;
end;
destructor TUIWrapper_LogSearch.Destroy;
begin
inherited;
end;
function TUIWrapper_LogSearch.GetFilterStr(keyword: String): String;
var
sList: TStringList;
begin
//sList := FDBManager.Get
end;
function TUIWrapper_LogSearch.HasLogDataSet(tableName: String): Boolean;
begin
result := ( FLogDataSet.ContainsKey( tableName ) = true ) and
( FLogDataSet.GetValue( tableName ) <> nil );
end;
procedure TUIWrapper_LogSearch.SearchLog(tableName, keyword: String);
var
data: TDataSet;
i: Integer;
sTarget: String;
begin
if HasLogDataSet( tableName ) = true then
begin
data := TDataSet( FLogDataSet.GetValue( tableName ) );
data.Open;
end
else
begin
exit;
end;
if keyword <> '' then
begin
data.Filter := 'msg like ''%' + keyword + '%''';
data.Filtered := true;
end
else
begin
data.Filter := '';
data.Filtered := false;
end;
//FListBox_LogData.
// for i := 0 to FListBox_LogData.Count - 1 do
// begin
// sTarget := FListBox_LogData.ListItems[ i ].Text;
//
// if ContainsStr( sTarget, keyword ) = true then
// FListBox_LogData.ListItems[ i ].Visible := true
// else
// FListBox_LogData.ListItems[ i ].Visible := false;
// end;
SetData( data );
end;
procedure TUIWrapper_LogSearch.SetData(data: TDataSet);
var
field: TField;
sDate: String;
i: Integer;
sbFieldVal: TStringBuilder;
begin
FListBox_LogData.Clear;
sbFieldVal := TStringBuilder.Create;
data.First;
while data.Eof = false do
begin
DateTimeToString( sDate, 'yyyy-MM-dd HH:mm:ss', data.Fields[ 0 ].AsDateTime );
for i := 1 to data.FieldCount - 1 do
begin
sbFieldVal.Append( ' ' + data.Fields[ i ].AsString )
end;
FListBox_LogData.Items.Add( sDate + '|' + sbFieldVal.ToString );
sbFieldVal.Clear;
data.Next;
end;
end;
procedure TUIWrapper_LogSearch.SetDataByTableName(tableName: String);
var
data: TDataSet;
qReader: TQueryReader;
sQuery: String;
begin
qReader := TQueryReader.Create( FDBManager.GetDBMSName, 'insightviewer' );
sQuery := qReader.GetQuery( 'datalog.' + tableName );
//sQuery := 'select datetime, division, actor, action || '' '' || alarmmessage from alarmlog;';
//FDBManager.Open;
data := FDBManager.ExecuteQuery( sQuery );
FLogDataSet.PutValue( tableName, data );
qReader.Free;
SetData( data );
FDBManager.Close;
end;
procedure TUIWrapper_LogSearch.SetDBManager(dbm: TAbsDBManager);
begin
FDBManager := dbm;
SetLogTables( dbm.GetDBMSName );
end;
procedure TUIWrapper_LogSearch.SetEnabled(val: Boolean);
begin
FComboBox_LogTableName.Enabled := val;
FEdit_SearchKeyword.Enabled := val;
FButton_SearchLog.Enabled := val;
FListBox_LogData.Enabled := val;
end;
procedure TUIWrapper_LogSearch.SetLogTables(dbmsName: String);
begin
if dbmsName = 'mssql' then
begin
FComboBox_LogTableName.Clear;
FComboBox_LogTableName.Items.Add( 'journal' );
end
else if dbmsName = 'firebird' then
begin
FComboBox_LogTableName.Clear;
FComboBox_LogTableName.Items.Add( 'EVENTLOG' );
FComboBox_LogTableName.Items.Add( 'ALARMLOG' );
end;
end;
procedure TUIWrapper_LogSearch.ListBox_LogDataMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
FListBox_LogData.AllowDrag := true;
end;
procedure TUIWrapper_LogSearch.OnLogDataSelected_Proc(Sender: TObject;
logData: ILogData);
begin
if Assigned( OnLogDataSelected ) = true then
OnLogDataSelected( Sender, logData );
end;
procedure TUIWrapper_LogSearch.ListBox_LogDataDblClick(Sender: TObject);
var
logData: TJournalData;
begin
logData := TJournalData.Create( FListBox_LogData.Selected.Text );
OnLogDataSelected_Proc( self, logData );
end;
procedure TUIWrapper_LogSearch.ListBox_LogDataDragEnd(Sender: TObject);
begin
FListBox_LogData.AllowDrag := false;
end;
procedure TUIWrapper_LogSearch.Clear;
begin
FLogDataSet.Clear;
end;
procedure TUIWrapper_LogSearch.ComboBox_LogTableNameChange(Sender: TObject);
begin
if FComboBox_LogTableName.ItemIndex > -1 then
begin
// if FLogDataStrList <> nil then FLogDataStrList.Free;
//
// FLogDataStrList := TStringList.Create;
// Copy( FLogDataStrList, FListBox_LogData.Items, FListBox_LogData.Items.InstanceSize );
SetDataByTableName( FComboBox_LogTableName.Selected.Text );
end;
end;
procedure TUIWrapper_LogSearch.ClearingEdit_KeywordKeyUp(Sender: TObject;
var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if KeyChar = #13 then
begin
SearchLog( FComboBox_LogTableName.Selected.Text, FEdit_SearchKeyword.Text );
end;
end;
procedure TUIWrapper_LogSearch.Button_LogSearchClick(Sender: TObject);
begin
SearchLog( FComboBox_LogTableName.Selected.Text, FEdit_SearchKeyword.Text );
end;
end.
|
{ 11/11/1999 9:11:55 AM > [sysdba on BILL] update: }
{ 11/11/1999 9:11:35 AM > [sysdba on BILL] checked out /To remove InfoPower
references }
unit ListSelect2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
datamod, Grids, DBGrids, Db, ActnList, Buttons, StdCtrls, DBISAMTb, TableCreator,
DBISAMTableAU, TickTable, sButton, sLabel, sSpeedButton;
type
TfrmListSelect2 = class(TForm)
OKBtn: TsButton;
CancelBtn: TsButton;
HelpBtn: TsButton;
IncludeBtn: TsSpeedButton;
IncAllBtn: TsSpeedButton;
ExcludeBtn: TsSpeedButton;
ExAllBtn: TsSpeedButton;
ActionList1: TActionList;
actAddSelected: TAction;
actAddAll: TAction;
actRemoveSelected: TAction;
actRemoveAll: TAction;
grdExclude: TDBGrid;
grdInclude: TDBGrid;
dsExc: TDataSource;
dsInc: TDataSource;
Label1: TsLabel;
Label2: TsLabel;
procedure actAddSelectedExecute(Sender: TObject);
procedure actRemoveSelectedExecute(Sender: TObject);
procedure grdExcludeDblClick(Sender: TObject);
procedure grdIncludeDblClick(Sender: TObject);
procedure actAddAllExecute(Sender: TObject);
procedure actRemoveAllExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure OKBtnClick(Sender: TObject);
private
FBaseList : TBaseList;
FKeys : TStringList;
procedure SetBaseList(const Value: TBaseList);
procedure RefreshButtons;
procedure AddToList;
procedure RemoveFromList;
{ Private declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent;ABaseList:TBaseList;ANoticeText:boolean);
destructor destroy;override;
property BaseList:TBaseList read FBaselist write SetBaseList;
end;
var
frmListSelect2: TfrmListSelect2;
implementation
uses dataReports;
{$R *.DFM}
constructor TfrmListSelect2.create(AOwner: TComponent;
ABaseList: TBaseList; ANoticeText: boolean);
begin
inherited create(AOwner);
tblInc.IndexDefs.clear;
tblInc.IndexDefs.Add('','Code',[ixPrimary,ixCaseInsensitive]);
tblInc.CreateTable;
tblInc.Active := true;
tblExc.IndexDefs.clear;
tblExc.IndexDefs.Add('','Code',[ixPrimary,ixCaseInsensitive]);
tblExc.CreateTable;
tblExc.Active := true;
BaseList := ABaseList;
FKeys := TStringList.Create;
end;
procedure TfrmListSelect2.SetBaseList(const Value: TBaseList);
procedure ReadTables(tbl1:TDBISAMTable);
begin
tbl1.First;
while not tbl1.eof do begin
if tbl1.fieldbyname('selected').asboolean then begin
tblInc.Append;
tblIncCode.Value := tbl1.fieldbyname('Code').asstring;
tblIncDesc.Value := tbl1.fieldbyname('Desc').asstring;
tblInc.Post;
end
else begin
tblExc.Append;
tblExcCode.Value := tbl1.fieldbyname('Code').asstring;
tblExcDesc.Value := tbl1.fieldbyname('Desc').asstring;
tblExc.Post;
end;
tbl1.Next;
end;
end;
begin
cursor := crHourGlass;
try
tblExc.emptyTable;
tblInc.EmptyTable;
with dmReports do begin
case value of
blTrak : begin
dmReports.Trak1Loaded := true; // this loads the table if needed
ReadTables(loTrak1);
caption := 'Select Categories';
end;
blOfcr : begin
dmReports.Ofcr1Loaded := true;
ReadTables(loOfcr1);
caption := 'Select Officers';
end;
blColl : begin
dmReports.Coll1Loaded := true;
ReadTables(loColl1);
caption := 'Select Collateral Codes';
end;
blBrch : begin
dmReports.Brch1Loaded := true;
ReadTables(loBrch1);
caption := 'Select Branches';
end;
blDivi : begin
dmReports.Divi1Loaded := true;
ReadTables(loDivi1);
caption := 'Select Divisions';
end;
end;
end;
finally
tblInc.First;
tblExc.First;
cursor := crDefault;
end;
RefreshButtons;
fBaseList := Value;
end;
procedure TfrmListSelect2.RefreshButtons;
begin
actAddSelected.enabled := tblExc.RecordCount > 0;
actAddAll.Enabled := tblExc.RecordCount > 0;
actRemoveSelected.Enabled := tblInc.RecordCount > 0;
actRemoveAll.Enabled := tblInc.RecordCount > 0;
end;
procedure TfrmListSelect2.AddToList;
begin
tblInc.Append;
tblIncCode.Value := tblExcCode.Value;
tblIncDesc.Value := tblExcDesc.Value;
tblInc.Post;
tblExc.Delete;
end;
procedure TfrmListSelect2.RemoveFromList;
begin
tblExc.Append;
tblExcCode.Value := tblIncCode.Value;
tblExcDesc.Value := tblIncDesc.Value;
tblExc.Post;
tblInc.Delete;
end;
procedure TfrmListSelect2.actAddSelectedExecute(Sender: TObject);
var bmark : TBookmark;
x : integer;
begin
bmark := tblExc.GetBookmark;
tblExc.DisableControls;
FKeys.Clear;
try
// mark them first
tblExc.first;
while (not tblExc.eof) do begin
if grdExclude.SelectedRows.CurrentRowSelected then FKeys.Add(tblExcCode.value);
tblExc.Next;
end;
// then move them
for x := 0 to pred(FKeys.Count) do begin
if tblExc.FindKey([FKeys[x]]) then AddToList;
end;
try
tblExc.GotoBookmark(bmark);
except
tblExc.first;
end;
finally
tblExc.EnableControls;
tblExc.FreeBookmark(bmark);
RefreshButtons;
end;
end;
procedure TfrmListSelect2.actRemoveSelectedExecute(Sender: TObject);
var bmark : TBookmark;
x : integer;
begin
bmark := tblInc.GetBookmark;
tblInc.DisableControls;
FKeys.Clear;
try
tblInc.first;
while (not tblInc.eof) do begin
if grdInclude.SelectedRows.CurrentRowSelected then FKeys.add(tblIncCode.Value);
tblInc.Next;
end;
// then move them
for x := 0 to pred(FKeys.Count) do begin
if tblInc.FindKey([FKeys[x]]) then RemoveFromList;
end;
try
tblInc.GotoBookmark(bmark);
except
tblInc.first;
end;
finally
tblInc.EnableControls;
tblInc.FreeBookmark(bmark);
RefreshButtons;
end;
end;
procedure TfrmListSelect2.grdExcludeDblClick(Sender: TObject);
begin
actAddSelected.Execute;
end;
procedure TfrmListSelect2.grdIncludeDblClick(Sender: TObject);
begin
actRemoveSelected.Execute;
end;
procedure TfrmListSelect2.actAddAllExecute(Sender: TObject);
begin
tblExc.First;
while not tblExc.Eof do begin
AddToList;
tblExc.First;
end;
RefreshButtons;
end;
procedure TfrmListSelect2.actRemoveAllExecute(Sender: TObject);
begin
tblInc.First;
while not tblInc.Eof do begin
RemoveFromList;
tblInc.First;
end;
RefreshButtons;
end;
destructor TfrmListSelect2.destroy;
begin
FKeys.Free;
tblExc.active := false;
tblExc.DeleteTable;
tblInc.Active := false;
tblInc.DeleteTable;
inherited;
end;
procedure TfrmListSelect2.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := modalresult in [mrOk,mrCancel];
if not canclose then MsgInformation('Select OK or CANCEL to close this dialog.');
end;
procedure TfrmListSelect2.OKBtnClick(Sender: TObject);
var switchit : boolean;
begin
cursor := crHourGlass;
try
with dmReports do begin
case baselist of
blTrak : begin
lotrak1.First;
while not lotrak1.eof do begin
if loTrak1selected.Value then switchit := tblExc.FindKey([loTrak1Code.value])
else switchit := tblInc.FindKey([loTrak1Code.value]);
if switchit then begin
loTrak1.edit;
loTrak1Selected.value := not loTrak1Selected.Value;
loTrak1.Post;
end;
loTrak1.Next;
end;
end;
blOfcr : begin
loOfcr1.First;
while not loOfcr1.eof do begin
if loOfcr1selected.Value then switchit := tblExc.FindKey([loOfcr1Code.value])
else switchit := tblInc.FindKey([loOfcr1Code.value]);
if switchit then begin
loOfcr1.edit;
loOfcr1Selected.value := not loOfcr1Selected.Value;
loOfcr1.Post;
end;
loOfcr1.Next;
end;
end;
blColl : begin
loColl1.First;
while not loColl1.eof do begin
if loColl1selected.Value then switchit := tblExc.FindKey([loColl1Code.value])
else switchit := tblInc.FindKey([loColl1Code.value]);
if switchit then begin
loColl1.edit;
loColl1Selected.value := not loColl1Selected.Value;
loColl1.Post;
end;
loColl1.Next;
end;
end;
blBrch : begin
loBrch1.First;
while not loBrch1.eof do begin
if loBrch1selected.Value then switchit := tblExc.FindKey([loBrch1Code.value])
else switchit := tblInc.FindKey([loBrch1Code.Value]);
if switchit then begin
loBrch1.edit;
loBrch1Selected.value := not loBrch1Selected.Value;
loBrch1.Post;
end;
loBrch1.Next;
end;
end;
blDivi : begin
loDivi1.First;
while not loDivi1.eof do begin
if loDivi1selected.Value then switchit := tblExc.FindKey([loDivi1Code.value])
else switchit := tblInc.FindKey([loDivi1Code.value]);
if switchit then begin
loDivi1.edit;
loDivi1Selected.value := not loDivi1Selected.Value;
loDivi1.Post;
end;
loDivi1.Next;
end;
end;
end;
end;
finally
cursor := crDefault;
end;
modalresult := mrOk;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
StringGrid1: TStringGrid;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
public
end;
type
tEintrag = Array [0..1] of string;
{ tDatabase }
tDatabase = class
Database : Array of tEintrag;
private
function GetEintrag(index: integer): tEintrag;
procedure SetEintrag(index: integer; AValue: tEintrag);
public
property Eintrag[index:integer] : tEintrag read GetEintrag write SetEintrag ; // strg shift C
procedure Add(AValue: tEintrag);
procedure DatabaseToGrid(AGrid : TStringGrid);
end;
var
Form1: TForm1;
Database : tDatabase;
implementation
{$R *.lfm}
{ tDatabase }
function tDatabase.GetEintrag(index: integer): tEintrag;
begin
if index < length(Database) then
result := Database[index];
end;
procedure tDatabase.SetEintrag(index: integer; AValue: tEintrag);
begin
if index < length(Database) then
Database[index] := AValue;
end;
procedure tDatabase.Add(AValue: tEintrag);
begin
SetLength(Database, Length(Database)+1);
Eintrag[Length(Database)-1] := AValue;
end;
procedure tDatabase.DatabaseToGrid(AGrid: TStringGrid);
var
i : integer;
begin
for i := 0 to Length(Database)-1 do
begin
AGrid.InsertRowWithValues(AGrid.RowCount,Eintrag[i]);
end;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
NeuerEintrag : TStringList;
Eintrag : Array of ansistring;
vNeuerEintrag : tEintrag;
begin
NeuerEintrag := TStringList.Create;
NeuerEintrag.Add(DateTimeToStr(now));
NeuerEintrag.Add('100°C');
setlength(Eintrag,2);
Eintrag[0] := DateTimeToStr(now);
Eintrag[1] := '101°C';
//StringGrid1.Rows[1]:= NeuerEintrag;
// StringGrid1.InsertRowWithValues(StringGrid1.RowCount,Eintrag);
NeuerEintrag.free;
vNeuerEintrag[0] := DateTimeToStr(now);
vNeuerEintrag[1] := '102°C';
Database.Add(vNeuerEintrag);
StringGrid1.RowCount:=1;
Database.DatabaseToGrid(StringGrid1);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Database := tDatabase.Create;
end;
end.
|
unit QueueModule;
{$MODE OBJFPC}
interface
type
TQueue = class(TObject)
private
FFront, FRear, FSize, FCapacity: Integer;
FQueue: Array of Integer;
function IsFull(): Boolean;
function IsEmpty(): Boolean;
function GetPeek(): Integer;
function GetSize(): Integer;
public
constructor Create(DefaultCapacity: Integer = 16);
function Enqueue(n: Integer): Boolean;
function Dequeue(): Integer;
function Contains(n: Integer): Boolean;
property Size: Integer read GetSize;
property Peek: Integer read GetPeek;
end;
implementation
constructor TQueue.Create(DefaultCapacity: Integer);
begin
Assert(DefaultCapacity <> 0, 'TQueue.Create: capacity must be greater than zero');
FCapacity := DefaultCapacity;
SetLength(FQueue, DefaultCapacity);
FFront := 0;
FRear := FCapacity - 1;
FSize := 0;
end;
function TQueue.IsFull(): Boolean;
begin
Result := (FSize = FCapacity);
end;
function TQueue.IsEmpty(): Boolean;
begin
Result := (FSize = 0);
end;
function TQueue.Enqueue(n: Integer): Boolean;
begin
if (IsFull) then
exit(False);
FRear := (FRear + 1) mod FCapacity;
FQueue[FRear] := n;
FSize := FSize + 1;
Result := True;
end;
function TQueue.Dequeue(): Integer;
begin
if IsEmpty() then
exit(MAXINT);
Result := FQueue[FFront];
FFront := (FFront + 1) mod FCapacity;
FSize := FSize - 1;
end;
function TQueue.Contains(n: Integer): Boolean;
var
i: Integer;
begin
i := FRear;
while i <> FFront do
begin
if n = FQueue[i] then
exit(True);
i := (i + 1) mod FCapacity;
end;
Result := False;
end;
function TQueue.GetSize: Integer;
var
i, cnt: Integer;
begin
i := FRear;
cnt := 0;
while i <> FFront do
begin
i := (i + 1) mod FCapacity;
cnt := cnt + 1;
end;
Result := cnt;
end;
function TQueue.GetPeek: Integer;
begin
if IsEmpty() then
begin
Result := -1;
exit;
end;
Result := FQueue[FFront];
end;
procedure Main;
var
q: TQueue;
begin
q := TQueue.Create;
with q do
begin
Enqueue(10);
Enqueue(20);
Enqueue(30);
WriteLn(q.Peek);
Free;
end;
end;
begin
Main;
end.
|
program distencworkercli;
{$mode objfpc}{$H+}
uses
Classes, Crt, SysUtils, lNet, lnetbase, IniFiles, Process, DateUtils, StrUtils,NumCPULib;
type TJob=Record
ProjectID,JobID:String;
FileName,FilePath:String;
user,pass:string;
WorkerID:String;
Started,Ended,LastUpdate:TDateTime;
EncCmd:string;
EncProcess,UpProcess:TProcess;
UploadID,UploadURL:String;
Encoder:String;
FrameCount:String;
Status,Progress:integer;
UpStarted:Boolean;
end;
{ TLTCPTest }
TLTCPTest = class
private
FQuit: boolean;
FCon: TLTcp; // the connection
{ these are all events which happen on our server connection. They are called inside CallAction
OnEr gets fired when a network error occurs.
OnRe gets fired when any of the server sockets receives new data.
OnDs gets fired when any of the server sockets disconnects gracefully.
}
procedure OnDs(aSocket: TLSocket);
procedure OnRe(aSocket: TLSocket);
procedure OnEr(const msg: string; aSocket: TLSocket);
public
constructor Create;
destructor Destroy; override;
// procedure Run;
end;
const
INI_SERVER_SECT='SERVER';
INI_WORKER_SECT='WORKER';
INI_UPLOAD_SECT='UPLOAD';
dc:Char=';'; //message delimiting char
OF_URL: array[0..4] of string =
('https://1fichier.com/login.pl?lg=en',
'https://api.1fichier.com/v1/upload/get_upload_server.cgi',
'https://upload.1fichier.com/upload.cgi?id=',
'https://upload.1fichier.com/end.pl?xid=',
'https://1fichier.com/console/get_dirs_for_upload.pl');
var
TCP: TLTCPTest;
SettingsINI:TINIFile;
ServerIP:string;
ServerPort:word;
BasePath:String;
SettingsFile:String;
CurlPath:String;
FFMpegPath,EncoderPath:String;
Jobs:Array of TJob;
JobCount:dword=0;
FQuit:Boolean;
StatusIntervalTime:word=30;
OF_COOKIE_TIME:TDateTime;
OF_COOKIE:String;
OF_COOKIE_INTERVAL:word=20;
OF_USER:String;
OF_PASS:String;
Workername:String;
CoreCount:longint;
LogFileName:String='log.txt';
LogFilePath:String;
LogFile:Text;
WorkDir,WorkDirName:String;
OS:String;
// implementation
{function StrToProcParams(const S:string;out P:TStringList);
begin
P:=TStringList.Create;
P.Delimiter:=' ';
P.DelimitedText:=S;
Result:=P;
P.Free;
end; }
procedure Log(var LogFile:Text; Line:String);
begin
append(LogFile);
writeln(Logfile,DateTimeToStr(Now)+' '+Line);
CloseFile(LogFile);
end;
procedure SaveINI;
begin
SetCurrentDir(BasePath);
SettingsINI := TINIFile.Create(SettingsFile);
try
SettingsINI.WriteString(INI_UPLOAD_SECT,'OF_COOKIE',OF_COOKIE);
SettingsINI.WriteDateTime(INI_UPLOAD_SECT,'OF_COOKIE_TIME',OF_COOKIE_TIME);
finally
FreeAndNil(SettingsINI);
end;
end;
procedure LoadIni;
begin
SettingsINI := TINIFile.Create(SettingsFile);
try
ServerIP:=SettingsINI.ReadString(INI_SERVER_SECT,'ServerIP','localhost');
ServerPort:=SettingsINI.ReadInteger(INI_SERVER_SECT,'ServerPort',6666);
Workername:=SettingsINI.ReadString(INI_WORKER_SECT,'Name','defaultworker');
CoreCount:=SettingsINI.ReadInteger(INI_WORKER_SECT,'threads',0);
WorkDirName:=SettingsINI.ReadString(INI_WORKER_SECT,'workdir','work');
OF_USER:=SettingsINI.ReadString(INI_UPLOAD_SECT,'OF_USER',OF_USER);
OF_PASS:=SettingsINI.ReadString(INI_UPLOAD_SECT,'OF_PASS',OF_PASS);
OF_COOKIE:=SettingsINI.Readstring(INI_UPLOAD_SECT,'OF_COOKIE','');
OF_COOKIE_TIME:=SettingsINI.ReadDateTime(INI_UPLOAD_SECT,'OF_COOKIE_TIME',EncodeDate(2000,1,1));
OF_COOKIE_INTERVAL:=SettingsINI.ReadInteger(INI_UPLOAD_SECT,'OF_COOKIE_INTERVAL',20);
finally
FreeAndNil(SettingsINI);
end;
end;
function GetCPUCores:word;
begin
{$IFDEF UNIX}
Result:=TNumCPULib.GetPhysicalCPUCount();
{$ENDIF}
{$IFDEF WINDOWS}
Result:=GetCPUCount;
{$ENDIF}
end;
function OSVersion: String;
var
osErr: integer;
response: longint;
begin
{$IFDEF LCLcarbon}
OSVersion := 'MAC';
{$ELSE}
{$IFDEF Linux}
OSVersion := 'LIN';
{$ELSE}
{$IFDEF UNIX}
OSVersion := 'LIN';
{$ELSE}
{$IFDEF WINDOWS}
OSVersion:= 'WIN';
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
procedure ExecToStrings(const ExecPath: string;
Params: array of string; POptions: TProcessOptions; out APOutput: TStringList;
ExtTProcess: TProcess = nil);
const
BUF_SIZE = 16384;
var
AProcess:TProcess;
OutputStream: TStream;
BytesRead: longint;
Buffer: array[1..BUF_SIZE] of byte;
begin
try
if ExtTProcess <> nil then AProcess:=ExtTProcess;
AProcess := TProcess.Create(nil);
AProcess.Executable := ExecPath;
AProcess.Options := POptions;
AProcess.Parameters.AddStrings(Params);
AProcess.Execute;
if poUsePipes in AProcess.Options then
begin
APOutput := nil;
OutputStream := TMemoryStream.Create;
while (AProcess.Output.NumBytesAvailable.ToBoolean) or (AProcess.Running) do
begin
BytesRead := AProcess.Output.Read(Buffer, BUF_SIZE);
OutputStream.Write(Buffer, BytesRead);
end;
APOutput := TStringList.Create;
with APOutput do
begin
OutputStream.Position := 0;
// Required to make sure all data is copied from the start
LoadFromStream(OutputStream);
end;
end;
finally
if ExtTProcess = nil then FreeAndNil(AProcess);
end;
end;
function GetOFCookie(out OF_COOKIE:string):boolean;
var
tmpp: dword;
CurlOutput:TStringList;
begin
CurlOutput:=TStringList.Create;
ExecToStrings(CurlPath, ['-v', {'--ipv4',} '-X', 'POST', '-F', 'mail=' + OF_USER, '-F', 'pass=' + OF_PASS, OF_URL[0]], [poUsePipes, poStderrToOutPut{,poNoConsole,poWaitOnExit}], CurlOutput);
tmpp := pos('SID=', CurlOutput.Text);
if tmpp>0 then begin
Result:=true;
OF_COOKIE := copy(CurlOutput.Text, tmpp, PosEx(';', CurlOutput.Text, tmpp + 4) - tmpp);
writeln('Got 1fichier cookie ' + OF_COOKIE);
//OF_COOKIE := StringReplace(OF_COOKIE, '"', '', [rfReplaceAll]);
end else Result:=false;
FreeAndNil(CurlOutput); FreeAndNil(CurlOutput);
end;
procedure Inits;
begin
BasePath := ExtractFilePath(ParamStr(0));
SettingsFile:=BasePath+'settings.ini';
writeln('settings=',SettingsFile,' exists=',fileexists(SettingsFile));
LoadIni;
OS:=OsVersion;
if OS='LIN' then begin
FFMpegPath := BasePath+'encoders'+PathDelim+'ffmpeg-git-20200211-amd64-static'+PathDelim+'ffmpeg';
EncoderPath := BasePath+'encoders'+PathDelim+'ffmpeg-git-20200211-amd64-static'+PathDelim+'aomenc';
CurlPath := '/bin/curl';
end
else if OS='WIN' then begin
FFMpegPath := BasePath+'encoders'+PathDelim+'ffmpeg-4.3-96152-g4fa2d5a692'+PathDelim+'ffmpeg.exe';
EncoderPath := BasePath+'encoders'+PathDelim+'ffmpeg-4.3-96152-g4fa2d5a692'+PathDelim+'aomenc.exe';
CurlPath := BasePath+'curl.exe';
end;
LogFilePath:=BasePath+LogFileName;
AssignFile(LogFile,LogFilePath);
if not FileExists(LogFilePath) then begin rewrite(LogFile);close(LogFile); end;
WorkDir:=BasePath+WorkDirName+PathDelim;
if not DirectoryExists(WorkDir) then
if CreateDir(WorkDir) then SetCurrentDir(WorkDir)
else else SetCurrentDir(WorkDir);
writeln('bet=',HoursBetween(Now,OF_COOKIE_TIME),'int=',OF_COOKIE_INTERVAL);
if (HoursBetween(Now,OF_COOKIE_TIME)>OF_COOKIE_INTERVAL) then
if GetOfCookie(OF_COOKIE) then OF_COOKIE_TIME:=Now;
if CoreCount=0 then CoreCount:=GetCPUCores;
writeln('os=',OS);
writeln(corecount,' cores');
Writeln('Press Esc to Exit, J to get one more job or 0 to kill all jobs (not working properly yet)');
end;
procedure CreateJob(var msg:tstringlist);
var i:word;
begin
inc(JobCount); setLength(Jobs,JobCount);
msg[6] := StringReplace(msg[6], 'ffmpeg',FFmpegPath,[rfReplaceAll]);
msg[6] := StringReplace(msg[6], 'aomenc',EncoderPath,[rfReplaceAll]);
// s:=StringReplace(S,'ffmpeg',EncoderPath,[rfReplaceAll]);
Jobs[JobCount-1].ProjectID:=msg[1];
Jobs[JobCount-1].JobID:=msg[2];
Jobs[JobCount-1].Encoder:=msg[3];
Jobs[JobCount-1].FrameCount:=msg[4];
Jobs[JobCount-1].FileName:=msg[5];
if not DirectoryExists(WorkDir+msg[1]+msg[2]) then
if CreateDir(WorkDir+msg[1]+msg[2]) then SetCurrentDir(WorkDir+msg[1]+msg[2])
else else SetCurrentDir(WorkDir+msg[1]+msg[2]);
Jobs[JobCOunt-1].FilePath:=WorkDir+msg[1]+msg[2]+PathDelim+msg[5];
Jobs[JobCount-1].WorkerID:=WorkerName;
Jobs[JobCount-1].UpStarted:=FALSE;
Jobs[JobCount-1].EncCmd:=msg[6];
log(LogFile,'All message strings:');
for i:=0 to msg.Count-1 do
log(logfile,inttostr(i)+' '+msg[i]);
writeln(msg[6]);
Jobs[JobCount-1].EncProcess:=TProcess.Create(nil);
Jobs[JobCount-1].EncProcess.Options:=[poUsePipes,poStderrToOutPut];
// Jobs[JobCount-1].EncProcess.Executable:='/usr/bin/konsole';
// Jobs[JobCount-1].EncProcesss.Parameters.Add('-e');
// Jobs[JobCount-1].EncProcess.Parameters.Add('/bin/bash');
if OS='LIN' then begin
Jobs[JobCount-1].EncProcess.Executable:='/bin/bash';
Jobs[JobCount-1].EncProcess.Parameters.Add('-c');
end else if OS='WIN' then begin
Jobs[JobCount-1].EncProcess.Executable:='cmd.exe';
Jobs[JobCount-1].EncProcess.Parameters.Add('/s');
Jobs[JobCount-1].EncProcess.Parameters.Add('/c');
end;
Jobs[JobCount-1].EncProcess.Parameters.Add(msg[6]);
Jobs[JobCOunt-1].EncProcess.Execute;
Jobs[JobCount-1].Started:=Now;
//RunCommand('konsole',['-e','/bin/bash','-c',s],t,[poStderrToOutPut]);
end;
procedure SendStopJob(const i:Word);
begin
TCP.FCon.SendMessage('STOPJOB'+dc+Jobs[i].ProjectID+dc+Jobs[i].JobID+dc+Jobs[i].WorkerID+dc);
TCP.FCon.Callaction;
end;
procedure DeleteJob(const i:dword);
begin
SendStopJob(i);
Delete(Jobs,i,1);
Dec(JobCount);
end;
procedure StopJob(const msg:tstringlist);
var Sl:TStringList;
i:longint;
begin
for i:=low(Jobs) to high(jobs) do
if Jobs[i].ProjectID=msg[1] then
if Jobs[i].JobID=msg[2] then begin DeleteJob(i); break; end;
end;
procedure ProcessMessage(const s:string);
var msg,sl:tstringlist;
i:word;
begin
sl:=TStringList.Create;
sl.QuoteChar:=#0;
sl.Delimiter:=dc; sl.StrictDelimiter:=true;
sl.DelimitedText:=s; // SHITTY CODE HERE Onwards
//for i:=0 to sl.count-1 do log(logfile,sl[i]);
repeat
msg:=TStringList.Create;
repeat
msg.add(sl[0]);
sl.Delete(0);
if sl.Count=0 then break
else If (sl[0]='STOPJOB') OR (sl[0]='TAKEJOB') then break; //then break;
until 1=0;
if msg[0]='STOPJOB' then StopJob(msg);
if msg[0]='TAKEJOB' then CreateJob(msg);
msg.free;
until sl.Count=0;
sl.free;
end;
procedure TLTCPTest.OnRe(aSocket: TLSocket);
var
s,t: string;
begin
if aSocket.GetMessage(s) > 0 then begin
Writeln(s);
Log(LogFile,'Got message: ');
Log(LogFile,S);
ProcessMessage(s);
end;
end;
procedure TLTCPTest.OnEr(const msg: string; aSocket: TLSocket);
begin
Writeln(msg); // if error occured, write it
FQuit := true; // and quit ASAP
end;
constructor TLTCPTest.Create;
begin
FCon := TLTCP.Create(nil); // create new TCP connection with no parent component
FCon.OnError := @OnEr; // assign callbacks
FCon.OnReceive := @OnRe;
FCOn.OnDisconnect := @OnDs;
FCon.Timeout := 150; // responsive enough, but won't hog cpu
end;
destructor TLTCPTest.Destroy;
begin
FCon.Free; // free the connection
inherited Destroy;
end;
procedure ReadProcOutput(var Proc:TProcess;var APOutput:TStringList);
const
BUF_SIZE = 16384; //changed from 2048
var OutputStream: TStream;
BytesRead: longint;
Buffer: array[1..BUF_SIZE] of byte;
begin
OutputStream := TMemoryStream.Create;
OutputStream.Position := 0;
while (Proc.Output.NumBytesAvailable.ToBoolean) do begin
BytesRead := Proc.Output.Read(Buffer, BUF_SIZE);
OutputStream.Write(Buffer, BytesRead);
end;
with APOutput do
begin
OutputStream.Position := 0;
// Required to make sure all data is copied from the start
LoadFromStream(OutputStream);
end;
OutputStream.Free;
end;
procedure GenerateProgress(const p:dword;const POutput:TSTringList);
var pr:string;
begin
if POutput.Text<>'' then begin
// writeln('output for ',Jobs[p].FileName,' is:');
// writeln(Poutput.text);
if pos('frame',POutput.Text)>0 then begin
pr:=copy(POutput.text,posex('/',POutput.Text,pos('frame',POutput.Text))+1,6);
pr:=trim(pr);
if pr<>'' then
try
Jobs[p].Progress:=trunc((strtoint(pr)/strtoint(Jobs[p].FrameCount))*100);
except
On E : EConvertError do;
end;
end;
end;
end;
procedure SendProgress(const Job:TJob);
begin
if TCP.FCon.Connected then begin
TCP.FCon.SendMessage('STATS'+dc+Job.ProjectID+dc+Job.JobID+dc+Job.WorkerID+dc+inttostr(Job.Progress)+dc+Job.UploadURL+dc);
TCP.FCon.Callaction;
end;
end;
procedure TLTCPTest.OnDs(aSocket: TLSocket);
begin
Writeln('Lost connection');
end;
procedure RunCurlUpload(var Job:TJob);
var
CurlOutput:TStringList;
begin
CurlOutput:=TStringList.Create;
ExecToStrings(CurlPath, ['-H', 'Content-Type: application/json','-X','POST',OF_URL[1]], [poUsePipes, poNoConsole], CurlOutput);
Job.UploadID := copy(CurlOutput[0], pos('"id":"', CurlOutput[0]) + 6, 10);
CurlOutput.Clear; // '2>',Job.FilePath+'.curld'] -?why
writeln('Got UploadId=' + Job.UploadId);
Log(LogFile,'Got UploadId=' + Job.UploadId);
ExecToStrings(CurlPath,['-v','-b',OF_COOKIE,'-F','file[]=@' + '"' + Job.FilePath + '"' +';filename=' + '"' + Job.FileName + '"', OF_URL[2] + Job.UploadID],[poWaitOnExit,poNoConsole],CurlOutput,Job.UpProcess);
FreeAndNil(CurlOutput);
end;
procedure StartUploadPiece(var Job:TJob);
begin
RunCurlUpload(Job);
Job.UpStarted:=True;
end;
function IsTaskFinished(const AProcess:TProcess):boolean;
begin
if Assigned(AProcess) then
if AProcess.Running then Result:=false
else Result:=true else Result:=true;
end;
procedure GetUploadURL(var Job:TJob);
var CurlOutput:TStringList;
begin
CurlOutput:=TStringList.Create;
ExecToStrings(CurlPath,['-i','-H','JSON: 1','-H','Accept: application/json',OF_URL[3] + Job.UploadID],[poUsePipes,poWaitOnExit,poNoConsole],CurlOutput);
Job.UploadURL := Copy(CurlOutput.Text, pos('"download":"', CurlOutput.Text) + 12, 42);
Writeln('Upload URL=',Job.UploadURL);
Log(LogFile,'Uploaded '+Job.FileName+' at '+Job.UploadURL);
CurlOutput.Free;
end;
procedure SendFinished(var Job:TJob);
begin
writeln('we got to sendfinished procedure');
SendProgress(Job);
Sleep(100);
end;
function GetFileSize(const path:string):Int64;
var Info : TUnicodeSearchRec;
begin
If FindFirst(path,faAnyFile, Info)=0 then
Result:=Info.Size;
FindClose(Info);
end;
procedure KillAllJobs;
var i:longint;
begin
for i:=high(Jobs) downto low(jobs) do
if Jobs[i].EncProcess.Running then Jobs[i].EncProcess.Terminate(1);
end;
procedure GetJob;
begin
TCP.FCon.SendMessage('GETJOB'+dc+OS+dc);
TCP.FCon.Callaction;
end;
procedure MainLoop;
var i:longint=-1;
POutput:TStringList;
c:char;
FQuit:Boolean;
begin
FQuit:=False;
repeat
if not (TCP.FCon.Connected) then begin
writeln('We are disconnected... trying to connect');
if TCP.FCon.Connect(ServerIP, ServerPort) then begin // if connect went ok
TCP.FCon.CallAction;
if TCP.FCon.Connected then Writeln('Connected, press ''escape'' to quit');
end;
end;
if Keypressed then begin
c := Readkey;
if c=#27 then FQuit := true;
if c='j' then GetJob;
if c='+' then begin inc(corecount); writeln('Threads is now ',CoreCount); end;
if c='-' then begin dec(corecount); writeln('Threads is now ',CoreCount); end;
if c='0' then KillAllJobs;
end;
if CoreCount>0 then if JobCount < CoreCount then GetJob;
for i:=High(jobs) downto low(jobs) do begin
POutput:=TStringList.Create;
ReadProcOutput(Jobs[i].EncProcess,POutput);
GenerateProgress(i,POutput); //can be moved below the if after debug //ParseOutput to Job[i].Progress;
if secondsbetween(Now,Jobs[i].LastUpdate) > StatusIntervalTime then begin
SendProgress(Jobs[i]); //Send Job[i].Progress to Server;
Jobs[i].LastUpdate:=Now;
if (IsTaskFinished(Jobs[i].EncProcess)) then
if (FileExists(Jobs[i].FilePath)) AND (GetFileSize(Jobs[i].FilePath)>2500) then begin //If encode is finished
Log(LogFile,'File '+Jobs[i].FilePath+' is encoded');
If not Jobs[i].UpStarted then begin log(logfile,'trying to up '+jobs[i].Filepath); StartUploadPiece(Jobs[i]); end; //initiate the upload process
if IsTaskFinished(Jobs[i].UpProcess) then begin //if the upload process finished
if Jobs[i].UploadURL='' then GetUploadURL(Jobs[i]); //if we don't already have the UrL then get it
if Jobs[i].UploadURL<>'' then BEGIN SendFinished(Jobs[i]); DeleteJob(i); end; //if we have url then send it and if server received the url ok then delete the job
end;
end else begin SendStopJob(i); DeleteJob(i); end;
end;
writeln(POutput.Text);
FreeAndNil(POutput);
end;
writeln('JOBS=',jobcount);
TCP.FCon.Callaction;
sleep(500);
if JobCount>0 then if secondsbetween(Now,Jobs[JobCount-1].Started) in [3..4] then SendProgress(Jobs[i]); //send the very first 1 or 2 stats updates to serevr before sending every 30 seconds
if (HoursBetween(Now,OF_COOKIE_TIME)>OF_COOKIE_INTERVAL) then
if GetOfCookie(OF_COOKIE) then OF_COOKIE_TIME:=Now;
if FQuit then for i:=high(jobs) downto low(jobs) do SendStopJob(i);
until FQuit;
end;
begin
Inits;
TCP := TLTCPTest.Create;
MainLoop;
SaveINI;
TCP.Free;
end.
|
unit Thread.ExtratoExpressas;
interface
uses
System.Classes, Common.ENum, Common.Utils, Control.Bases, Control.Cadastro, Control.EntregadoresExpressas, Control.Entregas,
Control.ExtraviosMultas, Control.Lancamentos, Control.Parametros, System.SysUtils, FireDAC.Comp.DataSet,
System.DateUtils;
type
TTHead_ExtratoExpressas = class(TThread)
private
procedure StartProcess;
procedure StopProcess;
procedure UpdateLOG;
protected
procedure Execute; override;
public
bVolumeExtra: Boolean;
bProcessaAnteriores: Boolean;
dtDataInicial: TDate;
dtDataFinal: TDate;
sListaClientes: String;
sListaBases: String;
iAno: Integer;
iMes: Integer;
iQuinzena: Integer;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TTHead_ExtratoExpressas.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses Data.SisGeF, Global.Parametros;
{ TTHead_ExtratoExpressas }
procedure TTHead_ExtratoExpressas.Execute;
var
FEntregas: TEntregasControl;
FLancamentos : TLancamentosControl;
FExtravios: TExtraviosMultasControl;
FEntregadores : TEntregadoresExpressasControl;
aParam, pParam: array of variant;
sExtrato, sUniqueKey, sLocate: String;
dtData1: TDate;
bFlagGrava: Boolean;
iDias, iAgente, iEntregador, iClienteEmpresa: Integer;
begin
try
try
{processa o extrato}
Synchronize(StartProcess);
FEntregas := TEntregasControl.Create;
if Data_Sisgef.mtbExtratosExpressas.Active then
begin
Data_Sisgef.mtbExtratosExpressas.Close;
end;
SetLength(aParam,9);
aParam[0] := bVolumeExtra;
aParam[1] := bProcessaAnteriores;
aParam[2] := dtDataInicial;
aParam[3] := dtDataFinal;
aParam[4] := sListaClientes;
aParam[5] := sListaBases;
aParam[6] := iAno;
aParam[7] := iMes;
aParam[8] := iQuinzena;
if FEntregas.EntregasExtratoEntregadores(aParam) then
begin
Data_Sisgef.mtbExtratosExpressas.Open;
Data_Sisgef.mtbExtratosExpressas.CopyDataSet(FEntregas.Entregas.Query,[coRestart, coAppend]);
Data_Sisgef.mtbExtratosExpressas.First;
end
else
begin
Global.Parametros.psMessage := 'Não existem informações de entregas neste período!';
Global.Parametros.pbProcess := False;
end;
Finalize(aParam);
Fentregas.Entregas.Query.Close;
Fentregas.Entregas.Query.Connection.Close;
if not Global.Parametros.pbProcess then
begin
Exit;
end;
sUniqueKey := Common.Utils.TUtils.GenerateUniqueKey('exp');
while not Data_Sisgef.mtbExtratosExpressas.Eof do
begin
if StrToIntDef(Data_Sisgef.mtbExtratosExpressasnum_extrato.AsString,0) = 0 then
begin
dtData1 := StrToDate('31/12/1899');
iDias := DaysBetween(dtData1,dtDataFinal);
sExtrato := IntToStr(iDias) + IntToStr(Data_Sisgef.mtbExtratosExpressascod_base.AsInteger) +
IntToStr(Data_Sisgef.mtbExtratosExpressascod_entregador.AsInteger);
Data_Sisgef.mtbExtratosExpressas.Edit;
Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime := dtDataInicial;
Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime := dtDataFinal;
Data_Sisgef.mtbExtratosExpressasnum_extrato.AsString := sExtrato;
Data_Sisgef.mtbExtratosExpressasdes_unique_key.AsString := sUniqueKey;
Data_Sisgef.mtbExtratosExpressas.Post;
end;
Data_Sisgef.mtbExtratosExpressas.Next;
end;
Data_Sisgef.mtbExtratosExpressas.First;
{processa os lançamentos}
FLancamentos := TLancamentosControl.Create;
SetLength(aParam,2);
aParam := [dtDataFinal,'S'];
if FLancamentos.ExtratoLancamentosEntregador(aParam) then
begin
FLancamentos.Lancamentos.Query.First;
FEntregadores := TEntregadoresExpressasControl.Create;
while not FLancamentos.Lancamentos.Query.Eof do
begin
SetLength(pParam,2);
pParam :=['CADASTRO', FLancamentos.Lancamentos.Query.FieldByName('cod_entregador').AsInteger];
if FEntregadores.LocalizarExato(pParam) then
begin
iAgente := FEntregadores.Entregadores.Agente;
iEntregador := FEntregadores.Entregadores.Entregador;
iClienteEmpresa := FEntregadores.Entregadores.Cliente;
bFlagGrava := True;
if not sListaClientes.IsEmpty then
begin
if Pos(iClienteEmpresa.ToString,sListaClientes) = 0 then
begin
bFlagGrava := False;
end;
end;
if bFlagGrava then
begin
if not sListaBases.IsEmpty then
begin
if Pos(iAgente.ToString,sListaBases) = 0 then
begin
bFlagGrava := False;
end;
end;
end;
Finalize(pParam);
if bFlagGrava then
begin
sLocate := 'cod_entregador = ' + iEntregador.ToString;
if Data_Sisgef.mtbExtratosExpressas.LocateEx(sLocate,[]) then
begin
Data_Sisgef.mtbExtratosExpressas.Edit;
if FLancamentos.Lancamentos.Query.FieldByName('des_tipo').AsString = 'CREDITO' then
begin
Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat := FLancamentos.Lancamentos.Query.FieldByName('val_total').AsFloat;
end
else if FLancamentos.Lancamentos.Query.FieldByName('des_tipo').AsString = 'DEBITO' then
begin
Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat := (0 - FLancamentos.Lancamentos.Query.FieldByName('val_total').AsFloat);
end;
Data_Sisgef.mtbExtratosExpressas.Post
end
else
begin
sExtrato := '0';
dtData1 := StrToDate('31/12/1899');
iDias := DaysBetween(dtData1, dtDataFinal);
sExtrato := IntToStr(iDias) + IntToStr(iAgente) +
IntToStr(iEntregador);
Data_Sisgef.mtbExtratosExpressas.Insert;
Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime := dtDataInicial;
Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime := dtDataFinal;
Data_Sisgef.mtbExtratosExpressascod_base.AsInteger := iAgente;
Data_Sisgef.mtbExtratosExpressascod_entregador.AsInteger := iEntregador;
Data_Sisgef.mtbExtratosExpressasnum_extrato.AsString := sExtrato;
Data_Sisgef.mtbExtratosExpressasval_verba.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasqtd_volumes_extra.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasqtd_entregas.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasqtd_atraso.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasval_performance.AsFloat := 0;
if FLancamentos.Lancamentos.Query.FieldByName('des_tipo').AsString = 'CREDITO' then
begin
Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat := FLancamentos.Lancamentos.Query.FieldByName('val_total').AsFloat;
Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat := 0;
end
else if FLancamentos.Lancamentos.Query.FieldByName('des_tipo').AsString = 'DEBITO' then
begin
Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat := (0 - FLancamentos.Lancamentos.Query.FieldByName('val_total').AsFloat);
end;
Data_Sisgef.mtbExtratosExpressasval_extravios.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasid_extrato.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasnum_ano.AsInteger := iAno;
Data_Sisgef.mtbExtratosExpressasnum_mes.AsInteger := iMes;
Data_Sisgef.mtbExtratosExpressasnum_quinzena.AsInteger := iQuinzena;
Data_Sisgef.mtbExtratosExpressasqtd_volumes.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasval_total_empresa.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasdes_unique_key.AsString := sUniqueKey;
Data_Sisgef.mtbExtratosExpressascod_cliente.AsInteger := iClienteEmpresa;
Data_Sisgef.mtbExtratosExpressas.Post;
end;
end;
end;
end;
Finalize(aParam);
FEntregadores.Free;
end;
{processa os extravios}
FExtravios := TExtraviosMultasControl.Create;
if FExtravios.ExtraviosExtratoEntregadores() then
begin
FExtravios.Extravios.Query.First;
FEntregadores := TEntregadoresExpressasControl.Create;
while not FLancamentos.Lancamentos.Query.Eof do
begin
SetLength(pParam,2);
pParam :=['ENTREGADOR', FExtravios.Extravios.Query.FieldByName('cod_entregador').AsInteger];
if FEntregadores.LocalizarExato(aParam) then
begin
iAgente := FEntregadores.Entregadores.Agente;
iEntregador := FEntregadores.Entregadores.Entregador;
iClienteEmpresa := FEntregadores.Entregadores.Cliente;
bFlagGrava := True;
if not sListaClientes.IsEmpty then
begin
if Pos(iClienteEmpresa.ToString,sListaClientes) = 0 then
begin
bFlagGrava := False;
end;
end;
if bFlagGrava then
begin
if not sListaBases.IsEmpty then
begin
if Pos(iAgente.ToString,sListaBases) = 0 then
begin
bFlagGrava := False;
end;
end;
end;
if bFlagGrava then
begin
sLocate := 'cod_entregador = ' + iEntregador.ToString;
if Data_Sisgef.mtbExtratosExpressas.LocateEx(sLocate,[]) then
begin
Data_Sisgef.mtbExtratosExpressas.Edit;
Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat := (0 - FExtravios.Extravios.Query.FieldByName('val_total').AsFloat);
Data_Sisgef.mtbExtratosExpressas.Post
end
else
begin
sExtrato := '0';
dtData1 := StrToDate('31/12/1899');
iDias := DaysBetween(dtData1, dtDataFinal);
sExtrato := IntToStr(iDias) + IntToStr(iAgente) +
IntToStr(iEntregador);
Data_Sisgef.mtbExtratosExpressas.Insert;
Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime := dtDataInicial;
Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime := dtDataFinal;
Data_Sisgef.mtbExtratosExpressascod_base.AsInteger := iAgente;
Data_Sisgef.mtbExtratosExpressascod_entregador.AsInteger := iEntregador;
Data_Sisgef.mtbExtratosExpressasnum_extrato.AsString := sExtrato;
Data_Sisgef.mtbExtratosExpressasval_verba.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasqtd_volumes_extra.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasqtd_entregas.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasqtd_atraso.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasval_performance.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasval_extravios.AsFloat := (0 - FExtravios.Extravios.Query.FieldByName('val_total').AsFloat);
Data_Sisgef.mtbExtratosExpressasid_extrato.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasnum_ano.AsInteger := iAno;
Data_Sisgef.mtbExtratosExpressasnum_mes.AsInteger := iMes;
Data_Sisgef.mtbExtratosExpressasnum_quinzena.AsInteger := iQuinzena;
Data_Sisgef.mtbExtratosExpressasqtd_volumes.AsInteger := 0;
Data_Sisgef.mtbExtratosExpressasval_total_empresa.AsFloat := 0;
Data_Sisgef.mtbExtratosExpressasdes_unique_key.AsString := sUniqueKey;
Data_Sisgef.mtbExtratosExpressascod_cliente.AsInteger := iClienteEmpresa;
Data_Sisgef.mtbExtratosExpressas.Post;
end;
end;
end;
end;
end;
Synchronize(StopProcess);
Global.Parametros.psMessage := 'Processo concluído. ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now);
Except on E: Exception do
begin
Global.Parametros.psMessage := '** ERROR **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message;
Global.Parametros.pbProcess := False;
end;
end;
finally
FEntregas.Free;
end;
end;
procedure TTHead_ExtratoExpressas.StartProcess;
begin
Global.Parametros.pdPos := 0;
Global.Parametros.psMessage := '';
Global.Parametros.psLOG := '';
Global.Parametros.pbProcess := True;
end;
procedure TTHead_ExtratoExpressas.StopProcess;
begin
Global.Parametros.pbProcess := False;
end;
procedure TTHead_ExtratoExpressas.UpdateLOG();
begin
if Global.Parametros.psLOG <> '' then
begin
Global.Parametros.psLOG := Global.Parametros.psLOG + #13;
end;
Global.Parametros.psLOG := Global.Parametros.psLOG + Global.Parametros.psMessage;
end;
end.
|
unit CommUnit;
interface
type
IFeedback = interface(IInterface)
['{0FBE993E-1FC4-4E8A-B014-53A0D82B2DC9}']
procedure WriteMessage(const msg:string);
procedure SetProgressMinMax(min,max:Integer);
procedure SetPosition(position:Integer);
end;
TComm = class(TObject)
private
procedure Phase1;
procedure Phase2;
protected
FFeedback: IFeedback;
public
constructor Create(feedback: IFeedback);
procedure DoWork;
end;
implementation
uses SysUtils;
{ TComm }
constructor TComm.Create(feedback: IFeedback);
begin
inherited Create;
Ffeedback := feedback;
end;
procedure TComm.DoWork;
var
i : integer;
begin
Phase1;
FFeedback.SetProgressMinMax(0, 99);
for i := 0 to 99 do
begin
Ffeedback.WriteMessage(Format('Durchlauf %d', [i]));
Ffeedback.SetPosition(i);
Sleep(20);
end;
end;
procedure TComm.Phase1;
begin
Ffeedback.WriteMessage('Phase 1...');
end;
procedure TComm.Phase2;
begin
end;
end.
|
unit ArchManImplementation;
interface
uses
ComObj, ActiveX, ArchMan_TLB, StdVcl, Classes,
FileMan, IniFiles, Windows, SysUtils{, SyncObjs};
type
TDDSArchiveManager = class(TAutoObject, IDDSArchiveManager)
private
FileManager:TFileManager;
Ini:TIniFile;
protected
// IDDSArchiveManager
procedure getLastRecTime(TrackID: Integer; out Time: TDateTime); safecall;
procedure readRecords(TrackID: Integer; FromTime: TDateTime;
Count: Integer; out Data: WideString); safecall;
procedure writeRecords(TrackID: Integer; FromTime: TDateTime;
Count: Integer; const Data: WideString); safecall;
procedure setTrackInfo(ID, RecSize, RecsPerDay: Integer); safecall;
procedure applySubstitutions(const Src: WideString; TrackID: Integer;
Time: TDateTime; out Result: WideString); safecall;
procedure StrToTrackID(const Str: WideString; out TrackID: Integer);
safecall;
{ Protected declarations }
public
constructor Create(aIni:TIniFile);
procedure AfterConstruction;override;
procedure BeforeDestruction;override;
procedure timerProc;
end;
implementation
uses ComServ,Main;
procedure TDDSArchiveManager.getLastRecTime(TrackID: Integer;
out Time: TDateTime);
begin
FileManager.GetLastRecTime(TrackID,Time);
end;
procedure TDDSArchiveManager.readRecords(TrackID: Integer;
FromTime: TDateTime; Count: Integer; out Data: WideString);
begin
FileManager.readRecords(TrackID,FromTime,Count,Data);
end;
procedure TDDSArchiveManager.writeRecords(TrackID: Integer;
FromTime: TDateTime; Count: Integer; const Data: WideString);
begin
FileManager.writeRecords(TrackID,FromTime,Count,Data);
end;
procedure TDDSArchiveManager.setTrackInfo(ID, RecSize,
RecsPerDay: Integer);
begin
FileManager.setTrackInfo(ID,RecSize,RecsPerDay);
end;
procedure TDDSArchiveManager.applySubstitutions(const Src: WideString;
TrackID: Integer; Time: TDateTime; out Result: WideString);
begin
Result:=FileMan.ApplySubstitutions(Src,TrackID,Time);
end;
procedure TDDSArchiveManager.StrToTrackID(const Str: WideString;
out TrackID: Integer);
begin
FileManager.StrToTrackID(Str,TrackID);
end;
constructor TDDSArchiveManager.Create(aIni: TIniFile);
begin
inherited Create;
Ini:=aIni;
end;
procedure TDDSArchiveManager.AfterConstruction;
begin
inherited;
FileManager:=TFileManager.CreateFromIniSection(Ini,'Archive');
end;
procedure TDDSArchiveManager.BeforeDestruction;
begin
Ini.Free;
FileManager.Free;
inherited;
end;
procedure TDDSArchiveManager.timerProc;
begin
FileManager.timerProc;
end;
initialization
TAutoObjectFactory.Create(ComServer, TDDSArchiveManager, Class_DDSArchiveManager,
ciInternal,tmSingle);
end.
|
unit Thread_201010_importar_pedidos_direct;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections,
Model.PlanilhaEntradaDIRECT, Control.Entregas, Control.PlanilhaEntradaDIRECT, Control.Sistema, FireDAC.Comp.Client, Common.ENum;
type
Tthread_201010_importar_pedidos_direct = class(TThread)
private
{ Private declarations }
FEntregas: TEntregasControl;
FPlanilha : TPlanilhaEntradaDIRECTControl;
FPlanilhasCSV : TObjectList<TPlanilhaEntradaDIRECT>;
sMensagem: String;
FdPos: Double;
bCancel : Boolean;
iPos : Integer;
iLinha : Integer;
iTotal: Integer;
fdEntregasInsert: TFDQuery;
fdEntregasUpdate: TFDQuery;
protected
procedure Execute; override;
procedure UpdateLog;
procedure UpdateProgress;
procedure TerminateProcess;
procedure BeginProcesso;
procedure SetupClassUpdate(FDQuery: TFDQuery);
procedure SetupClassInsert(i: Integer);
public
FFile: String;
iCodigoCliente: Integer;
end;
const
TABLENAME = 'tbentregas';
SQLINSERT = 'INSERT INTO ' + TABLENAME +
'(NUM_NOSSONUMERO, COD_AGENTE, COD_ENTREGADOR, COD_CLIENTE, NUM_NF, NOM_CONSUMIDOR, DES_ENDERECO, DES_COMPLEMENTO, ' +
'DES_BAIRRO, NOM_CIDADE, NUM_CEP, NUM_TELEFONE, DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO, QTD_VOLUMES, DAT_ATRIBUICAO, ' +
'DAT_BAIXA, DOM_BAIXADO, DAT_PAGAMENTO, DOM_PAGO, DOM_FECHADO, COD_STATUS, DAT_ENTREGA, QTD_PESO_REAL, ' +
'QTD_PESO_FRANQUIA, VAL_VERBA_FRANQUIA, VAL_ADVALOREM, VAL_PAGO_FRANQUIA, VAL_VERBA_ENTREGADOR, NUM_EXTRATO, ' +
'QTD_DIAS_ATRASO, QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO, DES_TIPO_PESO, DAT_RECEBIDO, DOM_RECEBIDO, ' +
'NUM_CTRC, NUM_MANIFESTO, DES_RASTREIO, NUM_LOTE_REMESSA, DES_RETORNO, DAT_CREDITO, DOM_CREDITO, NUM_CONTAINER, ' +
'VAL_PRODUTO, QTD_ALTURA, QTD_LARGURA, QTD_COMPRIMENTO, COD_FEEDBACK, DAT_FEEDBACK, DOM_CONFERIDO, NUM_PEDIDO, ' +
'COD_CLIENTE_EMPRESA, COD_AWB1) ' +
'VALUES ' +
'(:NUM_NOSSONUMERO, :COD_AGENTE, :COD_ENTREGADOR, :COD_CLIENTE, :NUM_NF, :NOM_CONSUMIDOR, :DES_ENDERECO, ' +
':DES_COMPLEMENTO, :DES_BAIRRO, :NOM_CIDADE, :NUM_CEP, :NUM_TELEFONE, :DAT_EXPEDICAO, :DAT_PREV_DISTRIBUICAO, ' +
':QTD_VOLUMES, :DAT_ATRIBUICAO, :DAT_BAIXA, :DOM_BAIXADO, :DAT_PAGAMENTO, :DOM_PAGO, :DOM_FECHADO, :COD_STATUS, ' +
':DAT_ENTREGA, :QTD_PESO_REAL, :QTD_PESO_FRANQUIA, :VAL_VERBA_FRANQUIA, :VAL_ADVALOREM, :VAL_PAGO_FRANQUIA, ' +
':VAL_VERBA_ENTREGADOR, :NUM_EXTRATO, :QTD_DIAS_ATRASO, :QTD_VOLUMES_EXTRA, :VAL_VOLUMES_EXTRA, :QTD_PESO_COBRADO, ' +
':DES_TIPO_PESO, :DAT_RECEBIDO, :DOM_RECEBIDO, :NUM_CTRC, :NUM_MANIFESTO, :DES_RASTREIO, :NUM_LOTE_REMESSA, ' +
':DES_RETORNO, :DAT_CREDITO, :DOM_CREDITO, :NUM_CONTAINER, :VAL_PRODUTO, :QTD_ALTURA, :QTD_LARGURA, :QTD_COMPRIMENTO, ' +
':COD_FEEDBACK, :DAT_FEEDBACK, :DOM_CONFERIDO, :NUM_PEDIDO, :COD_CLIENTE_EMPRESA, :COD_AWB1);';
SQLUPDATE = 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'COD_AGENTE = :COD_AGENTE, COD_ENTREGADOR = :COD_ENTREGADOR, ' +
'COD_CLIENTE = :COD_CLIENTE, NUM_NF = :NUM_NF, NOM_CONSUMIDOR = :NOM_CONSUMIDOR, DES_ENDERECO = :DES_ENDERECO, ' +
'DES_COMPLEMENTO = :DES_COMPLEMENTO, DES_BAIRRO = :DES_BAIRRO, NOM_CIDADE = :NOM_CIDADE, NUM_CEP = :NUM_CEP, ' +
'NUM_TELEFONE = :NUM_TELEFONE, DAT_EXPEDICAO = :DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO = :DAT_PREV_DISTRIBUICAO, ' +
'QTD_VOLUMES = :QTD_VOLUMES, DAT_ATRIBUICAO = :DAT_ATRIBUICAO, DAT_BAIXA = :DAT_BAIXA, DOM_BAIXADO = :DOM_BAIXADO, ' +
'DAT_PAGAMENTO = :DAT_PAGAMENTO, DOM_PAGO = :DOM_PAGO, DOM_FECHADO = :DOM_FECHADO, COD_STATUS = :COD_STATUS, ' +
'DAT_ENTREGA = :DAT_ENTREGA, QTD_PESO_REAL = :QTD_PESO_REAL, QTD_PESO_FRANQUIA = :QTD_PESO_FRANQUIA, ' +
'VAL_VERBA_FRANQUIA = :VAL_VERBA_FRANQUIA, VAL_ADVALOREM = :VAL_ADVALOREM, VAL_PAGO_FRANQUIA = :VAL_PAGO_FRANQUIA, ' +
'VAL_VERBA_ENTREGADOR = :VAL_VERBA_ENTREGADOR, NUM_EXTRATO = :NUM_EXTRATO, QTD_DIAS_ATRASO = :QTD_DIAS_ATRASO, ' +
'QTD_VOLUMES_EXTRA = :QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA = :VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO = :QTD_PESO_COBRADO, ' +
'DES_TIPO_PESO = :DES_TIPO_PESO, DAT_RECEBIDO = :DAT_RECEBIDO, DOM_RECEBIDO = :DOM_RECEBIDO, NUM_CTRC = :NUM_CTRC, ' +
'NUM_MANIFESTO = :NUM_MANIFESTO, DES_RASTREIO = :DES_RASTREIO, NUM_LOTE_REMESSA = :NUM_LOTE_REMESSA, ' +
'DES_RETORNO = :DES_RETORNO, DAT_CREDITO = :DAT_CREDITO, DOM_CREDITO = :DOM_CREDITO, NUM_CONTAINER = :NUM_CONTAINER, ' +
'VAL_PRODUTO = :VAL_PRODUTO, QTD_ALTURA = :QTD_ALTURA, QTD_LARGURA = :QTD_LARGURA, QTD_COMPRIMENTO = :QTD_COMPRIMENTO, ' +
'COD_FEEDBACK = :COD_FEEDBACK, DAT_FEEDBACK = :DAT_FEEDBACK, DOM_CONFERIDO = :DOM_CONFERIDO, ' +
'NUM_PEDIDO = :NUM_PEDIDO, COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA, COD_AWB1 = :COD_AWB1 ' +
'WHERE ' +
'NUM_NOSSONUMERO = :NUM_NOSSONUMERO;';
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Tthread_201010_importar_pedidos_direct.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ Tthread_201010_importar_pedidos_direct }
uses Common.Utils, Global.Parametros, View.ImportarPedidos;
procedure Tthread_201010_importar_pedidos_direct.BeginProcesso;
begin
bCancel := False;
view_ImportarPedidos.actCancelar.Enabled := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
view_ImportarPedidos.actAbrirArquivo.Enabled := False;
view_ImportarPedidos.dxLayoutItem8.Visible := True;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile;
UpdateLog;
end;
procedure Tthread_201010_importar_pedidos_direct.Execute;
begin
{ Place thread code here }
try
try
Synchronize(BeginProcesso);
FEntregas := TEntregasControl.Create;
FPlanilha := TPlanilhaEntradaDIRECTControl.Create;
FPlanilhasCSV := TObjectList<TPlanilhaEntradaDIRECT>.Create;
FPlanilhasCSV := FPlanilha.GetPlanilha(FFile);
if FPlanilhasCSV.Count > 0 then
begin
iPos := 0;
FdPos := 0;
iTotal := FPlanilhasCSV.Count;
fdEntregasInsert := TSistemaControl.GetInstance.Conexao.ReturnQuery;;
end;
Except
on E: Exception do
begin
Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR);
bCancel := True;
end;
end;
finally
end;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupClassInsert(i: Integer);
begin
FEntregas.Entregas.Distribuidor := 0;
FEntregas.Entregas.Entregador := 0;
FEntregas.Entregas.Cliente := FPlanilhasCSV[i].CodigoEmbarcador;
FEntregas.Entregas.NN := FPlanilhasCSV[i].Remessa;
FEntregas.Entregas.NF := FPlanilhasCSV[i].NF;
FEntregas.Entregas.Consumidor := FPlanilhasCSV[i].NomeConsumidor;
FEntregas.Entregas.Retorno := FPlanilhasCSV[i].Chave;
FEntregas.Entregas.Endereco := '';
FEntregas.Entregas.Complemento := '';
FEntregas.Entregas.Bairro := FPlanilhasCSV[i].Bairro;
FEntregas.Entregas.Cidade := FPlanilhasCSV[i].Municipio;
FEntregas.Entregas.Cep := FPlanilhasCSV[i].CEP;
FEntregas.Entregas.Telefone := '';
FEntregas.Entregas.Expedicao := FPlanilhasCSV[i].DataRegistro;
FEntregas.Entregas.Previsao := FPlanilhasCSV[i].DataChegadaLM + 1;
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Baixa := 0;
FEntregas.Entregas.Entrega := 0;
FEntregas.Entregas.Baixado := 'N';
FEntregas.Entregas.Atraso := 0;
FEntregas.Entregas.VerbaEntregador := 0;
FEntregas.Entregas.VerbaFranquia := 0;
if FPlanilhasCSV[i].PesoCubado > FPlanilhasCSV[i].PesoNominal then
begin
FEntregas.Entregas.PesoReal := FPlanilhasCSV[i].PesoCubado;
end
else
begin
FEntregas.Entregas.PesoReal := FPlanilhasCSV[i].PesoNominal;
end;
FEntregas.Entregas.PesoCobrado := FPlanilhasCSV[i].PesoNominal;
FEntregas.Entregas.Volumes := FPlanilhasCSV[i].Volumes;
FEntregas.Entregas.VolumesExtra := 0;
FEntregas.Entregas.ValorVolumes := 0;
FEntregas.Entregas.Container := '0';
FEntregas.Entregas.ValorProduto := FPlanilhasCSV[i].Valor;
FEntregas.Entregas.Atribuicao := 0;
FEntregas.Entregas.Altura := 0;
FEntregas.Entregas.Largura := 0;
FEntregas.Entregas.Comprimento := 0;
FEntregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' inserido por importação por ' +
Global.Parametros.pUser_Name;
FEntregas.Entregas.Pedido := FPlanilhasCSV[i].Pedido;
FEntregas.Entregas.CodCliente := iCodigoCliente;
FEntregas.Entregas.AWB1 := FPlanilhasCSV[i].AWB1;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupClassUpdate(FDQuery: TFDQuery);
begin
FEntregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger;
FEntregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger;
FEntregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString;
FEntregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString;
FEntregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger;
FEntregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString;
FEntregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString;
FEntregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString;
FEntregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString;
FEntregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString;
FEntregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString;
FEntregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString ;
FEntregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime;
FEntregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime;
FEntregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger;
FEntregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString;
FEntregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat;
FEntregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat;
FEntregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat;
FEntregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat;
FEntregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger;
FEntregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger;
FEntregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString;
FEntregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat;
FEntregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime;
FEntregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger;
FEntregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger;
FEntregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger;
FEntregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString;
FEntregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString;
FEntregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString;
FEntregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
FEntregas.Entregas.AWB1 := FDQuery.FieldByName('COD_AWB1').AsString;
end;
procedure Tthread_201010_importar_pedidos_direct.TerminateProcess;
begin
view_ImportarPedidos.actCancelar.Enabled := False;
view_ImportarPedidos.actFechar.Enabled := True;
view_ImportarPedidos.actImportar.Enabled := True;
view_ImportarPedidos.actAbrirArquivo.Enabled := True;
view_ImportarPedidos.edtArquivo.Clear;
view_ImportarPedidos.pbImportacao.Position := 0;
view_ImportarPedidos.pbImportacao.Clear;
view_ImportarPedidos.dxLayoutItem8.Visible := False;
view_ImportarPedidos.cboCliente.ItemIndex := 0;
end;
procedure Tthread_201010_importar_pedidos_direct.UpdateLog;
begin
view_ImportarPedidos.memLOG.Lines.Add(sMensagem);
view_ImportarPedidos.memLOG.Lines.Add('');
iLinha := view_ImportarPedidos.memLOG.Lines.Count - 1;
view_ImportarPedidos.memLOG.Refresh;
end;
procedure Tthread_201010_importar_pedidos_direct.UpdateProgress;
begin
view_ImportarPedidos.pbImportacao.Position := FdPos;
view_ImportarPedidos.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos);
view_ImportarPedidos.pbImportacao.Refresh;
view_ImportarPedidos.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iPos) + ' registros processados';
view_ImportarPedidos.memLOG.Refresh;
if not(view_ImportarPedidos.actCancelar.Visible) then
begin
view_ImportarPedidos.actCancelar.Visible := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
end;
end;
end.
|
unit adpInstanceControl;
interface
uses
Windows, Forms, SysUtils, Classes;
type
EInstanceControl = class(Exception);
TMaxInstancesReachedEvent = procedure(Sender :TObject; const LastInstanceHandle :THandle) of object;
TadpInstanceControl = class(TComponent)
private
fMappingName : string;
fMappingHandle: THandle;
fRemoveMe : boolean;
fEnabled: boolean;
fMaxInstances: Cardinal;
fOnMaxInstancesReached: TMaxInstancesReachedEvent;
protected
procedure Loaded; override;
procedure MaxInstancesReached(const LastInstanceHandle : THandle);
public
constructor Create(AOwner :TComponent); override;
destructor Destroy; override;
published
property Enabled : boolean read fEnabled write fEnabled;
property MaxInstances : Cardinal read fMaxInstances write fMaxInstances;
property OnMaxInstancesReached :TMaxInstancesReachedEvent read fOnMaxInstancesReached write fOnMaxInstancesReached;
end;
procedure Register;
implementation
type
PInstanceInfo = ^TInstanceInfo;
TInstanceInfo = packed record
PreviousHandle : THandle;
RunCounter : Cardinal;
end;
var
ThisOnce : TComponent = nil;
InstanceInfo : PInstanceInfo;
procedure Register;
begin
RegisterComponents('FFSNew', [TadpInstanceControl]);
end;
{ TInstanceControl }
constructor TadpInstanceControl.Create(AOwner: TComponent);
begin
if ThisOnce <> Nil then
begin
raise EInstanceControl.Create('Only one copy of this component can be dropped on a form!');
end
else
begin
inherited;
ThisOnce := Self;
fRemoveMe := True;
fEnabled := True;
fMaxInstances := 1;
end;
end;(*Create*)
destructor TadpInstanceControl.Destroy;
begin
ThisOnce := nil;
if (csDesigning in ComponentState) then
begin
inherited;
Exit;
end;
//remove this instance
if Enabled AND fRemoveMe then
begin
fMappingHandle := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(fMappingName));
if fMappingHandle <> 0 then
begin
InstanceInfo := MapViewOfFile(fMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
InstanceInfo^.RunCounter := InstanceInfo^.RunCounter - 1;
end
else
// RaiseLastOSError;
RaiseLastWin32Error ;
end;
if Assigned(InstanceInfo) then UnmapViewOfFile(InstanceInfo);
if fMappingHandle <> 0 then CloseHandle(fMappingHandle);
inherited;
end; (*Destroy*)
procedure TadpInstanceControl.MaxInstancesReached(const LastInstanceHandle: THandle);
begin
{Tell Delphi to hide it's hidden application window to avoid}
{a "flash" on the taskbar if we halt due to max instances reached condition}
Application.ShowMainForm := False;
ShowWindow(Application.Handle, SW_HIDE);
//notify this instance
if Assigned(fOnMaxInstancesReached) then OnMaxInstancesReached(self, LastInstanceHandle);
if IsIconic(LastInstanceHandle) then
ShowWindow(LastInstanceHandle, SW_RESTORE);
SetForegroundWindow(LastInstanceHandle);
Application.Terminate;
end; (*InstanceFound*)
procedure TadpInstanceControl.Loaded;
var
InstanceInfo: PInstanceInfo;
begin
inherited;
if (csDesigning in ComponentState) then Exit;
if not Enabled then Exit;
fMappingName :=StringReplace(ParamStr(0),'\','',[rfReplaceAll, rfIgnoreCase]);
fMappingName :=StringReplace(fMappingName,' ','',[rfReplaceAll, rfIgnoreCase]);
fMappingHandle := CreateFileMapping($FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(TInstanceInfo),
PChar(fMappingName));
if fMappingHandle = 0 then
// RaiseLastOSError
RaiseLastWin32Error
else
begin
if GetLastError <> ERROR_ALREADY_EXISTS then
begin
InstanceInfo := MapViewOfFile(fMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
InstanceInfo^.PreviousHandle := Application.Handle;
InstanceInfo^.RunCounter := 1;
end
else //already runing
begin
fMappingHandle := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(fMappingName));
if fMappingHandle <> 0 then
begin
InstanceInfo := MapViewOfFile(fMappingHandle,
FILE_MAP_ALL_ACCESS,
0,
0,
SizeOf(TInstanceInfo));
if InstanceInfo^.RunCounter >= MaxInstances then
begin
fRemoveMe:=False;
MaxInstancesReached(InstanceInfo^.PreviousHandle);
end
else
begin
InstanceInfo^.PreviousHandle := Application.Handle;
InstanceInfo^.RunCounter := 1 + InstanceInfo^.RunCounter;
end
end;
end;
end;
end; (*Loaded*)
initialization
finalization
if ThisOnce <> nil then ThisOnce.Free;
end.
|
unit URectangle;
interface
uses
UFigure, SysUtils, Graphics, ExtCtrls, StdCtrls, Windows, Math;
type
TRectangle = class(TFigure)
private
FSecondPoint: TPoint;
public
constructor Create(APoint: TPoint; AColor:TColor; ASecondPoint:TPoint);
function Area:real; override;
procedure Draw(Image: TImage); override;
function Contains(p: TPoint):boolean; override;
class function WhatItIs:string; override;
property SecondPoint:TPoint
read FSecondPoint write FSecondPoint;
end;
implementation
constructor TRectangle.Create(APoint: TPoint; AColor:TColor; ASecondPoint:TPoint);
begin
inherited Create(APoint, AColor);
FSecondPoint:= ASecondPoint;
end;
class function TRectangle.WhatItIs:string;
begin
Result:= 'Прямоугольник';
end;
function TRectangle.Area:real;
begin
Result:= abs((SecondPoint.Y - Point.Y) * (SecondPoint.X - Point.X));
end;
procedure TRectangle.Draw(Image: TImage);
var
Rect: TRect;
begin
Rect.TopLeft:= Point;
Rect.BottomRight:= SecondPoint;
Image.Canvas.Brush.Color:= Color;
image.Canvas.FillRect(rect);
end;
function TRectangle.Contains(p: TPoint):boolean;
begin
Result:= (p.X > Point.X) and (p.Y > Point.Y) and
(p.X < SecondPoint.X) and (p.Y < SecondPoint.Y);
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerNull;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
ClpCryptoLibTypes,
ClpAsn1Tags,
ClpIProxiedInterface,
ClpDerOutputStream,
ClpAsn1Null,
ClpIDerNull;
type
/// <summary>
/// A Null object.
/// </summary>
TDerNull = class(TAsn1Null, IDerNull)
strict private
class function GetInstance: IDerNull; static; inline;
class var
FInstance: IDerNull;
FZeroBytes: TCryptoLibByteArray;
class constructor DerNull();
strict protected
constructor Create(dummy: Int32);
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
function Asn1GetHashCode(): Int32; override;
public
procedure Encode(const derOut: TStream); override;
class property Instance: IDerNull read GetInstance;
end;
implementation
{ TDerNull }
function TDerNull.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
begin
result := Supports(asn1Object, IDerNull);
end;
function TDerNull.Asn1GetHashCode: Int32;
begin
result := -1;
end;
{$IFNDEF _FIXINSIGHT_}
constructor TDerNull.Create(dummy: Int32);
begin
Inherited Create();
end;
{$ENDIF}
class constructor TDerNull.DerNull;
begin
FInstance := TDerNull.Create(0);
System.SetLength(FZeroBytes, 0);
end;
procedure TDerNull.Encode(const derOut: TStream);
begin
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Null, FZeroBytes);
end;
class function TDerNull.GetInstance: IDerNull;
begin
result := FInstance;
end;
end.
|
unit PE.Build.Common;
interface
uses
System.Classes,
PE.Common,
PE.Image,
NullStream;
type
// Parent class for any directory builders.
// Override Build procedure and fill Stream with new dir data.
TDirectoryBuilder = class
protected
FPE: TPEImage;
public
constructor Create(PE: TPEImage);
// Builds bogus directory and return size.
// Override it if you have better implementation.
function EstimateTheSize: uint32; virtual;
// Build directory data and store it to stream.
// * DirRVA: RVA of directory start.
// * Stream: Stream to store data.
procedure Build(DirRVA: TRVA; Stream: TStream); virtual; abstract;
// If new section created, it's called to get the flags.
class function GetDefaultSectionFlags: uint32; virtual; abstract;
// If new section created, it's called to get the name.
class function GetDefaultSectionName: string; virtual; abstract;
// Return True if need to call Build each time when DirRVA changed.
class function NeedRebuildingIfRVAChanged: boolean; virtual; abstract;
end;
TDirectoryBuilderClass = class of TDirectoryBuilder;
implementation
{ TDirBuilder }
constructor TDirectoryBuilder.Create(PE: TPEImage);
begin
FPE := PE;
end;
function TDirectoryBuilder.EstimateTheSize: uint32;
var
tmp: TNullStream;
begin
tmp := TNullStream.Create;
try
Build(0, tmp);
Result := tmp.Size;
finally
tmp.Free;
end;
end;
end.
|
unit AceDeb;
interface
uses classes, forms, stdctrls, controls;
type
TStatList = class(TComponent)
private
MyList: TListBox;
MyForm: TForm;
protected
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure SaveToLog(Sender: TObject);
procedure ShowStatus(text: string);
procedure CreateForm;
end;
procedure DebugStatus(Text: String);
procedure DebugTime(Text: String);
procedure ResetTime;
function IsDebugEnabled: boolean;
procedure EnableAceDebug;
procedure DisableAceDebug;
procedure ToggleAceDebug;
implementation
uses dialogs, sysutils;
var
StatForm: TStatList;
AceDebugEnabled: boolean;
Timestamp: TDateTime;
procedure DebugStatus(Text: String);
begin
if AceDebugEnabled then
begin
if StatForm = nil then StatForm := TStatList.Create(Application);
StatForm.ShowStatus(Text);
end;
end;
procedure DebugTime(Text: String);
var
NewDateTime: TDateTime;
begin
NewDateTime := Now;
if TimeStamp = 0 then
TimeStamp := NewDateTime;
DebugStatus(' Elapsed: ' +
FormatDateTime('hh:nn:ss:zzz', NewDateTime - Timestamp));
DebugStatus(FormatDateTime('hh:nn:ss:zzz', NewDateTime) + ' ' + Text);
Timestamp := NewDateTime;
end;
procedure ResetTime;
begin
TimeStamp := 0;
end;
procedure EnableAceDebug;
begin
AceDebugEnabled := True;
end;
procedure ToggleAceDebug;
begin
AceDebugEnabled := not AceDebugEnabled;
end;
procedure DisableAceDebug;
begin
AceDebugEnabled := false;
end;
function IsDebugEnabled: boolean;
begin
result := AceDebugEnabled;
end;
constructor TStatList.Create(Owner: TComponent);
begin
inherited Create(Owner); // Initialize inherited parts
CreateForm;
end;
procedure TStatList.CreateForm;
begin
MyForm := TForm.Create(nil);
MyForm.Name := 'AceDebugForm';
MyList := TListBox.Create(MyForm);
MyList.Parent := MyForm;
MyList.Name := 'AceDebugList';
MyList.Align := AlClient;
MyList.OnDblClick := SaveToLog;
MyForm.Show;
end;
destructor TStatList.Destroy;
begin
if not (MyList = nil) then MyList.Free;
if not (MyForm = nil) then MyForm.Free;
inherited destroy;
end;
procedure TStatList.SaveToLog(Sender: TObject);
var
dlg: TSaveDialog;
begin
dlg := TSaveDialog.Create(nil);
if dlg.Execute
then (Sender as TListBox).Items.SaveToFile(dlg.FileName);
dlg.Free;
end;
procedure TStatList.ShowStatus(text: string);
begin
if MyForm = nil then CreateForm;
MyForm.Visible := true;
MyList.Items.Add(Text);
MyForm.Refresh;
// Application.ProcessMessages;
end;
Initialization
StatForm := nil;
AceDebugEnabled :=
{$IFDEF VER130} False;
{$ELSE} (UpperCase(GetEnvironmentVariable('ACEDEBUG')) = 'YES');
{$ENDIF}
ResetTime;
// Note you may also enable in code by directly setting the vaiable
end.
|
unit k2String;
{ Библиотека "K-2" }
{ Автор: Люлин А.В. © }
{ Модуль: k2TagString - }
{ Начат: 16.01.2006 17:41 }
{ $Id: k2String.pas,v 1.5 2008/02/21 13:48:21 lulin Exp $ }
// $Log: k2String.pas,v $
// Revision 1.5 2008/02/21 13:48:21 lulin
// - cleanup.
//
// Revision 1.4 2007/12/05 12:35:08 lulin
// - вычищен условный код, составлявший разницу ветки и Head'а.
//
// Revision 1.3 2006/11/03 11:00:44 lulin
// - объединил с веткой 6.4.
//
// Revision 1.2.14.1 2006/10/26 09:10:21 lulin
// - используем "родную" директиву.
//
// Revision 1.2 2006/01/18 10:51:18 lulin
// - bug fix: не компилировалось.
//
// Revision 1.1 2006/01/16 16:41:44 lulin
// - сделана возможность работать со строками без теговых оберток (почему-то на производительность не повлияло).
//
{$Include k2Define.inc }
interface
uses
l3Types,
l3Base,
k2Interfaces,
k2Base
;
type
_Parent_ = Tl3String;
{.$Define k2TagIsList}
{$Define k2TagIsString}
{$Include k2Tag.int}
Tk2String = class(_Tag_)
public
// public methods
constructor Create(aTagType: Tk2Type);
reintroduce;
{-}
procedure AssignString(aStr: Tl3CustomString);
override;
{-}
end;//Tk2String
implementation
uses
TypInfo,
Classes,
SysUtils,
l3String,
l3Stream,
k2Const,
k2Except,
k2Tags
;
{$Include k2Tag.int}
// start class Tk2String
constructor Tk2String.Create(aTagType: Tk2Type);
//reintroduce;
{-}
begin
f_TagType := aTagType;
inherited Create;
end;
procedure Tk2String.AssignString(aStr: Tl3CustomString);
//override;
{-}
begin
inherited;
if (f_TagType = nil) AND (aStr Is Tk2String) then
f_TagType := Tk2String(aStr).TagType;
end;
end.
|
unit vtPngImgListUtils;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VT$ImgList"
// Модуль: "w:/common/components/gui/Garant/VT/vtPngImgListUtils.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VT$ImgList::vtImgLists::vtPngImgListUtils
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\VT\vtDefine.inc}
interface
uses
l3Types,
l3ObjectList,
l3ProcedureList,
Graphics,
Windows,
l3ProtoObject,
vtPngImgList,
hyieutils
;
type
TvtImageListCreatorProc = function : TObject;
PvtImageListCreatorProc = ^TvtImageListCreatorProc;
TAlphaBlendFunc = function (DestDC: hDC;
X: Integer;
Y: Integer;
Width: Integer;
Height: Integer;
SrcDC: hDC;
XSrc: Integer;
YSrc: Integer;
SrcWidth: Integer;
SrcHeight: Integer;
const BlendFunc: TBlendFunction): Boolean;
TvtilCreators = class(Tl3ProcedureList)
public
// public methods
class function IsAssigned: Boolean;
public
// singleton factory method
class function Instance: TvtilCreators;
{- возвращает экземпляр синглетона. }
end;//TvtilCreators
ImgLibraryManager = class(Tl3ProtoObject)
private
// private fields
f_ImgDLL : THandle;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
public
// singleton factory method
class function Instance: ImgLibraryManager;
{- возвращает экземпляр синглетона. }
end;//ImgLibraryManager
var g_PILList : Tl3ObjectList;
var g_AlphaBlendFunc : TAlphaBlendFunc;
procedure PrepareAlphaBitmap(aSource: TIEBitmap;
aDest: TBitmap);
function AlphaBlend(DestDC: hDC;
X: Integer;
Y: Integer;
Width: Integer;
Height: Integer;
SrcDC: hDC;
XSrc: Integer;
YSrc: Integer;
SrcWidth: Integer;
SrcHeight: Integer;
const BlendFunc: TBlendFunction): Boolean;
function CalcTransparenctColor(aTransparensy: Byte;
HalfTransparent: Boolean): Byte;
procedure IterateExistingImageListsF(anAction: Tl3IteratorAction);
procedure AddImageListCreator(aCreator: PvtImageListCreatorProc);
procedure AddImageListCreatorPrim(aCreator: TvtImageListCreatorProc);
function GetAnother(aSize: TvtPILSize): TvtPILSize; overload;
function GetAnother(aBpp: TvtPILBpp): TvtPILBpp; overload;
function GetScreenColorDepth: Integer;
function AutoDetectColorDepth: TvtPILBpp;
procedure SetColorDepthGlobal(aBpp: TvtPILBpp);
implementation
uses
l3Base {a},
l3Bitmap,
SysUtils,
l3MinMax,
hyiedefs
;
var g_ScreenColorDepth : Integer;
// unit methods
procedure PrepareAlphaBitmap(aSource: TIEBitmap;
aDest: TBitmap);
//#UC START# *4FD1F66B03D5_4FD1F6B00129_var*
var
l_LineIdx, l_PixelIdx: integer;
l_DestColor: pRGBA;
l_DestGray: pRGBA;
l_Source: PRGB;
l_Alpha: PByte;
l_DisabledAlpha: Byte;
l_Gray: Byte;
//#UC END# *4FD1F66B03D5_4FD1F6B00129_var*
begin
//#UC START# *4FD1F66B03D5_4FD1F6B00129_impl*
aDest.Width := aSource.Width;
aDest.Height := aSource.Height*2;
aDest.PixelFormat := pf32Bit;
for l_LineIdx := 0 to aSource.Height-1 do
begin
l_DestColor := aDest.Scanline[l_LineIdx];
l_DestGray := aDest.Scanline[l_LineIdx+aSource.Height];
l_Source := aSource.Scanline[l_LineIdx];
l_Alpha := aSource.AlphaChannel.Scanline[l_LineIdx];
for l_PixelIdx:=0 to aSource.Width-1 do
begin
with l_DestColor^ do
begin
r := l_Source^.r * l_Alpha^ div cFullAlpha;
g := l_Source^.g * l_Alpha^ div cFullAlpha;
b := l_Source^.b * l_Alpha^ div cFullAlpha;
a := l_Alpha^;
end;
l_DisabledAlpha := l_Alpha^ * cDisabledAlpha div cFullAlpha;
l_Gray := max(max(l_Source^.r, l_Source^.g),l_Source^.b) * l_DisabledAlpha div cFullAlpha;
with l_DestGray^ do
begin
r := l_Gray;
g := l_Gray;
b := l_Gray;
a := l_DisabledAlpha;
end;
inc(l_Source);
inc(l_DestColor);
inc(l_DestGray);
inc(l_Alpha);
end;
end;
aDest.Dormant;
//#UC END# *4FD1F66B03D5_4FD1F6B00129_impl*
end;//PrepareAlphaBitmap
function AlphaBlend(DestDC: hDC;
X: Integer;
Y: Integer;
Width: Integer;
Height: Integer;
SrcDC: hDC;
XSrc: Integer;
YSrc: Integer;
SrcWidth: Integer;
SrcHeight: Integer;
const BlendFunc: TBlendFunction): Boolean;
//#UC START# *4FD1F6FB00AF_4FD1F6B00129_var*
//#UC END# *4FD1F6FB00AF_4FD1F6B00129_var*
begin
//#UC START# *4FD1F6FB00AF_4FD1F6B00129_impl*
if Assigned(g_AlphaBlendFunc) then
Result := g_AlphaBlendFunc(DestDC, X, Y, Width, Height, SrcDC, XSrc,
YSrc, SrcWidth, SrcHeight, BlendFunc)
else
begin
SetLastError(ERROR_INVALID_FUNCTION);
Result := false;
end;
//#UC END# *4FD1F6FB00AF_4FD1F6B00129_impl*
end;//AlphaBlend
function CalcTransparenctColor(aTransparensy: Byte;
HalfTransparent: Boolean): Byte;
//#UC START# *4FD1F75F023A_4FD1F6B00129_var*
//#UC END# *4FD1F75F023A_4FD1F6B00129_var*
begin
//#UC START# *4FD1F75F023A_4FD1F6B00129_impl*
if HalfTransparent
then Result := aTransparensy div 2
else Result := aTransparensy;
//#UC END# *4FD1F75F023A_4FD1F6B00129_impl*
end;//CalcTransparenctColor
procedure IterateExistingImageListsF(anAction: Tl3IteratorAction);
//#UC START# *4FD1F77B0267_4FD1F6B00129_var*
function DoItem(P: PPointer; Index: Long): Bool;
begin//DoItem
if (P^ <> nil) then
TvtImageListCreatorProc(P^);
P^ := nil;
Result := true;
end;//DoItem
//#UC END# *4FD1F77B0267_4FD1F6B00129_var*
begin
//#UC START# *4FD1F77B0267_4FD1F6B00129_impl*
if TvtilCreators.IsAssigned then
TvtilCreators.Instance.IterateAllF(l3L2IA(@DoItem));
try
if (g_PILList <> nil) then
g_PILList.IterateAll(anAction);
finally
l3FreeIA(anAction);
end;//try..finally
//#UC END# *4FD1F77B0267_4FD1F6B00129_impl*
end;//IterateExistingImageListsF
procedure AddImageListCreator(aCreator: PvtImageListCreatorProc);
//#UC START# *4FD1F81F02CF_4FD1F6B00129_var*
//#UC END# *4FD1F81F02CF_4FD1F6B00129_var*
begin
//#UC START# *4FD1F81F02CF_4FD1F6B00129_impl*
AddImageListCreatorPrim(TvtImageListCreatorProc(aCreator));
//#UC END# *4FD1F81F02CF_4FD1F6B00129_impl*
end;//AddImageListCreator
procedure AddImageListCreatorPrim(aCreator: TvtImageListCreatorProc);
//#UC START# *4FD1F900009A_4FD1F6B00129_var*
//#UC END# *4FD1F900009A_4FD1F6B00129_var*
begin
//#UC START# *4FD1F900009A_4FD1F6B00129_impl*
TvtilCreators.Instance.Add(TProcedure(aCreator));
//#UC END# *4FD1F900009A_4FD1F6B00129_impl*
end;//AddImageListCreatorPrim
function GetAnother(aSize: TvtPILSize): TvtPILSize;
//#UC START# *4FD1F96300AF_4FD1F6B00129_var*
//#UC END# *4FD1F96300AF_4FD1F6B00129_var*
begin
//#UC START# *4FD1F96300AF_4FD1F6B00129_impl*
if aSize = ps16x16
then Result := ps24x24
else Result := ps16x16;
//#UC END# *4FD1F96300AF_4FD1F6B00129_impl*
end;//GetAnother
function GetAnother(aBpp: TvtPILBpp): TvtPILBpp;
//#UC START# *4FD1F98902AB_4FD1F6B00129_var*
//#UC END# *4FD1F98902AB_4FD1F6B00129_var*
begin
//#UC START# *4FD1F98902AB_4FD1F6B00129_impl*
case aBpp of
bpp24: Result := bpp8;
bpp8: Result := bpp4;
else
Result := bpp24;
end;
//#UC END# *4FD1F98902AB_4FD1F6B00129_impl*
end;//GetAnother
function GetScreenColorDepth: Integer;
//#UC START# *4FD1F9AA00E5_4FD1F6B00129_var*
var
DC: HDC;
//#UC END# *4FD1F9AA00E5_4FD1F6B00129_var*
begin
//#UC START# *4FD1F9AA00E5_4FD1F6B00129_impl*
DC := GetDC(0);
try
Result := GetDeviceCaps(DC, BITSPIXEL);
finally
ReleaseDC(0, DC);
end;
//#UC END# *4FD1F9AA00E5_4FD1F6B00129_impl*
end;//GetScreenColorDepth
function AutoDetectColorDepth: TvtPILBpp;
//#UC START# *4FD1F9CB0196_4FD1F6B00129_var*
//#UC END# *4FD1F9CB0196_4FD1F6B00129_var*
begin
//#UC START# *4FD1F9CB0196_4FD1F6B00129_impl*
case GetScreenCOlorDepth of
1..4: Result := bpp4;
8: Result := bpp8;
16,24,32: Result := bpp24;
else
raise Exception.Create('Не удалось определить глубину цвета экрана');
end;
//#UC END# *4FD1F9CB0196_4FD1F6B00129_impl*
end;//AutoDetectColorDepth
procedure SetColorDepthGlobal(aBpp: TvtPILBpp);
//#UC START# *4FD1F9E601E9_4FD1F6B00129_var*
var
I: Integer;
l_NeedReset: Boolean;
//#UC END# *4FD1F9E601E9_4FD1F6B00129_var*
begin
//#UC START# *4FD1F9E601E9_4FD1F6B00129_impl*
I := GetScreenCOlorDepth;
l_NeedReset := I <> g_ScreenColorDepth;
g_ScreenColorDepth := I;
if g_PILList <> nil then
begin
for I := 0 to Pred(g_PILList.Count) do
begin
if g_PILList[I] is TvtPngImageList then
begin
if l_NeedReset then
TvtPngImageList(g_PILList[I]).ClearCache;
TvtPngImageList(g_PILList[I]).CurBpp := aBpp;
end;
if g_PILList[I] is TvtNonFixedPngImageList then
begin
if l_NeedReset then
TvtNonFixedPngImageList(g_PILList[I]).ClearCache;
TvtNonFixedPngImageList(g_PILList[I]).CurBpp := aBpp;
end;
end;
end;
//#UC END# *4FD1F9E601E9_4FD1F6B00129_impl*
end;//SetColorDepthGlobal
// start class TvtilCreators
var g_TvtilCreators : TvtilCreators = nil;
procedure TvtilCreatorsFree;
begin
l3Free(g_TvtilCreators);
end;
class function TvtilCreators.Instance: TvtilCreators;
begin
if (g_TvtilCreators = nil) then
begin
l3System.AddExitProc(TvtilCreatorsFree);
g_TvtilCreators := Create;
end;
Result := g_TvtilCreators;
end;
class function TvtilCreators.IsAssigned: Boolean;
//#UC START# *4FD318100335_4FD31272000C_var*
//#UC END# *4FD318100335_4FD31272000C_var*
begin
//#UC START# *4FD318100335_4FD31272000C_impl*
Result := Assigned(g_TvtilCreators);
//#UC END# *4FD318100335_4FD31272000C_impl*
end;//TvtilCreators.IsAssigned
// start class ImgLibraryManager
var g_ImgLibraryManager : ImgLibraryManager = nil;
procedure ImgLibraryManagerFree;
begin
l3Free(g_ImgLibraryManager);
end;
class function ImgLibraryManager.Instance: ImgLibraryManager;
begin
if (g_ImgLibraryManager = nil) then
begin
l3System.AddExitProc(ImgLibraryManagerFree);
g_ImgLibraryManager := Create;
end;
Result := g_ImgLibraryManager;
end;
procedure ImgLibraryManager.Cleanup;
//#UC START# *479731C50290_502518C60255_var*
//#UC END# *479731C50290_502518C60255_var*
begin
//#UC START# *479731C50290_502518C60255_impl*
if f_ImgDLL <> 0 then
FreeLibrary(f_ImgDLL);
g_AlphaBlendFunc := nil;
//#UC END# *479731C50290_502518C60255_impl*
end;//ImgLibraryManager.Cleanup
procedure ImgLibraryManager.InitFields;
//#UC START# *47A042E100E2_502518C60255_var*
//#UC END# *47A042E100E2_502518C60255_var*
begin
//#UC START# *47A042E100E2_502518C60255_impl*
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
f_ImgDLL := SafeLoadLibrary(msimg32);
if f_ImgDLL <> 0 then
g_AlphaBlendFunc := TAlphaBlendFunc(GetProcAddress(f_ImgDLL, 'AlphaBlend'));
if @g_AlphaBlendFunc = nil then
FreeLibrary(f_ImgDLL);
end;
//#UC END# *47A042E100E2_502518C60255_impl*
end;//ImgLibraryManager.InitFields
end. |
unit aePrimitiveShapes;
interface
uses aeConst, aeMaths, aeRenderable, System.Types, dglOpenGL, aeSceneNode, System.Generics.Collections,
aeMesh, aeVectorBuffer, aeIndexBuffer, aeTypes;
type
TaePrimitiveShapeType = (AE_PRIMITIVESHAPE_TYPE_DEFAULT, AE_PRIMITIVESHAPE_TYPE_RAY);
type
TaePrimitiveShape = class(TaeMesh)
private
_type: TaePrimitiveShapeType;
_vectorBuffer: TaeVectorBuffer;
_indexBuffer: TaeIndexBuffer;
public
property ShapeType: TaePrimitiveShapeType read _type write _type;
constructor Create;
end;
type
TaePrimitiveShapeNode = class(TaeSceneNode)
public
constructor Create;
procedure AddShape(shape: TaePrimitiveShape);
Procedure RenderShapes;
private
_shapes: TList<TaePrimitiveShape>;
end;
type
TaePrimitiveShapeRay = class(TaePrimitiveShape)
private
_lineVerts: Array [0 .. 5] of single;
procedure SetIndices;
const
RAY_RENDER_LEN = 10000.0;
public
constructor Create(orgin, direction: TPoint3D); overload;
constructor Create(ray: TaeRay3); overload;
constructor Create; overload;
procedure UpdateRay(r: TaeRay3);
end;
function GenerateUnitCubeVBO: TaeVertexIndexBuffer;
implementation
function GenerateUnitCubeVBO: TaeVertexIndexBuffer;
const
VERTICES: array [0 .. 47] of single = (1, 1, 1, 1, 1, 1, -1, 1, 1, 0, 1, 1, -1, -1, 1, 0, 0, 1, 1, -1, 1, 1, 0, 1, 1, -1, -1, 1, 0, 0, -1, -1, -1, 0, 0, 0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 1, 1, 0);
INDICES: array [0 .. 23] of word = (0, 1, 2, 3, // Front face
7, 4, 5, 6, // Back face
6, 5, 2, 1, // Left face
7, 0, 3, 4, // Right face
7, 6, 1, 0, // Top face
3, 2, 5, 4 // Bottom face
);
begin
Result.vertexBuffer := TaeVectorBuffer.Create;
Result.indexBuffer := TaeIndexBuffer.Create;
Result.vertexBuffer.PreallocateVectors(16);
Result.vertexBuffer.AddVectorRange(@VERTICES[0], 16);
Result.vertexBuffer.pack;
Result.indexBuffer.PreallocateIndices(24);
Result.indexBuffer.AddIndexRange(@INDICES[0], 24);
Result.indexBuffer.pack;
end;
{ TaePrimitiveShapeRay }
constructor TaePrimitiveShapeRay.Create(orgin, direction: TPoint3D);
begin
inherited Create;
self.UpdateRay(TaeRay3.Create(orgin, direction));
self.ShapeType := AE_PRIMITIVESHAPE_TYPE_RAY;
self.SetIndices;
self.SetRenderPrimitive(GL_LINES);
end;
constructor TaePrimitiveShapeRay.Create(ray: TaeRay3);
begin
inherited Create;
self.UpdateRay(ray);
self.ShapeType := AE_PRIMITIVESHAPE_TYPE_RAY;
self.SetIndices;
self.SetRenderPrimitive(GL_LINES);
end;
constructor TaePrimitiveShapeRay.Create;
begin
inherited;
self.ShapeType := AE_PRIMITIVESHAPE_TYPE_RAY;
self.SetIndices;
self.SetRenderPrimitive(GL_LINES);
end;
procedure TaePrimitiveShapeRay.SetIndices;
begin
self._indexBuffer.Clear;
self._indexBuffer.RemoveFromGPU;
self._indexBuffer.PreallocateIndices(2);
self._indexBuffer.AddIndex(0);
self._indexBuffer.AddIndex(1);
end;
procedure TaePrimitiveShapeRay.UpdateRay(r: TaeRay3);
begin
self._vectorBuffer.Clear;
self._vectorBuffer.RemoveFromGPU;
self._vectorBuffer.PreallocateVectors(2);
_lineVerts[0] := r.GetOrgin.x;
_lineVerts[1] := r.GetOrgin.y;
_lineVerts[2] := r.GetOrgin.z;
_lineVerts[3] := _lineVerts[0] + r.GetDirection.x * self.RAY_RENDER_LEN;
_lineVerts[4] := _lineVerts[1] + r.GetDirection.y * self.RAY_RENDER_LEN;
_lineVerts[5] := _lineVerts[2] + r.GetDirection.z * self.RAY_RENDER_LEN;
self._vectorBuffer.AddVectorRange(@_lineVerts[0], 2);
end;
{ TaePrimitiveShapeNode }
procedure TaePrimitiveShapeNode.AddShape(shape: TaePrimitiveShape);
begin
self._shapes.Add(shape);
end;
constructor TaePrimitiveShapeNode.Create;
begin
inherited Create('TaePrimitiveShapeNode');
self._NodeType := AE_SCENENODE_TYPE_PRIMITIVESHAPE;
self._shapes := TList<TaePrimitiveShape>.Create;
end;
procedure TaePrimitiveShapeNode.RenderShapes;
var
i: Integer;
begin
for i := 0 to self._shapes.Count - 1 do
begin
case self._shapes[i].ShapeType of
AE_PRIMITIVESHAPE_TYPE_DEFAULT:
begin
// error
end;
AE_PRIMITIVESHAPE_TYPE_RAY:
TaePrimitiveShapeRay(self._shapes[i]).Render;
end;
end;
end;
{ TaePrimitiveShape }
{ TaePrimitiveShape }
constructor TaePrimitiveShape.Create;
begin
inherited;
// we actually don't want to keep primitive shapes in ram. They are only for visualization.
self.SetPurgeAfterGPUUpload(true);
self._vectorBuffer := TaeVectorBuffer.Create;
self._indexBuffer := TaeIndexBuffer.Create;
self.SetVertexBuffer(self._vectorBuffer);
self.SetIndexBuffer(self._indexBuffer);
end;
end.
|
unit TTSLDOCTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSLDOCRecord = record
PLenderNum: String[4];
PCifFlag: String[1];
PLoanNum: String[20];
PDocCount: Integer;
PDescription: String[30];
PDateStamp: String[10];
End;
TTTSLDOCBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSLDOCRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSLDOC = (TTSLDOCPrimaryKey);
TTTSLDOCTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCifFlag: TStringField;
FDFLoanNum: TStringField;
FDFDocCount: TIntegerField;
FDFDescription: TStringField;
FDFDateStamp: TStringField;
FDFImage: TBlobField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanNum(const Value: String);
function GetPLoanNum:String;
procedure SetPDocCount(const Value: Integer);
function GetPDocCount:Integer;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPDateStamp(const Value: String);
function GetPDateStamp:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSLDOC);
function GetEnumIndex: TEITTSLDOC;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSLDOCRecord;
procedure StoreDataBuffer(ABuffer:TTTSLDOCRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanNum: TStringField read FDFLoanNum;
property DFDocCount: TIntegerField read FDFDocCount;
property DFDescription: TStringField read FDFDescription;
property DFDateStamp: TStringField read FDFDateStamp;
property DFImage: TBlobField read FDFImage;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanNum: String read GetPLoanNum write SetPLoanNum;
property PDocCount: Integer read GetPDocCount write SetPDocCount;
property PDescription: String read GetPDescription write SetPDescription;
property PDateStamp: String read GetPDateStamp write SetPDateStamp;
published
property Active write SetActive;
property EnumIndex: TEITTSLDOC read GetEnumIndex write SetEnumIndex;
end; { TTTSLDOCTable }
procedure Register;
implementation
function TTTSLDOCTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSLDOCTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSLDOCTable.GenerateNewFieldName }
function TTTSLDOCTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSLDOCTable.CreateField }
procedure TTTSLDOCTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanNum := CreateField( 'LoanNum' ) as TStringField;
FDFDocCount := CreateField( 'DocCount' ) as TIntegerField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFDateStamp := CreateField( 'DateStamp' ) as TStringField;
FDFImage := CreateField( 'Image' ) as TBlobField;
end; { TTTSLDOCTable.CreateFields }
procedure TTTSLDOCTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSLDOCTable.SetActive }
procedure TTTSLDOCTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSLDOCTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSLDOCTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSLDOCTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSLDOCTable.SetPLoanNum(const Value: String);
begin
DFLoanNum.Value := Value;
end;
function TTTSLDOCTable.GetPLoanNum:String;
begin
result := DFLoanNum.Value;
end;
procedure TTTSLDOCTable.SetPDocCount(const Value: Integer);
begin
DFDocCount.Value := Value;
end;
function TTTSLDOCTable.GetPDocCount:Integer;
begin
result := DFDocCount.Value;
end;
procedure TTTSLDOCTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TTTSLDOCTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TTTSLDOCTable.SetPDateStamp(const Value: String);
begin
DFDateStamp.Value := Value;
end;
function TTTSLDOCTable.GetPDateStamp:String;
begin
result := DFDateStamp.Value;
end;
procedure TTTSLDOCTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CifFlag, String, 1, N');
Add('LoanNum, String, 20, N');
Add('DocCount, Integer, 0, N');
Add('Description, String, 30, N');
Add('DateStamp, String, 10, N');
Add('Image, Blob, 0, N');
end;
end;
procedure TTTSLDOCTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CifFlag;LoanNum;DocCount, Y, Y, N, Y');
end;
end;
procedure TTTSLDOCTable.SetEnumIndex(Value: TEITTSLDOC);
begin
case Value of
TTSLDOCPrimaryKey : IndexName := '';
end;
end;
function TTTSLDOCTable.GetDataBuffer:TTTSLDOCRecord;
var buf: TTTSLDOCRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanNum := DFLoanNum.Value;
buf.PDocCount := DFDocCount.Value;
buf.PDescription := DFDescription.Value;
buf.PDateStamp := DFDateStamp.Value;
result := buf;
end;
procedure TTTSLDOCTable.StoreDataBuffer(ABuffer:TTTSLDOCRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanNum.Value := ABuffer.PLoanNum;
DFDocCount.Value := ABuffer.PDocCount;
DFDescription.Value := ABuffer.PDescription;
DFDateStamp.Value := ABuffer.PDateStamp;
end;
function TTTSLDOCTable.GetEnumIndex: TEITTSLDOC;
var iname : string;
begin
result := TTSLDOCPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSLDOCPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSLDOCTable, TTTSLDOCBuffer ] );
end; { Register }
function TTTSLDOCBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..6] of string = ('LENDERNUM','CIFFLAG','LOANNUM','DOCCOUNT','DESCRIPTION','DATESTAMP'
);
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 6) and (flist[x] <> s) do inc(x);
if x <= 6 then result := x else result := 0;
end;
function TTTSLDOCBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
5 : result := ftString;
6 : result := ftString;
end;
end;
function TTTSLDOCBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCifFlag;
3 : result := @Data.PLoanNum;
4 : result := @Data.PDocCount;
5 : result := @Data.PDescription;
6 : result := @Data.PDateStamp;
end;
end;
end.
|
unit FullScreenWindowMgr;
interface
uses
Windows, DirectDraw, Classes;
type
TFullScreenWindowManager =
class
public
constructor Create(hwndApp : HWND; const dd : IDirectDraw7; const FrontBuffer, BackBuffer : IDirectDrawSurface7);
destructor Destroy; override;
public
procedure RegisterWindow(Wnd : HWND; static : boolean; zorder : integer);
procedure UnregisterWindow(Wnd : HWND);
function UpdateScreen(const DirtyRects : array of TRect) : boolean;
function IsAnyWindowShowing : boolean;
private
fDirectDraw : IDirectDraw7;
fFrontBuffer : IDirectDrawSurface7;
fBackBuffer : IDirectDrawSurface7;
fClipper : IDirectDrawClipper;
fMainWindow : HWND;
fWindows : TList;
fNoGDIHardSupport : boolean;
fSurfaceSize : TPoint;
fSurfaceBpp : integer;
fMouseCursor : HCURSOR;
fIconInfo : TIconInfo;
end;
var
FSWindowManager : TFullScreenWindowManager = nil;
implementation
uses
SysUtils{, AxlDebug};
type
PWindowData = ^TWindowData;
TWindowData =
record
handle : HWND;
static : boolean;
zorder : integer;
bitmap : HBITMAP;
end;
//-------------------------------------------------------------------------------
// Name: CreateDibBMP()
// Desc: Creates an empty bitmap, used exclusively in CreateBMPFromWindow().
// Note that this is an internal (not exported) function.
//-------------------------------------------------------------------------------
function CreateDibBMP(dc : HDC; w, h : integer; bpp : word) : HBITMAP;
type
TDib =
record
bi : TBitmapInfoHeader;
ct : array [0..255] of dword;
end;
var
lpBits : pointer;
dib : TDib;
begin
dib.bi.biSize := sizeof(TBitmapInfoHeader);
dib.bi.biWidth := w;
dib.bi.biHeight := h;
dib.bi.biBitCount := bpp;
dib.bi.biPlanes := 1;
dib.bi.biCompression := 0;
dib.bi.biSizeImage := 0;
dib.bi.biClrUsed := 0;
if bpp = 15
then dib.bi.biBitCount := 16
else
if bpp = 16
then
begin
dib.bi.biCompression := BI_BITFIELDS;
dib.ct[0] := $F800;
dib.ct[1] := $07E0;
dib.ct[2] := $001F;
end;
Result := CreateDIBSection(dc, PBitmapInfo(@dib)^, DIB_RGB_COLORS, lpBits, 0, 0);
end;
//-------------------------------------------------------------------------------
// Name: CreateBMPFromWindow()
// Desc: Takes the hwnd of the content window, and returns a bitmap handle.
// Note that this is an internal (not exported) function.
//-------------------------------------------------------------------------------
function CreateBMPFromWindow(wnd : HWND; bpp : integer) : HBITMAP;
var
rc : TRect;
x : integer;
y : integer;
cx : integer;
cy : integer;
hdcScreen : HDC;
hdcMemory : HDC;
hbmBitmap : HBITMAP;
begin
// Create a bitmap of the window passed in
GetWindowRect(wnd, rc);
x := rc.left;
y := rc.top;
cx := rc.right - rc.left;
cy := rc.bottom - rc.top;
hdcScreen := GetDC(0);
hdcMemory := CreateCompatibleDC(0);
hbmBitmap := CreateDibBMP(hdcScreen, cx, cy, bpp);
// BLT the image from screen to bitmap
SelectObject(hdcMemory, hbmBitmap);
BitBlt(hdcMemory, 0, 0, cx, cy, hdcScreen, x, y, SRCCOPY);
DeleteDC(hdcMemory);
ReleaseDC(0, hdcScreen);
Result := hbmBitmap;
end;
//-------------------------------------------------------------------------------
// Name: Create (hwndApp : HWND; const dd : IDirectDraw7; const FrontBuffer,
// BackBuffer : IDirectDrawSurface7);
// Desc: Does preliminary setup of global values for FSWindow. It should get
// called each time DirectDraw surfaces are altered (i.e. changes to the
// device that the client application is running under).
//-------------------------------------------------------------------------------
constructor TFullScreenWindowManager.Create(hwndApp : HWND; const dd : IDirectDraw7; const FrontBuffer, BackBuffer : IDirectDrawSurface7);
var
ddsd : TDDSurfaceDesc2;
ddcaps : TDDCaps;
begin
if assigned(FSWindowManager)
then raise Exception.Create('Can have only one FullScreenWindowManager per apllication');
FSWindowManager := Self;
// Save handle to application window
fMainWindow := hwndApp;
ZeroMemory(@ddcaps, sizeof(ddcaps));
ddcaps.dwSize := sizeof(ddcaps);
dd.GetCaps(@ddcaps, nil);
if (ddcaps.dwCaps2 and DDCAPS2_CANRENDERWINDOWED) <> 0
then fNoGDIHardSupport := false
else fNoGDIHardSupport := true;
// Save DirectDraw object passed in
fDirectDraw := dd;
// Save buffers passed in
fFrontBuffer := FrontBuffer;
fBackBuffer := BackBuffer;
// Get DirectDraw surface dimensions
ZeroMemory(@ddsd, sizeof(ddsd));
ddsd.dwSize := sizeof(ddsd);
ddsd.dwFlags := DDSD_HEIGHT or DDSD_WIDTH;
fBackBuffer.GetSurfaceDesc(ddsd);
fSurfaceSize.x := ddsd.dwWidth;
fSurfaceSize.y := ddsd.dwHeight;
fSurfaceBpp := ddsd.ddpfPixelFormat.dwRGBBitCount;
fWindows := TList.Create;
end;
destructor TFullScreenWindowManager.Destroy;
begin
fWindows.Free;
FSWindowManager := nil;
inherited;
end;
//-------------------------------------------------------------------------------
// Name: RegisterWindow
// Desc: Prepairs the DirectDraw surface depending on 3D hardware. It should
// get called whenever a window (represented by the hwnd parameter) needs
// to be displayed under DirectDraw. RegisterWindow should also get
// called if the window changes its content (if its static content
// becomes dynamic, and vice-versa).
//-------------------------------------------------------------------------------
procedure TFullScreenWindowManager.RegisterWindow(wnd : HWND; static : boolean; zorder : integer);
var
rc : TRect;
wnddata : PWindowData;
begin
if wnd <> 0
then
begin
new(wnddata);
wnddata.handle := wnd;
wnddata.static := static;
wnddata.zorder := zorder;
if fNoGDIHardSupport
then
begin
// Constrain cursor to DirectDraw surface
rc.left := 0;
rc.top := 0;
rc.right := fSurfaceSize.x;
rc.bottom := fSurfaceSize.y;
ClipCursor(@rc);
// Need to create an image of content window just once
if static
then
begin
UpdateWindow(wnd);
// Assign content window image to global
wnddata.bitmap := CreateBMPFromWindow(wnd, fSurfaceBpp);
end;
end
else
if not IsAnyWindowShowing
then
begin
// Create a clipper (used in IDirectDrawSurface::Blt call)
if fDirectDraw.CreateClipper(0, fClipper, nil) = DD_OK
then fClipper.SetHWnd(0, fMainWindow);
// Normal GDI device, so just flip to GDI so content window can be seen
fDirectDraw.FlipToGDISurface;
fFrontBuffer.SetClipper(fClipper);
end;
fWindows.Add(wnddata);
end;
end;
//-------------------------------------------------------------------------------
// Name: UnregisterWindow
// Desc: Deletes objects associated with a content window. Note that these
// are objects created within this module, not objects created by the
// calling client (e.g. content window). Call this function whenever the
// content window is destroyed (e.g. WM_CLOSE).
//-------------------------------------------------------------------------------
procedure TFullScreenWindowManager.UnregisterWindow(wnd : HWND);
var
i : integer;
found : boolean;
wnddata : PWindowData;
begin
i := 0;
found := false;
wnddata := nil;
while not found and (i < fWindows.count) do
begin
wnddata := PWindowData(fWindows[i]);
if wnddata.handle = wnd
then found := true
else inc(i);
end;
if found
then
begin
if wnddata.bitmap <> 0
then DeleteObject(wnddata.bitmap);
dispose(wnddata);
fWindows.Delete(i);
end;
if fWindows.Count = 0
then
begin
if fNoGDIHardSupport
then ClipCursor(nil);
// Get rid of clipper object
if fClipper <> nil
then fClipper := nil;
end;
end;
//-------------------------------------------------------------------------------
// Name: UpdateScreen
// Desc: Is responsible for the actual rendering of the content windows
// (held in fWindows). This function must be called each
// time a DirectDraw frame gets rendered and IsAnyWindowShowing() returns
// True, so it should be placed in the main application's DirectDraw
// rendering routine. An example of this might look like the following:
//
// procedure RenderFrame;
// begin
// if IsAnyWindowShowing
// then UpdateScreen;
// else FrontBuffer.Blt(...);
// end;
//
//-------------------------------------------------------------------------------
function TFullScreenWindowManager.UpdateScreen(const DirtyRects : array of TRect) : boolean;
var
i : integer;
wnddata : PWindowData;
pt : TPoint;
rc : TRect;
x : integer;
y : integer;
cx : integer;
cy : integer;
hdcScreen : HDC;
hdcBackBuffer : HDC;
rgn : HRGN;
hdcMemory : HDC;
MouseCursorCur : HCURSOR;
R : TRect;
hres : HRESULT;
begin
if fNoGDIHardSupport
then
begin
// Get a DC to the screen (where our windows are) and
// Get a DC to the backbuffer on the non-GDI device (where we need to copy them)
hdcScreen := GetDC(0);
fBackBuffer.GetDC(hdcBackBuffer);
for i := 0 to pred(fWindows.Count) do
begin
wnddata := PWindowData(fWindows[i]);
GetWindowRect(wnddata.handle, rc);
x := rc.left;
y := rc.top;
cx := rc.right - rc.left;
cy := rc.bottom - rc.top;
// If window has a complex region associated with it, be sure to include it in the draw
rgn := CreateRectRgn(0, 0, 0, 0);
if GetWindowRgn(wnddata.handle, rgn) // = COMPLEXREGION
then
begin
OffsetRgn(rgn, rc.left, rc.top);
SelectClipRgn(hdcBackBuffer, rgn);
end;
// If content window is static (no animations, roll-overs, etc.) then
// create a dc for the bitmap and blt to the back buffer
if wnddata.static
then
begin
hdcMemory := CreateCompatibleDC(0);
SelectObject(hdcMemory, wnddata.bitmap);
BitBlt(hdcBackBuffer, x, y, cx, cy, hdcMemory, 0, 0, SRCCOPY);
DeleteDC(hdcMemory);
end
else
begin
// Special case for potentially quirky non-GDI drivers
{$IFDEF QUIRKY}
// If content is dynamic (updated each frame), always grab the screen copy
// by calling CreateBMPFromWindow to update image held in Bitmap
hdcMemory := CreateCompatibleDC(nil);
wnddata.bitmap := CreateBMPFromWindow(wnddata.handle);
SelectObject(hdcMemory, wnddata.bitmap);
BitBlt(hdcBackBuffer, x, y, cx, cy, hdcMemory, 0, 0, SRCCOPY);
DeleteDC(hdcMemory);
DeleteObject(Bitmap);
{$ELSE}
// Do a blt directly from the windows screen to the backbuffer
BitBlt(hdcBackBuffer, x, y, cx, cy, hdcScreen, x, y, SRCCOPY);
{$ENDIF}
end;
// Remove clipping region and clean up
SelectClipRgn(hdcBackBuffer, 0);
DeleteObject(rgn);
end;
// Now draw the mouse on the backbuffer
MouseCursorCur := GetCursor;
if MouseCursorCur <> fMouseCursor
then
begin
fMouseCursor := MouseCursorCur;
GetIconInfo(fMouseCursor, fIconInfo);
if fIconInfo.hbmMask <> 0
then DeleteObject(fIconInfo.hbmMask);
if fIconInfo.hbmColor <> 0
then DeleteObject(fIconInfo.hbmColor);
end;
GetCursorPos(pt);
dec(pt.x, fIconInfo.xHotspot);
dec(pt.y, fIconInfo.yHotspot);
DrawIcon(hdcBackBuffer, pt.x, pt.y, fMouseCursor);
fBackBuffer.ReleaseDC(hdcBackBuffer);
ReleaseDC(0, hdcScreen);
//hres := fFrontBuffer.Flip(nil, DDFLIP_WAIT);
hres := fFrontBuffer.Flip(nil, DDFLIP_DONOTWAIT);
if hres = DD_OK
then Result := true
else
if hres = DDERR_SURFACELOST
then Result := (fFrontBuffer._Restore = DD_OK) and (fFrontBuffer.Flip(nil, DDFLIP_DONOTWAIT) = DD_OK)
else Result := false;
end
else
begin
// GDI hardware
// Update the surface with a blt
//fFrontBuffer.SetClipper(fClipper);
//Result := fFrontBuffer.Blt(nil, fBackBuffer, nil, DDBLT_DONOTWAIT, nil) = DD_OK;
Result := true;
i := low(DirtyRects);
while Result and (i <= high(DirtyRects)) do
if not IsRectEmpty(DirtyRects[i])
then
begin
R := DirtyRects[i];
hres := fFrontBuffer.Blt(@R, fBackBuffer, @R, DDBLT_DONOTWAIT, nil);
if hres = DD_OK
then inc(i)
else
if hres = DDERR_SURFACELOST
then Result := fFrontBuffer._Restore = DD_OK
else Result := false;
end
else inc(i);
if not Result
then ;//WriteDebugStr('Blit to surface failed');
end;
end;
//-------------------------------------------------------------------------------
// Name: IsAnyWindowShowing
// Desc: Simply checks to see if there's any content window displayed. This check
// should be made prior to calling UpdateWindows.
//-------------------------------------------------------------------------------
function TFullScreenWindowManager.IsAnyWindowShowing : boolean;
begin
Result := fWindows.Count > 0;
end;
end.
|
unit UPCOperation;
interface
uses
Classes, URawBytes, UOperationResume, UAccountPreviousBlockInfo, UPCSafeBoxTransaction;
type
{ TPCOperation }
TPCOperation = Class
Private
Ftag: integer;
Protected
FPrevious_Signer_updated_block: Cardinal;
FPrevious_Destination_updated_block : Cardinal;
FPrevious_Seller_updated_block : Cardinal;
FHasValidSignature : Boolean;
FBufferedSha256 : TRawBytes;
public
constructor Create; virtual;
destructor Destroy; override;
// Skybuck: moved to here to make it accessable to TOperationsHashTree
procedure InitializeData; virtual;
function SaveOpToStream(Stream: TStream; SaveExtendedData : Boolean): Boolean; virtual; abstract;
function LoadOpFromStream(Stream: TStream; LoadExtendedData : Boolean): Boolean; virtual; abstract;
procedure FillOperationResume(Block : Cardinal; getInfoForAllAccounts : Boolean; Affected_account_number : Cardinal; var OperationResume : TOperationResume); virtual;
// Skybuck: added write properties for TOperationHashTree
Property Previous_Signer_updated_block : Cardinal read FPrevious_Signer_updated_block write FPrevious_Signer_updated_block; // deprecated
Property Previous_Destination_updated_block : Cardinal read FPrevious_Destination_updated_block write FPrevious_Destination_updated_block; // deprecated
Property Previous_Seller_updated_block : Cardinal read FPrevious_Seller_updated_block write FPrevious_Seller_updated_block; // deprecated
function GetBufferForOpHash(UseProtocolV2 : Boolean): TRawBytes; virtual;
function DoOperation(AccountPreviousUpdatedBlock : TAccountPreviousBlockInfo; AccountTransaction : TPCSafeBoxTransaction; var errors: AnsiString): Boolean; virtual; abstract;
procedure AffectedAccounts(list : TList); virtual; abstract;
class function OpType: Byte; virtual; abstract;
Class Function OperationToOperationResume(Block : Cardinal; Operation : TPCOperation; getInfoForAllAccounts : Boolean; Affected_account_number : Cardinal; var OperationResume : TOperationResume) : Boolean; virtual;
function OperationAmount : Int64; virtual; abstract;
function OperationAmountByAccount(account : Cardinal) : Int64; virtual;
function OperationFee: Int64; virtual; abstract;
function OperationPayload : TRawBytes; virtual; abstract;
function SignerAccount : Cardinal; virtual; abstract;
procedure SignerAccounts(list : TList); virtual;
function IsSignerAccount(account : Cardinal) : Boolean; virtual;
function IsAffectedAccount(account : Cardinal) : Boolean; virtual;
function DestinationAccount : Int64; virtual;
function SellerAccount : Int64; virtual;
function N_Operation : Cardinal; virtual; abstract;
function GetAccountN_Operation(account : Cardinal) : Cardinal; virtual;
Property tag : integer read Ftag Write Ftag;
function SaveToNettransfer(Stream: TStream): Boolean;
function LoadFromNettransfer(Stream: TStream): Boolean;
function SaveToStorage(Stream: TStream): Boolean;
function LoadFromStorage(Stream: TStream; LoadProtocolVersion : Word; APreviousUpdatedBlocks : TAccountPreviousBlockInfo): Boolean;
Property HasValidSignature : Boolean read FHasValidSignature;
Class function OperationHash_OLD(op : TPCOperation; Block : Cardinal) : TRawBytes;
Class function OperationHashValid(op : TPCOperation; Block : Cardinal) : TRawBytes;
class function IsValidOperationHash(const AOpHash : AnsiString) : Boolean;
class function TryParseOperationHash(const AOpHash : AnsiString; var block, account, n_operation: Cardinal; var md160Hash : TRawBytes) : Boolean;
Class function DecodeOperationHash(Const operationHash : TRawBytes; var block, account,n_operation : Cardinal; var md160Hash : TRawBytes) : Boolean;
Class function EqualOperationHashes(Const operationHash1, operationHash2 : TRawBytes) : Boolean;
Class function FinalOperationHashAsHexa(Const operationHash : TRawBytes) : AnsiString;
class function OperationHashAsHexa(const operationHash : TRawBytes) : AnsiString;
function Sha256 : TRawBytes;
// Skybuck: properties added to make these accessable to TOperationHashTree
// property HasValidSignature : Boolean read FHasValidSignature;
property BufferedSha256 : TRawBytes read FBufferedSha256 write FBufferedSha256;
End;
implementation
uses
SysUtils, UCrypto, UBaseType, UConst, UOpTransaction, UAccountComp, UOpChangeAccountInfoType;
{ TPCOperation }
constructor TPCOperation.Create;
begin
FHasValidSignature := False;
FBufferedSha256:='';
InitializeData;
end;
destructor TPCOperation.Destroy;
begin
inherited Destroy;
end;
function TPCOperation.GetBufferForOpHash(UseProtocolV2: Boolean): TRawBytes;
Var ms : TMemoryStream;
begin
// Protocol v2 change:
// In previous builds (previous to 2.0) there was a distinct method to
// save data for ophash and for calculate Sha256 value on merkle tree
//
// Starting in v2 we will use only 1 method to do both calcs
// We will use "UseProtocolV2" bool value to indicate which method
// want to calc.
// Note: This method will be overrided by OpTransaction, OpChange and OpRecover only
if (UseProtocolV2) then begin
ms := TMemoryStream.Create;
try
SaveOpToStream(ms,False);
ms.Position := 0;
setlength(Result,ms.Size);
ms.ReadBuffer(Result[1],ms.Size);
finally
ms.Free;
end;
end else Raise Exception.Create('ERROR DEV 20170426-1'); // This should never happen, if good coded
end;
procedure TPCOperation.SignerAccounts(list: TList);
begin
list.Clear;
list.Add(TObject(SignerAccount));
end;
class function TPCOperation.DecodeOperationHash(const operationHash: TRawBytes;
var block, account, n_operation: Cardinal; var md160Hash : TRawBytes) : Boolean;
{ Decodes a previously generated OperationHash }
var ms : TMemoryStream;
begin
Result := false;
block :=0;
account :=0;
n_operation :=0;
md160Hash:='';
if length(operationHash)<>32 then exit;
ms := TMemoryStream.Create;
try
ms.Write(operationHash[1],length(operationHash));
ms.position := 0;
ms.Read(block,4);
ms.Read(account,4);
ms.Read(n_operation,4);
SetLength(md160Hash, 20);
ms.ReadBuffer(md160Hash[1], 20);
Result := true;
finally
ms.free;
end;
end;
class function TPCOperation.IsValidOperationHash(const AOpHash : AnsiString) : Boolean;
var block, account, n_operation: Cardinal; md160Hash : TRawBytes;
begin
Result := TryParseOperationHash(AOpHash, block, account, n_operation, md160Hash);
end;
class function TPCOperation.TryParseOperationHash(const AOpHash : AnsiString; var block, account, n_operation: Cardinal; var md160Hash : TRawBytes) : Boolean;
var
ophash : TRawBytes;
begin
ophash := TCrypto.HexaToRaw(trim(AOpHash));
if Length(ophash) = 0 then
Exit(false);
If not TPCOperation.DecodeOperationHash(ophash,block,account,n_operation,md160Hash) then
Exit(false);
Result := true;
end;
class function TPCOperation.EqualOperationHashes(const operationHash1,operationHash2: TRawBytes): Boolean;
// operationHash1 and operationHash2 must be in RAW format (Not hexadecimal string!)
var b0,b1,b2,r1,r2 : TRawBytes;
begin
// First 4 bytes of OpHash are block number. If block=0 then is an unknown block, otherwise must match
b1 := copy(operationHash1,1,4);
b2 := copy(operationHash2,1,4);
r1 := copy(operationHash1,5,length(operationHash1)-4);
r2 := copy(operationHash2,5,length(operationHash2)-4);
b0 := TCrypto.HexaToRaw('00000000');
Result := (TBaseType.BinStrComp(r1,r2)=0) // Both right parts must be equal
AND ((TBaseType.BinStrComp(b1,b0)=0) Or (TBaseType.BinStrComp(b2,b0)=0) Or (TBaseType.BinStrComp(b1,b2)=0)); // b is 0 value or b1=b2 (b = block number)
end;
class function TPCOperation.FinalOperationHashAsHexa(const operationHash: TRawBytes): AnsiString;
begin
Result := TCrypto.ToHexaString(Copy(operationHash,5,28));
end;
class function TPCOperation.OperationHashAsHexa(const operationHash: TRawBytes): AnsiString;
begin
Result := TCrypto.ToHexaString(operationHash);
end;
procedure TPCOperation.InitializeData;
begin
FTag := 0;
FPrevious_Signer_updated_block := 0;
FPrevious_Destination_updated_block := 0;
FPrevious_Seller_updated_block := 0;
FHasValidSignature := false;
FBufferedSha256:='';
end;
procedure TPCOperation.FillOperationResume(Block: Cardinal; getInfoForAllAccounts : Boolean; Affected_account_number: Cardinal; var OperationResume: TOperationResume);
begin
//
end;
function TPCOperation.LoadFromNettransfer(Stream: TStream): Boolean;
begin
Result := LoadOpFromStream(Stream, False);
end;
function TPCOperation.LoadFromStorage(Stream: TStream; LoadProtocolVersion:Word; APreviousUpdatedBlocks : TAccountPreviousBlockInfo): Boolean;
begin
Result := false;
If LoadOpFromStream(Stream, LoadProtocolVersion>=CT_PROTOCOL_2) then begin
If LoadProtocolVersion<CT_PROTOCOL_3 then begin
if Stream.Size - Stream.Position<8 then exit;
Stream.Read(FPrevious_Signer_updated_block,Sizeof(FPrevious_Signer_updated_block));
Stream.Read(FPrevious_Destination_updated_block,Sizeof(FPrevious_Destination_updated_block));
if (LoadProtocolVersion=CT_PROTOCOL_2) then begin
Stream.Read(FPrevious_Seller_updated_block,Sizeof(FPrevious_Seller_updated_block));
end;
if Assigned(APreviousUpdatedBlocks) then begin
// Add to previous list!
if SignerAccount>=0 then
APreviousUpdatedBlocks.UpdateIfLower(SignerAccount,FPrevious_Signer_updated_block);
if DestinationAccount>=0 then
APreviousUpdatedBlocks.UpdateIfLower(DestinationAccount,FPrevious_Destination_updated_block);
if SellerAccount>=0 then
APreviousUpdatedBlocks.UpdateIfLower(SellerAccount,FPrevious_Seller_updated_block);
end;
end;
Result := true;
end;
end;
class function TPCOperation.OperationHash_OLD(op: TPCOperation; Block : Cardinal): TRawBytes;
{ OperationHash is a 32 bytes value.
First 4 bytes (0..3) are Block in little endian
Next 4 bytes (4..7) are Account in little endian
Next 4 bytes (8..11) are N_Operation in little endian
Next 20 bytes (12..31) are a RipeMD160 of the operation buffer to hash
//
This format is easy to undecode because include account and n_operation
}
var ms : TMemoryStream;
r : TRawBytes;
_a,_o : Cardinal;
begin
ms := TMemoryStream.Create;
try
ms.Write(Block,4);
_a := op.SignerAccount;
_o := op.N_Operation;
ms.Write(_a,4);
ms.Write(_o,4);
// BUG IN PREVIOUS VERSIONS: (1.5.5 and prior)
// Function DoRipeMD160 returned a 40 bytes value, because data was converted in hexa string!
// So, here we used only first 20 bytes, and WHERE HEXA values, so only 16 diff values per 2 byte!
ms.WriteBuffer(TCrypto.DoRipeMD160_HEXASTRING(op.GetBufferForOpHash(False))[1],20);
SetLength(Result,ms.size);
ms.Position:=0;
ms.Read(Result[1],ms.size);
finally
ms.Free;
end;
end;
class function TPCOperation.OperationHashValid(op: TPCOperation; Block : Cardinal): TRawBytes;
{ OperationHash is a 32 bytes value.
First 4 bytes (0..3) are Block in little endian
Next 4 bytes (4..7) are Account in little endian
Next 4 bytes (8..11) are N_Operation in little endian
Next 20 bytes (12..31) are a RipeMD160 of the SAME data used to calc Sha256
//
This format is easy to undecode because include account and n_operation
}
var ms : TMemoryStream;
r : TRawBytes;
_a,_o : Cardinal;
begin
ms := TMemoryStream.Create;
try
ms.Write(Block,4); // Save block (4 bytes)
_a := op.SignerAccount;
_o := op.N_Operation;
ms.Write(_a,4); // Save Account (4 bytes)
ms.Write(_o,4); // Save N_Operation (4 bytes)
ms.WriteBuffer(TCrypto.DoRipeMD160AsRaw(op.GetBufferForOpHash(True))[1],20); // Calling GetBufferForOpHash(TRUE) is the same than data used for Sha256
SetLength(Result,ms.size);
ms.Position:=0;
ms.Read(Result[1],ms.size);
finally
ms.Free;
end;
end;
class function TPCOperation.OperationToOperationResume(Block : Cardinal; Operation: TPCOperation; getInfoForAllAccounts : Boolean; Affected_account_number: Cardinal; var OperationResume: TOperationResume): Boolean;
Var spayload : AnsiString;
s : AnsiString;
begin
OperationResume := CT_TOperationResume_NUL;
OperationResume.Block:=Block;
If Operation.SignerAccount=Affected_account_number then begin
OperationResume.Fee := (-1)*Int64(Operation.OperationFee);
end;
OperationResume.AffectedAccount := Affected_account_number;
OperationResume.OpType:=Operation.OpType;
OperationResume.SignerAccount := Operation.SignerAccount;
OperationResume.n_operation := Operation.N_Operation;
Result := false;
case Operation.OpType of
CT_Op_Transaction : Begin
// Assume that Operation is TOpTransaction
OperationResume.DestAccount:=TOpTransaction(Operation).Data.target;
if (TOpTransaction(Operation).Data.opTransactionStyle = transaction_with_auto_buy_account) then begin
if TOpTransaction(Operation).Data.sender=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyTransactionBuyer;
OperationResume.OperationTxt := 'Tx-Out (PASA '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target)+' Purchase) '+TAccountComp.FormatMoney(TOpTransaction(Operation).Data.amount)+' PASC from '+
TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.sender)+' to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target);
If (TOpTransaction(Operation).Data.sender=TOpTransaction(Operation).Data.SellerAccount) then begin
// Valid calc when sender is the same than seller
OperationResume.Amount := (Int64(TOpTransaction(Operation).Data.amount) - (TOpTransaction(Operation).Data.AccountPrice)) * (-1);
end else OperationResume.Amount := Int64(TOpTransaction(Operation).Data.amount) * (-1);
Result := true;
end else if TOpTransaction(Operation).Data.target=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyTransactionTarget;
OperationResume.OperationTxt := 'Tx-In (PASA '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target)+' Purchase) '+TAccountComp.FormatMoney(TOpTransaction(Operation).Data.amount)+' PASC from '+
TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.sender)+' to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target);
OperationResume.Amount := Int64(TOpTransaction(Operation).Data.amount) - Int64(TOpTransaction(Operation).Data.AccountPrice);
OperationResume.Fee := 0;
Result := true;
end else if TOpTransaction(Operation).Data.SellerAccount=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyTransactionSeller;
OperationResume.OperationTxt := 'Tx-In Sold account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target)+' price '+TAccountComp.FormatMoney(TOpTransaction(Operation).Data.AccountPrice)+' PASC';
OperationResume.Amount := TOpTransaction(Operation).Data.AccountPrice;
OperationResume.Fee := 0;
Result := true;
end else exit;
end else begin
if TOpTransaction(Operation).Data.sender=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_TransactionSender;
OperationResume.OperationTxt := 'Tx-Out '+TAccountComp.FormatMoney(TOpTransaction(Operation).Data.amount)+' PASC from '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.sender)+' to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target);
OperationResume.Amount := Int64(TOpTransaction(Operation).Data.amount) * (-1);
Result := true;
end else if TOpTransaction(Operation).Data.target=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_TransactionReceiver;
OperationResume.OperationTxt := 'Tx-In '+TAccountComp.FormatMoney(TOpTransaction(Operation).Data.amount)+' PASC from '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.sender)+' to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpTransaction(Operation).Data.target);
OperationResume.Amount := TOpTransaction(Operation).Data.amount;
OperationResume.Fee := 0;
Result := true;
end else exit;
end;
End;
CT_Op_Changekey : Begin
OperationResume.OpSubtype := CT_OpSubtype_ChangeKey;
OperationResume.newKey := TOpChangeKey(Operation).Data.new_accountkey;
OperationResume.DestAccount := TOpChangeKey(Operation).Data.account_target;
OperationResume.OperationTxt := 'Change Key to '+TAccountComp.GetECInfoTxt( OperationResume.newKey.EC_OpenSSL_NID );
Result := true;
End;
CT_Op_ChangeKeySigned : Begin
OperationResume.OpSubtype := CT_OpSubtype_ChangeKeySigned;
OperationResume.newKey := TOpChangeKeySigned(Operation).Data.new_accountkey;
OperationResume.DestAccount := TOpChangeKeySigned(Operation).Data.account_target;
OperationResume.OperationTxt := 'Change '+TAccountComp.AccountNumberToAccountTxtNumber(OperationResume.DestAccount)+' account key to '+TAccountComp.GetECInfoTxt( OperationResume.newKey.EC_OpenSSL_NID );
Result := true;
end;
CT_Op_Recover : Begin
OperationResume.OpSubtype := CT_OpSubtype_Recover;
OperationResume.OperationTxt := 'Recover founds';
Result := true;
End;
CT_Op_ListAccountForSale : Begin
If TOpListAccount(Operation).IsPrivateSale then begin
OperationResume.OpSubtype := CT_OpSubtype_ListAccountForPrivateSale;
OperationResume.OperationTxt := 'List account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpListAccount(Operation).Data.account_target)+' for private sale price '+
TAccountComp.FormatMoney(TOpListAccount(Operation).Data.account_price)+' PASC pay to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpListAccount(Operation).Data.account_to_pay);
end else begin
OperationResume.OpSubtype := CT_OpSubtype_ListAccountForPublicSale;
OperationResume.OperationTxt := 'List account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpListAccount(Operation).Data.account_target)+' for sale price '+
TAccountComp.FormatMoney(TOpListAccount(Operation).Data.account_price)+' PASC pay to '+TAccountComp.AccountNumberToAccountTxtNumber(TOpListAccount(Operation).Data.account_to_pay);
end;
OperationResume.newKey := TOpListAccount(Operation).Data.new_public_key;
OperationResume.SellerAccount := Operation.SellerAccount;
Result := true;
End;
CT_Op_DelistAccount : Begin
OperationResume.OpSubtype := CT_OpSubtype_DelistAccount;
OperationResume.OperationTxt := 'Delist account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpDelistAccountForSale(Operation).Data.account_target)+' for sale';
Result := true;
End;
CT_Op_BuyAccount : Begin
OperationResume.DestAccount:=TOpBuyAccount(Operation).Data.target;
if TOpBuyAccount(Operation).Data.sender=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyAccountBuyer;
OperationResume.OperationTxt := 'Buy account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpBuyAccount(Operation).Data.target)+' for '+TAccountComp.FormatMoney(TOpBuyAccount(Operation).Data.AccountPrice)+' PASC';
OperationResume.Amount := Int64(TOpBuyAccount(Operation).Data.amount) * (-1);
Result := true;
end else if TOpBuyAccount(Operation).Data.target=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyAccountTarget;
OperationResume.OperationTxt := 'Purchased account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpBuyAccount(Operation).Data.target)+' by '+
TAccountComp.AccountNumberToAccountTxtNumber(TOpBuyAccount(Operation).Data.sender)+' for '+TAccountComp.FormatMoney(TOpBuyAccount(Operation).Data.AccountPrice)+' PASC';
OperationResume.Amount := Int64(TOpBuyAccount(Operation).Data.amount) - Int64(TOpBuyAccount(Operation).Data.AccountPrice);
OperationResume.Fee := 0;
Result := true;
end else if TOpBuyAccount(Operation).Data.SellerAccount=Affected_account_number then begin
OperationResume.OpSubtype := CT_OpSubtype_BuyAccountSeller;
OperationResume.OperationTxt := 'Sold account '+TAccountComp.AccountNumberToAccountTxtNumber(TOpBuyAccount(Operation).Data.target)+' by '+
TAccountComp.AccountNumberToAccountTxtNumber(TOpBuyAccount(Operation).Data.sender)+' for '+TAccountComp.FormatMoney(TOpBuyAccount(Operation).Data.AccountPrice)+' PASC';
OperationResume.Amount := TOpBuyAccount(Operation).Data.AccountPrice;
OperationResume.Fee := 0;
Result := true;
end else exit;
End;
CT_Op_ChangeAccountInfo : Begin
OperationResume.DestAccount := Operation.DestinationAccount;
s := '';
if (ait_public_key in TOpChangeAccountInfo(Operation).Data.changes_type) then begin
s := 'key';
end;
if (ait_account_name in TOpChangeAccountInfo(Operation).Data.changes_type) then begin
if s<>'' then s:=s+',';
s := s + 'name';
end;
if (ait_account_type in TOpChangeAccountInfo(Operation).Data.changes_type) then begin
if s<>'' then s:=s+',';
s := s + 'type';
end;
OperationResume.OperationTxt:= 'Changed '+s+' of account '+TAccountComp.AccountNumberToAccountTxtNumber(Operation.DestinationAccount);
OperationResume.OpSubtype:=CT_OpSubtype_ChangeAccountInfo;
Result := True;
end;
CT_Op_MultiOperation : Begin
OperationResume.isMultiOperation:=True;
OperationResume.OperationTxt := Operation.ToString;
OperationResume.Amount := Operation.OperationAmountByAccount(Affected_account_number);
OperationResume.Fee := 0;
Result := True;
end
else Exit;
end;
OperationResume.OriginalPayload := Operation.OperationPayload;
If TCrypto.IsHumanReadable(OperationResume.OriginalPayload) then OperationResume.PrintablePayload := OperationResume.OriginalPayload
else OperationResume.PrintablePayload := TCrypto.ToHexaString(OperationResume.OriginalPayload);
OperationResume.OperationHash:=TPCOperation.OperationHashValid(Operation,Block);
if (Block>0) And (Block<CT_Protocol_Upgrade_v2_MinBlock) then begin
OperationResume.OperationHash_OLD:=TPCOperation.OperationHash_OLD(Operation,Block);
end;
OperationResume.valid := true;
Operation.FillOperationResume(Block,getInfoForAllAccounts,Affected_account_number,OperationResume);
end;
function TPCOperation.IsSignerAccount(account: Cardinal): Boolean;
begin
Result := SignerAccount = account;
end;
function TPCOperation.IsAffectedAccount(account: Cardinal): Boolean;
Var l : TList;
begin
l := TList.Create;
Try
AffectedAccounts(l);
Result := (l.IndexOf(TObject(account))>=0);
finally
l.Free;
end;
end;
function TPCOperation.DestinationAccount: Int64;
begin
Result := -1;
end;
function TPCOperation.SellerAccount: Int64;
begin
Result := -1;
end;
function TPCOperation.GetAccountN_Operation(account: Cardinal): Cardinal;
begin
If (SignerAccount = account) then Result := N_Operation
else Result := 0;
end;
function TPCOperation.SaveToNettransfer(Stream: TStream): Boolean;
begin
Result := SaveOpToStream(Stream,False);
end;
function TPCOperation.SaveToStorage(Stream: TStream): Boolean;
begin
Result := SaveOpToStream(Stream,True);
end;
function TPCOperation.Sha256: TRawBytes;
begin
If Length(FBufferedSha256)=0 then begin
FBufferedSha256 := TCrypto.DoSha256(GetBufferForOpHash(true));
end;
Result := FBufferedSha256;
end;
function TPCOperation.OperationAmountByAccount(account: Cardinal): Int64;
begin
Result := 0;
end;
end.
|
unit kwInclude;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwInclude.pas"
// Начат: 04.05.2011 22:02
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::IncludesAndUses::IncludesAndUsesPack::Include
//
// Зарезервированное слово: INCLUDE
// Пример:
// {code}
// INCLUDE 'Included.script'
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
tfwScriptingInterfaces,
kwIncluded,
l3Interfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwIncludeLike.imp.pas}
TkwInclude = class(_tfwIncludeLike_)
{* Зарезервированное слово: INCLUDE
Пример:
[code]
INCLUDE 'Included.script'
[code] }
protected
// realized methods
function EndBracket(const aContext: TtfwContext): AnsiString; override;
protected
// overridden protected methods
function AfterWordMaxCount: Cardinal; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwInclude
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
l3String,
SysUtils,
l3Types,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwInclude;
{$Include ..\ScriptEngine\tfwIncludeLike.imp.pas}
// start class TkwInclude
function TkwInclude.EndBracket(const aContext: TtfwContext): AnsiString;
//#UC START# *4DB6C99F026E_4DC1949F00E1_var*
//#UC END# *4DB6C99F026E_4DC1949F00E1_var*
begin
//#UC START# *4DB6C99F026E_4DC1949F00E1_impl*
Result := DisabledEndBracket(aContext);
//#UC END# *4DB6C99F026E_4DC1949F00E1_impl*
end;//TkwInclude.EndBracket
class function TkwInclude.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'INCLUDE';
end;//TkwInclude.GetWordNameForRegister
function TkwInclude.AfterWordMaxCount: Cardinal;
//#UC START# *4DB9B446039A_4DC1949F00E1_var*
//#UC END# *4DB9B446039A_4DC1949F00E1_var*
begin
//#UC START# *4DB9B446039A_4DC1949F00E1_impl*
Result := 1;
//#UC END# *4DB9B446039A_4DC1949F00E1_impl*
end;//TkwInclude.AfterWordMaxCount
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwIncludeLike.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit DeleteRouteResponseUnit;
interface
uses
REST.Json.Types, System.Generics.Collections, SysUtils,
GenericParametersUnit, DataObjectUnit, CommonTypesUnit;
type
TDeleteRouteResponse = class(TGenericParameters)
private
[JSONName('deleted')]
FDeleted: boolean;
[JSONName('errors')]
FErrors: TList<String>;
[JSONName('route_id')]
FRouteId: String;
[JSONName('route_ids')]
FRouteIds: TStringArray;
public
constructor Create; override;
destructor Destroy; override;
property Deleted: boolean read FDeleted write FDeleted;
property Errors: TList<String> read FErrors write FErrors;
property RouteId: String read FRouteId write FRouteId;
property RouteIds: TStringArray read FRouteIds write FRouteIds;
end;
implementation
{ TDeleteRouteResponse }
constructor TDeleteRouteResponse.Create;
begin
inherited;
FErrors := nil;
SetLength(FRouteIds, 0);
end;
destructor TDeleteRouteResponse.Destroy;
begin
FreeAndNil(FErrors);
inherited;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.6 2/10/2005 2:24:38 PM JPMugaas
Minor Restructures for some new UnixTime Service components.
Rev 1.5 2004.02.03 5:44:36 PM czhower
Name changes
Rev 1.4 1/21/2004 4:21:02 PM JPMugaas
InitComponent
Rev 1.3 10/22/2003 08:48:06 PM JPMugaas
Minor code cleanup.
Rev 1.1 2003.10.12 6:36:46 PM czhower
Now compiles.
Rev 1.0 11/13/2002 08:03:28 AM JPMugaas
}
unit IdTimeUDPServer;
interface
{$i IdCompilerDefines.inc}
uses
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
Classes,
{$ENDIF}
IdAssignedNumbers, IdGlobal, IdSocketHandle, IdUDPBase, IdUDPServer;
type
TIdCustomTimeUDPServer = class(TIdUDPServer)
protected
FBaseDate : TDateTime;
procedure DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); override;
procedure InitComponent; override;
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
public
constructor Create(AOwner: TComponent); reintroduce; overload;
{$ENDIF}
end;
TIdTimeUDPServer = class(TIdCustomTimeUDPServer)
published
property DefaultPort default IdPORT_TIME;
{This property is used to set the Date the Time server bases it's
calculations from. If both the server and client are based from the same
date which is higher than the original date, you can extend it beyond the
year 2035}
property BaseDate : TDateTime read FBaseDate write FBaseDate;
end;
implementation
uses
{$IFDEF USE_VCL_POSIX}
Posix.SysTime,
{$ENDIF}
IdGlobalProtocols, IdStack, SysUtils;
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
constructor TIdCustomTimeUDPServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
{$ENDIF}
procedure TIdCustomTimeUDPServer.InitComponent;
begin
inherited;
DefaultPort := IdPORT_TIME;
{This indicates that the default date is Jan 1, 1900 which was specified
by RFC 868.}
FBaseDate := TIME_BASEDATE;
end;
procedure TIdCustomTimeUDPServer.DoUDPRead(AThread: TIdUDPListenerThread;
const AData: TIdBytes; ABinding: TIdSocketHandle);
var
LTime : Cardinal;
begin
inherited DoUDPRead(AThread, AData, ABinding);
LTime := Trunc(extended(Now + TimeZoneBias - Int(FBaseDate)) * 24 * 60 * 60);
LTime := GStack.HostToNetwork(LTime);
SendBuffer(ABinding.PeerIP, ABinding.PeerPort, ToBytes(LTime));
end;
end.
|
{ 2020/07/05 0.01 Move tests from flcDatastucts unit. }
{ 2020/07/07 0.02 Tests for String and Object arrays. }
{$INCLUDE ../../flcInclude.inc}
{$INCLUDE flcTestInclude.inc}
unit flcTestDataStructArrays;
interface
procedure Test;
implementation
uses
SysUtils,
flcStdTypes,
flcDataStructArrays;
procedure Test_1_Int32Array;
var
I : Int32;
F : TInt32Array;
begin
F := TInt32Array.Create;
for I := 0 to 16384 do
Assert(F.Add(I) = I, 'Array.Add');
Assert(F.Count = 16385, 'Array.Count');
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.GetItem');
for I := 0 to 16384 do
F[I] := I + 1;
for I := 0 to 16384 do
Assert(F[I] = I + 1, 'Array.SetItem');
F.Delete(0, 1);
Assert(F.Count = 16384, 'Array.Delete');
for I := 0 to 16383 do
Assert(F[I] = I + 2, 'Array.Delete');
F.Insert(0, 2);
F[0] := 0;
F[1] := 1;
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.Insert');
Assert(F.GetIndex(16382) = 16382);
F.Count := 4;
Assert(F.Count = 4, 'Array.SetCount');
F[0] := 9;
F[1] := -2;
F[2] := 3;
F[3] := 4;
F.Sort;
Assert(F[0] = -2, 'Array.Sort');
Assert(F[1] = 3, 'Array.Sort');
Assert(F[2] = 4, 'Array.Sort');
Assert(F[3] = 9, 'Array.Sort');
F.Count := 7;
F[0] := 3;
F[1] := 5;
F[2] := 5;
F[3] := 2;
F[4] := 5;
F[5] := 5;
F[6] := 1;
F.Sort;
Assert(F[0] = 1, 'Array.Sort');
Assert(F[1] = 2, 'Array.Sort');
Assert(F[2] = 3, 'Array.Sort');
Assert(F[3] = 5, 'Array.Sort');
Assert(F[4] = 5, 'Array.Sort');
Assert(F[5] = 5, 'Array.Sort');
Assert(F[6] = 5, 'Array.Sort');
F.Clear;
Assert(F.Count = 0, 'Array.Clear');
F.Free;
end;
procedure Test_1_Int64Array;
var
I : Int32;
F : TInt64Array;
begin
F := TInt64Array.Create;
for I := 0 to 16384 do
Assert(F.Add(I) = I, 'Array.Add');
Assert(F.Count = 16385, 'Array.Count');
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.GetItem');
for I := 0 to 16384 do
F[I] := I + 1;
for I := 0 to 16384 do
Assert(F[I] = I + 1, 'Array.SetItem');
F.Delete(0, 1);
Assert(F.Count = 16384, 'Array.Delete');
for I := 0 to 16383 do
Assert(F[I] = I + 2, 'Array.Delete');
F.Insert(0, 2);
F[0] := 0;
F[1] := 1;
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.Insert');
Assert(F.GetIndex(16382) = 16382);
F.Count := 4;
Assert(F.Count = 4, 'Array.SetCount');
F[0] := 9;
F[1] := -2;
F[2] := 3;
F[3] := 4;
F.Sort;
Assert(F[0] = -2, 'Array.Sort');
Assert(F[1] = 3, 'Array.Sort');
Assert(F[2] = 4, 'Array.Sort');
Assert(F[3] = 9, 'Array.Sort');
F.Count := 7;
F[0] := 3;
F[1] := 5;
F[2] := 5;
F[3] := 2;
F[4] := 5;
F[5] := 5;
F[6] := 1;
F.Sort;
Assert(F[0] = 1, 'Array.Sort');
Assert(F[1] = 2, 'Array.Sort');
Assert(F[2] = 3, 'Array.Sort');
Assert(F[3] = 5, 'Array.Sort');
Assert(F[4] = 5, 'Array.Sort');
Assert(F[5] = 5, 'Array.Sort');
Assert(F[6] = 5, 'Array.Sort');
F.Clear;
Assert(F.Count = 0, 'Array.Clear');
F.Free;
end;
procedure Test_1_UInt32Array;
var
I : Int32;
F : TUInt32Array;
begin
F := TUInt32Array.Create;
for I := 0 to 16384 do
Assert(F.Add(I) = I, 'Array.Add');
Assert(F.Count = 16385, 'Array.Count');
for I := 0 to 16384 do
Assert(F[I] = UInt32(I), 'Array.GetItem');
for I := 0 to 16384 do
F[I] := I + 1;
for I := 0 to 16384 do
Assert(F[I] = UInt32(I) + 1, 'Array.SetItem');
F.Delete(0, 1);
Assert(F.Count = 16384, 'Array.Delete');
for I := 0 to 16383 do
Assert(F[I] = UInt32(I) + 2, 'Array.Delete');
F.Insert(0, 2);
F[0] := 0;
F[1] := 1;
for I := 0 to 16384 do
Assert(F[I] = UInt32(I), 'Array.Insert');
Assert(F.GetIndex(16382) = 16382);
F.Count := 4;
Assert(F.Count = 4, 'Array.SetCount');
F[0] := 9;
F[1] := 2;
F[2] := 3;
F[3] := 4;
F.Sort;
Assert(F[0] = 2, 'Array.Sort');
Assert(F[1] = 3, 'Array.Sort');
Assert(F[2] = 4, 'Array.Sort');
Assert(F[3] = 9, 'Array.Sort');
F.Count := 7;
F[0] := 3;
F[1] := 5;
F[2] := 5;
F[3] := 2;
F[4] := 5;
F[5] := 5;
F[6] := 1;
F.Sort;
Assert(F[0] = 1, 'Array.Sort');
Assert(F[1] = 2, 'Array.Sort');
Assert(F[2] = 3, 'Array.Sort');
Assert(F[3] = 5, 'Array.Sort');
Assert(F[4] = 5, 'Array.Sort');
Assert(F[5] = 5, 'Array.Sort');
Assert(F[6] = 5, 'Array.Sort');
F.Clear;
Assert(F.Count = 0, 'Array.Clear');
F.Free;
end;
procedure Test_1_UInt64Array;
var
I : Int32;
F : TUInt64Array;
begin
F := TUInt64Array.Create;
for I := 0 to 16384 do
Assert(F.Add(I) = NativeInt(I), 'Array.Add');
Assert(F.Count = 16385, 'Array.Count');
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.GetItem');
for I := 0 to 16384 do
F[I] := I + 1;
for I := 0 to 16384 do
Assert(F[I] = I + 1, 'Array.SetItem');
F.Delete(0, 1);
Assert(F.Count = 16384, 'Array.Delete');
for I := 0 to 16383 do
Assert(F[I] = I + 2, 'Array.Delete');
F.Insert(0, 2);
F[0] := 0;
F[1] := 1;
for I := 0 to 16384 do
Assert(F[I] = I, 'Array.Insert');
Assert(F.GetIndex(16382) = 16382);
F.Count := 4;
Assert(F.Count = 4, 'Array.SetCount');
F[0] := 9;
F[1] := 2;
F[2] := 3;
F[3] := 4;
F.Sort;
Assert(F[0] = 2, 'Array.Sort');
Assert(F[1] = 3, 'Array.Sort');
Assert(F[2] = 4, 'Array.Sort');
Assert(F[3] = 9, 'Array.Sort');
F.Count := 7;
F[0] := 3;
F[1] := 5;
F[2] := 5;
F[3] := 2;
F[4] := 5;
F[5] := 5;
F[6] := 1;
F.Sort;
Assert(F[0] = 1, 'Array.Sort');
Assert(F[1] = 2, 'Array.Sort');
Assert(F[2] = 3, 'Array.Sort');
Assert(F[3] = 5, 'Array.Sort');
Assert(F[4] = 5, 'Array.Sort');
Assert(F[5] = 5, 'Array.Sort');
Assert(F[6] = 5, 'Array.Sort');
F.Clear;
Assert(F.Count = 0, 'Array.Clear');
F.Free;
end;
procedure Test_1_UnicodeStringArray;
var
I : Int32;
F : TUnicodeStringArray;
begin
F := TUnicodeStringArray.Create;
for I := 0 to 16384 do
Assert(F.Add(IntToStr(I)) = NativeInt(I));
Assert(F.Count = 16385);
for I := 0 to 16384 do
Assert(F[I] = IntToStr(I));
for I := 0 to 16384 do
F[I] := IntToStr(I + 1);
for I := 0 to 16384 do
Assert(F[I] = IntToStr(I + 1));
F.Delete(0, 1);
Assert(F.Count = 16384);
for I := 0 to 16383 do
Assert(F[I] = IntToStr(I + 2));
F.Insert(0, 2);
F[0] := '0';
F[1] := '1';
for I := 0 to 16384 do
Assert(F[I] = IntToStr(I));
Assert(F.GetIndex('16382') = 16382);
F.Count := 4;
Assert(F.Count = 4);
F[0] := '9';
F[1] := '2';
F[2] := '3';
F[3] := '4';
F.Sort;
Assert(F[0] = '2');
Assert(F[1] = '3');
Assert(F[2] = '4');
Assert(F[3] = '9');
F.Count := 7;
F[0] := '3';
F[1] := '5';
F[2] := '5';
F[3] := '2';
F[4] := '5';
F[5] := '5';
F[6] := '1';
F.Sort;
Assert(F[0] = '1');
Assert(F[1] = '2');
Assert(F[2] = '3');
Assert(F[3] = '5');
Assert(F[4] = '5');
Assert(F[5] = '5');
Assert(F[6] = '5');
F.Clear;
Assert(F.Count = 0);
F.Free;
end;
function IntToRawByteString(const I: Int64): RawByteString;
begin
Result := RawByteString(IntToStr(I));
end;
procedure Test_1_RawByteStringArray;
var
I : Int32;
F : TRawByteStringArray;
begin
F := TRawByteStringArray.Create;
for I := 0 to 16384 do
Assert(F.Add(IntToRawByteString(I)) = NativeInt(I));
Assert(F.Count = 16385);
for I := 0 to 16384 do
Assert(F[I] = IntToRawByteString(I));
for I := 0 to 16384 do
F[I] := IntToRawByteString(I + 1);
for I := 0 to 16384 do
Assert(F[I] = IntToRawByteString(I + 1));
F.Delete(0, 1);
Assert(F.Count = 16384);
for I := 0 to 16383 do
Assert(F[I] = IntToRawByteString(I + 2));
F.Insert(0, 2);
F[0] := '0';
F[1] := '1';
for I := 0 to 16384 do
Assert(F[I] = IntToRawByteString(I));
Assert(F.GetIndex('16382') = 16382);
F.Count := 4;
Assert(F.Count = 4);
F[0] := '9';
F[1] := '2';
F[2] := '3';
F[3] := '4';
F.Sort;
Assert(F[0] = '2');
Assert(F[1] = '3');
Assert(F[2] = '4');
Assert(F[3] = '9');
F.Count := 7;
F[0] := '3';
F[1] := '5';
F[2] := '5';
F[3] := '2';
F[4] := '5';
F[5] := '5';
F[6] := '1';
F.Sort;
Assert(F[0] = '1');
Assert(F[1] = '2');
Assert(F[2] = '3');
Assert(F[3] = '5');
Assert(F[4] = '5');
Assert(F[5] = '5');
Assert(F[6] = '5');
F.Clear;
Assert(F.Count = 0);
F.Free;
end;
procedure Test_1_ObjectArray;
var
O : array[0..16385] of TObject;
I : Int32;
F : TObjectArray;
begin
for I := 0 to 16385 do
O[I] := TObject.Create;
F := TObjectArray.Create(False);
Assert(F.Count = 0);
Assert(F.AddIfNotExists(O[0]) = 0);
Assert(F.Count = 1);
Assert(F.AddIfNotExists(O[0]) = 0);
Assert(F.Count = 1);
for I := 1 to 16384 do
Assert(F.Add(O[I]) = NativeInt(I));
Assert(F.Count = 16385);
for I := 0 to 16384 do
Assert(F[I] = O[I]);
for I := 0 to 16384 do
F[I] := O[I + 1];
for I := 0 to 16384 do
Assert(F[I] = O[I + 1]);
Assert(F.GetIndex(O[1]) = 0);
F.Delete(0, 1);
Assert(F.GetIndex(O[1]) = -1);
Assert(F.Count = 16384);
for I := 0 to 16383 do
Assert(F[I] = O[I + 2]);
F.Insert(0, 2);
F[0] := O[0];
F[1] := O[1];
for I := 0 to 16384 do
Assert(F[I] = O[I]);
Assert(F.GetIndex(O[0]) = 0);
Assert(F.GetIndex(O[16382]) = 16382);
Assert(F.HasValue(O[16382]));
Assert(F.GetIndex(O[16384]) = 16384);
Assert(not F.HasValue(F));
F.Clear;
Assert(F.Count = 0);
F.Free;
for I := 0 to 16385 do
O[I].Free;
end;
procedure Test_1;
begin
Test_1_Int32Array;
Test_1_Int64Array;
Test_1_UInt32Array;
Test_1_UInt64Array;
Test_1_UnicodeStringArray;
Test_1_RawByteStringArray;
Test_1_ObjectArray;
end;
procedure Test;
begin
Test_1;
end;
end.
|
unit udmImagemComprovante;
interface
uses
System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS;
type
TdmImagemComprovante = class(TdmPadrao)
qryManutencaoID_IMG: TIntegerField;
qryManutencaoCGC: TStringField;
qryManutencaoSERIE: TStringField;
qryManutencaoN_FISCAL: TFloatField;
qryManutencaoIMAGEM: TMemoField;
qryManutencaoENVIADO: TStringField;
qryManutencaoMSG_RETORNO: TStringField;
qryLocalizacaoID_IMG: TIntegerField;
qryLocalizacaoCGC: TStringField;
qryLocalizacaoSERIE: TStringField;
qryLocalizacaoN_FISCAL: TFloatField;
qryLocalizacaoIMAGEM: TMemoField;
qryLocalizacaoENVIADO: TStringField;
qryLocalizacaoMSG_RETORNO: TStringField;
qryImgComp: TIBCQuery;
qryImgCompID_IMG: TIntegerField;
qryImgCompCGC: TStringField;
qryImgCompSERIE: TStringField;
qryImgCompN_FISCAL: TFloatField;
qryImgCompIMAGEM: TMemoField;
qryImgCompENVIADO: TStringField;
qryImgCompMSG_RETORNO: TStringField;
qryImgCompDT_EMISSAO: TDateTimeField;
qryImgCompDT_ALTERACAO: TDateTimeField;
qryImgCompOPERADOR: TStringField;
qryLocalizacaoDT_EMISSAO: TDateTimeField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryManutencaoDT_EMISSAO: TDateTimeField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
private
{ Private declarations }
FId_Img: Integer;
FCgc : String;
Fserie : String;
FN_Fiscal: Real;
FDt_AlteracaoINI: TDateTime;
FDt_AlteracaoFIM: TDateTime;
public
{ Public declarations }
property Id_Img: Integer read FId_Img write FId_Img;
property CGC: String read Fcgc write Fcgc;
property Serie: String read FSerie write FSerie;
property N_Fiscal: Real read FN_Fiscal write FN_Fiscal;
property Dt_AlteracaoINI: TDatetime read FDt_AlteracaoINI write FDt_AlteracaoINI;
property Dt_AlteracaoFIM: TDatetime read FDt_AlteracaoFIM write FDt_AlteracaoFIM;
function LocalizaNotaEmbarcada(Dataset: TDataset = nil): Boolean;
function LocalizaNotaEmbarcadaPorID(Dataset: TDataset = nil): Boolean;
function LocalizaNotaEmbarcadaPorData(Dataset: TDataset = nil): Boolean;
end;
const SQL_DEFAULT = 'SELECT '+
'ID_IMG, '+
'CGC, '+
'SERIE, '+
'N_FISCAL, '+
'IMAGEM, '+
'ENVIADO, '+
'MSG_RETORNO, '+
'DT_EMISSAO, '+
'DT_ALTERACAO, '+
'OPERADOR '+
'FROM STWIMGCOMP ';
var
dmImagemComprovante: TdmImagemComprovante;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmImagemComprovante }
function TdmImagemComprovante.LocalizaNotaEmbarcada(
Dataset: TDataset): Boolean;
begin
if Dataset = Nil then
Dataset := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(' WHERE CGC = :CGC');
SQL.Add(' AND SERIE = :SERIE');
SQL.Add(' AND N_FISCAL = :N_FISCAL');
Params[0].AsString := Fcgc;
Params[1].AsString := FSerie;
Params[2].AsFloat := FN_FISCAL;
open;
Result := not isEmpty;
end;
end;
function TdmImagemComprovante.LocalizaNotaEmbarcadaPorData(
Dataset: TDataset): Boolean;
begin
if Dataset = Nil then
Dataset := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(' WHERE DT_ALTERACAO >= :DT_ALTERACAOINI');
SQL.Add(' AND DT_ALTERACAO <= :DT_ALTERACAOFIM');
SQL.Add(' ORDER BY ID_IMG');
Params[0].AsDateTime := FDt_AlteracaoINI;
Params[1].AsDateTime := FDt_AlteracaoFIM;
open;
Result := not isEmpty;
end;
end;
function TdmImagemComprovante.LocalizaNotaEmbarcadaPorID(
Dataset: TDataset): Boolean;
begin
if Dataset = Nil then
Dataset := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE ID_IMG = :ID_IMG');
Params[0].AsInteger := FId_Img;
open;
Result := not isEmpty;
end;
end;
{ TdmImagemComprovante }
end.
|
unit baraduke_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,m680x,namco_snd,main_engine,controls_engine,gfx_engine,
rom_engine,pal_engine,misc_functions,sound_engine;
function iniciar_baraduke:boolean;
implementation
const
//Baraduke
baraduke_rom:array[0..2] of tipo_roms=(
(n:'bd1_3.9c';l:$2000;p:$6000;crc:$ea2ea790),(n:'bd1_1.9a';l:$4000;p:$8000;crc:$4e9f2bdc),
(n:'bd1_2.9b';l:$4000;p:$c000;crc:$40617fcd));
baraduke_mcu:array[0..1] of tipo_roms=(
(n:'bd1_4b.3b';l:$4000;p:$8000;crc:$a47ecd32),(n:'cus60-60a1.mcu';l:$1000;p:$f000;crc:$076ea82a));
baraduke_chars:tipo_roms=(n:'bd1_5.3j';l:$2000;p:0;crc:$706b7fee);
baraduke_tiles:array[0..2] of tipo_roms=(
(n:'bd1_8.4p';l:$4000;p:0;crc:$b0bb0710),(n:'bd1_7.4n';l:$4000;p:$4000;crc:$0d7ebec9),
(n:'bd1_6.4m';l:$4000;p:$8000;crc:$e5da0896));
baraduke_sprites:array[0..3] of tipo_roms=(
(n:'bd1_9.8k';l:$4000;p:0;crc:$87a29acc),(n:'bd1_10.8l';l:$4000;p:$4000;crc:$72b6d20c),
(n:'bd1_11.8m';l:$4000;p:$8000;crc:$3076af9c),(n:'bd1_12.8n';l:$4000;p:$c000;crc:$8b4c09a3));
baraduke_prom:array[0..1] of tipo_roms=(
(n:'bd1-1.1n';l:$800;p:$0;crc:$0d78ebc6),(n:'bd1-2.2m';l:$800;p:$800;crc:$03f7241f));
baraduke_dip_a:array [0..4] of def_dip=(
(mask:$3;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'2C 1C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$4;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$18;dip_name:'1C 1C'),(dip_val:$10;dip_name:'2C 1C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Lives';number:4;dip:((dip_val:$40;dip_name:'2'),(dip_val:$60;dip_name:'3'),(dip_val:$20;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),());
baraduke_dip_b:array [0..5] of def_dip=(
(mask:$2;name:'Allow Continue From Last Level';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Freeze';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Round Select';number:2;dip:((dip_val:$8;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Difficulty';number:4;dip:((dip_val:$20;dip_name:'Easy'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Bonus Life';number:4;dip:((dip_val:$80;dip_name:'10K+'),(dip_val:$c0;dip_name:'10K 20K+'),(dip_val:$40;dip_name:'20K+'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),());
baraduke_dip_c:array [0..1] of def_dip=(
(mask:$2;name:'Cabinet';number:2;dip:((dip_val:$2;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
//Metro-cross
metrocross_rom:array[0..2] of tipo_roms=(
(n:'mc1-3.9c';l:$2000;p:$6000;crc:$3390b33c),(n:'mc1-1.9a';l:$4000;p:$8000;crc:$10b0977e),
(n:'mc1-2.9b';l:$4000;p:$c000;crc:$5c846f35));
metrocross_mcu:array[0..1] of tipo_roms=(
(n:'mc1-4.3b';l:$2000;p:$8000;crc:$9c88f898),(n:'cus60-60a1.mcu';l:$1000;p:$f000;crc:$076ea82a));
metrocross_chars:tipo_roms=(n:'mc1-5.3j';l:$2000;p:0;crc:$9b5ea33a);
metrocross_tiles:array[0..1] of tipo_roms=(
(n:'mc1-7.4p';l:$4000;p:0;crc:$c9dfa003),(n:'mc1-6.4n';l:$4000;p:$4000;crc:$9686dc3c));
metrocross_sprites:array[0..1] of tipo_roms=(
(n:'mc1-8.8k';l:$4000;p:0;crc:$265b31fa),(n:'mc1-9.8l';l:$4000;p:$4000;crc:$541ec029));
metrocross_prom:array[0..1] of tipo_roms=(
(n:'mc1-1.1n';l:$800;p:$0;crc:$32a78a8b),(n:'mc1-2.2m';l:$800;p:$800;crc:$6f4dca7b));
metrocross_dip_a:array [0..4] of def_dip=(
(mask:$3;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'2C 1C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$4;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Difficulty';number:4;dip:((dip_val:$10;dip_name:'Easy'),(dip_val:$18;dip_name:'Normal'),(dip_val:$8;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$20;dip_name:'2C 1C'),(dip_val:$60;dip_name:'1C 1C'),(dip_val:$40;dip_name:'2C 1C'),(),(),(),(),(),(),(),(),(),(),(),())),());
metrocross_dip_b:array [0..3] of def_dip=(
(mask:$20;name:'Freeze';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Round Select';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$80;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
inputport_selected,scroll_y0,scroll_y1:byte;
sprite_mask,counter,scroll_x0,scroll_x1:word;
prio,copy_sprites:boolean;
spritex_add,spritey_add:integer;
procedure update_video_baraduke;
procedure draw_sprites(prior:byte);
var
x,y,sizex,sizey,sy,f,atrib1,atrib2:byte;
nchar,sx,sprite_xoffs,sprite_yoffs,color:word;
flipx,flipy:boolean;
const
gfx_offs:array[0..1,0..1] of byte=((0,1),(2,3));
begin
sprite_xoffs:=memoria[$07f5]-256*(memoria[$07f4] and 1);
sprite_yoffs:=memoria[$07f7];
for f:=0 to $7e do begin
atrib1:=memoria[$180a+(f*$10)];
if prior<>(atrib1 and 1) then continue;
atrib2:=memoria[$180e+(f*$10)];
color:=memoria[$180c+(f*$10)];
flipx:=(atrib1 and $20)<>0;
flipy:=(atrib2 and $01)<>0;
sizex:=(atrib1 and $80) shr 7;
sizey:=(atrib2 and $04) shr 2;
sx:=((memoria[$180d+(f*$10)]+((color and $01) shl 8))+sprite_xoffs+spritex_add) and $1ff;
sy:=(240-memoria[$180f+(f*$10)])-sprite_yoffs-(16*sizey)+spritey_add;
nchar:=memoria[$180b+(f*$10)]*4;
if (((atrib1 and $10)<>0) and (sizex=0)) then nchar:=nchar+1;
if (((atrib2 and $10)<>0) and (sizey=0)) then nchar:=nchar+2;
color:=(color and $fe) shl 3;
for y:=0 to sizey do
for x:=0 to sizex do
put_gfx_sprite_diff((nchar+gfx_offs[y xor (sizey*byte(flipy))][x xor (sizex*byte(flipx))]) and sprite_mask,color,flipx,flipy,3,16*x,16*y);
actualiza_gfx_sprite_size(sx,sy,4,16*(sizex+1),16*(sizey+1));
end;
end;
var
f,color,nchar,pos:word;
sx,sy,x,y,atrib:byte;
begin
for x:=0 to 35 do begin
for y:=0 to 27 do begin
sx:=x-2;
sy:=y+2;
if (sx and $20)<>0 then pos:=sy+((sx and $1f) shl 5)
else pos:=sx+(sy shl 5);
if gfx[0].buffer[pos] then begin
color:=memoria[$4c00+pos];
nchar:=memoria[$4800+pos];
put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0);
gfx[0].buffer[pos]:=false;
end;
end;
end;
for f:=0 to $7ff do begin
x:=f mod 64;
y:=f div 64;
if gfx[1].buffer[f] then begin
atrib:=memoria[$2001+(f*2)];
nchar:=memoria[$2000+(f*2)]+(atrib and $3) shl 8;
if prio then put_gfx_trans(x*8,y*8,nchar,atrib shl 3,2,1)
else put_gfx(x*8,y*8,nchar,atrib shl 3,2,1);
gfx[1].buffer[f]:=false;
end;
if gfx[2].buffer[f] then begin
atrib:=memoria[$3001+(f*2)];
nchar:=memoria[$3000+(f*2)]+(atrib and $3) shl 8;
if prio then put_gfx(x*8,y*8,nchar,atrib shl 3,3,2)
else put_gfx_trans(x*8,y*8,nchar,atrib shl 3,3,2);
gfx[2].buffer[f]:=false;
end;
end;
if prio then begin
scroll_x_y(3,4,scroll_x1+24,scroll_y1+25);
draw_sprites(0);
scroll_x_y(2,4,scroll_x0+26,scroll_y0+25);
end else begin
scroll_x_y(2,4,scroll_x0+26,scroll_y0+25);
draw_sprites(0);
scroll_x_y(3,4,scroll_x1+24,scroll_y1+25);
end;
draw_sprites(1);
actualiza_trozo(0,0,288,224,1,0,0,288,224,4);
actualiza_trozo_final(0,0,288,224,4);
end;
procedure eventos_baraduke;
begin
if event.arcade then begin
//marcade.in0
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
//marcade.in1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
//marcade.in2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
end;
end;
procedure copy_sprites_hw;
var
i,j:byte;
begin
for i:=0 to $7f do begin
for j:=10 to 15 do memoria[$1800+(i*$10)+j]:=memoria[$1800+(i*$10)+j-6];
end;
copy_sprites:=false;
end;
procedure baraduke_principal;
var
f:word;
frame_m,frame_mcu:single;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
frame_mcu:=m6800_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 263 do begin
//Main CPU
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
//Sound CPU
m6800_0.run(frame_mcu);
frame_mcu:=frame_mcu+m6800_0.tframes-m6800_0.contador;
if f=239 then begin
update_video_baraduke;
m6809_0.change_irq(ASSERT_LINE);
m6800_0.change_irq(HOLD_LINE);
if copy_sprites then copy_sprites_hw;
end;
end;
eventos_baraduke;
video_sync;
end;
end;
function baraduke_getbyte(direccion:word):byte;
begin
case direccion of
0..$3fff,$4800..$4fff,$6000..$ffff:baraduke_getbyte:=memoria[direccion];
$4000..$43ff:baraduke_getbyte:=namco_snd_0.namcos1_cus30_r(direccion and $3ff);
end;
end;
procedure baraduke_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$1ff1,$1ff3..$1fff:memoria[direccion]:=valor;
$1ff2:begin
memoria[direccion]:=valor;
copy_sprites:=true;
end;
$2000..$2fff:if memoria[direccion]<>valor then begin
gfx[1].buffer[(direccion and $fff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$3000..$3fff:if memoria[direccion]<>valor then begin
gfx[2].buffer[(direccion and $fff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$4000..$43ff:namco_snd_0.namcos1_cus30_w(direccion and $3ff,valor);
$4800..$4fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$8000:; //WD
$8800:m6809_0.change_irq(CLEAR_LINE); // irq acknowledge
$b000:begin
scroll_x0:=(scroll_x0 and $ff) or (valor shl 8);
prio:=((scroll_x0 and $e00) shr 9)=6;
end;
$b001:scroll_x0:=(scroll_x0 and $ff00) or valor;
$b002:scroll_y0:=valor;
$b004:scroll_x1:=(scroll_x1 and $ff) or (valor shl 8);
$b005:scroll_x1:=(scroll_x1 and $ff00) or valor;
$b006:scroll_y1:=valor;
$6000..$7fff,$8001..$87ff,$8801..$afff,$b003,$b007..$ffff:; //ROM
end;
end;
function baraduke_mcu_getbyte(direccion:word):byte;
begin
case direccion of
$0..$ff:baraduke_mcu_getbyte:=m6800_0.m6803_internal_reg_r(direccion);
$1000..$1104,$1106..$13ff:baraduke_mcu_getbyte:=namco_snd_0.namcos1_cus30_r(direccion and $3ff);
$1105:begin
counter:=counter+1;
baraduke_mcu_getbyte:=(counter shr 4) and $ff;
end;
$8000..$c7ff,$f000..$ffff:baraduke_mcu_getbyte:=mem_snd[direccion];
end;
end;
procedure baraduke_mcu_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0..$ff:m6800_0.m6803_internal_reg_w(direccion,valor);
$1000..$13ff:namco_snd_0.namcos1_cus30_w(direccion and $3ff,valor);
$8000..$bfff,$f000..$ffff:exit;
$c000..$c7ff:mem_snd[direccion]:=valor;
end;
end;
function in_port1:byte;
var
ret:byte;
begin
ret:=$ff;
case inputport_selected of
0:ret:=(marcade.dswa and $f8) shr 3; //DSWA 0-4
1:ret:=((marcade.dswa and 7) shl 2) or ((marcade.dswb and $c0) shr 6); //DSWA 5-7 DSWB 0-1
2:ret:=(marcade.dswb and $3e) shr 1; //DSWB 2-6
3:ret:=((marcade.dswb and 1) shl 4) or (marcade.dswc and $f); //DSWB 7 DSWC 0-4
4:ret:=marcade.in0;
5:ret:=marcade.in2;
6:ret:=marcade.in1;
end;
in_port1:=ret;
end;
procedure out_port1(valor:byte);
begin
if (valor and $e0)=$60 then inputport_selected:=valor and $7;
end;
procedure sound_update_baraduke;
begin
namco_snd_0.update;
end;
procedure reset_baraduke;
begin
m6809_0.reset;
m6800_0.reset;
namco_snd_0.reset;
reset_audio;
marcade.in0:=$1f;
marcade.in1:=$1f;
marcade.in2:=$1f;
scroll_x0:=0;
scroll_y0:=0;
scroll_x1:=0;
scroll_y1:=0;
copy_sprites:=false;
end;
function iniciar_baraduke:boolean;
var
colores:tpaleta;
f:word;
memoria_temp:array[0..$7ffff] of byte;
const
pc_x:array[0..7] of dword=(8*8, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3);
pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8);
pt_x:array[0..7] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3);
pt_y:array[0..7] of dword=(0*8, 2*8, 4*8, 6*8, 8*8, 10*8, 12*8, 14*8);
ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4,
8*4, 9*4, 10*4, 11*4, 12*4, 13*4, 14*4, 15*4);
ps_y:array[0..15] of dword=(8*8*0, 8*8*1, 8*8*2, 8*8*3, 8*8*4, 8*8*5, 8*8*6, 8*8*7,
8*8*8, 8*8*9, 8*8*10, 8*8*11, 8*8*12, 8*8*13, 8*8*14, 8*8*15);
procedure convert_chars;
begin
init_gfx(0,8,8,$200);
gfx[0].trans[3]:=true;
gfx_set_desc_data(2,0,16*8,0,4);
convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false);
end;
procedure convert_tiles;
var
f:word;
begin
for f:=$2000 to $3fff do begin
memoria_temp[$8000+f+$2000]:=memoria_temp[$8000+f];
memoria_temp[$8000+f+$4000]:=memoria_temp[$8000+f] shl 4;
end;
for f:=0 to $1fff do memoria_temp[$8000+f+$2000]:=memoria_temp[$8000+f] shl 4;
gfx_set_desc_data(3,0,16*8,$8000*8,0,4);
init_gfx(1,8,8,$400);
gfx[1].trans[7]:=true;
convert_gfx(1,0,@memoria_temp[0],@pt_x,@pt_y,false,false);
init_gfx(2,8,8,$400);
gfx[2].trans[7]:=true;
convert_gfx(2,0,@memoria_temp[$4000],@pt_x,@pt_y,false,false);
end;
procedure convert_sprites(num:word);
begin
init_gfx(3,16,16,num);
gfx[3].trans[15]:=true;
gfx_set_desc_data(4,0,128*8,0,1,2,3);
convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,false);
end;
begin
llamadas_maquina.bucle_general:=baraduke_principal;
llamadas_maquina.reset:=reset_baraduke;
llamadas_maquina.fps_max:=60.606060;
iniciar_baraduke:=false;
iniciar_audio(false);
screen_init(1,288,224,true);
screen_init(2,512,256,true);
screen_mod_scroll(2,512,512,511,256,256,255);
screen_init(3,512,256,true);
screen_mod_scroll(3,512,512,511,256,256,255);
screen_init(4,512,256,false,true);
iniciar_video(288,224);
//Main CPU
m6809_0:=cpu_m6809.Create(49152000 div 32,264,TCPU_M6809);
m6809_0.change_ram_calls(baraduke_getbyte,baraduke_putbyte);
//MCU CPU
m6800_0:=cpu_m6800.create(49152000 div 8,264,TCPU_HD63701);
m6800_0.change_ram_calls(baraduke_mcu_getbyte,baraduke_mcu_putbyte);
m6800_0.change_io_calls(in_port1,nil,nil,nil,out_port1,nil,nil,nil);
m6800_0.init_sound(sound_update_baraduke);
//Sound
namco_snd_0:=namco_snd_chip.create(8,true);
case main_vars.tipo_maquina of
287:begin
//cargar roms main CPU
if not(roms_load(@memoria,baraduke_rom)) then exit;
//Cargar MCU
if not(roms_load(@mem_snd,baraduke_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,baraduke_chars)) then exit;
convert_chars;
//tiles
if not(roms_load(@memoria_temp,baraduke_tiles)) then exit;
convert_tiles;
//sprites
if not(roms_load(@memoria_temp,baraduke_sprites)) then exit;
convert_sprites($200);
sprite_mask:=$1ff;
spritex_add:=184;
spritey_add:=-14;
//Paleta
if not(roms_load(@memoria_temp,baraduke_prom)) then exit;
marcade.dswa:=$ff;
marcade.dswb:=$ff;
marcade.dswc:=$ff;
marcade.dswa_val:=@baraduke_dip_a;
marcade.dswb_val:=@baraduke_dip_b;
marcade.dswc_val:=@baraduke_dip_c;
end;
288:begin
//cargar roms main CPU
if not(roms_load(@memoria,metrocross_rom)) then exit;
//Cargar MCU
if not(roms_load(@mem_snd,metrocross_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,metrocross_chars)) then exit;
convert_chars;
//tiles
if not(roms_load(@memoria_temp,metrocross_tiles)) then exit;
for f:=$8000 to $bfff do memoria_temp[f]:=$ff;
convert_tiles;
//sprites
if not(roms_load(@memoria_temp,metrocross_sprites)) then exit;
convert_sprites($100);
sprite_mask:=$ff;
spritex_add:=-1;
spritey_add:=-32;
//Paleta
if not(roms_load(@memoria_temp,metrocross_prom)) then exit;
marcade.dswa:=$ff;
marcade.dswb:=$ff;
marcade.dswc:=$ff;
marcade.dswa_val:=@metrocross_dip_a;
marcade.dswb_val:=@metrocross_dip_b;
marcade.dswc_val:=@baraduke_dip_c;
end;
end;
for f:=0 to $7ff do begin
colores[f].r:=((memoria_temp[f+$800] shr 0) and $01)*$0e+((memoria_temp[f+$800] shr 1) and $01)*$1f+((memoria_temp[f+$800] shr 2) and $01)*$43+((memoria_temp[f+$800] shr 3) and $01)*$8f;
colores[f].g:=((memoria_temp[f] shr 0) and $01)*$0e+((memoria_temp[f] shr 1) and $01)*$1f+((memoria_temp[f] shr 2) and $01)*$43+((memoria_temp[f] shr 3) and $01)*$8f;
colores[f].b:=((memoria_temp[f] shr 4) and $01)*$0e+((memoria_temp[f] shr 5) and $01)*$1f+((memoria_temp[f] shr 6) and $01)*$43+((memoria_temp[f] shr 7) and $01)*$8f;
end;
set_pal(colores,$800);
//final
reset_baraduke;
iniciar_baraduke:=true;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Registry
Description : Util registry info
Author : Kike Pérez
Version : 2.0
Created : 22/01/2021
Modified : 25/01/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Registry;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
Winapi.Windows,
System.Win.Registry;
type
TRegRootKey = (rootCU, rootLM);
TRegistryUtils = class
public
class function GetNewReg(aRootKey : TRegRootKey; aReadOnly : Boolean = False) : TRegistry;
class function GetUniqueMachineId: TGUID; static;
class function IsDarkMode : Boolean;
end;
implementation
class function TRegistryUtils.GetNewReg(aRootKey : TRegRootKey; aReadOnly : Boolean = False) : TRegistry;
begin
if aReadOnly then Result := TRegistry.Create(KEY_READ)
else Result := TRegistry.Create(KEY_ALL_ACCESS);
if aRootKey = TRegRootKey.rootCU then Result.RootKey := HKEY_CURRENT_USER
else Result.RootKey := HKEY_LOCAL_MACHINE;
end;
class function TRegistryUtils.IsDarkMode : Boolean;
var
reg : TRegistry;
begin
reg := GetNewReg(TRegRootKey.rootCU,True);
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize');
Result := not reg.ReadBool('AppsUseLightTheme');
finally
reg.Free;
end;
end;
class function TRegistryUtils.GetUniqueMachineId : TGUID;
var
reg : TRegistry;
begin
reg := GetNewReg(TRegRootKey.rootLM,True);
try
reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Cryptography');
Result := StringToGUID(reg.ReadString('MachineGuid'));
finally
reg.Free;
end;
end;
end.
|
unit tmsUXlsProtect;
{$INCLUDE ..\FLXCOMPILER.INC}
{$INCLUDE ..\FLXCONFIG.INC}
interface
uses tmsUFlxMessages;
type
TEncryptionEngine = class;
/// <summary>
/// Holds an encryption engine and a password. Engine has to be created on demand (and is polymorphical) so we need to store password in another place.
/// </summary>
TEncryptionData = class
public
ReadPassword: UTF16String;
Engine: TEncryptionEngine;
ActualRecordLen: Int32;
constructor Create(const aReadPassword: UTF16String; const aOnPassword: TObject; const aXls: TObject);
function TotalSize(): Int32;
end;
/// <summary>
/// Base for all encrtyption engines.
/// </summary>
TEncryptionEngine = class
protected
constructor Create();
public
function CheckHash(const Password: UTF16String): Boolean;virtual; abstract;
function Decode(const Data: ByteArray; const StreamPosition: Int64; const StartPos: Int32; const Count: Int32; const RecordLen: Int32): ByteArray;virtual; abstract;
function Encode(const Data; const StreamPosition: Int64; const StartPos: Int32; const Count: Int32; const RecordLen: Int32): ByteArray;overload; virtual; abstract;
function Encode(const Data: UInt16; const StreamPosition: Int64; const RecordLen: Int32): UInt16;overload; virtual; abstract;
function Encode(const Data: UInt32; const StreamPosition: Int64; const RecordLen: Int32): UInt32;overload; virtual; abstract;
function GetFilePassRecord(): ByteArray;virtual; abstract;
function GetFilePassRecordLen(): Int32;virtual; abstract;
end;
implementation
{ TEncryptionData }
constructor TEncryptionData.Create(const aReadPassword: UTF16String; const aOnPassword: TObject; const aXls: TObject);
begin
inherited Create;
ReadPassword := aReadPassword;
end;
function TEncryptionData.TotalSize(): Int32;
begin
if Engine = nil then
begin Result := 0; exit; end;
Result := Engine.GetFilePassRecordLen;
end;
{ TEncryptionEngine }
constructor TEncryptionEngine.Create();
begin
inherited Create;
end;
end.
|
unit daDataProviderFactory;
// Модуль: "w:\common\components\rtl\Garant\DA\daDataProviderFactory.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TdaDataProviderFactory" MUID: (54F85EE102D1)
{$Include w:\common\components\rtl\Garant\DA\daDefine.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, daDataProviderParams
, daTypes
, ddAppConfig
;
type
TdaDataProviderFactory = class(Tl3ProtoObject)
private
f_ParamsStorage: IdaParamsStorage;
protected
procedure LoadCommonParams(aParams: TdaDataProviderParams);
procedure SaveCommonParams(aParams: TdaDataProviderParams);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
function MakeFromConfig: TdaDataProviderParams; virtual; abstract;
procedure SaveToConfig(aParams: TdaDataProviderParams); virtual; abstract;
function ParamType: TdaDataProviderParamsClass; virtual; abstract;
procedure CorrectByClient(aParams: TdaDataProviderParams;
CorrectTempPath: Boolean); virtual;
function IsParamsValid(aParams: TdaDataProviderParams;
Quiet: Boolean = False): Boolean; virtual;
procedure FillOutConfig(aConfig: TddAppConfiguration;
aEtalon: TdaDataProviderParams;
out aParams: TdaDataProviderParams); virtual; abstract;
procedure FillInConfig(aConfig: TddAppConfiguration;
aParams: TdaDataProviderParams;
ForInfoOnly: Boolean = False); virtual; abstract;
procedure BuildConfig(aConfig: TddAppConfiguration;
const aProviderKey: AnsiString = '';
ForInfoOnly: Boolean = False); virtual; abstract;
function MakeProvider(aParams: TdaDataProviderParams;
AllowClearLocks: Boolean): IdaDataProvider;
procedure LoadDBVersion(aParams: TdaDataProviderParams); virtual; abstract;
function CheckLogin(aParams: TdaDataProviderParams;
const aLogin: AnsiString;
const aPassword: AnsiString;
IsRequireAdminRights: Boolean;
SuppressExceptions: Boolean): TdaLoginError;
function DoMakeProvider(aParams: TdaDataProviderParams;
ForCheckLogin: Boolean;
AllowClearLocks: Boolean;
SetGlobalProvider: Boolean = True): IdaDataProvider; virtual; abstract;
procedure LoginCheckSucceed(aParams: TdaDataProviderParams); virtual; abstract;
class function Key: AnsiString; virtual; abstract;
function ParamKey: AnsiString;
public
property ParamsStorage: IdaParamsStorage
read f_ParamsStorage
write f_ParamsStorage;
end;//TdaDataProviderFactory
implementation
uses
l3ImplUses
, l3Base
//#UC START# *54F85EE102D1impl_uses*
//#UC END# *54F85EE102D1impl_uses*
;
procedure TdaDataProviderFactory.LoadCommonParams(aParams: TdaDataProviderParams);
//#UC START# *55001D8D038F_54F85EE102D1_var*
//#UC END# *55001D8D038F_54F85EE102D1_var*
begin
//#UC START# *55001D8D038F_54F85EE102D1_impl*
ParamsStorage.InitStorage;
aParams.Login := ParamsStorage.Login;
aParams.Password := ParamsStorage.Password;
aParams.DocStoragePath := ParamsStorage.DocStoragePath; // Invalid
aParams.DocImagePath := ParamsStorage.DocImagePath;
aParams.DocImageCachePath := ParamsStorage.DocImageCachePath;
aParams.HomeDirPath := ParamsStorage.HomeDirPath; // Invalid
//#UC END# *55001D8D038F_54F85EE102D1_impl*
end;//TdaDataProviderFactory.LoadCommonParams
procedure TdaDataProviderFactory.SaveCommonParams(aParams: TdaDataProviderParams);
//#UC START# *550AACDC0003_54F85EE102D1_var*
//#UC END# *550AACDC0003_54F85EE102D1_var*
begin
//#UC START# *550AACDC0003_54F85EE102D1_impl*
ParamsStorage.InitStorage;
ParamsStorage.Login := aParams.Login;
ParamsStorage.Password := aParams.Password;
ParamsStorage.DocStoragePath := aParams.DocStoragePath;
ParamsStorage.DocImagePath := aParams.DocImagePath;
ParamsStorage.DocImageCachePath := aParams.DocImagePath;
ParamsStorage.HomeDirPath := aParams.HomeDirPath;
//#UC END# *550AACDC0003_54F85EE102D1_impl*
end;//TdaDataProviderFactory.SaveCommonParams
procedure TdaDataProviderFactory.CorrectByClient(aParams: TdaDataProviderParams;
CorrectTempPath: Boolean);
//#UC START# *55110FBB00E5_54F85EE102D1_var*
//#UC END# *55110FBB00E5_54F85EE102D1_var*
begin
//#UC START# *55110FBB00E5_54F85EE102D1_impl*
Assert(ParamsStorage <> nil);
aParams.Login := ParamsStorage.Login;
aParams.Password := ParamsStorage.Password;
//#UC END# *55110FBB00E5_54F85EE102D1_impl*
end;//TdaDataProviderFactory.CorrectByClient
function TdaDataProviderFactory.IsParamsValid(aParams: TdaDataProviderParams;
Quiet: Boolean = False): Boolean;
//#UC START# *551166B40046_54F85EE102D1_var*
//#UC END# *551166B40046_54F85EE102D1_var*
begin
//#UC START# *551166B40046_54F85EE102D1_impl*
Result := (aParams.DocStoragePath <> '') and (aParams.HomeDirPath <> '');
if aParams.DocStoragePath = '' then
l3System.Msg2Log('Не указано расположение БД (док.)');
//#UC END# *551166B40046_54F85EE102D1_impl*
end;//TdaDataProviderFactory.IsParamsValid
function TdaDataProviderFactory.MakeProvider(aParams: TdaDataProviderParams;
AllowClearLocks: Boolean): IdaDataProvider;
//#UC START# *5515443E027B_54F85EE102D1_var*
//#UC END# *5515443E027B_54F85EE102D1_var*
begin
//#UC START# *5515443E027B_54F85EE102D1_impl*
Result := DoMakeProvider(aParams, False, AllowClearLocks);
//#UC END# *5515443E027B_54F85EE102D1_impl*
end;//TdaDataProviderFactory.MakeProvider
function TdaDataProviderFactory.CheckLogin(aParams: TdaDataProviderParams;
const aLogin: AnsiString;
const aPassword: AnsiString;
IsRequireAdminRights: Boolean;
SuppressExceptions: Boolean): TdaLoginError;
//#UC START# *551BE3520031_54F85EE102D1_var*
var
l_Provider: IdaDataProvider;
//#UC END# *551BE3520031_54F85EE102D1_var*
begin
//#UC START# *551BE3520031_54F85EE102D1_impl*
l_Provider := DoMakeProvider(aParams, True, False);
try
try
l_Provider.Start;
except
l_Provider.Stop;
Result := da_leConnectionError;
if SuppressExceptions then
Exit
else
raise;
end;
try
Result := l_Provider.CheckLogin(aLogin, aPassword, IsRequireAdminRights);
if (Result = da_leOk) then
begin
aParams.UserId := l_Provider.UserID;
aParams.Login := aLogin;
aParams.Password := aPassword;
LoginCheckSucceed(aParams);
end;
finally
l_Provider.Stop;
end;
finally
l_Provider := nil;
end;
//#UC END# *551BE3520031_54F85EE102D1_impl*
end;//TdaDataProviderFactory.CheckLogin
function TdaDataProviderFactory.ParamKey: AnsiString;
//#UC START# *550A8AC30010_54F85EE102D1_var*
//#UC END# *550A8AC30010_54F85EE102D1_var*
begin
//#UC START# *550A8AC30010_54F85EE102D1_impl*
Result := ParamType.ParamsKey;
//#UC END# *550A8AC30010_54F85EE102D1_impl*
end;//TdaDataProviderFactory.ParamKey
procedure TdaDataProviderFactory.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_54F85EE102D1_var*
//#UC END# *479731C50290_54F85EE102D1_var*
begin
//#UC START# *479731C50290_54F85EE102D1_impl*
f_ParamsStorage := nil;
inherited;
//#UC END# *479731C50290_54F85EE102D1_impl*
end;//TdaDataProviderFactory.Cleanup
procedure TdaDataProviderFactory.ClearFields;
begin
ParamsStorage := nil;
inherited;
end;//TdaDataProviderFactory.ClearFields
end.
|
unit Parsers.Excel.Notes;
interface
uses
Parsers.Excel, Parsers.Abstract, Parsers.Excel.Tools, SysUtils, Classes, GsDocument, StrUtils;
type
TExcelNoteRow = class(TExcelRowWrapper)
public
function GetCode: string;
function GetNote: string;
function GetTable(Code: string): Integer;
function IsRowCode(Code: string): Boolean;
function GetShortCodeTable(Code: string): string;
function GetPos(Code: string): Integer;
function IsRange: Boolean;
function IsTable: Boolean;
function IsTableRange: Boolean;
function CodeInRange(Code: string): Boolean;
function IsSimilarTable(Code: string): Boolean;
property Code: string read GetCode;
property Note: string read GetNote;
end;
TExcelNotesParser = class(TExcelParser<TGsDocument, TExcelNoteRow>)
private
FDocument: TGsDocument;
FS: TStringList;
protected
function DoGetDocument: TGsDocument; override;
procedure DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); override;
procedure DoParseRow(AExcelRow: TExcelNoteRow; ARowIndex: Integer; ADocument: TGsDocument); override;
public
constructor Create(ADocument: TGsDocument); reintroduce;
destructor Destroy; override;
end;
implementation
{ TExcelNotesParser }
constructor TExcelNotesParser.Create(ADocument: TGsDocument);
var
L: TList;
Row: TGsRow;
I: Integer;
begin
inherited Create;
FDocument := ADocument;
FS := TStringList.Create;
L := TList.Create;
try
FDocument.Chapters.EnumItems(L, TGsRow, True);
for I := 0 to L.Count - 1 do
begin
Row := TGsRow(L[I]);
FS.AddObject(TParserTools.GetCodeShortForm(StringReplace(Row.Number(True), FDocument.TypeName, '', [])), Row);
end;
finally
L.Free;
end;
end;
destructor TExcelNotesParser.Destroy;
begin
FS.Free;
inherited Destroy;
end;
function TExcelNotesParser.DoGetDocument: TGsDocument;
begin
Result := FDocument;
end;
procedure TExcelNotesParser.DoParseRow(AExcelRow: TExcelNoteRow; ARowIndex: Integer; ADocument: TGsDocument);
var
Index: Integer;
R: TGsRow;
I, J: Integer;
p: TGsChapter;
ls, rs, tc, tp: string;
S: TStringList;
begin
if AExcelRow.IsRange then
begin
for I := 0 to FS.Count - 1 do
begin
R := TGsRow(FS.Objects[I]);
// ls := TParserTools.GetStrBeforeDilimFromBegin(AExcelRow.Code, '÷');
// rs := TParserTools.GetStrAfterDilimFromEnd(ls, '-') + '-' + TParserTools.GetStrAfterDilimFromBegin(AExcelRow.Code, '÷');
//if (ls <= TParserTools.GetCodeShortForm(FS[I])) and (TParserTools.GetCodeShortForm(FS[I]) <= rs) then
if AExcelRow.CodeInRange(TParserTools.GetCodeShortForm(FS[I])) then
R.AddNote(AExcelRow.Note)
end;
end
else
begin
if AExcelRow.IsTable then
begin
for I := 0 to FS.Count - 1 do
begin
R := TGsRow(FS.Objects[I]);
if AExcelRow.GetShortCodeTable(FS[I]) = AExcelRow.Code then
R.AddNote(AExcelRow.Note);
end;
end
else if AExcelRow.IsTableRange then
begin
for I := 0 to FS.Count - 1 do
begin
ls := TParserTools.GetStrBeforeDilimFromBegin(AExcelRow.Code, '÷');
rs := TParserTools.GetStrAfterDilimFromBegin(AExcelRow.Code, '÷');
tc := TParserTools.GetStrAfterDilimFromEnd(ls, '-');
R := TGsRow(FS.Objects[I]);
p := R.Parent as TGsChapter;
while p.ChapterType <> ctTable do
p := p.Parent as TGsChapter;
S := TParserTools.GetCodeParts(ls);
try
tp := '';
for J := 0 to S.Count - 2 do
tp := tp + S[J] + '-';
rs := tp + rs;
tc := TParserTools.GetCodeShortForm(p.Document.Number + '-' + p.Number(False));
if (ls <= tc) and (tc <= rs) then
R.AddNote(AExcelRow.Note);
finally
S.Free;
end;
end;
end
else
begin
Index := FS.IndexOf(AExcelRow.Code);
if Index <> -1 then
begin
R := TGsRow(FS.Objects[Index]);
R.AddNote(AExcelRow.Note);
end
else
LogMessage('Не проставленно примечание по расценке: ' + AExcelRow.Code + ' ' + AExcelRow.Note);
end;
end;
end;
procedure TExcelNotesParser.DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument);
begin
inherited DoParseSheet(AExcelSheet, ADocument);
ADocument.Save;
end;
{ TExcelNoteRow }
function TExcelNoteRow.CodeInRange(Code: string): Boolean;
var
Left, Right: string;
p: Integer;
begin
Result := False;
p := Pos('÷', Self.Code);
if p > 0 then
begin
Left := Trim(System.Copy(Self.Code, 1, p - 1));
Right := Trim(System.Copy(Self.Code, p + 1, 255));
if GetShortCodeTable(Left) = GetShortCodeTable(Code) then
begin
Result := (GetPos(Left) <= GetPos(Code)) and (GetPos(Code) <= StrToInt(Right));
end;
end
else
Result := False;
end;
function TExcelNoteRow.GetCode: string;
begin
Result := StringReplace(Values[0], ';', '', [rfReplaceAll]);
end;
function TExcelNoteRow.GetNote: string;
begin
Result := Values[1];
end;
function TExcelNoteRow.GetPos(Code: string): Integer;
var
S: TStringList;
begin
S := TParserTools.GetCodeParts(Code);
try
Result := StrToInt(S[S.Count - 1]);
finally
S.Free;
end;
end;
function TExcelNoteRow.GetShortCodeTable(Code: string): string;
var
S: TStringList;
I: Integer;
begin
Code := TParserTools.GetCodeShortForm(Code);
S := TParserTools.GetCodeParts(Code);
try
Result := '';
for I := 0 to S.Count - 2 do
begin
Result := Result + S[I] + '-';
end;
if Result[Length(Result)] = '-' then
Result := LeftStr(Result, Length(Result) - 1);
finally
S.Free;
end;
end;
function TExcelNoteRow.GetTable(Code: string): Integer;
var
S: TStringList;
begin
S := TParserTools.GetCodeParts(Code);
try
if S.Count = 3 then
Result := StrToInt(S[2])
else if S.Count = 4 then
Result := StrToInt(S[3])
else
Result := -1;
finally
S.Free;
end;
end;
function TExcelNoteRow.IsRange: Boolean;
begin
Result := (Pos('÷', Self.Code) > 0) and not IsTableRange;
end;
function TExcelNoteRow.IsRowCode(Code: string): Boolean;
begin
Result := TParserTools.GetCharFreq(Code, '-') = 2;
end;
function TExcelNoteRow.IsSimilarTable(Code: string): Boolean;
begin
Result := GetTable(Code) = GetTable(Self.Code);
end;
function TExcelNoteRow.IsTable: Boolean;
begin
Result := TParserTools.GetCharFreq(Self.Code, '-') = 1;
end;
function TExcelNoteRow.IsTableRange: Boolean;
begin
Result := (TParserTools.GetCharFreq(Self.Code, '-') = 1) and (Pos('÷', Self.Code) > 0);
end;
end.
|
unit uSHComModule;
interface
uses
SysUtils, Classes,Messages,Forms,Windows,ExtCtrls,
u_c_byte_buffer,WinSock;
const wm_asynch_select= wm_User;
const k_buffer_max= 4096;
k_tcp_ip_chunk= 1500;
MAXSOCKCOUNT = 100;
const DisConnected = 0;
Connecting = 1;
Connected = 2;
type
TCARDStateChangeEvent = procedure(Sender: TObject; aFPNo,aUSERID : integer;aNodeName,aFPSEND:string) of object;
TFPReaderConnected = procedure(Sender: TObject; aFPNo: integer;aNodeIP:string;aNodePort:integer;aNodeName:string;aConnected:integer) of object;
TCardEvent = procedure(Sender: TObject; aFPNo : integer;aNodeName,aTxRx,aData:string) of object;
TFPUser = class(TComponent)
private
FFPUSERID: integer;
FFPSEND: string;
FFPDATA: string;
FFPPERMIT: string;
FFPCARD: string;
FFPNodeNo: integer;
FOnCARDStateChangeEvent: TCARDStateChangeEvent;
procedure SetFPSEND(const Value: string);
public
published
property FPNodeNo : integer read FFPNodeNo write FFPNodeNo;
property FPUSERID : integer read FFPUSERID write FFPUSERID;
property FPCARD : string read FFPCARD write FFPCARD;
property FPDATA : string read FFPDATA write FFPDATA;
property FPPERMIT : string read FFPPERMIT write FFPPERMIT;
property FPSEND : string read FFPSEND write SetFPSEND;
published
property OnCARDStateChangeEvent: TCARDStateChangeEvent read FOnCARDStateChangeEvent write FOnCARDStateChangeEvent;
end;
TFPNode = class(TComponent)
private
FOnCARDStateChangeEvent: TCARDStateChangeEvent;
FFPNodeName: string;
FWinSocket: tSocket;
FOpen: Boolean;
FSocketConnected: integer;
FOnConnected: TFPReaderConnected;
FReaderType: integer;
FOnCardEvent: TCardEvent;
FFPDeviceID: integer;
FFPDeviceType: integer;
procedure CARDStateChangeEvent(Sender: TObject; aFPNo,aUSERID : integer;aNodeName,aFPSEND:string);
procedure SetOpen(const Value: Boolean);
procedure SetSocketConnected(const Value: integer);
private
L_bCardDownLoading : Boolean;
L_bDestroy :Boolean;
L_bGetFDData:Boolean;
//********************* WinSock 변수
l_wsa_data: twsaData;
l_c_reception_buffer: c_byte_buffer;
L_bSocketWriting : Boolean;
L_nFPSendCount :integer;
L_nResult : integer;
L_stGetFDData : string;
ComBuff : string;
FHandle : THandle;
FPUserList : TStringList;
FFPNodePort: integer;
FFPNodeIP: string;
FFPNodeNo: integer;
FPSendTimer : TTimer;
SocketCheckTimer: TTimer; //소켓 Open 또는 Close
function GetHandle: THandle;
procedure FPSendTimerTimer(Sender: TObject);
procedure SocketCheckTimerTimer(Sender: TObject);
protected
procedure WndProc ( var Message : TMessage ); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HandleAllocated : Boolean;
procedure HandleNeeded;
procedure handle_fd_close_notification(p_socket: Integer);
procedure handle_fd_connect_notification(p_socket: Integer);
procedure handle_fd_read_notification(p_socket: tSocket);
procedure handle_fd_write_notification(p_socket: Integer);
procedure handle_wm_async_select(var Msg: TMessage); message wm_asynch_select;
procedure CommNodeTriggerAvail(Sender: TObject;SockNo:integer; Buf:String;DataLen: Integer);
procedure CommNodeWsError(Sender: TObject;SockNo:integer;SocketError: Integer);
function FP_HexSendPacket(aCmd : char;aHexAddress,aHexData:string):Boolean;
function FP_SendPacket(aCmd : char;aAddress:char;aData:string):Boolean;
function PutString(aData:string;aLen:integer):Boolean;
function CheckSHFDDataPacket(aData:String; var bData:String):string;
function SetEncrypt(aFPReaderID,aType:integer):Boolean;
function SHFDataPacektProcess(aHexPacket:string):Boolean;
function ShunghunSyncTime(aFPReaderID:integer;aSendData:string) : Boolean;
function SyncTimeSend : Boolean;
function UserCardSend(aFPReaderID,aUserID:integer;aUserCard,aPermit:string) : integer;
function UserFPDataSend(aFPReaderID,aUserID:integer;aFPDATA,aPermit:string) : integer;
function UserFPDelete(aFPReaderID,aUserID:integer): integer;
function UserAllDelete:integer;
public
procedure Add_FPData(aUserID:integer;aUserCard,aUserFPData,aFPPermit:string);
function GetFPData(aUserID:string):string;
published
property FPNodeNo : integer read FFPNodeNo write FFPNodeNo;
property FPNodeIP : string read FFPNodeIP write FFPNodeIP;
property FPNodePort :integer read FFPNodePort write FFPNodePort;
property FPNodeName :string read FFPNodeName write FFPNodeName;
property FPDeviceID : integer read FFPDeviceID write FFPDeviceID;
property FPDeviceType:integer read FFPDeviceType write FFPDeviceType; //0:2.0,1:2.4이상
property Handle : THandle read GetHandle;
property WinSocket : tSocket read FWinSocket write FWinSocket;
property Open : Boolean read FOpen write SetOpen;
ProPerty SocketConnected : integer read FSocketConnected Write SetSocketConnected;
Property ReaderType : integer read FReaderType write FReaderType; //0.등록기 타입
published
property OnCARDStateChangeEvent: TCARDStateChangeEvent read FOnCARDStateChangeEvent write FOnCARDStateChangeEvent;
property OnConnected : TFPReaderConnected read FOnConnected write FOnConnected;
property OnCardEvent : TCardEvent read FOnCardEvent write FOnCardEvent;
end;
TdmSHComModule = class(TDataModule)
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmSHComModule: TdmSHComModule;
SHNodeList : TStringList;
implementation
uses
uDataModule1,
uLomosUtil,
uSyFpReaderFunction;
{$R *.dfm}
{ TFPNode }
procedure TFPNode.Add_FPData(aUserID:integer;aUserCard, aUserFPData,aFPPermit: string);
var
stUserID : string;
nIndex : integer;
oFPUser : TFPUser;
begin
stUserID := FillZeroNumber(aUserID,G_nFPUserIDLength);
nIndex := FPUserList.IndexOf(stUserID);
if nIndex < 0 then
begin
oFPUser := TFPUser.Create(nil);
oFPUser.FPNodeNo := FPNodeNo;
oFPUser.FPUSERID := aUserID;
oFPUser.FPDATA := aUserFPData;
oFPUser.FPCARD := aUserCard;
oFPUser.FPPERMIT := aFPPermit;
oFPUser.OnCARDStateChangeEvent := CARDStateChangeEvent;
oFPUser.FPSEND := 'S';
FPUserList.AddObject(stUserID,oFPUser);
end else
begin
TFPUser(FPUserList.Objects[nIndex]).FPDATA := aUserFPData;
TFPUser(FPUserList.Objects[nIndex]).FPCARD := aUserCard;
TFPUser(FPUserList.Objects[nIndex]).FPPERMIT := aFPPermit;
TFPUser(FPUserList.Objects[nIndex]).FPSEND := 'S';
end;
end;
procedure TFPNode.CARDStateChangeEvent(Sender: TObject; aFPNo,
aUSERID: integer;aNodeName, aFPSEND: string);
begin
if Assigned(FOnCARDStateChangeEvent) then
begin
OnCARDStateChangeEvent(Self,aFPNo,aUSERID,FPNodeName,aFPSEND);
end;
end;
function TFPNode.CheckSHFDDataPacket(aData:String; var bData:String): string;
var
nIndex: Integer;
Lenstr: String;
DefinedDataLength: Integer;
StrBuff: String;
etxIndex: Integer;
stPacket : string;
stCrcData : string;
stHexCRC : string;
nCRC : word;
begin
Result:= '';
nIndex:= Pos(Ascii2Hex(STX),aData);
if nIndex = 0 then
begin
result := ''; //자릿수가 작게 들어온 경우
bData:= '';
Exit;
end;
if nIndex > 1 then
begin
//STX 가 처음이 아니면 STX앞데이터 삭제
Delete(aData,1,nIndex-1);
end;
if Length(aData) < 16 then
begin
result := ''; //자릿수가 작게 들어온 경우
bData:= aData;
Exit;
end;
Lenstr := Copy(aData,3,4);
Lenstr := copy(Lenstr,3,2) + copy(Lenstr,1,2);
//데이터 길이 위치 데이터가 숫자가 아니면...
(* if not isDigit(Lenstr) then
begin
Delete(aData,1,2); //1'st STX 삭제
nIndex:= Pos(Ascii2Hex(STX),aData); // 다음 STX 찾기
if nIndex = 0 then //STX가 없으면...
begin
//전체 데이터 버림
bData:= '';
end else if nIndex > 1 then // STX가 1'st가 아니면
begin
Delete(aData,1,nIndex-1);//STX 앞 데이터 삭제
bData:= aData;
end else
begin
bData:= aData;
end;
Exit;
end;
*)
//패킷에 정의된 길이
DefinedDataLength:= Hex2Dec(Lenstr);
//패킷에 정의된 길이보다 실제 데이터가 작으면
if Length(aData) < (DefinedDataLength * 2) then
begin
//실제 데이터를 다 못 받은 경우
bData:= aData;
Exit;
end;
stPacket := copy(aData,1,DefinedDataLength * 2);
Delete(aData, 1, DefinedDataLength * 2);
bData:= aData;
stCrcData := copy(stPacket,1, (DefinedDataLength * 2) - 4);
stCrcData := Hex2Ascii(stCrcData);
nCRC := crc16_ccitt(pchar(stCrcData),DefinedDataLength - 2);
stHexCRC := Dec2Hex64(nCRC,4);
stHexCRC := copy(stHexCRC,3,2) + copy(stHexCRC,1,2);
if stHexCRC = copy(stPacket,(DefinedDataLength * 2) - 4 + 1,4) then //CRC 체크하지 말자.
begin
result := stPacket; //패킷이 맞는거다.
end;
end;
procedure TFPNode.CommNodeTriggerAvail(Sender: TObject; SockNo: integer;
Buf: String; DataLen: Integer);
var
nIndex : integer;
stPacket : string;
st2 : string;
begin
ComBuff:= ComBuff + AsciiLen2Hex(Buf,DataLen);
nIndex:= Pos(Ascii2Hex(STX),ComBuff);
if nIndex = 0 then
begin
ComBuff := ''; //STX 가 없으면 잘못된 패킷이므로 수신데이터를 버리고 빠져 나간다.
end;
if nIndex > 1 then
begin
//STX 가 처음이 아니면 STX앞데이터 삭제
Delete(ComBuff,1,nIndex-1);
end;
if Length(Combuff) < 16 then Exit; //최소 패킷 수가 8바이트 이상이다.
repeat
stPacket:= CheckSHFDDataPacket(ComBuff,st2);
ComBuff:= st2;
if stPacket <> '' then SHFDataPacektProcess(stPacket);
until stPacket = '';
end;
procedure TFPNode.CommNodeWsError(Sender: TObject; SockNo,
SocketError: Integer);
begin
SocketError := 0;
SocketConnected := -1;
Open := False;
end;
constructor TFPNode.Create(AOwner: TComponent);
begin
inherited;
L_bDestroy := False;
FHandle := 0;
FPDeviceID := 1;
L_nFPSendCount := 0;
ReaderType := 1; //리더 타입으로 사용하자.
l_c_reception_buffer:= c_byte_buffer.create_byte_buffer('reception_buffer', k_buffer_max);
FPUserList := TStringList.Create;
SocketCheckTimer:= TTimer.Create(nil);
SocketCheckTimer.Interval := 2000;
SocketCheckTimer.OnTimer := SocketCheckTimerTimer;
SocketCheckTimer.Enabled := True;
FPSendTimer := TTimer.Create(nil);
FPSendTimer.Interval := 1000;
FPSendTimer.OnTimer := FPSendTimerTimer;
FPSendTimer.Enabled := True;
end;
destructor TFPNode.Destroy;
var
i : integer;
begin
if Open then Open := False;
SocketCheckTimer.Enabled := False;
FPSendTimer.Enabled := False;
L_bDestroy := True;
Delay(1000); //정리하는 시간을 좀 갖자.
if FPUserList.Count > 0 then
begin
for i := FPUserList.Count - 1 downto 0 do
TFPUser(FPUserList.Objects[i]).Free;
end;
FPUserList.Clear;
inherited;
end;
procedure TFPNode.FPSendTimerTimer(Sender: TObject);
begin
if L_bDestroy then Exit;
if ReaderType = 0 then //등록기 타입으로 동작시에는 이 루틴은 타지 말자.
begin
FPSendTimer.Enabled := False;
Exit;
end;
Try
FPSendTimer.Enabled := False;
L_bCardDownLoading := True;
if G_bApplicationTerminate then Exit;
if SocketConnected <> Connected then Exit; //접속이 안되어 있으면 전송 하지 말자.
if FPUserList.Count < 1 then Exit; //전송할 데이터가 없으면 빠져 나가자.
if L_nFPSendCount > FPUserList.Count - 1 then L_nFPSendCount := 0;
if (TFPUser(FPUserList.Objects[L_nFPSendCount]).FPPERMIT = '1') and (TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND = 'S') then
begin
//여기에서 카드 정보 전송 하고 응답을 기다린다.
if UserCardSend(FPDeviceID,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPUSERID,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPCARD,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPPERMIT) = 1 then // 전송 성공 후 응답 받은 경우
begin
TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND := 'F';
end else
begin
Open := False;
Exit;
end;
end;
if (TFPUser(FPUserList.Objects[L_nFPSendCount]).FPPERMIT = '1') and (TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND = 'F') then
begin
//여기에서 지문 정보 전송 하고 응답을 기다린다.
if UserFPDataSend(FPDeviceID,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPUSERID,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPDATA,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPPERMIT) = 1 then
begin
TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND := 'Y';
end else
begin
Open := False;
Exit;
end;
end;
if TFPUser(FPUserList.Objects[L_nFPSendCount]).FPPERMIT = '0' then
begin
//여기서 지문 삭제 정보 전송하고 응답을 기다린다.
if UserFPDelete(FPDeviceID,TFPUser(FPUserList.Objects[L_nFPSendCount]).FPUSERID) = 1 then
begin
TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND := 'Y';
end else
begin
Open := False;
Exit;
end;
end;
if TFPUser(FPUserList.Objects[L_nFPSendCount]).FPSEND = 'Y' then //전송 성공 했으면 삭제 하자.
begin
TFPUser(FPUserList.Objects[L_nFPSendCount]).Free;
FPUserList.Delete(L_nFPSendCount);
end else L_nFPSendCount := L_nFPSendCount + 1;
Finally
L_bCardDownLoading := False;
FPSendTimer.Enabled := Not G_bApplicationTerminate;
End;
end;
function TFPNode.FP_HexSendPacket(aCmd: char;
aHexAddress,aHexData: string): Boolean;
var
stPacket : string;
nLength : integer;
stHexLen : string;
nCRC : word;
stHexCRC : string;
begin
stPacket := aHexAddress + Ascii2Hex(aCmd) + aHexData;
nLength := Length(stPacket) + (6 * 2);
nLength := nLength div 2;
stHexLen := Dec2Hex64(nLength,4);
stHexLen := copy(stHexLen,3,2) + copy(stHexLen,1,2); //앞 뒤를 바꾼다.
stPacket := STX + Hex2Ascii(stHexLen) + Hex2Ascii(stPacket) + ETX;
nCRC := crc16_ccitt(pchar(stPacket),nLength - 2);
stHexCRC := Dec2Hex64(nCRC,4);
stHexCRC := copy(stHexCRC,3,2) + copy(stHexCRC,1,2); //앞 뒤를 바꾼다.
stPacket := stPacket + Hex2Ascii(stHexCRC);
PutString(stPacket,nLength);
if Assigned(FOnCARDEvent) then
begin
OnCARDEvent(Self,FPNodeNo,FPNodeName,'TX',Ascii2Hex(stPacket));
end;
end;
function TFPNode.FP_SendPacket(aCmd, aAddress: char;
aData: string): Boolean;
var
stPacket : string;
nLength : integer;
stHexLen : string;
nCRC : word;
stHexCRC : string;
begin
stPacket := aAddress + aCmd + aData;
nLength := Length(stPacket) + 6;
stHexLen := Dec2Hex64(nLength,4);
stHexLen := copy(stHexLen,3,2) + copy(stHexLen,1,2); //앞 뒤를 바꾼다.
stPacket := STX + Hex2Ascii(stHexLen) + stPacket + ETX;
nCRC := crc16_ccitt(pchar(stPacket),nLength - 2);
stHexCRC := Dec2Hex64(nCRC,4);
stHexCRC := copy(stHexCRC,3,2) + copy(stHexCRC,1,2); //앞 뒤를 바꾼다.
stPacket := stPacket + Hex2Ascii(stHexCRC);
PutString(stPacket,nLength);
end;
function TFPNode.GetFPData(aUserID: string): string;
var
stUserID : string;
Tick: DWORD;
NowTick: DWORD;
stAddr : string;
begin
if FPDeviceType = 1 then //2.4 버젼은 SetEncrpt 설정해 주자.
begin
// SetEncrypt(FPDeviceID,2); //설정 되어 있는데로 놔두자. 1.암호화 해제,2.암호화
end;
if FPDeviceID < 9 then stAddr := Dec2Hex(FPDeviceID - 1,2)
else
begin
stAddr := Dec2Hex(FPDeviceID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stUserID := FillZeroStrNum(aUserID,G_nFPUserIDLength);
stUserID := FillZeroStrNum(stUserID,10,False);
stUserID := Ascii2Hex(stUserID);
L_stGetFDData := '';
Try
L_nResult := 0;
L_bGetFDData := True;
FP_HexSendPacket(cmdFPGetFP,stAddr,stUserID);
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
L_bGetFDData := False;
result := L_stGetFDData;
End;
end;
function TFPNode.GetHandle: THandle;
begin
HandleNeeded;
Result := FHandle;
end;
function TFPNode.HandleAllocated: Boolean;
begin
Result := ( FHandle <> 0 );
end;
procedure TFPNode.HandleNeeded;
begin
if not HandleAllocated
then FHandle := AllocateHWND ( WndProc );
end;
procedure TFPNode.handle_fd_close_notification(p_socket: Integer);
var
l_status: Integer;
l_linger: TLinger;
l_absolute_linger: array[0..3] of char absolute l_linger;
begin
if WSAIsBlocking
then
begin
WSACancelBlockingCall;
end;
Open := False;
end;
procedure TFPNode.handle_fd_connect_notification(p_socket: Integer);
begin
SocketConnected:= Connected;
end;
procedure TFPNode.handle_fd_read_notification(p_socket: tSocket);
var
l_remaining: Integer;
l_pt_start_reception: Pointer;
l_packet_bytes: Integer;
l_eol_position: Integer;
stTemp : String;
begin
if l_c_reception_buffer = nil then Exit;
with l_c_reception_buffer do
begin
l_remaining:= m_buffer_size- m_write_index;
// -- if not at least a tcp-ip chunk, increase the room
if l_remaining < k_tcp_ip_chunk then
begin
// -- reallocate
double_the_capacity;
l_remaining:= m_buffer_size- m_write_index;
end;
// -- add the received data to the current buffer
l_pt_start_reception:= @ m_oa_byte_buffer[m_write_index];
// -- get the data from the client socket
//LogSave(ExeFolder + '\..\log\log'+ ConnectIP +'.log','RecvStart ');
l_packet_bytes:= Recv(WinSocket, l_pt_start_reception^, l_remaining, 0);
if l_packet_bytes < 0 then
begin
LogSave(ExeFolder + '\..\log\log'+ FormatDateTIme('yyyymmdd',Now)+'.log','Error connect(Recv) '+ FPNodeIP);
CommNodeWsError(Self,p_socket,WSAGetLastError);
end else
begin
m_write_index:= m_write_index+ l_packet_bytes;
stTemp := ByteCopy(l_pt_start_reception,l_packet_bytes);
//LogSave(ExeFolder + '\..\log\log'+ ConnectIP +'.log',stTemp);
CommNodeTriggerAvail(Self,p_socket,stTemp,l_packet_bytes);
end;
end; // with g_c_reception_buffer
end;
procedure TFPNode.handle_fd_write_notification(p_socket: Integer);
begin
L_bSocketWriting := False; //전송 완료 소켓 버퍼 Write 공간 생김
end;
procedure TFPNode.handle_wm_async_select(var Msg: TMessage);
var
l_param: Integer;
l_error, l_notification: Integer;
l_socket_handle: Integer;
begin
if L_bDestroy then Exit;
l_param:= Msg.lParam;
l_socket_handle:= Msg.wParam;
// -- extract the error and the notification code from l_param
l_error:= wsaGetSelectError(l_param);
l_notification:= wsaGetSelectEvent(l_param);
if l_error <= wsaBaseErr then
begin
case l_notification of
FD_CONNECT: handle_fd_connect_notification(l_socket_handle);
FD_ACCEPT: {display_bug_stop('no_client_accept')} ;
FD_WRITE: handle_fd_write_notification(l_socket_handle);
FD_READ: handle_fd_read_notification(l_socket_handle);
FD_CLOSE:
begin
LogSave(ExeFolder + '\..\log\log'+ FormatDateTIme('yyyymmdd',Now)+'.log','Error connect(fd_close_EVENT) -' + FPNodeIP);
handle_fd_close_notification(l_socket_handle);
end;
end // case
end else
begin
if l_notification= FD_CLOSE then
begin
LogSave(ExeFolder + '\..\log\log'+ FormatDateTIme('yyyymmdd',Now)+'.log','Error connect(fd_close_ERR) -' + FPNodeIP);
handle_fd_close_notification(l_socket_handle);
end
else
begin
LogSave(ExeFolder + '\..\log\log'+ FormatDateTIme('yyyymmdd',Now)+'.log','Error connect(SELECT) -'+ inttostr(l_notification) + '-' + FPNodeIP);
handle_fd_close_notification(l_socket_handle);
end;
end;
end;
function TFPNode.PutString(aData: string;aLen:integer): Boolean;
var
l_result: Integer;
buf: array of Byte;
i : integer;
begin
Try
result := False;
if WinSocket = INVALID_SOCKET then Exit;
if Not Open then Exit;
While L_bSocketWriting do
begin
if Not Open then Exit;
Application.ProcessMessages;
sleep(1);
end;//전송 중에는 보내지 말자. => 전송 완료 메시지 이벤트가 발생 안되어 무용지물
SetLength(buf, aLen);
for i := 1 to aLen do
begin
buf[i-1] := ord(aData[i]);
end;
Try
l_result:= Send(WinSocket,buf[0], aLen, 0);
if l_result < 0 then
begin
if l_result = wsaEWouldBlock then
begin
L_bSocketWriting := True; //Socket에 Full 나면 Write
end else
begin
LogSave(ExeFolder + '\..\log\log'+ FormatDateTIme('yyyymmdd',Now)+'.log','Error connect(Send) -'+ inttostr(l_result) + '-' + FPNodeIP);
CommNodeWsError(Self,WinSocket,WSAGetLastError);
end;
end;
Except
Exit;
End;
result := True;
Finally
// FTCSDeviceSender.Leave;
End;
end;
function TFPNode.SetEncrypt(aFPReaderID, aType: integer): Boolean;
var
stData : string;
stAddr : string;
Tick: DWORD;
NowTick: DWORD;
begin
result := False;
if aFPReaderID < 9 then stAddr := Dec2Hex(aFPReaderID - 1,2)
else
begin
stAddr := Dec2Hex(aFPReaderID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stData := FillZeroNumber(aType,3);
stData := Ascii2Hex(stData);
Try
L_nResult := 0;
FP_HexSendPacket(cmdFPSetEncrypt,stAddr,stData);
Tick := GetTickCount + DWORD(3000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
if L_nResult = 1 then result := True;
End;
end;
procedure TFPNode.SetOpen(const Value: Boolean);
var
l_result : Integer;
l_error: Integer;
l_socket_address_in: tSockAddrIn;
l_ip_z: array[0..255] of char;
rset: TFDSet;
t: TTimeVal;
rslt: integer;
stConnectIP : string;
begin
if FOpen = Value then Exit;
FOpen := Value;
stConnectIP := FPNodeIP;
if Value then
begin
SocketConnected:= Connecting; //Connecting
l_result := wsaStartup(MAKEWORD(1, 1), l_wsa_data);
if l_result <> 0 then
begin
Open := False;
Exit; //소켓생성 실패 시에 Open False
end;
WinSocket:= Socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
if WinSocket = INVALID_SOCKET then
begin
Open := False;
Exit; //소켓생성 실패 시에 Open False
end;
l_result:= wsaAsyncSelect(WinSocket, Handle,
wm_asynch_select,
FD_CONNECT+ FD_READ+ FD_WRITE+ FD_CLOSE);
FillChar(l_socket_address_in, sizeof(l_socket_address_in), 0);
with l_socket_address_in do
begin
sin_family:= pf_Inet;
// -- the requested service
sin_port:= hToNs(FPNodePort);
// -- the server IP address
if Not IsIPTypeCheck(FPNodeIP) then
begin
stConnectIP := GetIpFromDomain(FPNodeIP);
end;
StrPCopy(l_ip_z, stConnectIP);
sin_addr.s_Addr:= inet_addr(PAnsichar(AnsiString(l_ip_z)));
end; // with m_socket_address_in
l_result:= Connect(WinSocket, l_socket_address_in,
sizeof(l_socket_address_in));
if l_result<> 0 then
begin
l_error:= WSAGetLastError;
if l_error <> wsaEWouldBlock then
begin
//LogSave(ExeFolder + '\..\log\Connectlog'+ FormatDateTIme('yyyymmdd',Now)+'.log',ConnectIP + 'OpenError' + inttostr(WinSocket));
Open := False;
Exit; //소켓생성 실패 시에 Open False
end else
begin
end;
//LogSave(ExeFolder + '\..\log\Connectlog'+ FormatDateTIme('yyyymmdd',Now)+'.log',ConnectIP + 'Open' + inttostr(WinSocket));
end;
end else
begin
SocketConnected:= DisConnected;
if WinSocket <> INVALID_SOCKET then
begin
//LogSave(ExeFolder + '\..\log\Connectlog'+ FormatDateTIme('yyyymmdd',Now)+'.log',ConnectIP + 'Close' + inttostr(WinSocket));
shutdown(WinSocket,SD_BOTH);
l_result:= CloseSocket(WinSocket);
if l_result = 0 then
begin
WinSocket:= INVALID_SOCKET;
end else
begin
WinSocket:= INVALID_SOCKET;
end;
if WSAISBlocking then WSACancelBlockingCall; //--추가 20141215 충남대에서 에러 때문에 혹시나 해서...ㅠ.ㅠ
WSACleanup;
end;
end;
end;
procedure TFPNode.SetSocketConnected(const Value: integer);
begin
if FSocketConnected = Value then Exit;
FSocketConnected := Value;
if Assigned(FOnConnected) then
begin
OnConnected(Self,FPNodeNo,FPNodeIP,FPNodePort,FPNodeName,Value);
end;
end;
function TFPNode.SHFDataPacektProcess(aHexPacket: string): Boolean;
var
stResult : string;
begin
if Assigned(FOnCARDEvent) then
begin
OnCARDEvent(Self,FPNodeNo,FPNodeName,'RX',aHexPacket);
end;
stResult := copy(aHexPacket,4*2 + 1,2);
//if stResult = '00' then L_nResult:= 1
//else L_nResult := -1; //에러 발생한거다
L_nResult:= 1; //에러 응답시 체크 하지 말자 2016-07-26
if L_bGetFDData then //지문 조회 중인 거다... 여기에서 지문 데이터 수신 하자.
begin
L_bGetFDData := False;
if FPDeviceID < 9 then Delete(aHexPacket,1,4*2 + 2)
else Delete(aHexPacket,1,4*2 + 2 + 2);
L_stGetFDData := copy(aHexPacket,1,Length(aHexPacket) - 6);
end;
end;
function TFPNode.ShunghunSyncTime(aFPReaderID: integer;
aSendData: string): Boolean;
var
stAddr : string;
stSendData : string;
Tick: DWORD;
NowTick: DWORD;
begin
(* Dec(L_nConnectedTime);
if Not Connected then
begin
if L_nConnectedTime > 0 then Exit; //소켓 Close 후에 3초 간은 들어 오지 말자.
if SocketOpen then
begin
SocketOpen := False;
Exit;
end;
L_nConnectedTime := 6;
SocketOpen := True;
Exit; //접속 안되어 있으면 전송 하러 가지 말자.
end;
if L_bCardDownLoading then Exit;
if L_bModuleDestory then Exit;
Try
L_bCardDownLoading := True;
if aFPReaderID < 9 then stAddr := Dec2Hex(aFPReaderID - 1,2)
else
begin
stAddr := Dec2Hex(aFPReaderID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stSendData := Ascii2Hex(aSendData);
L_nResult := 0;
L_cFPCmd := cmdFPTimeSet;
FP_HexSendPacket(cmdFPTimeSet,stAddr,stSendData);
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
if L_nResult = 1 then SyncTime := now; //현재시간으로 시간 동기화를 했다.
SocketOpen := False;
Finally
L_bCardDownLoading := False;
End;
*)
end;
procedure TFPNode.SocketCheckTimerTimer(Sender: TObject);
begin
if L_bDestroy then Exit;
if G_bApplicationTerminate then Exit;
if ReaderType = 0 then //등록기 타입으로 동작시에는 이 루틴은 타지 말자.
begin
SocketCheckTimer.Enabled := False;
Exit;
end;
//SocketCheckTimer.Interval := 10000; //10초 주기별로
if FPUserList.Count > 0 then
begin
//전송할 데이터가 있으면...
if SocketConnected = Connected then Exit; //접속 성공 상태이면 빠져 나간다.
if Open then Open := False
else Open := True;
end else
begin
//없으면 소켓 Close
Open := False;
end;
end;
function TFPNode.SyncTimeSend: Boolean;
var
stSendData:string;
begin
(* if SyncTime > Now - 1 then Exit; //시간 전송 한지 하루가 안 지났으면 전송하지 말자
if L_bCardDownLoading then Exit; //현재 카드 데이터 전송중이면 시간 전송하지 말자.
stSendData := inttostr(DayofWeek(now)) + copy(formatdateTime('yyyymmddhhnnss',now),3,12);
ShunghunSyncTime(FPReaderID,stSendData);
*)
end;
function TFPNode.UserAllDelete: integer;
var
stUserID : string;
Tick: DWORD;
NowTick: DWORD;
stSendData : string;
stAddr : string;
begin
if FPDeviceID < 9 then stAddr := Dec2Hex(FPDeviceID - 1,2)
else
begin
stAddr := Dec2Hex(FPDeviceID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
Try
L_nResult := 0;
FP_HexSendPacket(cmdFPAllDelete,stAddr,'');
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
result := L_nResult;
End;
end;
function TFPNode.UserCardSend(aFPReaderID,aUserID: integer;
aUserCard,aPermit: string): integer;
var
stUserID : string;
stCardNo : string;
stPassword : string;
stMode : string;
stTimeTable : string;
stAdmin : string;
stGrade : string;
stDate : string;
Tick: DWORD;
NowTick: DWORD;
stSendData : string;
stAddr : string;
begin
if FPDeviceType = 1 then //2.4 버젼은 SetEncrpt 설정해 주자.
begin
// SetEncrypt(aFPReaderID,2); //설정되어 있는데로 놔두자. 1.암호화 해제,2.암호화
end;
if aFPReaderID < 9 then stAddr := Dec2Hex(aFPReaderID - 1,2)
else
begin
stAddr := Dec2Hex(aFPReaderID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stUserID := FillZeroNumber(aUserID,G_nFPUserIDLength);
stUserID := FillZeroStrNum(stUserID,10,False);
stUserID := Ascii2Hex(stUserID);
stPassword := FillCharString('','F',10 * 2);
stMode := '33333330';
stMode := Ascii2Hex(stMode);
stTimeTable := FillCharString('','F',168 * 2);
stAdmin := '30';
stGrade := '01';
stDate := FillCharString('','F',20 * 2);
if CARDLENGTHTYPE = 0 then
begin
if IsNumericCardNo then stCardNo:= Dec2Hex64(strtoint64(aUserCard),8)
else stCardNo:= aUserCard;
end else if CARDLENGTHTYPE = 1 then //16byte
begin
if copy(aUserCard,15,2) = '**' then stCardNo:= copy(aUserCard,1,8)
else
begin
stCardNo := copy(aUserCard,1,10) + copy(aUserCard,15,2);
stCardNo := Ascii2Hex(stCardNo);
end;
end else if CARDLENGTHTYPE = 2 then //KT사옥(현재는 지원하지 않는다.)
begin
end;
if FPDeviceType = 1 then stCardNo := FillCharString(stCardNo,'F',72)
else stCardNo := FillCharString(stCardNo,'F',24); //24자리 카드 번호를 만든다.
stSendData := stUserID + stCardNo + stPassword + stMode + stTimeTable + stAdmin + stGrade + stDate;
Try
L_nResult := 0;
FP_HexSendPacket(cmdFPCard,stAddr,stSendData);
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
result := L_nResult;
End;
end;
function TFPNode.UserFPDataSend(aFPReaderID,aUserID: integer;
aFPDATA,aPermit: string): integer;
var
stUserID : string;
Tick: DWORD;
NowTick: DWORD;
stSendData : string;
stAddr : string;
begin
if aFPReaderID < 9 then stAddr := Dec2Hex(aFPReaderID - 1,2)
else
begin
stAddr := Dec2Hex(aFPReaderID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stUserID := FillZeroNumber(aUserID,G_nFPUserIDLength);
stUserID := FillZeroStrNum(stUserID,10,False);
stUserID := Ascii2Hex(stUserID);
stSendData := stUserID + aFPDATA;
Try
L_nResult := 0;
FP_HexSendPacket(cmdFPData,stAddr,stSendData);
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
result := L_nResult;
End;
end;
function TFPNode.UserFPDelete(aFPReaderID, aUserID: integer): integer;
var
stUserID : string;
Tick: DWORD;
NowTick: DWORD;
stSendData : string;
stAddr : string;
begin
if aFPReaderID < 9 then stAddr := Dec2Hex(aFPReaderID - 1,2)
else
begin
stAddr := Dec2Hex(aFPReaderID - 1,4);
stAddr := copy(stAddr,3,2) + copy(stAddr,1,2);
end;
stUserID := FillZeroNumber(aUserID,G_nFPUserIDLength);
stUserID := FillZeroStrNum(stUserID,10,False);
stUserID := Ascii2Hex(stUserID);
stSendData := stUserID;
Try
L_nResult := 0;
FP_HexSendPacket(cmdFPDelete,stAddr,stSendData);
Tick := GetTickCount + DWORD(2000);
while (L_nResult = 0) do
begin
NowTick := GetTickCount;
if Tick < NowTick then break;
Application.ProcessMessages;
end;
Finally
result := L_nResult;
End;
end;
procedure TFPNode.WndProc(var Message: TMessage);
begin
if L_bDestroy then Exit;
Try
Dispatch ( Message );
Except
Exit;
End;
end;
{ TFPUser }
procedure TFPUser.SetFPSEND(const Value: string);
begin
if FFPSEND = Value then Exit;
FFPSEND := Value;
//여기에서 이벤트 발생 시켜서 데이터베이스
if Assigned(FOnCARDStateChangeEvent) then
begin
OnCARDStateChangeEvent(Self,FPNodeNo,FPUSERID,'',Value);
end;
end;
end.
|
{$INCLUDE ../../flcInclude.inc}
{$INCLUDE ../flcCrypto.inc}
unit flcTestEncodingASN1;
interface
{$IFDEF CRYPTO_TEST}
procedure Test;
{$ENDIF}
implementation
{$IFDEF CRYPTO_TEST}
uses
flcEncodingASN1;
{ }
{ Test }
{ }
{$ASSERTIONS ON}
procedure TestParseProc(
const TypeID: Byte; const DataBuf; const DataSize: NativeInt;
const ObjectIdx: Int32; const CallerData: NativeInt);
var
I : Int64;
S : RawByteString;
begin
case CallerData of
0 : case ObjectIdx of
0 : begin
Assert(TypeID = ASN1_ID_SEQUENCE);
Assert(ASN1Parse(DataBuf, DataSize, TestParseProc, 1) = DataSize);
end;
else
Assert(False);
end;
1 : case ObjectIdx of
0 : begin
Assert(TypeID = ASN1_ID_INTEGER);
ASN1DecodeInteger64(TypeID, DataBuf, DataSize, I);
Assert(I = 123);
end;
1 : begin
Assert(TypeID = ASN1_ID_PRINTABLESTRING);
ASN1DecodeString(TypeID, DataBuf, DataSize, S);
Assert(S = 'ABC');
end;
else
Assert(False);
end;
else
Assert(False);
end;
end;
procedure Test;
var S : RawByteString;
L, I, J : Integer;
D : TASN1ObjectIdentifier;
begin
Assert(ASN1EncodeLength(0) = #$00);
Assert(ASN1EncodeLength(1) = #$01);
Assert(ASN1EncodeLength($7F) = #$7F);
Assert(ASN1EncodeLength($80) = #$81#$80);
Assert(ASN1EncodeLength($FF) = #$81#$FF);
Assert(ASN1EncodeLength($100) = #$82#$01#$00);
Assert(ASN1EncodeOID(OID_3DES_wrap) = #$06#$0b#$2a#$86#$48#$86#$f7#$0d#$01#$09#$10#$03#$06);
Assert(ASN1EncodeOID(OID_RC2_wrap) = #$06#$0b#$2a#$86#$48#$86#$f7#$0d#$01#$09#$10#$03#$07);
S := RawByteString(#$2a#$86#$48#$86#$f7#$0d#$01#$09#$10#$03#$06);
L := Length(S);
Assert(ASN1DecodeDataOID(S[1], L, D) = L);
Assert(Length(D) = 9);
Assert((D[0] = 1) and (D[1] = 2) and (D[2] = 840) and (D[3] = 113549) and
(D[4] = 1) and (D[5] = 9) and (D[6] = 16) and (D[7] = 3) and (D[8] = 6));
Assert(ASN1OIDToStrB(D) = '1.2.840.113549.1.9.16.3.6');
S := RawByteString(#$2a#$86#$48#$86#$f7#$0d#$03#$06);
L := Length(S);
Assert(ASN1DecodeDataOID(S[1], L, D) = L);
Assert(Length(D) = 6);
Assert((D[0] = 1) and (D[1] = 2) and (D[2] = 840) and (D[3] = 113549) and
(D[4] = 3) and (D[5] = 6));
Assert(ASN1EncodeInteger32(0) = #$02#$01#$00);
Assert(ASN1EncodeInteger32(1) = #$02#$01#$01);
Assert(ASN1EncodeInteger32(-1) = #$02#$01#$FF);
Assert(ASN1EncodeInteger32(-$80) = #$02#$01#$80);
Assert(ASN1EncodeInteger32(-$81) = #$02#$02#$7F#$FF);
Assert(ASN1EncodeInteger32(-$FF) = #$02#$02#$01#$FF);
Assert(ASN1EncodeInteger32($7F) = #$02#$01#$7F);
Assert(ASN1EncodeInteger32($80) = #$02#$02#$80#$00);
Assert(ASN1EncodeInteger32($FF) = #$02#$02#$FF#$00);
for I := -512 to 512 do
begin
S := ASN1EncodeInteger32(I);
Assert(S = ASN1EncodeInteger64(I));
L := Length(S);
Assert(ASN1DecodeDataInteger32(S[3], L - 2, J) = L - 2);
Assert(J = I);
end;
S :=
ASN1EncodeSequence(
ASN1EncodeInteger32(123) +
ASN1EncodePrintableString('ABC')
);
L := Length(S);
Assert(L > 0);
Assert(ASN1Parse(S[1], L, @TestParseProc, 0) = L);
end;
{$ENDIF}
end.
|
unit Mini;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, scStyledForm, scControls,
scGPControls, dxGDIPlusClasses, scGPImages, scGPPagers, Vcl.ExtCtrls, scModernControls;
const
WM_MouseEnter = $B013;
WM_MouseLeave = $B014;
type
TFm_MiniBox = class(TForm)
SF_MinBox: TscStyledForm;
PN_MinBox: TscGPPanel;
BTN_Play_Pause: TscGPButton;
BTN_Last: TscGPButton;
BTN_Next: TscGPButton;
BTN_Close: TscGPGlyphButton;
BTN_Small: TscGPGlyphButton;
BTN_Voice: TscGPButton;
BTN_PlayList: TscGPButton;
Lb_Song_Name: TscGPLabel;
Lb_Song_Singer: TscGPLabel;
Music_Logo_Img: TscGPImage;
PV_Main: TscGPPageViewer;
PVP_Control: TscGPPageViewerPage;
PVP_Info: TscGPPageViewerPage;
procedure BTN_Play_PauseClick(Sender: TObject);
procedure BTN_SmallClick(Sender: TObject);
procedure BTN_CloseClick(Sender: TObject);
procedure BTN_NextClick(Sender: TObject);
procedure BTN_LastClick(Sender: TObject);
procedure BTN_VoiceClick(Sender: TObject);
procedure BTN_PlayListClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
procedure CreateParams(var Params: TCreateParams); override;
procedure WMMouseEnter(var Msg: TMessage); message WM_MouseEnter;
procedure WMMouseLeave(var Msg: TMessage); message WM_MouseLeave;
procedure WMForm_Move(var Msg: TMessage); message WM_MOVE;
{ Public declarations }
end;
var
Fm_MiniBox: TFm_MiniBox;
bo: Boolean;
implementation
uses
Main, List, Bass;
{$R *.dfm}
procedure TFm_MiniBox.BTN_CloseClick(Sender: TObject);
begin //关闭程序
Fm_Main.TMR_Play.Enabled := False;
Fm_Main.TMR_Bottom_Wave.Enabled := false;
BASS_ChannelStop(HS);
Application.Terminate;
end;
procedure TFm_MiniBox.BTN_LastClick(Sender: TObject);
begin
case Loop_Type of
0: //列表循环的上一首
begin
try
Fm_Main.Last_Music;
except
Fm_Main.Last_Music;
end;
end;
2: //随机上一首
begin
try
Fm_Main.Loop_Random;
except
Fm_Main.Loop_Random;
end;
end;
end;
end;
procedure TFm_MiniBox.BTN_NextClick(Sender: TObject);
begin
case Loop_Type of
0: //列表循环的下一首
begin
try
Fm_Main.Loop_List;
except
Fm_Main.Loop_List;
end;
end;
1: //列表循环的下一首
begin
try
Fm_Main.Loop_List;
except
Fm_Main.Loop_List;
end;
end;
2: //随机循环的下一首
begin
try
Fm_Main.Loop_Random;
except
Fm_Main.Loop_Random;
end;
end;
end;
end;
procedure TFm_MiniBox.BTN_PlayListClick(Sender: TObject);
begin
Fm_List.SF_List.DropDown(Fm_MiniBox, Fm_MiniBox.Left, Fm_MiniBox.Top + 50);
end;
procedure TFm_MiniBox.BTN_Play_PauseClick(Sender: TObject);
begin
if MEM.Size > 0 then
begin
if Bo_Play then
begin
BASS_ChannelSetAttribute(HS, BASS_ATTRIB_VOL, Fm_Main.Trc_Voice.Value / Fm_Main.Trc_Voice.MaxValue);
Fm_Main.Tmr_Play.Enabled := True; //播放音乐
BASS_ChannelPlay(HS, false);
BTN_Play_Pause.ImageIndex := 1;
Fm_Main.BTN_Play_Pause.ImageIndex := 1; //播放按钮显示为暂停
Fm_Main.N_Play_Pause.ImageIndex := 5; //任务栏按钮显示为暂停
Fm_Main.N_Play_Pause.Caption := '暂停';
Bo_Play := false;
end
else
begin
Fm_Main.Tmr_Play.Enabled := false; //停止播放音乐
BASS_ChannelPause(HS);
BTN_Play_Pause.ImageIndex := 0;
Fm_Main.BTN_Play_Pause.ImageIndex := 0; //播放按钮显示为播放
Fm_Main.N_Play_Pause.ImageIndex := 4; //任务栏按钮显示为播放
Fm_Main.N_Play_Pause.Caption := '播放';
Bo_Play := True;
end;
end;
end;
procedure TFm_MiniBox.BTN_SmallClick(Sender: TObject);
begin
Fm_Main.TMR_Bottom_Wave.Enabled := True;
Fm_Main.Show;
Fm_MiniBox.Hide;
end;
procedure TFm_MiniBox.BTN_VoiceClick(Sender: TObject);
begin
Fm_Main.CP_Voice.Popup(BTN_Voice);
end;
procedure TFm_MiniBox.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WndParent := 0;
Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW; //如果不想在任务栏显示窗口图标
end;
procedure TFm_MiniBox.FormShow(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_HIDE);
bo := true;
end;
procedure TFm_MiniBox.WMForm_Move(var Msg: TMessage);
begin
if (self.Top < 10) and (Self.Top <> 0) and bo then
begin
self.Top := 0;
Sleep(20);
end;
end;
procedure TFm_MiniBox.WMMouseEnter(var Msg: TMessage);
var
rc, rcF: TRECT;
pt, ptF: TPOINT;
i: Word;
begin
GetWindowRect(Self.PVP_Info.Handle, rc); //取矩形区域
GetCursorPos(pt); //取得当前鼠标所在位置
if PtInRect(rc, pt) then //如果鼠标不在Self.PVP_Info范围内
begin
// if PV_Main.PageIndex <> 0 then
// begin
// Change.FreezeControlClient(PV_Main, PV_Main.ClientRect);
PV_Main.PageIndex := 0;
// try
// Change.Execute;
// finally
// Change.Restore;
// end;
// end;
// PV_Main.ActivePage := PVP_Control;
end;
GetWindowRect(Self.Handle, rcF); //取矩形区域
GetCursorPos(ptF); //取得当前鼠标所在位置
if PtInRect(rcF, ptF) and (Self.Top =-45) then //如果鼠标在窗体范围内
begin
bo := false;
for i := 9 downto 1 do
begin
Self.Top := Self.Top + i;
Sleep(20);
end;
end;
end;
procedure TFm_MiniBox.WMMouseLeave(var Msg: TMessage);
var
rc, rcF: TRECT;
pt, ptF: TPOINT;
i: Word;
begin
GetWindowRect(Self.PVP_Info.Handle, rc); //取矩形区域
GetCursorPos(pt); //取得当前鼠标所在位置
if (not PtInRect(rc, pt)) then //如果鼠标不在窗体范围内
begin
// if PV_Main.PageIndex <> 1 then
// begin
// Change.FreezeControlClient(PV_Main, PV_Main.ClientRect);
PV_Main.PageIndex := 1;
// try
// Change.Execute;
// finally
// Change.Restore;
// end;
// end;
// PV_Main.ActivePage := PVP_Info;
end;
GetWindowRect(Self.Handle, rcF); //取矩形区域
GetCursorPos(ptF); //取得当前鼠标所在位置
if (not PtInRect(rcF, ptF)) and (Self.Top = 0) then //如果鼠标不在窗体范围内
begin
bo := false;
for i := 1 to 9 do
begin
Self.Top := Self.Top - i;
Sleep(20);
end;
end
else
begin
bo := TRUE;
end;
end;
end.
|
unit MainWindow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, DirectoryServer;
type
TDirectoryWin = class(TForm)
Image1: TImage;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Label3: TLabel;
DirectoryFullName: TEdit;
Label1: TLabel;
SecurePort: TEdit;
Start: TButton;
UnsecuredPort: TEdit;
Label2: TLabel;
SessionTimer: TTimer;
Label4: TLabel;
lbSections: TLabel;
procedure FormCreate(Sender: TObject);
procedure StartClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SessionTimerTimer(Sender: TObject);
private
fSecureDirServer : TDirectoryServer;
fUnsecuredDirServer : TDirectoryServer;
fSessionTTL : TDateTime;
end;
var
DirectoryWin: TDirectoryWin;
implementation
uses
Registry, DirectoryRegistry;
{$R *.DFM}
procedure TDirectoryWin.FormCreate(Sender: TObject);
var
Reg : TRegistry;
begin
fSessionTTL := EncodeTime(0, 5, 0, 0); // 5 Minutes to Live
try
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey( tidRegKey_Directory, false )
then DirectoryFullName.Text := Reg.ReadString( 'FullName' );
finally
Reg.Free;
end;
except
end
end;
procedure TDirectoryWin.StartClick( Sender : TObject );
begin
fSecureDirServer := TDirectoryServer.Create( StrToInt( SecurePort.Text ), DirectoryFullName.Text, true );
fUnsecuredDirServer := TDirectoryServer.Create( StrToInt( UnsecuredPort.Text ), DirectoryFullName.Text, false );
Start.Enabled := false;
if Sender <> self
then Application.Minimize;
end;
procedure TDirectoryWin.FormShow( Sender : TObject );
begin
if uppercase(paramstr(1)) = 'AUTORUN'
then StartClick( self );
end;
procedure TDirectoryWin.SessionTimerTimer(Sender: TObject);
begin
try
lbSections.Caption := IntToStr(fSecureDirServer.SessionCount);
fSecureDirServer.CheckSessions(fSessionTTL);
except
end;
try
fUnsecuredDirServer.CheckSessions(fSessionTTL);
except
end;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit AlarmOptions;
interface
uses SysUtils, IniFiles, classes, Forms, WinTypes, VirtualTable;
var
AlertUseLogFile: Boolean;
AlertLogFileName: string;
AlertRefreshInterval: integer;
AlertShowSystemTrayIcon: boolean;
AlertSentToMail: boolean;
AlertSentToSMS: boolean;
procedure AlertOptionsLoadFromIni;
procedure AlertOptionsSaveToIni;
procedure AlertLogLoadFromFile(vt: TVirtualTable);
procedure AlertLogSaveToFile(vt: TVirtualTable);
implementation
procedure AlertOptionsLoadFromIni;
begin
with TIniFile.create(changefileext(paramstr(0),'.ini')) do
try
AlertUseLogFile := ReadBool('Alarm Options','UseLogFile', False);
AlertLogFileName := ReadString('Alarm Options','LogFile', '');
AlertRefreshInterval := ReadInteger('Alarm Options','RefreshInterval', 200);
AlertShowSystemTrayIcon := ReadBool('Alarm Options','ShowSystemTrayIcon', False);
AlertSentToMail := ReadBool('Alarm Options','SentToMail', False);
AlertSentToSMS := ReadBool('Alarm Options','SentToSMS', False);
finally
free;
end;
end;
procedure AlertOptionsSaveToIni;
begin
with TIniFile.create(changefileext(paramstr(0),'.ini')) do
try
WriteBool('Alarm Options','UseLogFile', AlertUseLogFile);
WriteString('Alarm Options','LogFile', AlertLogFileName);
WriteInteger('Alarm Options','RefreshInterval', AlertRefreshInterval);
WriteBool('Alarm Options','ShowSystemTrayIcon', AlertShowSystemTrayIcon);
WriteBool('Alarm Options','SentToMail', AlertSentToMail);
WriteBool('Alarm Options','SentToSMS', AlertSentToSMS);
finally
free;
end;
end;
procedure AlertLogLoadFromFile(vt: TVirtualTable);
begin
AlertOptionsLoadFromIni;
if FileExists(AlertLogFileName) then
vt.LoadFromFile(AlertLogFileName);
end;
procedure AlertLogSaveToFile(vt: TVirtualTable);
begin
AlertOptionsLoadFromIni;
vt.SaveToFile(AlertLogFileName);
end;
end.
select {+ALL_ROWS } 'Physical I/O',
hash_value,
round(100 * nvl(dsk_reads/sum_disk,0),2) disk_io_pct
from
(select hash_value,
disk_reads dsk_reads
from sys.v_$sqlarea order by 2 desc),
(select sum(disk_reads) sum_disk
from sys.v_$sqlarea where disk_reads > 0)
where rownum < 2
union all
select 'Logical I/O',
hash_value,
round(100 * nvl(log_reads/sum_log,0),2) log_io_pct
from
(select hash_value,
buffer_gets log_reads
from sys.v_$sqlarea order by 2 desc),
(select sum(buffer_gets) sum_log
from sys.v_$sqlarea where buffer_gets > 0)
where rownum < 2
union all
select 'CPU',
hash_value,
round(100 * nvl(cpu/sum_cpu,0),2) cpu_pct
from
(select hash_value,
cpu_time cpu
from sys.v_$sqlarea order by 2 desc),
(select sum(cpu_time) sum_cpu
from sys.v_$sqlarea where cpu_time > 0)
where rownum < 2
union all
select 'Elapsed Time',
hash_value,
round(100 * nvl(etime/sum_etime,0),2) etime_pct
from
(select hash_value,
elapsed_time etime
from sys.v_$sqlarea order by 2 desc),
(select sum(elapsed_time) sum_etime
from sys.v_$sqlarea where elapsed_time > 0)
where rownum < 2;
SELECT
ms_ratio_num,
ms_ratio_den,
100*( ROUND( ( ms_ratio_num/ms_ratio_den ), 4 ) ) ms_ratio,
TO_NUMBER( DECODE( 0, NULL, 0, 100*( ROUND( ( ms_ratio_num - 0 )/ ( DECODE( (ms_ratio_den - 0 ), 0, 1, ( ms_ratio_den - 0 ) ) ), 4 ) ) ) ) ms_delta_ratio,
pe_ratio_num,
pe_ratio_den,
100*( ROUND( ( pe_ratio_num/pe_ratio_den ), 4 ) ) pe_ratio,
TO_NUMBER( DECODE( 237902, NULL, 0, 100*( ROUND( ( pe_ratio_num - 237854 )/ ( DECODE( (pe_ratio_den - 237902 ), 0, 1, ( pe_ratio_den -237902 ) ) ), 4 ) ) ) ) pe_delta_ratio,
cpup_ratio_num,
cpup_ratio_den,
100*( ROUND( ( cpup_ratio_num/cpup_ratio_den ), 4 ) ) cpup_ratio,
TO_NUMBER( DECODE( 868895, NULL, 0, 100*( ROUND( ( cpup_ratio_num - 833232 )/ ( DECODE( (cpup_ratio_den - 868895 ), 0, 1, ( cpup_ratio_den - 868895 ) ) ), 4 ) ) ) ) cpup_delta_ratio
FROM
(SELECT b.VALUE ms_ratio_num,
DECODE ((a.VALUE + b.VALUE), 0, 1, (a.VALUE + b.VALUE)) ms_ratio_den
FROM v$sysstat a, v$sysstat b
WHERE a.name = 'sorts (disk)' AND b.name = 'sorts (memory)' ),
(SELECT ( a.VALUE - b.VALUE) pe_ratio_num,
DECODE (a.VALUE, 0, 1, a.VALUE) pe_ratio_den
FROM sys.v_$sysstat a, sys.v_$sysstat b
WHERE a.name = 'execute count' AND b.name = 'parse count (hard)'),
(SELECT pc.value cpup_ratio_num,
DECODE( ec.value, 0, 1, ec.value ) cpup_ratio_den
FROM sys.v_$sysstat ec,
sys.v_$sysstat pc
WHERE ec.name='CPU used by this session' and pc.name='parse time cpu')
select active_sessions,
inactive_sessions,
open_cursors,
commits,
rollbacks,
sessions_blocked,
sessions_waiting,
sessions_in_disk_sorts,
sessions_in_enqueue_waits
from
(SELECT count(*) active_sessions
FROM SYS.V_$SESSION
WHERE USERNAME IS NOT NULL AND
STATUS = 'ACTIVE' ),
(SELECT count(*) inactive_sessions
FROM SYS.V_$SESSION
WHERE USERNAME IS NOT NULL AND
STATUS <> 'ACTIVE' ),
(SELECT COUNT(*) open_cursors
FROM SYS.V_$OPEN_CURSOR),
(select value commits
from sys.v_$sysstat
where name = 'user commits'),
(select value rollbacks
from sys.v_$sysstat
where name = 'user rollbacks'),
(SELECT count(*) sessions_blocked
FROM SYS.V_$SESSION
WHERE LOCKWAIT IS NOT NULL),
(SELECT count(*) sessions_waiting
FROM sys.v_$session_wait
WHERE event NOT IN
('lock element cleanup',
'pmon timer',
'rdbms ipc message',
'smon timer',
'SQL*Net message from client',
'SQL*Net break/reset to client',
'SQL*Net message to client',
'dispatcher timer',
'Null event',
'parallel query dequeue wait',
'parallel query idle wait - Slaves',
'pipe get',
'PL/SQL lock timer',
'slave wait',
'virtual circuit status',
'WMON goes to sleep')),
(SELECT COUNT(*) sessions_in_disk_sorts
FROM SYS.V_$SORT_USAGE),
(select nvl(count(sid),0) sessions_in_enqueue_waits
from sys.v_$session_wait a,
sys.v_$event_name b
where a.event = 'enqueue' and
a.event (+) = b.name);
SELECT SID,
USERNAME,
ROUND(100 * TOTAL_USER_IO/TOTAL_IO,2)
FROM
(SELECT b.SID SID,
nvl(b.USERNAME,p.NAME) USERNAME,
sum(VALUE) TOTAL_USER_IO
FROM sys.V_$STATNAME c,
sys.V_$SESSTAT a,
sys.V_$SESSION b,
sys.v_$bgprocess p
WHERE a.STATISTIC#=c.STATISTIC# and
p.paddr (+) = b.paddr and
b.SID=a.SID AND
c.NAME in ('physical reads','physical writes')
GROUP BY b.SID, nvl(b.USERNAME,p.name)
ORDER BY 3 DESC),
(select sum(value) TOTAL_IO
from sys.V_$STATNAME c,
sys.V_$SESSTAT a
WHERE a.STATISTIC#=c.STATISTIC# and
c.NAME in ('physical reads','physical writes'))
WHERE ROWNUM < 6;
SELECT percent_shared_pool_free,
buffer_busy_waits,
free_buffer_wait_avg,
object_reloads,
redo_log_space_waits,
redo_log_space_wait_time,
db_size_in_mb - db_caches db_buffers_in_mb,
db_caches,
fixed_size_in_mb,
lb_size_in_mb,
sp_size_in_mb,
lp_size_in_mb,
jp_size_in_mb
FROM
(SELECT ROUND (100 * (free_bytes / shared_pool_size), 2)
percent_shared_pool_free
FROM (SELECT SUM (bytes) free_bytes
FROM sys.v_$sgastat
WHERE name = 'free memory'
AND pool = 'shared pool'),
(SELECT SUM(bytes) shared_pool_size
FROM sys.v_$sgastat d
WHERE d.pool = 'shared pool')),
(select nvl(sum(total_waits),0) buffer_busy_waits
from sys.v_$system_event a,
sys.v_$event_name b
where a.event = 'buffer busy waits' and
a.event (+) = b.name),
(select (round((a.value / b.value),3)) free_buffer_wait_avg
from sys.v_$sysstat a,
sys.v_$sysstat b
where a.name = 'free buffer inspected' and
b.name = 'free buffer requested'),
(select sum(reloads) object_reloads
from sys.v_$librarycache),
(select value redo_log_space_waits
from sys.v_$sysstat
where name = 'redo log space requests'),
(select value redo_log_space_wait_time
from sys.v_$sysstat
where name = 'redo log space wait time'),
(SELECT NVL(ROUND (MAX(a.bytes) / 1024 / 1024, 2),0) db_size_in_mb
FROM sys.v_$sgastat a
WHERE (a.name = 'db_block_buffers' or a.name = 'buffer_cache')),
(SELECT NVL(ROUND (SUM (b.value) / 1024 / 1024, 2),0) db_caches
FROM sys.v_$parameter b
WHERE b.name like '%k_cache_size'),
(SELECT ROUND ( NVL( SUM(b.bytes), 0 ) / 1024 / 1024, 2) fixed_size_in_mb
FROM sys.v_$sgastat b
WHERE b.name = 'fixed_sga'),
(SELECT ROUND ( NVL( SUM(c.bytes), 0 ) / 1024 / 1024, 2) lb_size_in_mb
FROM sys.v_$sgastat c
WHERE c.name= 'log_buffer' ),
(SELECT ROUND ( NVL( SUM(d.bytes), 0 ) / 1024 / 1024, 2) sp_size_in_mb
FROM sys.v_$sgastat d
WHERE d.pool = 'shared pool' ),
(SELECT ROUND ( NVL( SUM(d.bytes), 0 ) / 1024 / 1024, 2) lp_size_in_mb
FROM sys.v_$sgastat d
WHERE d.pool = 'large pool' ),
(SELECT ROUND ( NVL( SUM(d.bytes), 0 ) / 1024 / 1024, 2) jp_size_in_mb
FROM sys.v_$sgastat d
WHERE d.pool = 'java pool' );
select total_chained_objects,
objects_at_max_extents,
objects_no_room_expand,
invalid_objects,
tabs_idx_same_ts,
locked_objects,
object_blocks,
free_list_waits,
enqueue_waits
from
(select chained_row_tables + chained_part_tables + chained_subpart_tables total_chained_objects
from
(select count(*) chained_row_tables
from sys.tab$
where chncnt > 0),
(select count(*) chained_part_tables
from sys.tabpart$
where chncnt > 0),
(select count(*) chained_subpart_tables
from sys.tabsubpart$
where chncnt > 0)),
(SELECT COUNT(*) objects_at_max_extents
FROM SYS.SEG$
WHERE (EXTENTS = MAXEXTS AND MAXEXTS > 0)),
(SELECT count(*) objects_no_room_expand
FROM sys.seg$ s, sys.ts$ ts
WHERE s.ts# = ts.ts# AND
DECODE(BITAND(ts.flags, 3), 1, TO_NUMBER(NULL), s.extsize * ts.blocksize) > (SELECT nvl(MAX(bytes),0)
FROM sys.dba_free_space a, sys.ts$ b
WHERE b.name = a.tablespace_name (+)
AND b.ts# = ts.ts#)),
(SELECT COUNT(*) invalid_objects
FROM SYS.OBJ$
WHERE STATUS NOT IN (0,1)),
(SELECT {+ ALL_ROWS ORDERED CLUSTER(T) CLUSTER(I) STAR_TRANSFORMATION USE_HASH(O,T,I) }
COUNT(*) tabs_idx_same_ts
FROM SYS.OBJ$ O,
SYS.TAB$ T,
SYS.IND$ I
WHERE O.OBJ# = T.OBJ#
AND I.BO# = O.OBJ#
AND I.TS# = T.TS#
AND T.TS# <> 0
AND I.TS# <> 0
AND O.OWNER# IN
(SELECT {+ CLUSTER() PUSH_SUBQ }
USER#
FROM SYS.USER$
WHERE NAME NOT IN ('SYS','SYSTEM','OUTLN', 'XDB'))),
(SELECT COUNT(*) locked_objects
FROM SYS.V_$LOCKED_OBJECT),
(SELECT count(*) object_blocks
FROM SYS.V_$SESSION
WHERE LOCKWAIT IS NOT NULL),
(SELECT COUNT free_list_waits
FROM SYS.V_$WAITSTAT
WHERE CLASS='free list'),
(select nvl(count(sid),0) enqueue_waits
from sys.v_$session_wait a,
sys.v_$event_name b
where a.event = 'enqueue' and
a.event (+) = b.name);
select objects_at_max_extents,
objects_no_room_to_expand,
autoextend_at_limit,
offline_tablespaces,
redo_bytes,
redo_wastage
from
(SELECT COUNT(*) objects_at_max_extents
FROM SYS.SEG$
WHERE (EXTENTS = MAXEXTS AND MAXEXTS > 0)),
(SELECT count(*) objects_no_room_to_expand
FROM sys.seg$ s, sys.ts$ ts
WHERE s.ts# = ts.ts# AND
DECODE(BITAND(ts.flags, 3), 1, TO_NUMBER(NULL), s.extsize * ts.blocksize) > (SELECT nvl(MAX(bytes),0)
FROM sys.dba_free_space a, sys.ts$ b
WHERE b.name = a.tablespace_name (+)
AND b.ts# = ts.ts#)),
(select count(*) autoextend_at_limit
from sys.file$ f,
sys.ts$ ts
where f.ts# = ts.ts# and
f.inc > 0 and
ts.blocksize * f.blocks = ts.blocksize * f.maxextend),
(SELECT COUNT (*) offline_tablespaces
FROM sys.dba_tablespaces
WHERE status not in ('ONLINE', 'READ ONLY')),
(SELECT VALUE redo_bytes
FROM SYS.V_$SYSSTAT
WHERE UPPER(NAME)='REDO SIZE'),
(SELECT VALUE redo_wastage
FROM SYS.V_$SYSSTAT
WHERE NAME = 'redo wastage');
SELECT percent_shared_pool_free,
problem_tablespaces,
problem_objects,
current_object_blocks,
enqueue_waits,
free_list_waits,
total_used_space,
total_free_space,
archive_log,
active_processes,
inactive_processes
FROM
(SELECT ROUND (100 * (free_bytes / shared_pool_size), 2) percent_shared_pool_free
FROM
(SELECT SUM(bytes) free_bytes FROM sys.v_$sgastat WHERE name = 'free memory'AND pool = 'shared pool' ),
(SELECT SUM(bytes) shared_pool_size from sys.v_$sgastat d where d.pool = 'shared pool' )),
(SELECT CNT_PERM + CNT_TEMP problem_tablespaces FROM
(SELECT COUNT(*) CNT_PERM FROM
(select round((100*Sum_Free_Blocks /
Sum_Alloc_Blocks),2) PCT_FREE
from
(select Tablespace_Name,
SUM(Blocks) Sum_Alloc_Blocks,
NVL(sum(bytes),0) AS Total_space
from DBA_DATA_FILES
group by Tablespace_Name),
(select B.Tablespace_Name FS_TS_NAME,
NVL(sum(bytes),0) as Total_Free_Space,
NVL(SUM(Blocks),0) AS Sum_Free_Blocks
from DBA_FREE_SPACE A, DBA_TABLESPACES B
WHERE A.TABLESPACE_NAME (+) = B.TABLESPACE_NAME
group by B.Tablespace_Name)
where Tablespace_Name = FS_TS_NAME)
WHERE PCT_FREE < 10),
(SELECT COUNT(*) CNT_TEMP FROM
(SELECT (100 -(NVL(t.bytes /a.bytes * 100, 0))) PCT_FREE
FROM sys.dba_tablespaces d,
(select tablespace_name,
sum(bytes) bytes
from dba_temp_files
group by tablespace_name) a,
(select tablespace_name,
sum(bytes_cached) bytes
from SYS.v_$temp_extent_pool
group by tablespace_name)t
WHERE d.tablespace_name = a.tablespace_name(+) AND
d.tablespace_name = t.tablespace_name(+) AND
d.extent_management like 'LOCAL' AND d.contents like 'TEMPORARY')
WHERE PCT_FREE < 10)),
(SELECT EXT_PBM + NEXT_PBM problem_objects
FROM
(SELECT COUNT(*) EXT_PBM
FROM SYS.SEG$
WHERE (EXTENTS = MAXEXTS AND MAXEXTS > 0) OR
(MAXEXTS - 2 = EXTENTS AND MAXEXTS > 0)),
(SELECT COUNT(*) NEXT_PBM
FROM SYS.SEG$ S,
SYS.TS$ TS
WHERE S.TS# = TS.TS# AND
DECODE(BITAND(TS.FLAGS, 3), 1, TO_NUMBER(NULL),
S.EXTSIZE * TS.BLOCKSIZE) >
(SELECT MAX(BYTES)
FROM SYS.DBA_FREE_SPACE A
WHERE TS.NAME = A.TABLESPACE_NAME ))),
(SELECT count(*) current_object_blocks
FROM SYS.V_$SESSION
WHERE LOCKWAIT IS NOT NULL),
(select nvl(count(sid),0) enqueue_waits
from sys.v_$session_wait a,
sys.v_$event_name b
where a.event = 'enqueue' and
a.event (+) = b.name),
(SELECT COUNT free_list_waits
FROM SYS.V_$WAITSTAT WHERE CLASS='free list'),
(SELECT round(((total_space_perm + nvl(total_space_temp,0)) -
(total_free_space_perm + nvl(total_free_space_temp,0)))/1048576,2) total_used_space,
ROUND((total_free_space_perm + nvl(total_free_space_temp,0)) / 1048576,2) total_free_space
FROM
(SELECT SUM(bytes) AS total_space_perm FROM SYS.DBA_DATA_FILES),
(SELECT SUM(bytes) AS total_space_temp FROM SYS.DBA_TEMP_FILES),
(SELECT SUM(bytes) AS total_free_space_perm FROM SYS.DBA_FREE_SPACE),
(SELECT SUM(bytes_cached) AS total_free_space_temp from SYS.v_$temp_extent_pool)),
(select decode(log_mode,'NOARCHIVELOG','No','Yes') archive_log from SYS.v_$database),
(SELECT count(*) active_processes
FROM SYS.V_$SESSION
WHERE USERNAME IS NOT NULL AND
STATUS = 'ACTIVE'),
(SELECT count(*) inactive_processes
FROM SYS.V_$SESSION
WHERE USERNAME IS NOT NULL AND
STATUS <> 'ACTIVE');
|
/// <summary>
/// implements utility functions for file accesss
/// This is an extract from u_dzFileUtils in dzlib http://blog.dummzeuch.de/dzlib/ </summary>
unit GX_dzFileUtils;
{$I GX_CondDefine.inc}
{$IFDEF GX_VER200_up}
{$DEFINE SUPPORTS_UNICODE_STRING}
{$ENDIF}
{$WARN UNIT_PLATFORM OFF}
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows,
SysUtils,
Classes;
const
/// <summary>
/// set of char constant containing all characters that are invalid in a filename </summary>
INVALID_FILENAME_CHARS: set of AnsiChar = ['\', '/', ':', '*', '?', '"', '<', '>', '|'];
type
TFileSystem = class
public
class function ExpandFileNameRelBaseDir(const _FileName, _BaseDir: string): string;
///<summary>
/// Replaces all invalid characters in the file name with the given character </summary>
/// @param S is the input filename
/// @param ReplaceChar is the character to use for replacing in valid characters
/// defaults to '_'
/// @param AllowPathChars determines whether the name may contain '\' characters and a single
/// ':' as the second character, so a full path can be converted.
/// @returns a valid filename </summary>
class function MakeValidFilename(const _s: string; _ReplaceChar: Char = '_'; _AllowPathChars: Boolean = True): string;
end;
type
TFileAttributes = (
dfaReadonly,
dfaHidden, // Hidden files
dfaSysFile, // System files
dfaDirectory, // Directory files
dfaArchive // Archive files
);
TFileAttributeSet = set of TFileAttributes;
const
ALL_FILES_ATTRIB_SET = [dfaHidden, dfaSysFile, dfaDirectory, dfaArchive];
type
TFileInfoRec = record
Filename: string;
Size: Int64;
Timestamp: TDateTime;
end;
type
/// <summary>
/// a simple wrapper around FindFirst/FindNext which allows to search for
/// specified attributes only (e.g. only directories), it automatically
/// ignores the special '.' and '..' directories. </summary>
TSimpleDirEnumerator = class
protected
/// stores the search mask ('c:\windows\*.exe')
FMask: string;
/// set of attributes a file must match
FMustHaveAttr: TFileAttributeSet;
/// set of attributes a file may have
FMayHaveAttr: TFileAttributeSet;
/// internally used TSearchRec structure
FSr: TSearchRec;
/// true if FindFirst was called and returned no error code
FActive: Boolean;
/// number of matching files found
FMatchCount: Integer;
public
/// <summary>
/// Creates a TSimpleDirEnumerator, sets the Mask, MustHaveAttr and MayHaveAttr
/// properties.
/// MustHaveAttr is set to [] and MayHaveAttr is set to include all possible
/// attributes, so calling FindNext will find any files or subdirectories,
/// but the special '.' and '..' directories
/// @param Mask is the file search mask and should include a path </summary>
constructor Create(const _Mask: string; _MayHaveAttr: TFileAttributeSet = ALL_FILES_ATTRIB_SET);
/// <summary>
/// Destructor, will call FindClose if necessary </summary>
destructor Destroy; override;
/// <summary>
/// creates a TSimpleDirEnumerator, calls its FindAll method and frees it
/// @param IncludePath determines whether the List of filenames includes the full path or not </summary>
class function Execute(const _Mask: string; _List: TStrings;
_MayHaveAttr: TFileAttributeSet = ALL_FILES_ATTRIB_SET; _IncludePath: Boolean = False; _Sort: Boolean = True): Integer;
class function EnumFilesOnly(const _Mask: string; _List: TStrings;
_IncludePath: Boolean = False; _Sort: Boolean = True): Integer;
class function EnumDirsOnly(const _Mask: string; _List: TStrings;
_IncludePath: Boolean = False; _Sort: Boolean = True): Integer;
/// <summary>
/// Calls SysUtils.FindFirst on first call and SysUtls.FindNext in later
/// calls.
/// @param Filename is the name of the file found, if result is true, if you need
/// more information about it, use the SR property, note that it
/// does not include the path
/// @param IncludePath determines whether the List of filenames includes the full path or not
/// defaults to false
/// @Returns true, if a matching file was found, false otherwise </summary>
function FindNext(out _FileName: string; _IncludePath: Boolean = False): Boolean; overload;
/// <summary>
/// Calls SysUtils.FindFirst on first call and SysUtls.FindNext in later
/// calls. If it returns true, use the SR property to get information about
/// the file. See the overloaded @link(FindNext) version if you need only
/// the filename.
/// @Returns true, if a matching file was found, false otherwise </summary>
function FindNext: Boolean; overload;
/// <summary>
/// Calls FindNext until it returns false, stores all filenames in List and
/// returns the number of files found.
/// @param List is a TStrings object which will be filled with the filenames
/// of matching files, may be nil.
/// @param IncludePath determines whether the List of filenames includes the full path or not
/// @returns the number of matching files </summary>
function FindAll(_List: TStrings = nil; _IncludePath: Boolean = False): Integer;
/// <summary>
/// Calls FindClose so FindNext will start again. Reset does not change any
/// properties (e.g. Mask, MustHaveAttr, MayHaveAttr) </summary>
procedure Reset;
/// <summary>
/// Returns the number of matches so far, that is the number of successful
/// calls to FindNext. </summary>
property MatchCount: Integer read FMatchCount;
/// <summary>
/// Returns the search mask </summary>
property Mask: string read FMask; // write fMask;
/// <summary>
/// the set of attributes a file must have to be found by FindNext </summary>
property MustHaveAttr: TFileAttributeSet read FMustHaveAttr write FMustHaveAttr;
/// <summary>
/// the set of allowed attributes for a file to be found by FindNext </summary>
property MayHaveAttr: TFileAttributeSet read FMayHaveAttr write FMayHaveAttr;
/// <summary>
/// the search rec containing additional information about the file </summary>
property Sr: TSearchRec read FSr;
end;
implementation
{ TSimpleDirEnumerator }
constructor TSimpleDirEnumerator.Create(const _Mask: string;
_MayHaveAttr: TFileAttributeSet = ALL_FILES_ATTRIB_SET);
begin
FMask := _Mask;
FMustHaveAttr := [];
FMayHaveAttr := _MayHaveAttr;
end;
destructor TSimpleDirEnumerator.Destroy;
begin
Reset;
inherited;
end;
class function TSimpleDirEnumerator.EnumDirsOnly(const _Mask: string; _List: TStrings;
_IncludePath, _Sort: Boolean): Integer;
var
enum: TSimpleDirEnumerator;
List: TStringList;
begin
enum := TSimpleDirEnumerator.Create(_Mask, [dfaDirectory, dfaArchive]);
try
enum.MustHaveAttr := [dfaDirectory];
List := TStringList.Create;
try
Result := enum.FindAll(List, _IncludePath);
if _Sort then
List.Sort;
_List.AddStrings(List);
finally
FreeAndNil(List);
end;
finally
FreeAndNil(enum);
end;
end;
class function TSimpleDirEnumerator.EnumFilesOnly(const _Mask: string; _List: TStrings;
_IncludePath, _Sort: Boolean): Integer;
begin
Result := Execute(_Mask, _List, [dfaArchive], _IncludePath, _Sort);
end;
class function TSimpleDirEnumerator.Execute(const _Mask: string; _List: TStrings;
_MayHaveAttr: TFileAttributeSet = ALL_FILES_ATTRIB_SET;
_IncludePath: Boolean = False; _Sort: Boolean = True): Integer;
var
enum: TSimpleDirEnumerator;
List: TStringList;
begin
enum := TSimpleDirEnumerator.Create(_Mask, _MayHaveAttr);
try
List := TStringList.Create;
try
Result := enum.FindAll(List, _IncludePath);
if _Sort then
List.Sort;
_List.AddStrings(List);
finally
FreeAndNil(List);
end;
finally
FreeAndNil(enum);
end;
end;
function TSimpleDirEnumerator.FindAll(_List: TStrings = nil; _IncludePath: Boolean = False): Integer;
var
s: string;
Path: string;
begin
if _IncludePath then
Path := ExtractFilePath(FMask)
else
Path := '';
Result := 0;
while FindNext(s) do begin
Inc(Result);
if Assigned(_List) then
_List.Add(Path + s);
end;
end;
function TSimpleDirEnumerator.FindNext(out _FileName: string; _IncludePath: Boolean = False): Boolean;
var
Res: Integer;
Attr: Integer;
function AttrOk(_EnumAttr: TFileAttributes; _SysAttr: Integer): Boolean;
begin
Result := True;
if _EnumAttr in FMustHaveAttr then
if (Attr and _SysAttr) = 0 then
Result := False;
end;
procedure CondAddAttr(_EnumAttr: TFileAttributes; _SysAttr: Integer);
begin
if _EnumAttr in FMayHaveAttr then
Attr := Attr + _SysAttr;
end;
var
Path: string;
begin
Path := ExtractFilePath(FMask);
repeat
if not FActive then begin
FMatchCount := 0;
Attr := 0;
CondAddAttr(dfaReadonly, SysUtils.faReadOnly);
CondAddAttr(dfaHidden, SysUtils.faHidden);
CondAddAttr(dfaSysFile, SysUtils.faSysFile);
CondAddAttr(dfaDirectory, SysUtils.faDirectory);
CondAddAttr(dfaArchive, SysUtils.faArchive);
Res := FindFirst(FMask, Attr, FSr);
Result := (Res = 0);
if Result then
FActive := True;
end else begin
Res := SysUtils.FindNext(FSr);
Result := (Res = 0);
end;
if not Result then
Exit;
if (Sr.Name = '.') or (Sr.Name = '..') then
Continue;
if FMustHaveAttr <> [] then begin
Attr := FSr.Attr;
if not AttrOk(dfaReadonly, SysUtils.faReadOnly) then
Continue;
if not AttrOk(dfaHidden, SysUtils.faHidden) then
Continue;
if not AttrOk(dfaSysFile, SysUtils.faSysFile) then
Continue;
if not AttrOk(dfaDirectory, SysUtils.faDirectory) then
Continue;
if not AttrOk(dfaArchive, SysUtils.faArchive) then
Continue;
end;
Inc(FMatchCount);
if _IncludePath then
_FileName := Path + Sr.Name
else
_FileName := Sr.Name;
Exit;
until False;
end;
function TSimpleDirEnumerator.FindNext: Boolean;
var
s: string;
begin
Result := FindNext(s);
end;
procedure TSimpleDirEnumerator.Reset;
begin
if FActive then
FindClose(FSr);
FActive := False;
end;
{ TFileSystem }
const
shlwapi32 = 'shlwapi.dll';
function PathIsRelative(pszPath: PChar): BOOL; stdcall; external shlwapi32
{$IFDEF GX_VER200_up}
name 'PathIsRelativeW';
{$ELSE}
name 'PathIsRelativeA';
{$ENDIF}
function PathCanonicalize(pszBuf: PChar; pszPath: PChar): BOOL; stdcall; external shlwapi32
{$IFDEF GX_VER200_up}
name 'PathCanonicalizeW';
{$ELSE}
name 'PathCanonicalizeA';
{$ENDIF}
// taken from
// http://stackoverflow.com/a/5330691/49925
class function TFileSystem.ExpandFileNameRelBaseDir(const _FileName, _BaseDir: string): string;
var
Buffer: array[0..MAX_PATH - 1] of Char;
begin
if PathIsRelative(PChar(_FileName)) then begin
Result := IncludeTrailingPathDelimiter(_BaseDir) + _FileName;
end else begin
Result := _FileName;
end;
if PathCanonicalize(@Buffer[0], PChar(Result)) then begin
Result := Buffer;
end;
end;
{$IFNDEF SUPPORTS_UNICODE_STRING}
function CharInSet(_c: Char; const _CharSet: TSysCharSet): Boolean;
begin
Result := _c in _CharSet;
end;
{$ENDIF ~SUPPORTS_UNICODE_STRING}
class function TFileSystem.MakeValidFilename(const _s: string; _ReplaceChar: Char = '_';
_AllowPathChars: Boolean = True): string;
var
i: Integer;
InvalidChars: set of AnsiChar;
begin
Result := _s;
InvalidChars := INVALID_FILENAME_CHARS;
if _AllowPathChars then
InvalidChars := InvalidChars - ['\'];
for i := 1 to Length(Result) do begin
if CharInSet(Result[i], InvalidChars) then begin
if not _AllowPathChars or (i <> 2) or (Result[2] <> ':') or not CharInSet(UpCase(Result[1]), ['A'..'Z']) then
Result[i] := _ReplaceChar;
end;
end;
end;
end.
|
unit u_GeoCacherCache;
interface
uses
Classes,
SysUtils;
const
CFakeVersion = $2020;
type
TGeoCacherDbRootCache = class
private
FRootPath: string;
function DoPatchProto(const AFileName: string): Cardinal;
function DoPatchXml(const AFileName: string): Cardinal;
procedure DoUpdateIni(const AFileName: string; const ACrc32: Cardinal);
public
function PatchAll: Integer;
public
constructor Create(const ARootPath: string);
end;
implementation
uses
IniFiles,
libcrc32,
libge.dbroot;
{ TGeoCacherDbRootCache }
constructor TGeoCacherDbRootCache.Create(const ARootPath: string);
begin
inherited Create;
FRootPath := IncludeTrailingPathDelimiter(ARootPath) + 'cache\dbroot\earth';
end;
function TGeoCacherDbRootCache.PatchAll: Integer;
var
VPath: string;
VName: string;
VCrc32: Cardinal;
VSearch: TSearchRec;
begin
Result := 0;
VPath := IncludeTrailingPathDelimiter(FRootPath);
if FindFirst(VPath + '*.ini', faAnyFile - faDirectory, VSearch) = 0 then
try
repeat
VName := VPath + ChangeFileExt(VSearch.Name, '');
if FileExists(VName) then begin
if Pos('output=proto', LowerCase(VName)) > 0 then begin
VCrc32 := DoPatchProto(VName);
end else begin
VCrc32 := DoPatchXml(VName);
end;
if VCrc32 <> 0 then begin
DoUpdateIni(VName + '.ini', VCrc32);
Inc(Result);
end;
end else begin
Assert(False, 'Can''t locate dbRoot for ini: ' + VName + '.ini');
//DeleteFile(VName + '.ini');
end;
until FindNext(VSearch) <> 0;
finally
FindClose(VSearch);
end;
end;
function TGeoCacherDbRootCache.DoPatchProto(const AFileName: string): Cardinal;
var
VStr: string_t;
VRoot: dbroot_t;
VStream: TMemoryStream;
VIsPatched: Boolean;
begin
Result := 0;
VIsPatched := False;
VStream := TMemoryStream.Create;
try
VStream.LoadFromFile(AFileName);
if dbroot_open(VStream.Memory, VStream.Size, VRoot) then begin
try
if dbroot_set_quadtree_version(CFakeVersion, VRoot) then begin
if dbroot_pack(VStr, VRoot) then begin
VStream.Clear;
VStream.WriteBuffer(VStr.data^, VStr.size);
VIsPatched := True;
end else begin
Assert(False, string(VRoot.error));
end;
end else begin
Assert(False, string(VRoot.error));
end;
finally
if not dbroot_close(VRoot) then begin
Assert(False, string(VRoot.error));
end;
end;
end else begin
Assert(False, string(VRoot.error));
end;
if VIsPatched then begin
Result := crc32(0, VStream.Memory, VStream.Size);
VStream.SaveToFile(AFileName);
end;
finally
VStream.Free;
end;
end;
type
TXmlDbRootHeader = packed record
MagicId: Cardinal;
Unknown: Word;
Version: Word;
end;
PXmlDbRootHeader = ^TXmlDbRootHeader;
const
CXmlDbRootMagic = $4E876494;
function TGeoCacherDbRootCache.DoPatchXml(const AFileName: string): Cardinal;
var
VHeader: PXmlDbRootHeader;
VStream: TMemoryStream;
VIsPatched: Boolean;
begin
Result := 0;
VIsPatched := False;
VStream := TMemoryStream.Create;
try
VStream.LoadFromFile(AFileName);
if VStream.Size > SizeOf(TXmlDbRootHeader) then begin
VHeader := PXmlDbRootHeader(VStream.Memory);
if VHeader.MagicId = CXmlDbRootMagic then begin
VHeader.Version := $4200 xor CFakeVersion;
VIsPatched := True;
end;
end;
if VIsPatched then begin
Result := crc32(0, VStream.Memory, VStream.Size);
VStream.SaveToFile(AFileName);
end;
finally
VStream.Free;
end;
end;
procedure TGeoCacherDbRootCache.DoUpdateIni(const AFileName: string; const ACrc32: Cardinal);
var
VIniFile: TMemIniFile;
begin
VIniFile := TMemIniFile.Create(AFileName);
try
VIniFile.WriteString('Main', 'CRC32', '$' + IntToHex(ACrc32, 8));
VIniFile.DeleteKey('Main', 'LastModified');
VIniFile.UpdateFile;
finally
VIniFile.Free;
end;
end;
end.
|
{***********************************************************************}
{ TAdvCurve component }
{ for Delphi & C++Builder }
{ }
{ written by }
{ TMS Software }
{ Copyright © 2013 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{***********************************************************************}
unit AdvCurveRegDE;
interface
{$I TMSDEFS.INC}
uses
Classes, AdvCurve, AdvCurveDE, AdvCurveEditor
{$IFDEF DELPHI6_LVL}
, DesignIntf, DesignEditors
{$ELSE}
, DsgnIntf
{$ENDIF}
;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('TMS Misc', [TAdvCurveEditorDialog]);
RegisterPropertyEditor(TypeInfo(TCurvePoints),TAdvCurve,'Points',TCurvePointsProperty);
RegisterComponentEditor(TAdvCurve, TCurveEditor);
end;
end.
|
unit fmuEJReportPrint;
interface
uses
// VCL
Controls, StdCtrls, ExtCtrls, ComCtrls, Classes, SysUtils, Graphics,
// This
untPages, untUtil, untDriver, Spin;
type
{ TfmEKLZReportInRange }
TfmEJReportPrint = class(TPage)
lblDepartment: TLabel;
lblStartDate: TLabel;
dtpStartDate: TDateTimePicker;
lblEndDate: TLabel;
dtpEndDate: TDateTimePicker;
btnEKLZDepartmentReportInDatesRange: TButton;
btnEKLZSessionReportInDatesRange: TButton;
lblFirstSessionNumber: TLabel;
lblLastSessionNumber: TLabel;
btnEKLZDepartmentReportInSessionsRange: TButton;
btnEKLZSessionReportInSessionsRange: TButton;
cbReportType: TComboBox;
lblReportType: TLabel;
btnInterruptPrint: TButton;
seDepartment: TSpinEdit;
seFirstSessionNumber: TSpinEdit;
seLastSessionNumber: TSpinEdit;
procedure btnEKLZDepartmentReportInDatesRangeClick(Sender: TObject);
procedure btnEKLZDepartmentReportInSessionsRangeClick(Sender: TObject);
procedure btnEKLZSessionReportInDatesRangeClick(Sender: TObject);
procedure btnEKLZSessionReportInSessionsRangeClick(Sender: TObject);
procedure btnInterruptPrintClick(Sender: TObject);
end;
implementation
{$R *.DFM}
{ TfmEKLZReportInRange }
procedure TfmEJReportPrint.btnEKLZDepartmentReportInDatesRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ReportType := cbReportType.ItemIndex > 0;
Driver.Department := seDepartment.Value;
Driver.FirstSessionDate := dtpStartDate.Date;
Driver.LastSessionDate := dtpEndDate.Date;
Driver.EKLZDepartmentReportInDatesRange;
finally
EnableButtons(True);
end;
end;
procedure TfmEJReportPrint.btnEKLZDepartmentReportInSessionsRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ReportType := cbReportType.ItemIndex > 0;
Driver.Department := seDepartment.Value;
Driver.FirstSessionNumber := seFirstSessionNumber.Value;
Driver.LastSessionNumber := seLastSessionNumber.Value;
Driver.EKLZDepartmentReportInSessionsRange;
finally
EnableButtons(True);
end;
end;
procedure TfmEJReportPrint.btnEKLZSessionReportInDatesRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ReportType := cbReportType.ItemIndex > 0;
Driver.FirstSessionDate := dtpStartDate.Date;
Driver.LastSessionDate := dtpEndDate.Date;
Driver.EKLZSessionReportInDatesRange;
finally
EnableButtons(True);
end;
end;
procedure TfmEJReportPrint.btnEKLZSessionReportInSessionsRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ReportType := cbReportType.ItemIndex > 0;
Driver.FirstSessionNumber := seFirstSessionNumber.Value;
Driver.LastSessionNumber := seLastSessionNumber.Value;
Driver.EKLZSessionReportInSessionsRange;
finally
EnableButtons(True);
end;
end;
procedure TfmEJReportPrint.btnInterruptPrintClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.StopEKLZDocumentPrinting;
finally
EnableButtons(True);
end;
end;
end.
|
unit blitter_williams;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
main_engine,cpu_misc,m6809;
type
williams_blitter=class
constructor create(xor_:byte;window_enable:boolean;clip_address:word);
destructor free;
public
procedure reset;
procedure blitter_w(dir,valor:byte);
procedure set_read_write(getbyte:tgetbyte;putbyte:tputbyte);
private
ram:array[0..7] of byte;
xor_:byte;
remap:array[0..$ffff] of byte;
window_enable:boolean;
clip_address:word;
getbyte:tgetbyte;
putbyte:tputbyte;
procedure blit_pixel(dstaddr,srcdata:word);
function blitter_core(sstart,dstart:word;w,h:byte):byte;
end;
const
CONTROLBYTE_NO_EVEN=$80;
CONTROLBYTE_NO_ODD=$40;
CONTROLBYTE_SHIFT=$20;
CONTROLBYTE_SOLID=$10;
CONTROLBYTE_FOREGROUND_ONLY=8;
CONTROLBYTE_SLOW=4; //2us blits instead of 1us
CONTROLBYTE_DST_STRIDE_256=2;
CONTROLBYTE_SRC_STRIDE_256=1;
var
blitter_0:williams_blitter;
implementation
constructor williams_blitter.create(xor_:byte;window_enable:boolean;clip_address:word);
const
dummy_table:array[0..$f] of byte=(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
var
i,f:byte;
begin
self.xor_:=xor_;
self.window_enable:=window_enable;
self.clip_address:=clip_address;
for i:=0 to 255 do
for f:=0 to 255 do
self.remap[i*256+f]:=(dummy_table[f shr 4] shl 4) or dummy_table[f and $0f];
end;
destructor williams_blitter.free;
begin
end;
procedure williams_blitter.reset;
begin
fillchar(self.ram,8,0);
end;
procedure williams_blitter.set_read_write(getbyte:tgetbyte;putbyte:tputbyte);
begin
self.getbyte:=getbyte;
self.putbyte:=putbyte;
end;
procedure williams_blitter.blit_pixel(dstaddr,srcdata:word);
var
solid,keepmask,curpix:byte;
begin
// always read from video RAM regardless of the bank setting
if (dstaddr<$c000) then curpix:=memoria[dstaddr]
else curpix:=self.getbyte(dstaddr); //current pixel values at dest
solid:=self.ram[1];
keepmask:=$ff; //what part of original dst byte should be kept, based on NO_EVEN and NO_ODD flags
//even pixel (D7-D4)
if (((self.ram[0] and CONTROLBYTE_FOREGROUND_ONLY)<>0) and ((srcdata and $f0)=0)) then begin //FG only and src even pixel=0
if (self.ram[0] and CONTROLBYTE_NO_EVEN)<>0 then keepmask:=keepmask and $0f;
end else begin
if ((self.ram[0] and CONTROLBYTE_NO_EVEN))=0 then keepmask:=keepmask and $0f;
end;
//odd pixel (D3-D0)
if (((self.ram[0] and CONTROLBYTE_FOREGROUND_ONLY)<>0) and ((srcdata and $0f)=0)) then begin //FG only and src odd pixel=0
if (self.ram[0] and CONTROLBYTE_NO_ODD)<>0 then keepmask:=keepmask and $f0;
end else begin
if ((self.ram[0] and CONTROLBYTE_NO_ODD))=0 then keepmask:=keepmask and $f0;
end;
curpix:=curpix and keepmask;
if (self.ram[0] and CONTROLBYTE_SOLID)<>0 then curpix:=curpix or (solid and not(keepmask))
else curpix:=curpix or (srcdata and not(keepmask));
// if the window is enabled, only blit to videoram below the clipping address
// note that we have to allow blits to non-video RAM (e.g. tileram, Sinistar $DXXX SRAM) because those
// are not blocked by the window enable
if (not(self.window_enable) or (dstaddr<self.clip_address) or (dstaddr>=$c000)) then self.putbyte(dstaddr,curpix);
end;
function williams_blitter.blitter_core(sstart,dstart:word;w,h:byte):byte;
var
accesses,y,x:byte;
sxadv,syadv,dxadv,dyadv:word;
source,dest,pixdata:word;
begin
accesses:=0;
// compute how much to advance in the x and y loops
if (self.ram[0] and CONTROLBYTE_SRC_STRIDE_256)<>0 then begin
sxadv:=$100;
syadv:=1;
end else begin
sxadv:=1;
syadv:=w;
end;
if (self.ram[0] and CONTROLBYTE_DST_STRIDE_256)<>0 then begin
dxadv:=$100;
dyadv:=1;
end else begin
dxadv:=1;
dyadv:=w;
end;
pixdata:=0;
// loop over the height
for y:=0 to (h-1) do begin
source:=sstart;
dest:=dstart;
// loop over the width
for x:=0 to (w-1) do begin
if ((self.ram[0] and CONTROLBYTE_SHIFT)=0) then begin //no shift
self.blit_pixel(dest,self.remap[self.getbyte(source)]);
end else begin //shift one pixel right
pixdata:=(pixdata shl 8) or self.remap[self.getbyte(source)];
self.blit_pixel(dest,(pixdata shr 4) and $ff);
end;
accesses:=accesses+2;
// advance src and dst pointers
source:=source+sxadv;
dest:=dest+dxadv;
end;
// note that PlayBall! indicates the X coordinate doesn't wrap
if (self.ram[0] and CONTROLBYTE_DST_STRIDE_256)<>0 then dstart:=(dstart and $ff00) or ((dstart+dyadv) and $ff)
else dstart:=dstart+dyadv;
if (self.ram[0] and CONTROLBYTE_SRC_STRIDE_256)<>0 then sstart:=(sstart and $ff00) or ((sstart+syadv) and $ff)
else sstart:=sstart+syadv;
end;
blitter_core:=accesses;
end;
procedure williams_blitter.blitter_w(dir,valor:byte);
var
estimated_clocks_at_4MHz,sstart,dstart:word;
w,h,accesses:byte;
begin
self.ram[dir]:=valor;
if (dir<>0) then exit;
// compute the starting locations
sstart:=(self.ram[2] shl 8)+self.ram[3];
dstart:=(self.ram[4] shl 8)+self.ram[5];
// compute the width and height
w:=self.ram[6] xor self.xor_;
h:=self.ram[7] xor self.xor_;
// adjust the width and height
if (w=0) then w:=1;
if (h=0) then h:=1;
// do the actual blit
accesses:=self.blitter_core(sstart,dstart,w,h);
// based on the number of memory accesses needed to do the blit, compute how long the blit will take
estimated_clocks_at_4MHz:=4;
if (valor and CONTROLBYTE_SLOW)<>0 then estimated_clocks_at_4MHz:=estimated_clocks_at_4MHz+(4*(accesses+2))
else estimated_clocks_at_4MHz:=estimated_clocks_at_4MHz+(2*(accesses+3));
m6809_0.contador:=m6809_0.contador+((estimated_clocks_at_4MHz+3) div 4);
end;
end.
|
unit fb2rtf_engine;
interface
uses MSXML2_TLB,Windows;
type
TRTFConverter = class
Private
XSLVar,DOM:IXMLDOMDocument2;
ProcessorVar:IXSLProcessor;
Function GetXSL:IXMLDOMDocument2;
Procedure SetXSL(AXSL:IXMLDOMDocument2);
Function GetProcessor:IXSLProcessor;
Function ConvertDOM:String;
Public
SkipImages, SkipCover, SkipDescr, EncCompat, ImgCompat:Boolean;
property Processor:IXSLProcessor read GetProcessor;
property XSL:IXMLDOMDocument2 read GetXSL write SetXsl;
Constructor Create;
Procedure Convert(ADOM:IDispatch;FN:String);
Procedure EscapeText;
Procedure ExtractImages;
end;
Function ExportDOM(AParent:THandle;DOM:IDispatch;FN:String; SkipImages, SkipCover, SkipDescr, EncCompat, ImgCompat:boolean):HResult;
implementation
uses SysUtils, Classes, Variants, Graphics, pngimage, Jpeg;
Type
TStoreArray=Array of byte;
Procedure TRTFConverter.EscapeText;
Const
StartC=WideChar(#0);
EndC=WideChar(#255);
Var
NodeList,NodeList1:IXMLDOMNodeList;
S:WideString;
I:Integer;
TranslatedChars:array[StartC..EndC] of WideString;
IC:WideChar;
Function Trim(S:WideString):WideString;
Const
TrimSym:WideString=' '#9#10#13;
Begin
if S='' then Exit;
While (S<>'') and (Pos(S[1],TrimSym)<>0) do
Delete(S,1,1);
While (S<>'') and (Pos(S[Length(S)],TrimSym)<>0) do
SetLength(S,Length(S)-1);
Result:=S;
end;
Function LineEmpty(const S:WideString):Boolean;
Begin
Result:=False;
if Trim(S)='' then
Result:=True;
end;
Function CharToUTFTrans(C:WideChar):WideString;
Var
CharAsWord:Word absolute C;
Begin
if not EncCompat and (CharAsWord>=$410) and (CharAsWord<=$451) then
Begin
Result:=C;
Exit;
end;
Result:=IntToStr(CharAsWord);
While Length(Result)<4 do
Result:='0'+Result;
Result:='\uc1\u'+Result+'?';
end;
Function EscapeString(S:WideString):WideString;
Var
I:Integer;
Begin
Result:='';
For I:=1 to Length(S) do
Begin
If (Word(S[I])>=$20) and (Word(S[I])<$7E) then
Begin
Result:=Result+S[I];
Continue;
end;
If Word(S[I])<=255 then
Result:=Result+TranslatedChars[S[I]]
else
Result:=Result+CharToUTFTrans(S[I]);
end;
end;
begin
For IC:=#0 to #255 do
TranslatedChars[IC]:=CharToUTFTrans(IC);
For IC:=#32 to #126 do
TranslatedChars[IC]:=IC;
TranslatedChars[WideChar('\')]:='\''5c';
TranslatedChars[WideChar('{')]:='\''7b';
TranslatedChars[WideChar('}')]:='\''7d';
TranslatedChars[WideChar(#10)]:=' ';
TranslatedChars[WideChar(#13)]:=' ';
TranslatedChars[WideChar(#9)]:='\tab ';
TranslatedChars[WideChar('-')]:='\_';
TranslatedChars[WideChar(#160)]:='\~';
TranslatedChars[WideChar(#173)]:='\-';
TranslatedChars[WideChar('–')]:='\endash';
TranslatedChars[WideChar('—')]:='\endash';
Dom.setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"');
NodeList:=Dom.selectNodes('//*[name()!=''binary'']/text()');
if NodeList<>Nil then
for I:=0 to NodeList.length-1 do
Begin
S:=NodeList.item[I].xml;
if not LineEmpty(S) then
NodeList.item[I].text:=EscapeString(S);
end;
end;
Procedure TRTFConverter.ExtractImages;
Const
JPG=0;
PNG=1;
Var
NodeList,NodeList1:IXMLDOMNodeList;
I,I1:Integer;
ItemID:WideString;
ItemContentType:String;
ImgType:Integer;
F:TMemoryStream;
ImgAsVar:Variant;
TheArr:TStoreArray;
ImgStr:String;
Function ImgToStr(F:TStream;ImgType:Integer):String;
Var
PNGImg:TPngObject;
JPegImg:TJPEGImage;
Graph:TGraphic;
BMP:TBitmap;
I:Integer;
B:Byte;
Const
ImgDescrs:array[JPG..PNG] of string=('jpeg','png');
function BitmapToRTF(pict: TBitmap): string;
var
bi, bb, rtf: string;
bis, bbs: Cardinal;
achar: ShortString;
hexpict: string;
I: Integer;
begin
GetDIBSizes(pict.Handle, bis, bbs);
SetLength(bi, bis);
SetLength(bb, bbs);
GetDIB(pict.Handle, pict.Palette, PChar(bi)^, PChar(bb)^);
rtf := '{\rtf1 {\pict\dibitmap0 ';
SetLength(hexpict, (Length(bb) + Length(bi)) * 2);
I := 2;
for bis := 1 to Length(bi) do
begin
achar := IntToHex(Integer(bi[bis]), 2);
hexpict[I - 1] := achar[1];
hexpict[I] := achar[2];
Inc(I, 2);
end;
for bbs := 1 to Length(bb) do
begin
achar := IntToHex(Integer(bb[bbs]), 2);
hexpict[I - 1] := achar[1];
hexpict[I] := achar[2];
Inc(I, 2);
end;
rtf := rtf + hexpict + ' }}';
Result := rtf;
end;
Begin
Result:='';
If ImgType=JPG then
Begin
JPegImg:=TJPEGImage.Create;
JpegImg.LoadFromStream(F);
Graph:=JpegImg;
end else if ImgType=PNG then
Begin
PNGImg:=TPngObject.Create;
pngImg.LoadFromStream(F);
Graph:=pngImg
end else Exit;
if not ImgCompat then
Begin
Result:='{\pict\'+ImgDescrs[ImgType]+'blip\picw'+IntToStr(Graph.Width)+'\pich'+IntToStr(Graph.Height)+
'\picwgoal'+IntToStr(Graph.Width*15)+'\pichgoal'+IntToStr(Graph.Height*15)+#13;
F.Seek(0,soFromBeginning);
For I:=1 to F.Size do
Begin
F.Read(B,1);
Result:=Result+IntToHex(B,2);
if I mod 80 = 0 then Result:=Result+#10;
end;
Result:=Result+'}'
end else
Begin
// Result:='{\pict\dibitmap0';
BMP:=TBitmap.Create;
bmp.Assign(Graph);
{ case bmp.PixelFormat of
pf1bit:Result:=Result+'\wbmbitspixel1';
pf8bit:Result:=Result+'\wbmbitspixel8';
pf16bit:Result:=Result+'\wbmbitspixel16';
pf24bit:Result:=Result+'\wbmbitspixel24';
pf32bit:Result:=Result+'\wbmbitspixel32';
end;
// & \wbmplanes & \wbmwidthbytes
Result:=Result+'\picw'+IntToStr(Graph.Width)+'\pich'+IntToStr(Graph.Height)+
'\picwgoal'+IntToStr(Graph.Width*15)+'\pichgoal'+IntToStr(Graph.Height*15)+#13;}
Result:=BitmapToRTF(bmp);
end;
Graph.Free;
end;
Begin
Dom.setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"');
NodeList:=Dom.selectNodes('//fb:binary');
if NodeList<>Nil then
for I:=0 to NodeList.length-1 do
Begin
ItemID:=NodeList.item[I].attributes.getNamedItem('id').text;
ItemContentType:=NodeList.item[I].attributes.getNamedItem('content-type').text;
if LowerCase(ItemContentType)='image/jpeg' then
ImgType:=JPG
else if LowerCase(ItemContentType)='image/png' then
ImgType:=PNG
else Continue;
NodeList.item[I].Set_dataType('bin.base64');
ImgAsVar:=NodeList.item[I].nodeTypedValue;
DynArrayFromVariant(Pointer(TheArr),ImgAsVar,TypeInfo(TStoreArray));
F:=TMemoryStream.Create;
F.Write(TheArr[0],Length(TheArr));
F.Seek(0,soFromBeginning);
ImgStr:=ImgToStr(F,ImgType);
F.Free;
NodeList1:=Dom.selectNodes('//fb:image[@xlink:href=''#'+ItemID+''']');
if NodeList1<>Nil then
for I1:=0 to NodeList1.length-1 do
NodeList1.item[I1].text:=ImgStr;
end;
end;
Function TRTFConverter.ConvertDOM:String;
Var
ImgUseDepth:Integer;
XDoc1:IXMLDOMDocument2;
Begin
// this thing is to fix strange DOM from FBE, not knowing that
// http://www.gribuser.ru/xml/fictionbook/2.0 is a default namespace
// for attributes %[ ]
XDoc1:=CoFreeThreadedDOMDocument40.Create;
XDoc1.loadXML(Dom.XML);
Dom:=XDoc1;
ImgUseDepth:=2;
if SkipImages then ImgUseDepth:=0 else if SkipCover then ImgUseDepth:=1;
Processor.addParameter('saveimages',ImgUseDepth,'');
Processor.addParameter('skipannotation',Integer(SkipDescr),'');
Dom.async:=False;
Processor.input:= DOM;
Processor.transform;
Result:=Processor.output;
end;
Function ExportDOM;
Var
Converter:TRTFConverter;
Begin
Converter:=TRTFConverter.Create;
Converter.SkipImages:=SkipImages;
Converter.SkipCover:=SkipCover;
Converter.SkipDescr:=SkipDescr;
Converter.EncCompat:=EncCompat;
Converter.ImgCompat:=ImgCompat;
Converter.Convert(DOM,FN);
Converter.Free;
end;
Constructor TRTFConverter.Create;
Begin
XSLVar:=Nil;
end;
Procedure TRTFConverter.Convert;
Var
F:TFileStream;
ResultText:String;
OutVar:IXMLDOMDocument2;
Begin
if ADOM=Nil then
Begin
MessageBox(0,'NILL document value, please provide valid IXMLDOMDocument2 on input.','Error',mb_ok or MB_ICONERROR);
Exit;
end;
if ADOM.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then
Begin
MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR);
exit;
end;
DOM:=OutVar;
Try
EscapeText;
ExtractImages;
ResultText:=ConvertDOM;
F:=TFileStream.Create(FN,fmCreate);
F.Write(ResultText[1],Length(ResultText));
F.Free;
except
on E: Exception do MessageBox(0,PChar(E.Message),'Error',mb_ok or MB_ICONERROR);
end
end;
Function TRTFConverter.GetXSL;
Var
ModulePath:String;
XTmp:IXMLDOMDocument2;
Begin
If XSLVar=Nil then
Begin
SetLength(ModulePath,2000);
GetModuleFileName(HInstance,@ModulePath[1],1999);
SetLength(ModulePath,Pos(#0,ModulePath)-1);
ModulePath:=ExtractFileDir(ModulePath);
ModulePath:=IncludeTrailingPathDelimiter(ModulePath);
XTmp:=CoFreeThreadedDOMDocument40.Create;
if not XTmp.load(ModulePath+'FB2_2_rtf.xsl') then
Raise Exception.Create(XTmp.parseError.reason);
XSL:=XTmp;
end;
Result:=XSLVar;
end;
Procedure TRTFConverter.SetXSL;
Var
Template:IXSLTemplate;
Begin
XSLVar:=AXSL;
Template := CoXSLTemplate40.Create;
Template._Set_stylesheet(XSL);
ProcessorVar:=Template.createProcessor;
end;
Function TRTFConverter.GetProcessor;
Var
XTmp:IXMLDOMDocument2;
Begin
if (ProcessorVar=Nil) then GetXSL;
Result:=ProcessorVar;
end;
end.
|
unit MathUtils;
interface
function Dist( x1, y1, x2, y2 : integer ) : integer;
function min( a, b : integer ) : integer;
function max( a, b : integer ) : integer;
function minI64( a, b : int64) : int64;
function maxI64( a, b : int64 ) : int64;
function realmin( a, b : single ) : single;
function realmax( a, b : single ) : single;
function currmin( a, b : currency ) : currency;
function currmax( a, b : currency ) : currency;
function FormatMoney( money : currency ) : string;
function FormatMoneyStr( str : string ) : string;
function FormattedStrToMoney( str : string ) : currency;
function intcond (cond : boolean; exp1, exp2 : integer) : integer;
function realcond(cond : boolean; exp1, exp2 : single ) : single;
function SmartRound(value : single) : integer;
implementation
uses
SysUtils;
function Dist( x1, y1, x2, y2 : integer ) : integer;
begin
result := abs(x1 - x2) + abs(y1 - y2)
end;
function min( a, b : integer ) : integer;
begin
if a < b
then result := a
else result := b
end;
function max( a, b : integer ) : integer;
begin
if a > b
then result := a
else result := b
end;
function minI64(a, b : int64) : int64;
begin
if a < b
then result := a
else result := b
end;
function maxI64(a, b : int64) : int64;
begin
if a > b
then result := a
else result := b
end;
function realmin( a, b : single ) : single;
begin
if a < b
then result := a
else result := b
end;
function realmax( a, b : single ) : single;
begin
if a > b
then result := a
else result := b
end;
function currmin( a, b : currency ) : currency;
begin
if a < b
then result := a
else result := b
end;
function currmax( a, b : currency ) : currency;
begin
if a > b
then result := a
else result := b
end;
function FormatMoney( money : currency ) : string;
var
cents : currency;
begin
if money = 0
then result := '$0'
else
if abs(money) > 1
then
begin
result := Format('%.0n', [int(money)]);
if money >= 0
then insert('$', result, 1)
else insert('$', result, 2);
end
else
begin
cents := int(100*money);
if cents = 0
then result := '$0'
else result := Format('%.0ną', [cents]);
end;
end;
function FormatMoneyStr( str : string ) : string;
begin
if str <> ''
then
try
result := FormatMoney(StrToCurr(str));
except
result := FormatMoney(0);
end
else result := FormatMoney(0);
end;
function FormattedStrToMoney( str : string ) : currency;
var
i : integer;
begin
for i := length(str) downto 1 do
if str[i] in ['$', ',', ' ', 'A'..'Z']
then system.delete( str, i, 1 );
result := StrToCurr( str );
end;
function intcond(cond : boolean; exp1, exp2 : integer) : integer;
begin
if cond
then result := exp1
else result := exp2;
end;
function realcond(cond : boolean; exp1, exp2 : single ) : single;
begin
if cond
then result := exp1
else result := exp2;
end;
function SmartRound(value : single) : integer;
begin
if value > 0
then result := max(1, round(value))
else result := 0;
end;
end.
|
unit Unit_SelecaoDeFornecedores;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.Grids;
type
Tfrm_SelecaoDeFornecedores = class(TForm)
for_Panel1: TPanel;
for_ComboBox: TLabel;
label_Pesquisa: TLabel;
btn_Fechar1: TBitBtn;
cbx_PesquisaFornecedor: TComboBox;
for_Pesquisa: TMaskEdit;
Grid_Fornecedores: TStringGrid;
Procedure Pinta_Grid;
Procedure Popula_Grid(Condicao : String);
procedure FormShow(Sender: TObject);
procedure Grid_FornecedoresSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
Procedure Grid_FornecedoresDblClick(Sender: TObject);
procedure btn_Fechar1Click(Sender: TObject);
procedure Calcula_Valor_Disponivel;
procedure SetCompraVista;
procedure SetCompraPrazo;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_SelecaoDeFornecedores: Tfrm_SelecaoDeFornecedores;
Linha : Integer;
ValorDisponivel : String;
tipoCompra : String;
implementation
{$R *.dfm}
uses Unit_Persistencia, Unit_Compra, Unit_Caixa, Unit_ContasPagar;
Procedure Tfrm_SelecaoDeFornecedores.Pinta_Grid;
begin
Grid_Fornecedores.Cells[0,0] := 'Cód.';
Grid_Fornecedores.Cells[1,0] := 'Nome Fantasia';
Grid_Fornecedores.Cells[2,0] := 'Razão Social';
Grid_Fornecedores.Cells[3,0] := 'Inscrição Estadual';
Grid_Fornecedores.Cells[4,0] := 'CNPJ';
Grid_Fornecedores.Cells[5,0] := 'Endereço';
Grid_Fornecedores.Cells[6,0] := 'Telefone';
Grid_Fornecedores.Cells[7,0] := 'Email';
Grid_Fornecedores.ColWidths[0] := 50;
Grid_Fornecedores.ColWidths[1] := 150;
Grid_Fornecedores.ColWidths[2] := 150;
Grid_Fornecedores.ColWidths[3] := 150;
Grid_Fornecedores.ColWidths[4] := 100;
Grid_Fornecedores.ColWidths[5] := 100;
Grid_Fornecedores.ColWidths[6] := 100;
Grid_Fornecedores.ColWidths[7] := 100;
end;
Procedure Tfrm_SelecaoDeFornecedores.Popula_Grid(Condicao : String);
Var
Fornecedores_Atuais : Fornecedores_Cadastrados;
I : Integer;
Begin
SetLength(Fornecedores_Atuais,0);
Grid_Fornecedores.RowCount := 2;
Grid_Fornecedores.Cells[0,1] := '';
Grid_Fornecedores.Cells[1,1] := '';
Grid_Fornecedores.Cells[2,1] := '';
Grid_Fornecedores.Cells[3,1] := '';
Grid_Fornecedores.Cells[4,1] := '';
Grid_Fornecedores.Cells[5,1] := '';
Grid_Fornecedores.Cells[6,1] := '';
Fornecedores_Atuais := Retorna_Fornecedores_Cadastrados(Condicao);
For I := 0 To Length(Fornecedores_Atuais)-1 Do
Begin
Grid_Fornecedores.RowCount := Grid_Fornecedores.RowCount + 1;
Grid_Fornecedores.Cells[0,I+1] := IntToStr(Fornecedores_Atuais[I].For_Codigo);
Grid_Fornecedores.Cells[1,I+1] := Fornecedores_Atuais[I].For_NomeFantasia;
Grid_Fornecedores.Cells[2,I+1] := Fornecedores_Atuais[I].For_RazaoSocial;
Grid_Fornecedores.Cells[3,I+1] := Fornecedores_Atuais[I].For_InscricaoEstadual;
Grid_Fornecedores.Cells[4,I+1] := Fornecedores_Atuais[I].For_CNPJ;
Grid_Fornecedores.Cells[5,I+1] := Fornecedores_Atuais[I].For_Endereco;
Grid_Fornecedores.Cells[6,I+1] := Fornecedores_Atuais[I].For_Telefone;
Grid_Fornecedores.Cells[7,I+1] := Fornecedores_Atuais[I].For_Email;
End;
Grid_Fornecedores.RowCount := Grid_Fornecedores.RowCount - 1;
End;
procedure Tfrm_SelecaoDeFornecedores.Calcula_Valor_Disponivel;
begin
Application.CreateForm(Tfrm_Caixa, frm_Caixa);
frm_Caixa.Pinta_Grid;
frm_Caixa.Calcula_Valor_Disponivel;
frm_Caixa.Popula_Grid('');
frm_Caixa.Calcula_Valor_Total;
valorDisponivel := frm_Caixa.cai_ValorTotal.Text;
frm_Caixa.Destroy;
end;
procedure Tfrm_SelecaoDeFornecedores.SetCompraVista;
begin
tipoCompra := 'Vista';
end;
procedure Tfrm_SelecaoDeFornecedores.SetCompraPrazo;
begin
tipoCompra := 'Prazo';
end;
procedure Tfrm_SelecaoDeFornecedores.Grid_FornecedoresSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
Linha := ARow;
end;
Procedure Tfrm_SelecaoDeFornecedores.Grid_FornecedoresDblClick(Sender: TObject);
var
Temp : Dados_Fornecedor;
ValorAPagar : String;
I, J : Integer;
Temp2 : Dados_NotaCompra;
aux : String;
Data : TDateTime;
count : String;
entrada : String;
qtdParcelas : String;
frete : String;
imposto : String;
begin
frete := InputBox('Digite o valor do frete.','Digite o valor do frete.', '0');
imposto := InputBox('Digite o valor do imposto.','Digite o valor do imposto.', '0');
Temp := Retorna_Dados_Fornecedor(StrToInt(Grid_Fornecedores.Cells[0,Linha]));
ValorAPagar := frm_Compra.GRID_Carrinho.Cells[5, frm_Compra.GRID_Carrinho.RowCount - 1];
aux := '';
Temp2.Nc_ProdutosComprados := '';
count := '0';
if tipoCompra = 'Vista' then
begin
Temp2.Nc_Codigo := StrToInt(Retorna_Proximo_Codigo_NotaCompra);
Temp2.Nc_CodigoFornecedor := Temp.For_Codigo;
for J := 1 to frm_Compra.GRID_Carrinho.RowCount-2 do
begin
count := FloatToStr(StrToFloat(count) + StrToFloat(frm_Compra.GRID_Carrinho.Cells[2, J]));
aux := (
frm_Compra.GRID_Carrinho.Cells[0, J]+':'+frm_Compra.GRID_Carrinho.Cells[1, J]+':'+
frm_Compra.GRID_Carrinho.Cells[2, J]+':'+frm_Compra.GRID_Carrinho.Cells[4, J]+':'+
frm_Compra.GRID_Carrinho.Cells[5, J]+'\n'
);
Temp2.Nc_ProdutosComprados := Temp2.Nc_ProdutosComprados + aux;
end;
Data := StrToDateTime(FormatDateTime('dd/mm/yyyy', Now));
Temp2.Nc_Data := DateToStr(Data);
Temp2.Nc_ValorTotal := FloatToStr(
StrToFloat(ValorAPagar) +
StrToFloat(frete) +
StrToFloat(imposto)
);
Temp2.Nc_Frete := frete;
Temp2.Nc_Imposto := imposto;
if StrToFloat(Temp2.Nc_ValorTotal) > StrToFloat(valorDisponivel) then
begin
ShowMessage('Não há dinheiro suficiente no caixa para realizar esta compra.');
exit;
end
else
begin
Grava_Dados_NotaCompra(Temp2);
frete := FloatToStr(StrToFloat(frete)/StrToFloat(count));
imposto := FloatToStr(StrToFloat(imposto)/StrToFloat(count));
frm_Compra.AtualizaEstoque(frete, imposto);
frm_Caixa.Insere_Caixa('Compra', Temp2.Nc_ValorTotal, Temp2.Nc_Codigo);
ShowMessage('Compra realizada.');
frm_Compra.limpa_Carrinho;
frm_SelecaoDeFornecedores.Close;
end;
end
else if tipoCompra = 'Prazo' then
begin
Entrada := InputBox('Digite o valor de entrada','Digite a entrada', '0');
ValorAPagar := FloatToStr(StrToFloat(ValorAPagar) - StrToFloat(Entrada));
QtdParcelas := InputBox('Digite a quantidade de Parcelas.','Digite a quantidade de Parcelas.', '0');
if QtdParcelas = '0' then
begin
ShowMessage('Quantidade não pode ser igual a 0.');
end
else if QtdParcelas > '6' then
begin
ShowMessage('Máximo de 6 parcelas.');
end
else begin
For I := 0 To StrToInt(QtdParcelas)-1 Do
begin
aux := '';
Temp2.Nc_ProdutosComprados := '';
Temp2.Nc_Codigo := StrToInt(Retorna_Proximo_Codigo_NotaCompra);
Temp2.Nc_CodigoFornecedor := Temp.For_Codigo;
for J := 1 to frm_Compra.GRID_Carrinho.RowCount-2 do
begin
count := FloatToStr(StrToFloat(count) + StrToFloat(frm_Compra.GRID_Carrinho.Cells[2, J]));
aux := (
frm_Compra.GRID_Carrinho.Cells[0, J]+':'+frm_Compra.GRID_Carrinho.Cells[1, J]+':'+
frm_Compra.GRID_Carrinho.Cells[2, J]+':'+frm_Compra.GRID_Carrinho.Cells[4, J]+':'+
frm_Compra.GRID_Carrinho.Cells[5, J]+'\n'
);
Temp2.Nc_ProdutosComprados := Temp2.Nc_ProdutosComprados + aux;
end;
// Gera data
Data := StrToDateTime(FormatDateTime('dd/mm/yyyy', Now));
for J := 0 to I+1 do
Data := IncMonth(Data);
Temp2.Nc_Data := DateToStr(Data);
Temp2.Nc_Frete := frete;
Temp2.Nc_Imposto := imposto;
Temp2.Nc_ValorTotal := FloatToStr(StrToFloat(ValorAPagar)/StrToInt(QtdParcelas));
Grava_Dados_NotaCompra(Temp2);
frm_ContasPagar.Insere_ContaPagar(
Temp.For_Codigo,
'Parcela '+ IntToStr(I+1)+'/'+ QtdParcelas,
FloatToStr(StrToFloat(ValorAPagar)/StrToInt(QtdParcelas)),
Temp2.Nc_Codigo
);
end;
frete := FloatToStr(StrToFloat(frete)/StrToFloat(count));
imposto := FloatToStr(StrToFloat(imposto)/StrToFloat(count));
frm_Compra.AtualizaEstoque(frete, imposto);
ShowMessage('Compra realizada.');
frm_Compra.limpa_Carrinho;
frm_SelecaoDeFornecedores.Close;
end;
end;
end;
procedure Tfrm_SelecaoDeFornecedores.btn_Fechar1Click(Sender: TObject);
begin
frm_SelecaoDeFornecedores.Close;
end;
procedure Tfrm_SelecaoDeFornecedores.FormShow(Sender: TObject);
begin
Pinta_Grid;
Popula_Grid('');
Calcula_Valor_Disponivel;
end;
end.
|
unit SDConsoleForm;
interface
uses
Windows, Forms, BaseForm, Classes, Controls,
StdCtrls, Sysutils, ExtCtrls, Dialogs, VirtualTrees,
define_dealitem, define_dealmarket, define_datasrc, define_price, define_datetime,
StockDataConsoleApp, StockDataConsoleTask, DealItemsTreeView, StockDayDataAccess,
ComCtrls;
type
TFormSDConsoleData = record
DownloadAllTasks: array[TDealDataSource] of PDownloadTask;
AppStartTimer: TTimer;
DealItemTree: TDealItemTreeCtrl;
DayDataAccess: StockDayDataAccess.TStockDayDataAccess;
DayDataSrc: TDealDataSource;
WeightMode: TRT_WeightMode;
end;
TfrmSDConsole = class(TfrmBase)
tmrRefreshDownloadTask: TTimer;
pnlBottom: TPanel;
pnlTop: TPanel;
pnlRight: TPanel;
mmo1: TMemo;
splRight: TSplitter;
pnlMain: TPanel;
pnlLeft: TPanel;
splLeft: TSplitter;
pnlMiddle: TPanel;
pnlDayDataTop: TPanel;
vtDayDatas: TVirtualStringTree;
cmbDayDataSrc: TComboBoxEx;
Label1: TLabel;
pnlLeftBottom: TPanel;
btnClear: TButton;
btnSaveDic: TButton;
btnSaveTxt: TButton;
btnCheckEnd: TButton;
btnOpen: TButton;
btnSaveIni: TButton;
btnRefresh: TButton;
lbl1: TLabel;
cmbDownloadSrc: TComboBoxEx;
btnDownload: TButton;
chkShutDown: TCheckBox;
edtStock163: TEdit;
edtStockSina: TEdit;
procedure btnDownloadClick(Sender: TObject);
procedure btnShutDownClick(Sender: TObject);
procedure tmrRefreshDownloadTaskTimer(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnSaveDicClick(Sender: TObject);
procedure btnSaveIniClick(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure cmbDayDataSrcChange(Sender: TObject);
private
{ Private declarations }
fFormSDConsoleData: TFormSDConsoleData;
procedure DealItemChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure SetDayDataSrc(AValue: TDealDataSource);
function GetDayDataSrc: TDealDataSource;
procedure tmrAppStartTimer(Sender: TObject);
function GetStockCode: integer;
function GetDataSrc: TDealDataSource;
procedure SaveDealItemDBAsDic(AFileUrl: string);
procedure SaveDealItemDBAsIni(AFileUrl: string);
function NewDownloadAllTask(ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask;
procedure RequestDownloadStockData(ADownloadTask: PDownloadTask; ADataSrc: TDealDataSource; AStockCode: integer);
procedure RequestDownloadProcessTaskStockData(AProcessTask: PDownloadProcessTask);
procedure LoadDayDataTreeView(AStockItem: PDealItemNode);
procedure DayDataTreeViewInitialize;
procedure vtDayDatasGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
protected
procedure FormCreate(Sender: TObject);
public
{ Public declarations }
constructor Create(Owner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
define_StockDataApp,
define_stock_quotes,
define_dealstore_file,
windef_msg,
win.shutdown,
win.iobuffer,
ShellAPI,
UtilsHttp,
//UtilsLog,
HTMLParserAll3,
BaseStockFormApp,
StockDayData_Load,
BaseWinApp,
SDFrameDataViewer,
db_dealItem_LoadIni,
db_dealitem_load,
db_dealitem_save;
type
PStockDayDataNode = ^TStockDayDataNode;
TStockDayDataNode = record
DayIndex: integer;
QuoteData: PRT_Quote_Day;
end;
constructor TfrmSDConsole.Create(Owner: TComponent);
begin
inherited;
FillChar(fFormSDConsoleData, SizeOf(fFormSDConsoleData), 0);
fFormSDConsoleData.AppStartTimer := TTimer.Create(Application);
fFormSDConsoleData.AppStartTimer.Interval := 100;
fFormSDConsoleData.AppStartTimer.OnTimer := tmrAppStartTimer;
fFormSDConsoleData.AppStartTimer.Enabled := true;
Self.OnCreate := FormCreate;
cmbDayDataSrc.Clear;
cmbDayDataSrc.Items.Add('');
cmbDayDataSrc.Items.Add(GetDataSrcName(src_163));
cmbDayDataSrc.Items.Add(GetDataSrcName(src_sina));
cmbDownloadSrc.Clear;
cmbDownloadSrc.Items.Add(GetDataSrcName(src_163));
cmbDownloadSrc.Items.Add(GetDataSrcName(src_sina));
cmbDownloadSrc.Items.Add(GetDataSrcName(src_all));
end;
procedure TfrmSDConsole.FormCreate(Sender: TObject);
begin
DragAcceptFiles(Handle, True) ;
//
end;
function TfrmSDConsole.GetStockCode: integer;
var
tmpCode: string;
tmpPos: integer;
begin
Result := 0;
tmpCode := Trim(cmbDownloadSrc.Text);
tmpPos := Pos(':', tmpCode);
if 0 < tmpPos then
begin
tmpCode := Copy(tmpCode, tmpPos + 1, maxint);
Result := StrToIntDef(tmpCode, 0);
end;
end;
procedure TfrmSDConsole.tmrAppStartTimer(Sender: TObject);
begin
if nil <> Sender then
begin
if Sender is TTimer then
begin
TTimer(Sender).Enabled := false;
TTimer(Sender).OnTimer := nil;
end;
if Sender = fFormSDConsoleData.AppStartTimer then
begin
fFormSDConsoleData.AppStartTimer.Enabled := false;
fFormSDConsoleData.AppStartTimer.OnTimer := nil;
end;
end;
fFormSDConsoleData.DealItemTree := TDealItemTreeCtrl.Create(pnlLeft);
fFormSDConsoleData.DealItemTree.InitializeDealItemsTree(fFormSDConsoleData.DealItemTree.TreeView);
fFormSDConsoleData.DealItemTree.AddDealItemsTreeColumn_FirstDeal;
//fFormSDConsoleData.DealItemTree.AddDealItemsTreeColumn_lastDeal;
fFormSDConsoleData.DealItemTree.AddDealItemsTreeColumn_EndDeal;
fFormSDConsoleData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockIndexDB);
fFormSDConsoleData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB);
TVirtualStringTree(fFormSDConsoleData.DealItemTree.TreeView).TreeOptions.SelectionOptions :=
TVirtualStringTree(fFormSDConsoleData.DealItemTree.TreeView).TreeOptions.SelectionOptions + [toMultiSelect];
TVirtualStringTree(fFormSDConsoleData.DealItemTree.TreeView).OnChange := DealItemChange;
DayDataTreeViewInitialize;
end;
procedure TfrmSDConsole.DealItemChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
tmpNode: PDealItemNode;
begin
if nil <> Node then
begin
tmpNode := fFormSDConsoleData.DealItemTree.TreeView.GetNodeData(Node);
if nil <> tmpNode then
begin
LoadDayDataTreeView(tmpNode);
end;
end;
end;
procedure TfrmSDConsole.RequestDownloadProcessTaskStockData(AProcessTask: PDownloadProcessTask);
begin
TStockDataConsoleApp(App.AppAgent).TaskConsole.RunProcessTask(AProcessTask);
end;
type
TDayColumns = (
colIndex,
colDate, colOpen, colClose, colHigh, colLow,
colDayVolume, colDayAmount,
colWeight
);
const
DayColumnsText: array[TDayColumns] of String = (
'Index', '日期',
'开盘', '收盘', '最高', '最低',
'成交量', '成交金额', '权重'
);
DayColumnsWidth: array[TDayColumns] of integer = (
60, 0,
0, 0, 0, 0,
0, 0, 0
);
procedure TfrmSDConsole.DayDataTreeViewInitialize;
var
col_day: TDayColumns;
tmpCol: TVirtualTreeColumn;
begin
vtDayDatas.NodeDataSize := SizeOf(TStockDayDataNode);
vtDayDatas.Header.Options := [hoColumnResize, hoVisible];
vtDayDatas.Header.Columns.Clear;
vtDayDatas.TreeOptions.SelectionOptions := [toFullRowSelect];
vtDayDatas.TreeOptions.AnimationOptions := [];
vtDayDatas.TreeOptions.MiscOptions := [toAcceptOLEDrop,toFullRepaintOnResize,toInitOnSave,toToggleOnDblClick,toWheelPanning,toEditOnClick];
vtDayDatas.TreeOptions.PaintOptions := [toShowButtons,toShowDropmark,{toShowRoot} toShowTreeLines,toThemeAware,toUseBlendedImages];
vtDayDatas.TreeOptions.StringOptions := [toSaveCaptions,toAutoAcceptEditChange];
for col_day := low(TDayColumns) to high(TDayColumns) do
begin
tmpCol := vtDayDatas.Header.Columns.Add;
tmpCol.Text := DayColumnsText[col_day];
case col_day of
colIndex: tmpCol.Width := vtDayDatas.Canvas.TextWidth('2000');
colDate: tmpCol.Width := vtDayDatas.Canvas.TextWidth('2016-12-12');
colOpen: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000');
colClose: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000');
colHigh: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000');
colLow: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000');
colDayVolume: ;
colDayAmount: ;
colWeight: tmpCol.Width := vtDayDatas.Canvas.TextWidth('300000');
end;
if 0 <> tmpCol.Width then
begin
tmpCol.Width := tmpCol.Width + vtDayDatas.TextMargin + vtDayDatas.Indent;
end else
begin
if 0 = DayColumnsWidth[col_day] then
begin
tmpCol.Width := 120;
end else
begin
tmpCol.Width := DayColumnsWidth[col_day];
end;
end;
end;
vtDayDatas.OnGetText := vtDayDatasGetText;
//vtDayDatas.OnChange := vtDayDatasChange;
end;
procedure TfrmSDConsole.vtDayDatasGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
tmpNodeData: PStockDayDataNode;
begin
CellText := '';
tmpNodeData := Sender.GetNodeData(Node);
if nil <> tmpNodeData then
begin
if nil <> tmpNodeData.QuoteData then
begin
if Integer(colIndex) = Column then
begin
CellText := IntToStr(Node.Index);
exit;
end;
if Integer(colDate) = Column then
begin
CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData.DealDate.Value);
exit;
end;
if Integer(colOpen) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceOpen.Value);
exit;
end;
if Integer(colClose) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceClose.Value);
exit;
end;
if Integer(colHigh) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceHigh.Value);
exit;
end;
if Integer(colLow) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.PriceRange.PriceLow.Value);
exit;
end;
if Integer(colDayVolume) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.DealVolume);
exit;
end;
if Integer(colDayAmount) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.DealAmount);
exit;
end;
if Integer(colWeight) = Column then
begin
CellText := IntToStr(tmpNodeData.QuoteData.Weight.Value);
exit;
end;
end;
end;
end;
procedure TfrmSDConsole.LoadDayDataTreeView(AStockItem: PDealItemNode);
var
i: integer;
tmpStockDataNode: PStockDayDataNode;
tmpStockData: PRT_Quote_Day;
tmpNode: PVirtualNode;
tmpDataSrc: TDealDataSource;
begin
if nil = AStockItem then
exit;
vtDayDatas.BeginUpdate;
try
vtDayDatas.Clear;
if nil = AStockItem then
exit;
//fFormSDConsoleData.DayDataAccess := AStockItem.StockDayDataAccess;
tmpDataSrc := GetDayDataSrc;
if src_unknown = tmpDataSrc then
exit;
if nil <> fFormSDConsoleData.DayDataAccess then
begin
FreeAndNil(fFormSDConsoleData.DayDataAccess);
end;
if nil = fFormSDConsoleData.DayDataAccess then
begin
if src_163 = tmpDataSrc then
fFormSDConsoleData.WeightMode := weightNone;
if src_sina = tmpDataSrc then
fFormSDConsoleData.WeightMode := weightBackward;
fFormSDConsoleData.DayDataAccess := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.DealItem, tmpDataSrc, fFormSDConsoleData.WeightMode);
LoadStockDayData(App, fFormSDConsoleData.DayDataAccess);
end;
//fDataViewerData.Rule_BDZX_Price := AStockItem.Rule_BDZX_Price;
//fDataViewerData.Rule_CYHT_Price := AStockItem.Rule_CYHT_Price;
for i := fFormSDConsoleData.DayDataAccess.RecordCount - 1 downto 0 do
begin
tmpStockData := fFormSDConsoleData.DayDataAccess.RecordItem[i];
tmpNode := vtDayDatas.AddChild(nil);
tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode);
tmpStockDataNode.QuoteData := tmpStockData;
tmpStockDataNode.DayIndex := i;
end;
finally
vtDayDatas.EndUpdate;
end;
end;
procedure TfrmSDConsole.RequestDownloadStockData(ADownloadTask: PDownloadTask; ADataSrc: TDealDataSource; AStockCode: integer);
begin
if IsWindow(TBaseWinApp(App).AppWindow) then
begin
PostMessage(TBaseWinApp(App).AppWindow, WM_Console_Command_Download, AStockCode, GetDealDataSourceCode(ADataSrc))
end;
end;
procedure TfrmSDConsole.tmrRefreshDownloadTaskTimer(Sender: TObject);
function CheckTask(ADownloadTask: PDownloadTask; AStockCodeDisplay: TEdit): integer;
var
exitcode_process: DWORD;
tick_gap: DWORD;
waittime: DWORD;
begin
Result := 0;
if nil = ADownloadTask then
exit;
Result := 1;
if nil <> ADownloadTask.DownProcessTaskArray[0].DealItem then
AStockCodeDisplay.Text := ADownloadTask.DownProcessTaskArray[0].DealItem.sCode;
if TaskStatus_End = ADownloadTask.TaskStatus then
begin
Result := 0;
end else
begin
Windows.GetExitCodeProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, exitcode_process);
if Windows.STILL_ACTIVE <> exitcode_process then
begin
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle := 0;
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0;
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd := 0;
// 这里下载进程 shutdown 了
if TaskStatus_Active = ADownloadTask.TaskStatus then
begin
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
ADownloadTask.DownProcessTaskArray[0].DealItem := TStockDataConsoleApp(App.AppAgent).TaskConsole.Console_GetNextDownloadDealItem(@ADownloadTask.DownProcessTaskArray[0]);
end;
if nil <> ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
RequestDownloadProcessTaskStockData(@ADownloadTask.DownProcessTaskArray[0]);
end;
end;
end else
begin
if ADownloadTask.DownProcessTaskArray[0].MonitorDealItem <> ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
ADownloadTask.DownProcessTaskArray[0].MonitorDealItem := ADownloadTask.DownProcessTaskArray[0].DealItem;
ADownloadTask.DownProcessTaskArray[0].MonitorTick := GetTickCount;
end else
begin
//Log('SDConsoleForm.pas', 'tmrRefreshDownloadTaskTimer CheckTask TerminateProcess Wnd :' +
// IntToStr(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd));
if 0 = ADownloadTask.DownProcessTaskArray[0].MonitorTick then
begin
ADownloadTask.DownProcessTaskArray[0].MonitorTick := GetTickCount;
end else
begin
tick_gap := GetTickCount - ADownloadTask.DownProcessTaskArray[0].MonitorTick;
waittime := 10 * 1000;
case ADownloadTask.TaskDataSrc of
src_all : waittime := 30 * 1000;
src_ctp: waittime := 10 * 1000;
src_offical: waittime := 10 * 1000;
src_tongdaxin: waittime := 10 * 1000;
src_tonghuasun: waittime := 10 * 1000;
src_dazhihui: waittime := 10 * 1000;
src_sina: waittime := 3 * 60 * 1000;
src_163: waittime := 25 * 1000;
src_qq: waittime := 20 * 1000;
src_xq: waittime := 20 * 1000;
end;
if tick_gap > waittime then
begin
//Log('SDConsoleForm.pas', 'tmrRefreshDownloadTaskTimer CheckTask TerminateProcess Wnd :' +
// IntToStr(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd));
TerminateProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, 0);
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle := 0;
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0;
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd := 0;
end;
end;
end;
end;
end;
end;
var
tmpActiveCount: integer;
begin
inherited;
tmpActiveCount := CheckTask(fFormSDConsoleData.DownloadAllTasks[src_163], edtStock163);
tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadAllTasks[src_sina], edtStockSina);
// tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadQQAllTask, edtStockQQ);
// tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadXQAllTask, edtStockXQ);
if 0 = tmpActiveCount then
begin
if chkShutDown.Checked then
win.shutdown.ShutDown;
end;
end;
function TfrmSDConsole.GetDataSrc: TDealDataSource;
var
s: string;
tmpName: string;
tmpSrc: TDealDataSource;
begin
Result := src_unknown;
s := lowercase(Trim(cmbDownloadSrc.Text));
for tmpSrc := Low(TDealDataSource) to High(TDealDataSource) do
begin
tmpName := lowercase(GetDataSrcName(tmpSrc));
if '' <> tmpName then
begin
if 0 < Pos(tmpName, s) then
begin
Result := tmpSrc;
exit;
end;
end;
end;
end;
procedure TfrmSDConsole.btnDownloadClick(Sender: TObject);
var
tmpCode: integer;
tmpSrc: TDealDataSource;
begin
tmpCode := GetStockCode;
tmpSrc := GetDataSrc;
if src_Unknown <> tmpSrc then
begin
if 0 <> tmpCode then
begin
RequestDownloadStockData(nil, tmpSrc, tmpCode);
end else
begin
fFormSDConsoleData.DownloadAllTasks[tmpSrc] := NewDownloadAllTask(tmpSrc, fFormSDConsoleData.DownloadAllTasks[tmpSrc]);
end;
end;
end;
procedure TfrmSDConsole.btnOpenClick(Sender: TObject);
var
tmpFileUrl: string;
tmpOpenDlg: TOpenDialog;
i: integer;
tmpIsDone: Boolean;
begin
tmpOpenDlg := TOpenDialog.Create(Self);
try
tmpOpenDlg.InitialDir := ExtractFilePath(ParamStr(0));
tmpOpenDlg.DefaultExt := '.dic';
tmpOpenDlg.Filter := 'dic file|*.dic|ini file|*.ini';
tmpOpenDlg.Options := tmpOpenDlg.Options + [ofAllowMultiSelect];
//tmpOpenDlg.OptionsEx := [];
if not tmpOpenDlg.Execute then
exit;
tmpIsDone := false;
for i := 0 to tmpOpenDlg.Files.Count - 1 do
begin
tmpFileUrl := tmpOpenDlg.Files[i];
if 0 < Pos('.ini', lowercase(tmpFileUrl)) then
begin
db_dealItem_LoadIni.LoadDBStockItemIniFromFile(App, TBaseStockApp(App).StockItemDB, tmpFileUrl);
tmpIsDone := true;
end;
if 0 < Pos('.dic', lowercase(tmpFileUrl)) then
begin
db_dealItem_Load.LoadDBStockItemDicFromFile(App, TBaseStockApp(App).StockItemDB, tmpFileUrl);
tmpIsDone := true;
end;
end;
if tmpIsDone then
begin
fFormSDConsoleData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB);
end;
finally
tmpOpenDlg.Free;
end;
end;
type
PParseRecord = ^TParseRecord;
TParseRecord = record
HeadParse: THttpHeadParseSession;
HtmlDoc: PHtmlDocDomNode;
IsInDiv: Integer;
Stocks: TStringList;
end;
function getNodeText(ANode: PHtmlDomNode): string;
var
i: integer;
tmpNode: PHtmlDomNode;
begin
Result := '';
if nil = ANode then
exit;
Result := ANode.NodeValue;
if nil <> ANode.ChildNodes then
begin
for i := 0 to ANode.ChildNodes.Length - 1 do
begin
tmpNode := ANode.ChildNodes.item(i);
Result := result + tmpNode.NodeValue;
end;
end;
end;
function getAttribValue(ANode: PHtmlDomNode; AttribName: string): string;
var
i: integer;
tmpNode: PHtmlDomNode;
begin
Result := '';
if nil = ANode then
exit;
if '' = AttribName then
exit;
for i := 0 to ANode.attributes.length - 1 do
begin
tmpNode := ANode.attributes.item(i);
if SameText(AttribName, tmpNode.nodeName) then
begin
Result := getNodeText(tmpNode);
end;
end;
end;
function HtmlParse_StockItem(AParseRecord: PParseRecord; ANode: PHtmlDomNode): Boolean;
var
i, tmpcnt: Integer;
tmpNode: PHtmlDomNode;
tmpValue: string;
tmpOldIsInDiv: integer;
tmpDealItem: PRT_DealItem;
tmpStockCode: string;
tmpStockName: string;
tmpIsStock: Boolean;
begin
result := false;
tmpOldIsInDiv := AParseRecord.IsInDiv;
try
// div class="quotebody"
if 0 = AParseRecord.IsInDiv then
begin
if SameText('div', string(lowercase(ANode.nodeName))) then
begin
if nil <> ANode.attributes then
begin
for i := 0 to ANode.attributes.length - 1 do
begin
tmpNode := ANode.attributes.item(i);
if SameText('class', tmpNode.nodeName) then
begin
tmpValue := getNodeText(tmpNode);
if SameText('quotebody', tmpValue) then
begin
AParseRecord.IsInDiv := 1;
end;
end;
end;
end;
end;
end;
if 1 = AParseRecord.IsInDiv then
begin
if SameText('li', string(lowercase(ANode.nodeName))) then
begin
AParseRecord.IsInDiv := 2;
end;
end;
if 2 = AParseRecord.IsInDiv then
begin
if SameText('a', string(lowercase(ANode.nodeName))) then
begin
tmpValue := getAttribValue(ANode, 'href');
if '' <> tmpValue then
begin
tmpValue := getNodeText(ANode);
if '' <> tmpValue then
begin
i := Pos('(', tmpValue);
if 0 < i then
begin
tmpStockName := Copy(tmpValue, 1, i - 1);
tmpStockCode := Copy(tmpValue, i + 1, maxint);
tmpStockCode := Trim(StringReplace(tmpStockCode, ')', '', [rfReplaceAll]));
if '' <> tmpStockCode then
begin
if 6 = Length(tmpStockCode) then
begin
tmpIsStock := ('6' = tmpStockCode[1]) or
(('0' = tmpStockCode[1]) and ('0' = tmpStockCode[2])) or
('3' = tmpStockCode[1]);
if tmpIsStock then
begin
if nil <> GlobalBaseStockApp then
begin
if nil <> GlobalBaseStockApp.StockItemDB then
begin
tmpDealItem := GlobalBaseStockApp.StockItemDB.FindDealItemByCode(tmpStockCode);
if nil = tmpDealItem then
begin
if ('6' = tmpStockCode[1]) then
begin
tmpDealItem := GlobalBaseStockApp.StockItemDB.AddDealItem(Market_SH, tmpStockCode);
end else
begin
tmpDealItem := GlobalBaseStockApp.StockItemDB.AddDealItem(Market_SZ, tmpStockCode);
end;
tmpDealItem.Name := tmpStockName;
end;
end;
end;
if ('6' = tmpStockCode[1]) then
begin
AParseRecord.Stocks.Add(Market_SH + tmpStockCode + ',' + tmpStockName);
end else
begin
AParseRecord.Stocks.Add(Market_SZ + tmpStockCode + ',' + tmpStockName);
end;
end;
end;
end;
end;
end;
end;
end;
end;
if nil <> ANode.childNodes then
begin
tmpcnt := ANode.childNodes.length;
for i := 0 to tmpcnt - 1 do
begin
tmpNode := ANode.childNodes.item(i);
if not result then
begin
result := HtmlParse_StockItem(AParseRecord, tmpNode);
end else
begin
HtmlParse_StockItem(AParseRecord, tmpNode);
end;
end;
end;
finally
AParseRecord.IsInDiv := tmpOldIsInDiv;
end;
end;
procedure TfrmSDConsole.btnRefreshClick(Sender: TObject);
var
tmpUrl: string;
tmpParseRec: TParseRecord;
tmpHttpSession: THttpClientSession;
tmpHttpData: PIOBuffer;
tmpStr: string;
begin
inherited;
FillChar(tmpHttpSession, SizeOf(tmpHttpSession), 0);
tmpUrl := 'http://quote.eastmoney.com/stocklist.html';
tmpHttpData := nil;
tmpHttpData := GetHttpUrlData(tmpUrl, @tmpHttpSession, tmpHttpData);
if nil <> tmpHttpData then
begin
FillChar(tmpParseRec, SizeOf(tmpParseRec), 0);
tmpParseRec.Stocks := TStringList.Create;
HttpBufferHeader_Parser(tmpHttpData, @tmpParseRec.HeadParse);
if (199 < tmpParseRec.HeadParse.RetCode) and (300 > tmpParseRec.HeadParse.RetCode)then
begin
try
tmpParseRec.HtmlDoc := HtmlParserparseString(WideString(AnsiString(PAnsiChar(@tmpHttpData.Data[tmpParseRec.HeadParse.HeadEndPos + 1]))));
if tmpParseRec.HtmlDoc <> nil then
begin
try
HtmlParse_StockItem(@tmpParseRec, PHtmlDomNode(tmpParseRec.HtmlDoc));
tmpParseRec.Stocks.Delimiter := '|';
tmpStr := tmpParseRec.Stocks.Text;
if '' <> tmpStr then
begin
tmpParseRec.Stocks.Text := StringReplace(tmpStr, #13#10, '|', [rfReplaceAll]);
end;
//tmpParseRec.Stocks.SaveToFile('e:\stock.txt');
TBaseStockApp(App).StockItemDB.Sort;
fFormSDConsoleData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB);
finally
HtmlDomNodeFree(PHtmlDomNode(tmpParseRec.HtmlDoc));
tmpParseRec.HtmlDoc := nil;
end;
end;
except
end;
end;
end;
end;
function TfrmSDConsole.NewDownloadAllTask(ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask;
begin
Result := ADownloadTask;
if nil = Result then
begin
Result := TStockDataConsoleApp(App.AppAgent).TaskConsole.GetDownloadTask(ADataSrc, 0);
if nil = Result then
begin
Result := TStockDataConsoleApp(App.AppAgent).TaskConsole.NewDownloadTask(ADataSrc, 0);
end;
RequestDownloadStockData(Result, ADataSrc, 0);
end;
if not tmrRefreshDownloadTask.Enabled then
tmrRefreshDownloadTask.Enabled := True;
end;
procedure TfrmSDConsole.btnClearClick(Sender: TObject);
begin
inherited;
fFormSDConsoleData.DealItemTree.Clear;
TBaseStockApp(App).StockItemDB.Clear;
end;
procedure TfrmSDConsole.SaveDealItemDBAsDic(AFileUrl: string);
begin
TBaseStockApp(App).StockItemDB.Sort;
db_dealItem_Save.SaveDBStockItemToDicFile(App, TBaseStockApp(App).StockItemDB, AFileUrl);
end;
procedure TfrmSDConsole.SaveDealItemDBAsIni(AFileUrl: string);
begin
TBaseStockApp(App).StockItemDB.Sort;
db_dealItem_Save.SaveDBStockItemToIniFile(App, TBaseStockApp(App).StockItemDB, AFileUrl);
end;
procedure TfrmSDConsole.btnSaveDicClick(Sender: TObject);
var
tmpFileUrl: string;
tmpSaveDlg: TSaveDialog;
begin
tmpFileUrl := '';
tmpSaveDlg := TSaveDialog.Create(Self);
try
tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0));
tmpSaveDlg.DefaultExt := '.dic';
tmpSaveDlg.Filter := 'dic file|*.dic';
if not tmpSaveDlg.Execute then
exit;
tmpFileUrl := tmpSaveDlg.FileName;
if '' <> Trim(tmpFileUrl) then
begin
SaveDealItemDBAsDic(tmpFileUrl);
end;
finally
tmpSaveDlg.Free;
end;
end;
procedure TfrmSDConsole.btnSaveIniClick(Sender: TObject);
var
tmpFileUrl: string;
tmpSaveDlg: TSaveDialog;
begin
tmpFileUrl := '';
tmpSaveDlg := TSaveDialog.Create(Self);
try
tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0));
tmpSaveDlg.DefaultExt := '.ini';
tmpSaveDlg.Filter := 'ini file|*.ini';
if not tmpSaveDlg.Execute then
exit;
tmpFileUrl := tmpSaveDlg.FileName;
if '' <> Trim(tmpFileUrl) then
begin
SaveDealItemDBAsIni(tmpFileUrl);
end;
finally
tmpSaveDlg.Free;
end;
end;
procedure TfrmSDConsole.btnShutDownClick(Sender: TObject);
begin
inherited;
win.shutdown.ShutDown;
end;
procedure TfrmSDConsole.SetDayDataSrc(AValue: TDealDataSource);
begin
end;
function TfrmSDConsole.GetDayDataSrc: TDealDataSource;
var
s: string;
tmpSrc: TDealDataSource;
begin
Result := src_unknown;
s := '';
if 0 < cmbDayDataSrc.ItemIndex then
begin
s := Trim(cmbDayDataSrc.Items[cmbDayDataSrc.ItemIndex]);
end;
if '' <> s then
begin
for tmpSrc := Low(TDealDataSource) to High(TDealDataSource) do
begin
if 0 < Pos(GetDataSrcName(tmpSrc), s) then
begin
Result := tmpSrc;
Break;
end;
end;
end;
end;
procedure TfrmSDConsole.cmbDayDataSrcChange(Sender: TObject);
begin
inherited;
if '' = Trim(cmbDayDataSrc.Text) then
exit;
//
end;
end.
|
unit kwIn;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwIn.pas"
// Начат: 11.05.2011 20:14
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwIn
//
// {code}
// : InParameter IN A IN B
// A . B .
// ;
//
// : "Напечатать два значения"
// InParameter
// ;
//
// 2 'Hello' InParameter
//
// "Напечатать два значения {(10)} {('Привет')}"
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
l3Interfaces,
tfwScriptingInterfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwVar.imp.pas}
TkwIn = class(_tfwVar_)
{* [code]
: InParameter IN A IN B
A . B .
;
: "Напечатать два значения"
InParameter
;
2 'Hello' InParameter
"Напечатать два значения [(10)] [('Привет')]"
[code] }
protected
// overridden protected methods
procedure AfterCompile(var aPrevContext: TtfwContext;
var theNewContext: TtfwContext;
aCompiled: TkwCompiledWord); override;
function CompiledWordClass: RkwCompiledWord; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwIn
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
kwCompiledPopToVar,
SysUtils,
kwCompiledIn,
kwCompiledVar,
l3String,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwIn;
{$Include ..\ScriptEngine\tfwVar.imp.pas}
// start class TkwIn
class function TkwIn.GetWordNameForRegister: AnsiString;
//#UC START# *4DB0614603C8_4DCAB5CD03C9_var*
//#UC END# *4DB0614603C8_4DCAB5CD03C9_var*
begin
//#UC START# *4DB0614603C8_4DCAB5CD03C9_impl*
Result := 'IN';
//#UC END# *4DB0614603C8_4DCAB5CD03C9_impl*
end;//TkwIn.GetWordNameForRegister
procedure TkwIn.AfterCompile(var aPrevContext: TtfwContext;
var theNewContext: TtfwContext;
aCompiled: TkwCompiledWord);
//#UC START# *4DB6CE2302C9_4DCAB5CD03C9_var*
//#UC END# *4DB6CE2302C9_4DCAB5CD03C9_var*
begin
//#UC START# *4DB6CE2302C9_4DCAB5CD03C9_impl*
aPrevContext.rCompiler.CompileInParameterPopCode(aPrevContext, aCompiled As TkwCompiledIn);
inherited;
//#UC END# *4DB6CE2302C9_4DCAB5CD03C9_impl*
end;//TkwIn.AfterCompile
function TkwIn.CompiledWordClass: RkwCompiledWord;
//#UC START# *4DBAEE0D028D_4DCAB5CD03C9_var*
//#UC END# *4DBAEE0D028D_4DCAB5CD03C9_var*
begin
//#UC START# *4DBAEE0D028D_4DCAB5CD03C9_impl*
Result := TkwCompiledIn;
//#UC END# *4DBAEE0D028D_4DCAB5CD03C9_impl*
end;//TkwIn.CompiledWordClass
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwVar.imp.pas}
{$IfEnd} //not NoScripts
end. |
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.7 9/8/2004 10:10:40 PM JPMugaas
Now should work properly in DotNET versions of Delphi.
Rev 1.6 9/5/2004 3:16:58 PM JPMugaas
Should work in D9 DotNET.
Rev 1.5 2/26/2004 8:53:22 AM JPMugaas
Hack to restore the property editor for SASL mechanisms.
Rev 1.4 1/25/2004 3:11:10 PM JPMugaas
SASL Interface reworked to make it easier for developers to use.
SSL and SASL reenabled components.
Rev 1.3 10/19/2003 6:05:38 PM DSiders
Added localization comments.
Rev 1.2 10/12/2003 1:49:30 PM BGooijen
Changed comment of last checkin
Rev 1.1 10/12/2003 1:43:30 PM BGooijen
Changed IdCompilerDefines.inc to Core\IdCompilerDefines.inc
Rev 1.0 11/14/2002 02:19:14 PM JPMugaas
2002-08 Johannes Berg
Form for the SASL List Editor. It doesn't use a DFM/XFM to be
more portable between Delphi/Kylix versions, and to make less
trouble maintaining it.
}
unit IdDsnSASLListEditorFormVCL;
interface
{$I IdCompilerDefines.inc}
uses
{$IFDEF WIDGET_KYLIX}
QControls, QForms, QStdCtrls, QButtons, QExtCtrls, QActnList, QGraphics,
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE}
Controls, Forms, StdCtrls, Buttons, ExtCtrls, ActnList, Graphics,
{$ENDIF}
Classes, IdSASLCollection;
type
TfrmSASLListEditorVCL = class(TForm)
protected
lbAvailable: TListBox;
lbAssigned: TListBox;
sbAdd: TSpeedButton;
sbRemove: TSpeedButton;
{$IFDEF USE_TBitBtn}
BtnCancel: TBitBtn;
BtnOk: TBitBtn;
{$ELSE}
BtnCancel: TButton;
BtnOk: TButton;
{$ENDIF}
Label1: TLabel;
Label2: TLabel;
sbUp: TSpeedButton;
sbDown: TSpeedButton;
SASLList: TIdSASLEntries;
FListOwner: TComponent;
actEditor: TActionList;
actAdd : TAction;
actRemove : TAction;
actMoveUp : TAction;
actMoveDown : TAction;
procedure actAddUpdate(Sender: TObject);
procedure actAddExecute(Sender: TObject);
procedure actRemoveUpdate(Sender:TObject);
procedure actRemoveExecute(Sender:TObject);
procedure actMoveUpUpdate(Sender:TObject);
procedure actMoveUpExecute(Sender:TObject);
procedure actMoveDownExecute(Sender:TObject);
procedure actMoveDownUpdate(Sender:TObject);
procedure FormCreate;
procedure UpdateList;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
function Execute : Boolean;
procedure SetList(const CopyFrom: TIdSASLEntries);
procedure GetList(const CopyTo: TIdSASLEntries);
procedure SetComponentName(const Name: string);
end;
implementation
uses
{$IFDEF WIDGET_LCL}
LResources,
{$ENDIF}
IdDsnCoreResourceStrings,
IdGlobal, IdResourceStrings, IdSASL,
SysUtils;
{ TfrmSASLListEditorVCL }
{$IFNDEF WIDGET_LCL}
{$IFDEF WINDOWS}
{$R IdSASLListEditorForm.RES}
{$ENDIF}
{$IFDEF KYLIX}
{$R IdSASLListEditorForm.RES}
{$ENDIF}
{$ENDIF}
constructor TfrmSASLListEditorVCL.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner,0);
FormCreate;
UpdateList;
end;
procedure TfrmSASLListEditorVCL.GetList(const CopyTo: TIdSASLEntries);
begin
CopyTo.Assign(SASLList);
end;
procedure TfrmSASLListEditorVCL.SetList(const CopyFrom: TIdSASLEntries);
var
i, idx: integer;
begin
SASLList.Assign(CopyFrom);
for i := 0 to CopyFrom.Count-1 do begin
if Assigned(CopyFrom[i].SASL) then
begin
idx := lbAvailable.Items.IndexOf(CopyFrom[i].SASL.Name);
if idx >= 0 then begin
lbAvailable.Items.Delete(idx);
end;
end;
end;
UpdateList;
end;
procedure TfrmSASLListEditorVCL.UpdateList;
var
i: integer;
l : TList;
begin
lbAssigned.Clear;
for i := 0 to SASLList.Count -1 do begin
if Assigned(SASLList[i].SASL) then
begin
lbAssigned.Items.AddObject(SASLList[i].SASL.Name + ': ' + String(SASLList[i].SASL.ServiceName), SASLList[i]);
end;
end;
lbAvailable.Clear;
l := GlobalSASLList.LockList;
try
for i := 0 to l.Count-1 do begin
if SASLList.IndexOfComp(TIdSASL(l[i])) < 0 then begin
if Assigned(l[i]) then
begin
lbAvailable.Items.AddObject(TIdSASL(l[i]).Name + ': ' + String(TIdSASL(l[i]).ServiceName), TIdSASL(l[i]));
end;
end;
end;
finally
GlobalSASLList.UnlockList;
end;
end;
procedure TfrmSASLListEditorVCL.SetComponentName(const Name: string);
begin
Caption := IndyFormat(Caption, [Name]);
end;
procedure TfrmSASLListEditorVCL.FormCreate;
begin
SASLList := TIdSASLEntries.Create(Self);
Left := 292;
Top := 239;
{$IFDEF WIDGET_KYLIX}
BorderStyle := fbsDialog;
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE}
BorderStyle := bsDialog;
{$ENDIF}
Caption := RSADlgSLCaption;
{$IFDEF USE_TBitBtn}
ClientHeight := 349;
{$ELSE}
ClientHeight := 344;
{$ENDIF}
ClientWidth := 452;
Position := poScreenCenter;
//workaround for problem - form position does not work like in VCL
Left := (Screen.Width - Width) div 2;
Top := (Screen.Height - Height) div 2;
{we do the actions here so that the rest of the components can bind to them}
actEditor := TActionList.Create(Self);
actAdd := TAction.Create(Self);
actAdd.ActionList := actEditor;
actAdd.Hint := RSADlgSLAdd;
actAdd.OnExecute := actAddExecute;
actAdd.OnUpdate := actAddUpdate;
actRemove := TAction.Create(Self);
actRemove.ActionList := actEditor;
actRemove.Hint := RSADlgSLRemove;
actRemove.OnExecute := actRemoveExecute;
actRemove.OnUpdate := actRemoveUpdate;
actMoveUp := TAction.Create(Self);
actMoveUp.ActionList := actEditor;
actMoveUp.Hint := RSADlgSLMoveUp;
actMoveUp.OnExecute := actMoveUpExecute;
actMoveUp.OnUpdate := actMoveUpUpdate;
actMoveDown := TAction.Create(Self);
actMoveDown.ActionList := actEditor;
actMoveDown.Hint := RSADlgSLMoveDown;
actMoveDown.OnExecute := actMoveDownExecute;
actMoveDown.OnUpdate := actMoveDownUpdate;
sbAdd := TSpeedButton.Create(Self);
with sbAdd do
begin
Name := 'sbAdd'; {do not localize}
Parent := Self;
Action := actAdd;
Left := 184;
Top := 88;
Width := 57;
Height := 25;
ShowHint := True;
{$IFDEF WIDGET_LCL}
Glyph.LoadFromLazarusResource('DIS_ARROWRIGHT'); {do not localize}
{$ELSE}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
Glyph.LoadFromResourceName(HInstance, 'ARROWRIGHT'); {do not localize}
NumGlyphs := 2;
{$ENDIF}
{$ENDIF}
end;
sbRemove := TSpeedButton.Create(Self);
with sbRemove do
begin
Name := 'sbRemove'; {do not localize}
Parent := Self;
Action := actRemove;
Left := 184;
Top := 128;
Width := 57;
Height := 25;
ShowHint := True;
{$IFDEF WIDGET_LCL}
Glyph.LoadFromLazarusResource('DIS_ARROWLEFT'); {do not localize}
{$ELSE}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
Glyph.LoadFromResourceName(HInstance, 'ARROWLEFT'); {do not localize}
NumGlyphs := 2;
{$ENDIF}
{$ENDIF}
end;
Label1 := TLabel.Create(Self);
with Label1 do
begin
Name := 'Label1'; {do not localize}
Parent := Self;
Left := 8;
Top := 8;
Width := 42;
Height := 13;
Caption := RSADlgSLAvailable;
end;
Label2 := TLabel.Create(Self);
with Label2 do
begin
Name := 'Label2'; {do not localize}
Parent := Self;
Left := 248;
Top := 8;
Width := 136;
Height := 13;
Caption := RSADlgSLAssigned
end;
sbUp := TSpeedButton.Create(Self);
with sbUp do
begin
Name := 'sbUp'; {do not localize}
Parent := Self;
Action := actMoveUp;
Left := 424;
Top := 88;
Width := 23;
Height := 22;
ShowHint := True;
{$IFDEF WIDGET_LCL}
Glyph.LoadFromLazarusResource('DIS_ARROWUP'); {do not localize}
{$ELSE}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
Glyph.LoadFromResourceName(HInstance, 'ARROWUP'); {do not localize}
NumGlyphs := 2;
{$ENDIF}
{$ENDIF}
end;
sbDown := TSpeedButton.Create(Self);
with sbDown do
begin
Name := 'sbDown'; {do not localize}
Parent := Self;
Action := actMoveDown;
Left := 424;
Top := 128;
Width := 23;
Height := 22;
ShowHint := True;
{$IFDEF WIDGET_LCL}
Glyph.LoadFromLazarusResource('DIS_ARROWDOWN'); {do not localize}
{$ELSE}
{$IFDEF WIDGET_VCL_LIKE_OR_KYLIX}
Glyph.LoadFromResourceName(HInstance, 'ARROWDOWN'); {do not localize}
NumGlyphs := 2;
{$ENDIF}
{$ENDIF}
end;
lbAvailable := TListBox.Create(Self);
with lbAvailable do
begin
Name := 'lbAvailable'; {do not localize}
Parent := Self;
Left := 8;
Top := 24;
Width := 169;
Height := 281;
ItemHeight := 13;
TabOrder := 0;
end;
lbAssigned := TListBox.Create(Self);
with lbAssigned do
begin
Name := 'lbAssigned'; {do not localize}
Parent := Self;
Left := 248;
Top := 24;
Width := 169;
Height := 281;
ItemHeight := 13;
TabOrder := 1;
end;
{$IFDEF USE_TBitBtn}
BtnCancel := TBitBtn.Create(Self);
{$ELSE}
BtnCancel := TButton.Create(Self);
{$ENDIF}
with BtnCancel do
begin
Name := 'BtnCancel'; {do not localize}
Left := 368;
Top := 312;
Width := 75;
{$IFDEF WIDGET_LCL}
Height := 30;
Kind := bkCancel;
{$ELSE}
Height := 25;
Cancel := True;
Caption := RSCancel;
ModalResult := 2;
{$ENDIF}
Parent := Self;
end;
{$IFDEF USE_TBitBtn}
BtnOk := TBitBtn.Create(Self);
{$ELSE}
BtnOk := TButton.Create(Self);
{$ENDIF}
with BtnOk do
begin
Name := 'BtnOk'; {do not localize}
Parent := Self;
Left := 287;
Top := 312;
Width := 75;
{$IFDEF WIDGET_LCL}
Height := 30;
Kind := bkOk;
{$ELSE}
Height := 25;
Caption := RSOk;
Default := True;
ModalResult := 1;
{$ENDIF}
TabOrder := 2;
TabOrder := 3;
end;
end;
procedure TfrmSASLListEditorVCL.actAddExecute(Sender: TObject);
var
sel: integer;
begin
sel := lbAvailable.ItemIndex;
if sel >= 0 then begin
SASLList.Add.SASL := TIdSASL(lbAvailable.Items.Objects[sel]);
UpdateList;
end;
end;
procedure TfrmSASLListEditorVCL.actAddUpdate(Sender: TObject);
var
LEnabled : Boolean;
begin
//we do this in a round about way because we should update the glyph
//with an enabled/disabled form so a user can see what is applicable
LEnabled := (lbAvailable.Items.Count <> 0) and
(lbAvailable.ItemIndex <> -1);
{$IFDEF WIDGET_LCL}
if LEnabled <> actAdd.Enabled then
begin
if LEnabled then begin
sbAdd.Glyph.LoadFromLazarusResource('ARROWRIGHT'); {do not localize}
end else begin
sbAdd.Glyph.LoadFromLazarusResource('DIS_ARROWRIGHT'); {do not localize}
end;
end;
{$ENDIF}
actAdd.Enabled := LEnabled;
end;
procedure TfrmSASLListEditorVCL.actMoveDownExecute(Sender: TObject);
var
sel: integer;
begin
sel := lbAssigned.ItemIndex;
if (sel >= 0) and (sel < lbAssigned.Items.Count-1) then begin
SASLList.Items[sel].Index := sel+1;
Updatelist;
lbAssigned.ItemIndex := sel+1;
end;
end;
procedure TfrmSASLListEditorVCL.actMoveDownUpdate(Sender: TObject);
var
LEnabled : Boolean;
begin
LEnabled := (lbAssigned.Items.Count > 1) and
(lbAssigned.ItemIndex <> -1) and
(lbAssigned.ItemIndex < (lbAssigned.Items.Count - 1));
{$IFDEF WIDGET_LCL}
if LEnabled <> actMoveDown.Enabled then
begin
if LEnabled then begin
sbDown.Glyph.LoadFromLazarusResource('ARROWDOWN'); {do not localize}
end else begin
sbDown.Glyph.LoadFromLazarusResource('DIS_ARROWDOWN'); {do not localize}
end;
end;
{$ENDIF}
actMoveDown.Enabled := LEnabled;
end;
procedure TfrmSASLListEditorVCL.actMoveUpExecute(Sender: TObject);
var
sel: integer;
begin
sel := lbAssigned.ItemIndex;
// >0 is intentional, can't move the top element up!!
if sel > 0 then begin
SASLList.Items[Sel].Index := sel-1;
UpdateList;
lbAssigned.ItemIndex := sel -1;
end;
end;
procedure TfrmSASLListEditorVCL.actMoveUpUpdate(Sender: TObject);
var
LEnabled : Boolean;
begin
//we do this in a round about way because we should update the glyph
//with an enabled/disabled form so a user can see what is applicable
LEnabled := (lbAssigned.Items.Count > 1) and
(lbAssigned.ItemIndex > 0); // -1 not selected and 0 = top
{$IFDEF WIDGET_LCL}
if LEnabled <> actMoveUp.Enabled then
begin
if LEnabled then begin
sbUp.Glyph.LoadFromLazarusResource('ARROWUP'); {do not localize}
end else begin
sbUp.Glyph.LoadFromLazarusResource('DIS_ARROWUP'); {do not localize}
end;
end;
{$ENDIF}
actMoveUp.Enabled := LEnabled;
end;
procedure TfrmSASLListEditorVCL.actRemoveExecute(Sender: TObject);
var
sel: integer;
begin
sel := lbAssigned.ItemIndex;
if sel >= 0 then begin
SASLList.Delete(sel);
end;
UpdateList;
{ sel := lbAssigned.ItemIndex;
if sel >= 0 then begin
SASLList.Remove(TIdSASL(lbAssigned.Items.Objects[sel]));
UpdateList;
end; }
end;
procedure TfrmSASLListEditorVCL.actRemoveUpdate(Sender: TObject);
var
LEnabled : Boolean;
begin
LEnabled := (lbAssigned.Items.Count <> 0) and
(lbAssigned.ItemIndex <> -1);
{$IFDEF WIDGET_LCL}
if LEnabled <> actRemove.Enabled then
begin
if LEnabled then begin
sbRemove.Glyph.LoadFromLazarusResource('ARROWLEFT'); {do not localize}
end else begin
sbRemove.Glyph.LoadFromLazarusResource('DIS_ARROWLEFT'); {do not localize}
end;
end;
{$ENDIF}
actRemove.Enabled := LEnabled;
end;
function TfrmSASLListEditorVCL.Execute: Boolean;
begin
Result := ShowModal = mrOk;
end;
{$IFDEF WIDGET_LCL}
initialization
{$I IdDsnSASLListEditorFormVCL.lrs}
{$ENDIF}
end.
|
unit UDMMaterialFornecedor;
interface
uses
SysUtils, Classes, DB, DBTables, DBIProcs, Variants;
type
TDMMaterialFornecedor = class(TDataModule)
tMaterialFornecedor: TTable;
dsMaterialFornecedor: TDataSource;
tMaterialFornecedorCodMaterial: TIntegerField;
tMaterialFornecedorCodFornecedor: TIntegerField;
tMaterialFornecedorItem: TIntegerField;
tMaterialFornecedorNomeMaterialForn: TStringField;
tMaterialFornecedorCodMaterialForn: TStringField;
tMaterialFornecedorCodGrade: TIntegerField;
tMaterialFornecedorCodCor: TIntegerField;
tMaterialFornecedorCodPosicao: TIntegerField;
tMaterialFornecedorTamanho: TStringField;
tFornecedores: TTable;
tFornecedoresCodForn: TIntegerField;
tFornecedoresNomeForn: TStringField;
tMaterialFornecedorlkNomeFornecedor: TStringField;
tCor: TTable;
tCorCodigo: TIntegerField;
tCorNome: TStringField;
tMaterialFornecedorlkNomeCor: TStringField;
tMaterialFornecedorCodBarra: TStringField;
tMaterialFornecedorCodMaterialFornPadrao: TStringField;
procedure tMaterialFornecedorAfterPost(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Excluir_MaterialFornecedor(CodMaterial, CodCor, CodGrade : Integer);
function fnc_Existe_MaterialFornecedor(CodMaterial, CodFornecedor, CodCor : Integer ; Tamanho : String) : Boolean;
end;
var
DMMaterialFornecedor: TDMMaterialFornecedor;
implementation
{$R *.dfm}
procedure TDMMaterialFornecedor.Excluir_MaterialFornecedor(CodMaterial,
CodCor, CodGrade: Integer);
begin
tMaterialFornecedor.Filtered := False;
if (CodCor = 0) and (CodGrade = 0) then
tMaterialFornecedor.Filter := 'CodMaterial = '''+IntToStr(CodMaterial)+''''
else
if (CodCor > 0) and (CodGrade = 0) then
tMaterialFornecedor.Filter := 'CodMaterial = '''+IntToStr(CodMaterial)+''' and CodCor = '''+IntToStr(CodCor)+''''
else
if (CodCor = 0) and (CodGrade > 0) then
tMaterialFornecedor.Filter := 'CodMaterial = '''+IntToStr(CodMaterial)+''' and CodGrade = ''' + IntToStr(CodGrade)+''''
else
if (CodCor > 0) and (CodGrade > 0) then
tMaterialFornecedor.Filter := 'CodMaterial = '''+IntToStr(CodMaterial)+''' and CodCor = '''+IntToStr(CodCor)+''' and CodGrade = ''' + IntToStr(CodGrade)+'''';
tMaterialFornecedor.Filtered := True;
tMaterialFornecedor.First;
while not tMaterialFornecedor.Eof do
tMaterialFornecedor.Delete;
end;
procedure TDMMaterialFornecedor.tMaterialFornecedorAfterPost(
DataSet: TDataSet);
begin
DbiSaveChanges(tMaterialFornecedor.Handle);
end;
procedure TDMMaterialFornecedor.DataModuleCreate(Sender: TObject);
begin
tMaterialFornecedor.Open;
tFornecedores.Open;
tCor.Open;
end;
function TDMMaterialFornecedor.fnc_Existe_MaterialFornecedor(CodMaterial,
CodFornecedor, CodCor: Integer; Tamanho: String): Boolean;
begin
Result := False;
if CodCor <= 0 then
CodCor := 0;
if Trim(Tamanho) <> '' then
if (tMaterialFornecedor.Locate('CodMaterial;CodFornecedor;CodCor;Tamanho',VarArrayOf([CodMaterial,CodFornecedor,CodCor,Tamanho]),[loCaseInsensitive])) then
Result := True;
if not(Result) then
if (tMaterialFornecedor.Locate('CodMaterial;CodFornecedor;CodCor',VarArrayOf([CodMaterial,CodFornecedor,CodCor]),[loCaseInsensitive])) then
Result := True;
if not(Result) then
if (tMaterialFornecedor.Locate('CodMaterial;CodFornecedor',VarArrayOf([CodMaterial,CodFornecedor]),[loCaseInsensitive])) then
Result := True;
end;
end.
|
unit TestUEuropean;
{
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, UEuropean, UBird;
type
// Test methods for class TEuropean
TestTEuropean = class(TTestCase)
strict private
FEuropean: TEuropean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestgetSpeed;
end;
implementation
procedure TestTEuropean.SetUp;
begin
FEuropean := TEuropean.Create;
end;
procedure TestTEuropean.TearDown;
begin
FEuropean.Free;
FEuropean := nil;
end;
procedure TestTEuropean.TestgetSpeed;
var
ReturnValue: string;
begin
ReturnValue := FEuropean.getSpeed;
CheckEquals(ReturnValue, 'European', 'сообщение об ошибке');
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTEuropean.Suite);
end.
|
{| Unit: bseerr
| Version: 1.00
| translated from file bseerr.H
| Original translation: Peter Sawatzki (ps)
| Contributing:
| (fill in)
|
| change history:
| Date: Ver: Author:
| 11/23/93 1.00 ps original translation by ps
}
Unit BseErr;
Interface
{* This file includes the error codes for Base OS/2 applications. }
{** Error codes }
Const
NO_ERROR = 0;
ERROR_INVALID_FUNCTION = 1;
ERROR_FILE_NOT_FOUND = 2;
ERROR_PATH_NOT_FOUND = 3;
ERROR_TOO_MANY_OPEN_FILES = 4;
ERROR_ACCESS_DENIED = 5;
ERROR_INVALID_HANDLE = 6;
ERROR_ARENA_TRASHED = 7;
ERROR_NOT_ENOUGH_MEMORY = 8;
ERROR_INVALID_BLOCK = 9;
ERROR_BAD_ENVIRONMENT = 10;
ERROR_BAD_FORMAT = 11;
ERROR_INVALID_ACCESS = 12;
ERROR_INVALID_DATA = 13;
ERROR_INVALID_DRIVE = 15;
ERROR_CURRENT_DIRECTORY = 16;
ERROR_NOT_SAME_DEVICE = 17;
ERROR_NO_MORE_FILES = 18;
ERROR_WRITE_PROTECT = 19;
ERROR_BAD_UNIT = 20;
ERROR_NOT_READY = 21;
ERROR_BAD_COMMAND = 22;
ERROR_CRC = 23;
ERROR_BAD_LENGTH = 24;
ERROR_SEEK = 25;
ERROR_NOT_DOS_DISK = 26;
ERROR_SECTOR_NOT_FOUND = 27;
ERROR_OUT_OF_PAPER = 28;
ERROR_WRITE_FAULT = 29;
ERROR_READ_FAULT = 30;
ERROR_GEN_FAILURE = 31;
ERROR_SHARING_VIOLATION = 32;
ERROR_LOCK_VIOLATION = 33;
ERROR_WRONG_DISK = 34;
ERROR_FCB_UNAVAILABLE = 35;
ERROR_SHARING_BUFFER_EXCEEDED = 36;
ERROR_NOT_SUPPORTED = 50;
ERROR_REM_NOT_LIST = 51;
ERROR_DUP_NAME = 52;
ERROR_BAD_NETPATH = 53;
ERROR_NETWORK_BUSY = 54;
ERROR_DEV_NOT_EXIST = 55;
ERROR_TOO_MANY_CMDS = 56;
ERROR_ADAP_HDW_ERR = 57;
ERROR_BAD_NET_RESP = 58;
ERROR_UNEXP_NET_ERR = 59;
ERROR_BAD_REM_ADAP = 60;
ERROR_PRINTQ_FULL = 61;
ERROR_NO_SPOOL_SPACE = 62;
ERROR_PRINT_CANCELLED = 63;
ERROR_NETNAME_DELETED = 64;
ERROR_NETWORK_ACCESS_DENIED = 65;
ERROR_BAD_DEV_TYPE = 66;
ERROR_BAD_NET_NAME = 67;
ERROR_TOO_MANY_NAMES = 68;
ERROR_TOO_MANY_SESS = 69;
ERROR_SHARING_PAUSED = 70;
ERROR_REQ_NOT_ACCEP = 71;
ERROR_REDIR_PAUSED = 72;
ERROR_FILE_EXISTS = 80;
ERROR_DUP_FCB = 81;
ERROR_CANNOT_MAKE = 82;
ERROR_FAIL_I24 = 83;
ERROR_OUT_OF_STRUCTURES = 84;
ERROR_ALREADY_ASSIGNED = 85;
ERROR_INVALID_PASSWORD = 86;
ERROR_INVALID_PARAMETER = 87;
ERROR_NET_WRITE_FAULT = 88;
ERROR_NO_PROC_SLOTS = 89;
ERROR_NOT_FROZEN = 90;
ERR_TSTOVFL = 91;
ERR_TSTDUP = 92;
ERROR_NO_ITEMS = 93;
ERROR_INTERRUPT = 95;
ERROR_DEVICE_IN_USE = 99;
ERROR_TOO_MANY_SEMAPHORES = 100;
ERROR_EXCL_SEM_ALREADY_OWNED = 101;
ERROR_SEM_IS_SET = 102;
ERROR_TOO_MANY_SEM_REQUESTS = 103;
ERROR_INVALID_AT_INTERRUPT_TIME = 104;
ERROR_SEM_OWNER_DIED = 105;
ERROR_SEM_USER_LIMIT = 106;
ERROR_DISK_CHANGE = 107;
ERROR_DRIVE_LOCKED = 108;
ERROR_BROKEN_PIPE = 109;
ERROR_OPEN_FAILED = 110;
ERROR_BUFFER_OVERFLOW = 111;
ERROR_DISK_FULL = 112;
ERROR_NO_MORE_SEARCH_HANDLES = 113;
ERROR_INVALID_TARGET_HANDLE = 114;
ERROR_PROTECTION_VIOLATION = 115;
ERROR_VIOKBD_REQUEST = 116;
ERROR_INVALID_CATEGORY = 117;
ERROR_INVALID_VERIFY_SWITCH = 118;
ERROR_BAD_DRIVER_LEVEL = 119;
ERROR_CALL_NOT_IMPLEMENTED = 120;
ERROR_SEM_TIMEOUT = 121;
ERROR_INSUFFICIENT_BUFFER = 122;
ERROR_INVALID_NAME = 123;
ERROR_INVALID_LEVEL = 124;
ERROR_NO_VOLUME_LABEL = 125;
ERROR_MOD_NOT_FOUND = 126;
ERROR_PROC_NOT_FOUND = 127;
ERROR_WAIT_NO_CHILDREN = 128;
ERROR_CHILD_NOT_COMPLETE = 129;
ERROR_DIRECT_ACCESS_HANDLE = 130;
ERROR_NEGATIVE_SEEK = 131;
ERROR_SEEK_ON_DEVICE = 132;
ERROR_IS_JOIN_TARGET = 133;
ERROR_IS_JOINED = 134;
ERROR_IS_SUBSTED = 135;
ERROR_NOT_JOINED = 136;
ERROR_NOT_SUBSTED = 137;
ERROR_JOIN_TO_JOIN = 138;
ERROR_SUBST_TO_SUBST = 139;
ERROR_JOIN_TO_SUBST = 140;
ERROR_SUBST_TO_JOIN = 141;
ERROR_BUSY_DRIVE = 142;
ERROR_SAME_DRIVE = 143;
ERROR_DIR_NOT_ROOT = 144;
ERROR_DIR_NOT_EMPTY = 145;
ERROR_IS_SUBST_PATH = 146;
ERROR_IS_JOIN_PATH = 147;
ERROR_PATH_BUSY = 148;
ERROR_IS_SUBST_TARGET = 149;
ERROR_SYSTEM_TRACE = 150;
ERROR_INVALID_EVENT_COUNT = 151;
ERROR_TOO_MANY_MUXWAITERS = 152;
ERROR_INVALID_LIST_FORMAT = 153;
ERROR_LABEL_TOO_LONG = 154;
ERROR_TOO_MANY_TCBS = 155;
ERROR_SIGNAL_REFUSED = 156;
ERROR_DISCARDED = 157;
ERROR_NOT_LOCKED = 158;
ERROR_BAD_THREADID_ADDR = 159;
ERROR_BAD_ARGUMENTS = 160;
ERROR_BAD_PATHNAME = 161;
ERROR_SIGNAL_PENDING = 162;
ERROR_UNCERTAIN_MEDIA = 163;
ERROR_MAX_THRDS_REACHED = 164;
ERROR_MONITORS_NOT_SUPPORTED = 165;
ERROR_UNC_DRIVER_NOT_INSTALLED = 166;
ERROR_LOCK_FAILED = 167;
ERROR_SWAPIO_FAILED = 168;
ERROR_SWAPIN_FAILED = 169;
ERROR_BUSY = 170;
ERROR_INVALID_SEGMENT_NUMBER = 180;
ERROR_INVALID_CALLGATE = 181;
ERROR_INVALID_ORDINAL = 182;
ERROR_ALREADY_EXISTS = 183;
ERROR_NO_CHILD_PROCESS = 184;
ERROR_CHILD_ALIVE_NOWAIT = 185;
ERROR_INVALID_FLAG_NUMBER = 186;
ERROR_SEM_NOT_FOUND = 187;
ERROR_INVALID_STARTING_CODESEG = 188;
ERROR_INVALID_STACKSEG = 189;
ERROR_INVALID_MODULETYPE = 190;
ERROR_INVALID_EXE_SIGNATURE = 191;
ERROR_EXE_MARKED_INVALID = 192;
ERROR_BAD_EXE_FORMAT = 193;
ERROR_ITERATED_DATA_EXCEEDS_64K = 194;
ERROR_INVALID_MINALLOCSIZE = 195;
ERROR_DYNLINK_FROM_INVALID_RING = 196;
ERROR_IOPL_NOT_ENABLED = 197;
ERROR_INVALID_SEGDPL = 198;
ERROR_AUTODATASEG_EXCEEDS_64k = 199;
ERROR_RING2SEG_MUST_BE_MOVABLE = 200;
ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201;
ERROR_INFLOOP_IN_RELOC_CHAIN = 202;
ERROR_ENVVAR_NOT_FOUND = 203;
ERROR_NOT_CURRENT_CTRY = 204;
ERROR_NO_SIGNAL_SENT = 205;
ERROR_FILENAME_EXCED_RANGE = 206;
ERROR_RING2_STACK_IN_USE = 207;
ERROR_META_EXPANSION_TOO_LONG = 208;
ERROR_INVALID_SIGNAL_NUMBER = 209;
ERROR_THREAD_1_INACTIVE = 210;
ERROR_INFO_NOT_AVAIL = 211;
ERROR_LOCKED = 212;
ERROR_BAD_DYNALINK = 213;
ERROR_TOO_MANY_MODULES = 214;
ERROR_NESTING_NOT_ALLOWED = 215;
ERROR_CANNOT_SHRINK = 216;
ERROR_ZOMBIE_PROCESS = 217;
ERROR_STACK_IN_HIGH_MEMORY = 218;
ERROR_INVALID_EXITROUTINE_RING = 219;
ERROR_GETBUF_FAILED = 220;
ERROR_FLUSHBUF_FAILED = 221;
ERROR_TRANSFER_TOO_LONG = 222;
ERROR_SMG_NO_TARGET_WINDOW = 224;
ERROR_NO_CHILDREN = 228;
ERROR_INVALID_SCREEN_GROUP = 229;
ERROR_BAD_PIPE = 230;
ERROR_PIPE_BUSY = 231;
ERROR_NO_DATA = 232;
ERROR_PIPE_NOT_CONNECTED = 233;
ERROR_MORE_DATA = 234;
ERROR_VC_DISCONNECTED = 240;
ERROR_CIRCULARITY_REQUESTED = 250;
ERROR_DIRECTORY_IN_CDS = 251;
ERROR_INVALID_FSD_NAME = 252;
ERROR_INVALID_PATH = 253;
ERROR_INVALID_EA_NAME = 254;
ERROR_EA_LIST_INCONSISTENT = 255;
ERROR_EA_LIST_TOO_LONG = 256;
ERROR_NO_META_MATCH = 257;
ERROR_FINDNOTIFY_TIMEOUT = 258;
ERROR_NO_MORE_ITEMS = 259;
ERROR_SEARCH_STRUC_REUSED = 260;
ERROR_CHAR_NOT_FOUND = 261;
ERROR_TOO_MUCH_STACK = 262;
ERROR_INVALID_ATTR = 263;
ERROR_INVALID_STARTING_RING = 264;
ERROR_INVALID_DLL_INIT_RING = 265;
ERROR_CANNOT_COPY = 266;
ERROR_DIRECTORY = 267;
ERROR_OPLOCKED_FILE = 268;
ERROR_OPLOCK_THREAD_EXISTS = 269;
ERROR_VOLUME_CHANGED = 270;
ERROR_FINDNOTIFY_HANDLE_IN_USE = 271;
ERROR_FINDNOTIFY_HANDLE_CLOSED = 272;
ERROR_NOTIFY_OBJECT_REMOVED = 273;
ERROR_ALREADY_SHUTDOWN = 274;
ERROR_EAS_DIDNT_FIT = 275;
ERROR_EA_FILE_CORRUPT = 276;
ERROR_EA_TABLE_FULL = 277;
ERROR_INVALID_EA_HANDLE = 278;
ERROR_NO_CLUSTER = 279;
ERROR_CREATE_EA_FILE = 280;
ERROR_CANNOT_OPEN_EA_FILE = 281;
ERROR_INVALID_PROCID = 303;
ERROR_INVALID_PDELTA = 304;
ERROR_NOT_DESCENDANT = 305;
ERROR_NOT_SESSION_MANAGER = 306;
ERROR_INVALID_PCLASS = 307;
ERROR_INVALID_SCOPE = 308;
ERROR_INVALID_THREADID = 309;
ERROR_DOSSUB_SHRINK = 310;
ERROR_DOSSUB_NOMEM = 311;
ERROR_DOSSUB_OVERLAP = 312;
ERROR_DOSSUB_BADSIZE = 313;
ERROR_DOSSUB_BADFLAG = 314;
ERROR_DOSSUB_BADSELECTOR = 315;
ERROR_MR_MSG_TOO_LONG = 316;
ERROR_MR_MID_NOT_FOUND = 317;
ERROR_MR_UN_ACC_MSGF = 318;
ERROR_MR_INV_MSGF_FORMAT = 319;
ERROR_MR_INV_IVCOUNT = 320;
ERROR_MR_UN_PERFORM = 321;
ERROR_TS_WAKEUP = 322;
ERROR_TS_SEMHANDLE = 323;
ERROR_TS_NOTIMER = 324;
ERROR_TS_HANDLE = 326;
ERROR_TS_DATETIME = 327;
ERROR_SYS_INTERNAL = 328;
ERROR_QUE_CURRENT_NAME = 329;
ERROR_QUE_PROC_NOT_OWNED = 330;
ERROR_QUE_PROC_OWNED = 331;
ERROR_QUE_DUPLICATE = 332;
ERROR_QUE_ELEMENT_NOT_EXIST = 333;
ERROR_QUE_NO_MEMORY = 334;
ERROR_QUE_INVALID_NAME = 335;
ERROR_QUE_INVALID_PRIORITY = 336;
ERROR_QUE_INVALID_HANDLE = 337;
ERROR_QUE_LINK_NOT_FOUND = 338;
ERROR_QUE_MEMORY_ERROR = 339;
ERROR_QUE_PREV_AT_END = 340;
ERROR_QUE_PROC_NO_ACCESS = 341;
ERROR_QUE_EMPTY = 342;
ERROR_QUE_NAME_NOT_EXIST = 343;
ERROR_QUE_NOT_INITIALIZED = 344;
ERROR_QUE_UNABLE_TO_ACCESS = 345;
ERROR_QUE_UNABLE_TO_ADD = 346;
ERROR_QUE_UNABLE_TO_INIT = 347;
ERROR_VIO_INVALID_MASK = 349;
ERROR_VIO_PTR = 350;
ERROR_VIO_APTR = 351;
ERROR_VIO_RPTR = 352;
ERROR_VIO_CPTR = 353;
ERROR_VIO_LPTR = 354;
ERROR_VIO_MODE = 355;
ERROR_VIO_WIDTH = 356;
ERROR_VIO_ATTR = 357;
ERROR_VIO_ROW = 358;
ERROR_VIO_COL = 359;
ERROR_VIO_TOPROW = 360;
ERROR_VIO_BOTROW = 361;
ERROR_VIO_RIGHTCOL = 362;
ERROR_VIO_LEFTCOL = 363;
ERROR_SCS_CALL = 364;
ERROR_SCS_VALUE = 365;
ERROR_VIO_WAIT_FLAG = 366;
ERROR_VIO_UNLOCK = 367;
ERROR_SGS_NOT_SESSION_MGR = 368;
ERROR_SMG_INVALID_SGID = 369;
ERROR_SMG_INVALID_SESSION_ID = 369;
ERROR_SMG_NOSG = 370;
ERROR_SMG_NO_SESSIONS = 370;
ERROR_SMG_GRP_NOT_FOUND = 371;
ERROR_SMG_SESSION_NOT_FOUND = 371;
ERROR_SMG_SET_TITLE = 372;
ERROR_KBD_PARAMETER = 373;
ERROR_KBD_NO_DEVICE = 374;
ERROR_KBD_INVALID_IOWAIT = 375;
ERROR_KBD_INVALID_LENGTH = 376;
ERROR_KBD_INVALID_ECHO_MASK = 377;
ERROR_KBD_INVALID_INPUT_MASK = 378;
ERROR_MON_INVALID_PARMS = 379;
ERROR_MON_INVALID_DEVNAME = 380;
ERROR_MON_INVALID_HANDLE = 381;
ERROR_MON_BUFFER_TOO_SMALL = 382;
ERROR_MON_BUFFER_EMPTY = 383;
ERROR_MON_DATA_TOO_LARGE = 384;
ERROR_MOUSE_NO_DEVICE = 385;
ERROR_MOUSE_INV_HANDLE = 386;
ERROR_MOUSE_INV_PARMS = 387;
ERROR_MOUSE_CANT_RESET = 388;
ERROR_MOUSE_DISPLAY_PARMS = 389;
ERROR_MOUSE_INV_MODULE = 390;
ERROR_MOUSE_INV_ENTRY_PT = 391;
ERROR_MOUSE_INV_MASK = 392;
NO_ERROR_MOUSE_NO_DATA = 393;
NO_ERROR_MOUSE_PTR_DRAWN = 394;
ERROR_INVALID_FREQUENCY = 395;
ERROR_NLS_NO_COUNTRY_FILE = 396;
ERROR_NLS_OPEN_FAILED = 397;
ERROR_NLS_NO_CTRY_CODE = 398;
ERROR_NO_COUNTRY_OR_CODEPAGE = 398;
ERROR_NLS_TABLE_TRUNCATED = 399;
ERROR_NLS_BAD_TYPE = 400;
ERROR_NLS_TYPE_NOT_FOUND = 401;
ERROR_VIO_SMG_ONLY = 402;
ERROR_VIO_INVALID_ASCIIZ = 403;
ERROR_VIO_DEREGISTER = 404;
ERROR_VIO_NO_POPUP = 405;
ERROR_VIO_EXISTING_POPUP = 406;
ERROR_KBD_SMG_ONLY = 407;
ERROR_KBD_INVALID_ASCIIZ = 408;
ERROR_KBD_INVALID_MASK = 409;
ERROR_KBD_REGISTER = 410;
ERROR_KBD_DEREGISTER = 411;
ERROR_MOUSE_SMG_ONLY = 412;
ERROR_MOUSE_INVALID_ASCIIZ = 413;
ERROR_MOUSE_INVALID_MASK = 414;
ERROR_MOUSE_REGISTER = 415;
ERROR_MOUSE_DEREGISTER = 416;
ERROR_SMG_BAD_ACTION = 417;
ERROR_SMG_INVALID_CALL = 418;
ERROR_SCS_SG_NOTFOUND = 419;
ERROR_SCS_NOT_SHELL = 420;
ERROR_VIO_INVALID_PARMS = 421;
ERROR_VIO_FUNCTION_OWNED = 422;
ERROR_VIO_RETURN = 423;
ERROR_SCS_INVALID_FUNCTION = 424;
ERROR_SCS_NOT_SESSION_MGR = 425;
ERROR_VIO_REGISTER = 426;
ERROR_VIO_NO_MODE_THREAD = 427;
ERROR_VIO_NO_SAVE_RESTORE_THD = 428;
ERROR_VIO_IN_BG = 429;
ERROR_VIO_ILLEGAL_DURING_POPUP = 430;
ERROR_SMG_NOT_BASESHELL = 431;
ERROR_SMG_BAD_STATUSREQ = 432;
ERROR_QUE_INVALID_WAIT = 433;
ERROR_VIO_LOCK = 434;
ERROR_MOUSE_INVALID_IOWAIT = 435;
ERROR_VIO_INVALID_HANDLE = 436;
ERROR_VIO_ILLEGAL_DURING_LOCK = 437;
ERROR_VIO_INVALID_LENGTH = 438;
ERROR_KBD_INVALID_HANDLE = 439;
ERROR_KBD_NO_MORE_HANDLE = 440;
ERROR_KBD_CANNOT_CREATE_KCB = 441;
ERROR_KBD_CODEPAGE_LOAD_INCOMPL = 442;
ERROR_KBD_INVALID_CODEPAGE_ID = 443;
ERROR_KBD_NO_CODEPAGE_SUPPORT = 444;
ERROR_KBD_FOCUS_REQUIRED = 445;
ERROR_KBD_FOCUS_ALREADY_ACTIVE = 446;
ERROR_KBD_KEYBOARD_BUSY = 447;
ERROR_KBD_INVALID_CODEPAGE = 448;
ERROR_KBD_UNABLE_TO_FOCUS = 449;
ERROR_SMG_SESSION_NON_SELECT = 450;
ERROR_SMG_SESSION_NOT_FOREGRND = 451;
ERROR_SMG_SESSION_NOT_PARENT = 452;
ERROR_SMG_INVALID_START_MODE = 453;
ERROR_SMG_INVALID_RELATED_OPT = 454;
ERROR_SMG_INVALID_BOND_OPTION = 455;
ERROR_SMG_INVALID_SELECT_OPT = 456;
ERROR_SMG_START_IN_BACKGROUND = 457;
ERROR_SMG_INVALID_STOP_OPTION = 458;
ERROR_SMG_BAD_RESERVE = 459;
ERROR_SMG_PROCESS_NOT_PARENT = 460;
ERROR_SMG_INVALID_DATA_LENGTH = 461;
ERROR_SMG_NOT_BOUND = 462;
ERROR_SMG_RETRY_SUB_ALLOC = 463;
ERROR_KBD_DETACHED = 464;
ERROR_VIO_DETACHED = 465;
ERROR_MOU_DETACHED = 466;
ERROR_VIO_FONT = 467;
ERROR_VIO_USER_FONT = 468;
ERROR_VIO_BAD_CP = 469;
ERROR_VIO_NO_CP = 470;
ERROR_VIO_NA_CP = 471;
ERROR_INVALID_CODE_PAGE = 472;
ERROR_CPLIST_TOO_SMALL = 473;
ERROR_CP_NOT_MOVED = 474;
ERROR_MODE_SWITCH_INIT = 475;
ERROR_CODE_PAGE_NOT_FOUND = 476;
ERROR_UNEXPECTED_SLOT_RETURNED = 477;
ERROR_SMG_INVALID_TRACE_OPTION = 478;
ERROR_VIO_INTERNAL_RESOURCE = 479;
ERROR_VIO_SHELL_INIT = 480;
ERROR_SMG_NO_HARD_ERRORS = 481;
ERROR_CP_SWITCH_INCOMPLETE = 482;
ERROR_VIO_TRANSPARENT_POPUP = 483;
ERROR_CRITSEC_OVERFLOW = 484;
ERROR_CRITSEC_UNDERFLOW = 485;
ERROR_VIO_BAD_RESERVE = 486;
ERROR_INVALID_ADDRESS = 487;
ERROR_ZERO_SELECTORS_REQUESTED = 488;
ERROR_NOT_ENOUGH_SELECTORS_AVA = 489;
ERROR_INVALID_SELECTOR = 490;
ERROR_SMG_INVALID_PROGRAM_TYPE = 491;
ERROR_SMG_INVALID_PGM_CONTROL = 492;
ERROR_SMG_INVALID_INHERIT_OPT = 493;
ERROR_VIO_EXTENDED_SG = 494;
ERROR_VIO_NOT_PRES_MGR_SG = 495;
ERROR_VIO_SHIELD_OWNED = 496;
ERROR_VIO_NO_MORE_HANDLES = 497;
ERROR_VIO_SEE_ERROR_LOG = 498;
ERROR_VIO_ASSOCIATED_DC = 499;
ERROR_KBD_NO_CONSOLE = 500;
ERROR_MOUSE_NO_CONSOLE = 501;
ERROR_MOUSE_INVALID_HANDLE = 502;
ERROR_SMG_INVALID_DEBUG_PARMS = 503;
ERROR_KBD_EXTENDED_SG = 504;
ERROR_MOU_EXTENDED_SG = 505;
ERROR_SMG_INVALID_ICON_FILE = 506;
ERROR_USER_DEFINED_BASE = $FF00;
ERROR_I24_WRITE_PROTECT = 0;
ERROR_I24_BAD_UNIT = 1;
ERROR_I24_NOT_READY = 2;
ERROR_I24_BAD_COMMAND = 3;
ERROR_I24_CRC = 4;
ERROR_I24_BAD_LENGTH = 5;
ERROR_I24_SEEK = 6;
ERROR_I24_NOT_DOS_DISK = 7;
ERROR_I24_SECTOR_NOT_FOUND = 8;
ERROR_I24_OUT_OF_PAPER = 9;
ERROR_I24_WRITE_FAULT = 10;
ERROR_I24_READ_FAULT = 11;
ERROR_I24_GEN_FAILURE = 12;
ERROR_I24_DISK_CHANGE = 13;
ERROR_I24_WRONG_DISK = 15;
ERROR_I24_UNCERTAIN_MEDIA = 16;
ERROR_I24_CHAR_CALL_INTERRUPTED = 17;
ERROR_I24_NO_MONITOR_SUPPORT = 18;
ERROR_I24_INVALID_PARAMETER = 19;
ERROR_I24_DEVICE_IN_USE = 20;
ALLOWED_FAIL = $0001;
ALLOWED_ABORT = $0002;
ALLOWED_RETRY = $0004;
ALLOWED_IGNORE = $0008;
ALLOWED_ACKNOWLEDGE = $0010;
ALLOWED_DISPATCH = $8000;
I24_OPERATION = $01;
I24_AREA = $06;
I24_CLASS = $80;
ERRCLASS_OUTRES = 1;
ERRCLASS_TEMPSIT = 2;
ERRCLASS_AUTH = 3;
ERRCLASS_INTRN = 4;
ERRCLASS_HRDFAIL = 5;
ERRCLASS_SYSFAIL = 6;
ERRCLASS_APPERR = 7;
ERRCLASS_NOTFND = 8;
ERRCLASS_BADFMT = 9;
ERRCLASS_LOCKED = 10;
ERRCLASS_MEDIA = 11;
ERRCLASS_ALREADY = 12;
ERRCLASS_UNK = 13;
ERRCLASS_CANT = 14;
ERRCLASS_TIME = 15;
ERRACT_RETRY = 1;
ERRACT_DLYRET = 2;
ERRACT_USER = 3;
ERRACT_ABORT = 4;
ERRACT_PANIC = 5;
ERRACT_IGNORE = 6;
ERRACT_INTRET = 7;
ERRLOC_UNK = 1;
ERRLOC_DISK = 2;
ERRLOC_NET = 3;
ERRLOC_SERDEV = 4;
ERRLOC_MEM = 5;
TC_NORMAL = 0;
TC_HARDERR = 1;
TC_GP_TRAP = 2;
TC_SIGNAL = 3;
Implementation
End.
|
unit ClassHash;
interface
uses
Collection, Classes;
type
TCollection = Collection.TCollection;
type
TClassIdEntry =
class
public
constructor Create(anId : integer; aName : string);
destructor Destroy; override;
private
fId : integer;
fName : string;
fLarge : TStringList;
fSmall : TStringList;
public
property Id : integer read fId write fId;
property Name : string read fName write fName;
property Large : TStringList read fLarge;
property Small : TStringList read fSmall;
end;
TClassIdHash =
class
public
constructor Create;
destructor Destroy; override;
function Compare(Item1, Item2 : TObject) : integer;
private
fEntries : TCollection;
public
procedure AddEntry(Name : string);
private
function GetEntryById(id : integer) : TClassIdEntry;
function GetEntries(index : integer) : TClassIdEntry;
function GetCount : integer;
public
property Count : integer read GetCount;
property EntryById[id : integer] : TClassIdEntry read GetEntryById;
property Entries[index : integer] : TClassIdEntry read GetEntries; default;
end;
var
ClassIdHash : TClassIdHash;
function CreateClusterHash(Path, Cluster : string) : boolean;
function RenumerateCluster(Cluster, sourcePath, destPath : string; FirstNum : integer) : boolean;
implementation
uses
SysUtils, CompStringsParser, DelphiStreamUtils, VisualClassManager;
// TClassIdEntry
constructor TClassIdEntry.Create(anId : integer; aName : string);
begin
inherited Create;
fId := anId;
fName := aName;
fLarge := TStringList.Create;
fSmall := TStringList.Create;
end;
destructor TClassIdEntry.Destroy;
begin
fLarge.Free;
fSmall.Free;
inherited;
end;
// TClassIdHash
constructor TClassIdHash.Create;
begin
inherited Create;
fEntries := TSortedCollection.Create(0, rkBelonguer, Compare);
end;
destructor TClassIdHash.Destroy;
begin
fEntries.Free;
inherited;
end;
function TClassIdHash.Compare(Item1, Item2 : TObject) : integer;
begin
result := TClassIdEntry(Item1).fId - TClassIdEntry(Item2).fId;
end;
procedure TClassIdHash.AddEntry(Name : string);
var
aux : string;
id : integer;
p : integer;
Entry : TClassIdEntry;
begin
// Dis.2115.smallFarm.Construction.final.ini
p := 1;
aux := GetNextStringUpTo(Name, p, '.');
aux := GetNextStringUpTo(Name, p, '.');
id := StrToInt(aux);
aux := GetNextStringUpTo(Name, p, '.');
Entry := EntryById[id];
if Entry = nil
then
begin
Entry := TClassIdEntry.Create(id div 10, aux);
fEntries.Insert(Entry);
end;
aux := lowercase(aux);
if pos('small', aux) <> 0
then Entry.fSmall.Add(copy(Name, 1, length(Name) - 4))
else Entry.fLarge.Add(copy(Name, 1, length(Name) - 4));
end;
function TClassIdHash.GetEntryById(id : integer) : TClassIdEntry;
var
i : integer;
begin
i := 0;
while (i < fEntries.Count) and (TClassIdEntry(fEntries[i]).fId <> id div 10) do
inc(i);
if i < fEntries.Count
then result := TClassIdEntry(fEntries[i])
else result := nil;
end;
function TClassIdHash.GetEntries(index : integer) : TClassIdEntry;
begin
result := TClassIdEntry(fEntries[index]);
end;
function TClassIdHash.GetCount : integer;
begin
result := fEntries.Count;
end;
// CreateClusterHash
function CreateClusterHash(Path, Cluster : string) : boolean;
var
Search : TSearchRec;
found : integer;
//Stream : TStream;
//i : integer;
begin
ClassIdHash := TClassIdHash.Create;
found := FindFirst(Path + Cluster + '*.ini', faArchive, Search);
while found = 0 do
begin
ClassIdHash.AddEntry(Search.Name);
found := FindNext(Search);
end;
result := true;
{// Remove latter!!!!!!!!!!!
Stream := TFileStream.Create(Path + 'hash.txt', fmCreate);
for i := 0 to pred(ClassIdHash.fEntries.Count) do
begin
DelphiStreamUtils.WriteLine(Stream, 'Class: ' + TClassIdEntry(ClassIdHash.fEntries[i]).Name);
if TClassIdEntry(ClassIdHash.fEntries[i]).fLarge.Count > 0
then
begin
DelphiStreamUtils.WriteLine(Stream, '');
TClassIdEntry(ClassIdHash.fEntries[i]).fLarge.SaveToStream(Stream);
end;
if TClassIdEntry(ClassIdHash.fEntries[i]).fSmall.Count > 0
then
begin
DelphiStreamUtils.WriteLine(Stream, '');
TClassIdEntry(ClassIdHash.fEntries[i]).fSmall.SaveToStream(Stream);
end;
DelphiStreamUtils.WriteLine(Stream, '');
end;
Stream.Free;
}
end;
function ReplaceId(Name : string; NewId : integer) : string;
var
p : integer;
cluster : string;
aux : string;
begin
p := 1;
cluster := GetNextStringUpTo(Name, p, '.');
inc(p);
aux := GetNextStringUpTo(Name, p, '.');
inc(p);
aux := copy(Name, p, length(Name) - p + 1);
result := cluster + '.' + IntToStr(NewId) + '.' + aux;
end;
function ExtractId(Name : string) : integer;
var
p : integer;
aux : string;
begin
try
p := 1;
aux := GetNextStringUpTo(Name, p, '.');
aux := GetNextStringUpTo(Name, p, '.');
result := StrToInt(aux);
except
result := 0;
end;
end;
procedure RenumerateFile(srcPath, dstPath, Name : string; oldNames, newNames : TStringList; newId : integer);
var
VsCls : TVisualClass;
inh : string;
p : integer;
aux : string;
newInh : string;
function GetNewName(name : string) : string;
var
idx : integer;
begin
idx := oldNames.IndexOf(name);
if idx <> -1
then result := newNames[idx]
else result := name;
end;
begin
VsCls := TVisualClass.CreateFromINI(srcPath);
if VsCls.Id <> 0
then VsCls.Id := newId;
inh := VsCls.ReadString('General', 'Inherits', '');
if inh <> ''
then
begin
p := 0;
newInh := '';
aux := trim(GetNextStringUpTo(inh, p, ','));
while aux <> '' do
begin
if newInh = ''
then newInh := GetNewName(aux)
else newInh := newInh + ', ' + GetNewName(aux);
inc(p);
aux := trim(GetNextStringUpTo(inh, p, ','));
end;
VsCls.WriteString('General', 'Inherits', newInh);
end;
VsCls.WriteString('General', 'Name', Name);
VsCls.StoreToINI(dstPath);
end;
function RenumerateCluster(Cluster, sourcePath, destPath : string; FirstNum : integer) : boolean;
var
i, j : integer;
Entry : TClassIdEntry;
oldNames : TStringList;
newNames : TStringList;
aux : string;
currNum : integer;
oldId : integer;
oldName : string;
idFile : Text;
begin
currNum := FirstNum;
oldNames := TStringList.Create;
newNames := TStringList.Create;
CreateClusterHash(sourcePath, Cluster);
Assign(idFile, destPath + Cluster + '.txt');
Rewrite(idFile);
for i := 0 to pred(ClassIdHash.Count) do
begin
Entry := ClassIdHash[i];
// Renumerate Facility
if Entry.Small.Count > 0
then
begin
WriteLn(idFile, 'Small ' + Entry.Name + ' = ' + IntToStr(currNum + 1));
for j := 0 to pred(Entry.Small.Count) do
begin
oldName := Entry.Small[j];
oldId := ExtractId(oldName);
oldNames.Add(oldName);
if oldId mod 10 = 0
then aux := ReplaceId(oldName, currNum)
else aux := ReplaceId(oldName, currNum + j);
newNames.Add(aux);
end;
for j := 0 to pred(Entry.Small.Count) do
begin
oldName := Entry.Small[j];
oldId := ExtractId(oldName);
if oldId mod 10 = 0
then aux := ReplaceId(oldName, currNum)
else aux := ReplaceId(oldName, currNum + j);
if oldId mod 10 = 0
then RenumerateFile(sourcePath + oldName + '.ini', destPath + aux + '.ini', aux, oldNames, newNames, currNum)
else RenumerateFile(sourcePath + oldName + '.ini', destPath + aux + '.ini', aux, oldNames, newNames, currNum + j);
end;
inc(currNum, 20);
end;
if Entry.Large.Count > 0
then
begin
WriteLn(idFile, Entry.Name + ' = ' + IntToStr(currNum + 1));
for j := 0 to pred(Entry.Large.Count) do
begin
oldName := Entry.Large[j];
oldId := ExtractId(oldName);
oldNames.Add(oldName);
if oldId mod 10 = 0
then aux := ReplaceId(oldName, currNum)
else aux := ReplaceId(oldName, currNum + j);
newNames.Add(aux);
end;
for j := 0 to pred(Entry.Large.Count) do
begin
oldName := Entry.Large[j];
oldId := ExtractId(oldName);
if oldId mod 10 = 0
then aux := ReplaceId(oldName, currNum)
else aux := ReplaceId(oldName, currNum + j);
if oldId mod 10 = 0
then RenumerateFile(sourcePath + oldName + '.ini', destPath + aux + '.ini', aux, oldNames, newNames, currNum)
else RenumerateFile(sourcePath + oldName + '.ini', destPath + aux + '.ini', aux, oldNames, newNames, currNum + j);
end;
inc(currNum, 20);
end;
end;
CloseFile(idFile);
result := true;
end;
end.
|
unit Integrals_;
interface
uses Unit4;
function IntRectR(F: TFunc2d; a,b: double; N: integer): TReal; overload;
function IntRectM(F: TFunc2d; a,b: double; N: integer): TReal;
function IntRectL(F: TFunc2d; a,b: double; N: integer): TReal; overload;
function IntTrapz(F: TFunc2d; a,b: double; N: integer): TReal;
function IntSimps(F: TFunc2d; a,b: double; N: integer): TReal;
function IntRectR(FP: TpointsArray2d): TReal; overload;
function IntRectL(FP: TpointsArray2d): TReal; overload;
implementation
function IntRectR(F: TFunc2d; a,b: double; N: integer): TReal;
var opres: TReal;
steph: double;
i: integer;
begin
result.error:=false;
result.result:=0;
setlength(varvect,1);
steph:=(b-a)/N;
for i := 1 to N do
begin
varvect[0]:=a+i*steph;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result;
end;
result.result:=result.result*steph;
end;
function IntRectL(F: TFunc2d; a,b: double; N: integer): TReal;
var opres: TReal;
steph: double;
i: integer;
begin
result.error:=false;
result.result:=0;
setlength(varvect,1);
steph:=(b-a)/N;
for i := 0 to N-1 do
begin
varvect[0]:=a+i*steph;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result;
end;
result.result:=result.result*steph;
end;
function IntRectM(F: TFunc2d; a,b: double; N: integer): TReal;
var opres: TReal;
steph,steph2: double;
i: integer;
begin
result.error:=false;
result.result:=0;
setlength(varvect,1);
steph:=(b-a)/N;
steph2:=steph/2;
for i := 1 to N do
begin
varvect[0]:=a+i*steph-steph2;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result;
end;
result.result:=result.result*steph;
end;
function IntTrapz(F: TFunc2d; a,b: double; N: integer): TReal;
var opres: TReal;
steph: double;
i: integer;
begin
result.error:=false;
result.result:=0;
setlength(varvect,1);
steph:=(b-a)/N;
varvect[0]:=a;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=opres.result/2;
for i := 1 to N-1 do
begin
varvect[0]:=a+i*steph;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result;
end;
varvect[0]:=b;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result/2;
result.result:=result.result*steph;
end;
function IntSimps(F: TFunc2d; a,b: double; N: integer): TReal;
var opres: TReal;
steph: double;
i: integer;
begin
result.error:=false;
result.result:=0;
if not odd(N) then
begin
result.Error:=true; exit;
end;
setlength(varvect,1);
steph:=(b-a)/N;
varvect[0]:=a;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=opres.result;
for i := 1 to N-1 do
begin
varvect[0]:=a+i*steph;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
if odd(i) then
result.result:=result.result+4*opres.result
else
result.result:=result.result+2*opres.result;
end;
varvect[0]:=b;
opres:=GetOpres(F.DataAr,F.OperAr,VarVect);
if opres.Error then begin result.Error:=true; exit; end;
result.result:=result.result+opres.result;
result.result:=result.result*steph/3;
end;
function IntRectR(FP: TpointsArray2d): TReal; overload;
var
i,N: integer;
begin
result.error:=false;
result.result:=0;
N:=length(FP)-1;
for i := 1 to N do
begin
if not FP[i].IsMathEx then begin result.Error:=true; exit; end;
result.result:=result.result+(FP[i].y*FP[i].x-FP[i-1].x);
end;
end;
function IntRectL(FP: TpointsArray2d): TReal; overload;
var
i,N: integer;
begin
result.error:=false;
result.result:=0;
N:=length(FP)-2;
for i := 0 to N do
begin
if not FP[i].IsMathEx then begin result.Error:=true; exit; end;
result.result:=result.result+(FP[i].y*FP[i+1].x-FP[i].x);
end;
end;
end.
|
unit tfwDictionaryWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwDictionaryWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "tfwDictionaryWordsPack" MUID: (55E727F40334)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwDictionary
, tfwClassLike
, tfwScriptingInterfaces
, TypInfo
, l3Interfaces
, tfwMembersIterator
, tfwScriptEngineExInterfaces
, tfwKeywordsIterator
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *55E727F40334impl_uses*
//#UC END# *55E727F40334impl_uses*
;
type
TkwPopDictionaryWordsIterator = {final} class(TtfwClassLike)
{* Слово скрипта pop:Dictionary:WordsIterator }
private
function WordsIterator(const aCtx: TtfwContext;
aDictionary: TtfwDictionary): ItfwValueList;
{* Реализация слова скрипта pop:Dictionary:WordsIterator }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopDictionaryWordsIterator
TkwPopDictionaryKeywordByName = {final} class(TtfwClassLike)
{* Слово скрипта pop:Dictionary:KeywordByName }
private
function KeywordByName(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:KeywordByName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopDictionaryKeywordByName
TkwPopDictionaryKeyWordsIterator = {final} class(TtfwClassLike)
{* Слово скрипта pop:Dictionary:KeyWordsIterator }
private
function KeyWordsIterator(const aCtx: TtfwContext;
aDictionary: TtfwDictionary): ItfwValueList;
{* Реализация слова скрипта pop:Dictionary:KeyWordsIterator }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopDictionaryKeyWordsIterator
TkwPopDictionaryOwnKeywordByName = {final} class(TtfwClassLike)
{* Слово скрипта pop:Dictionary:OwnKeywordByName }
private
function OwnKeywordByName(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:OwnKeywordByName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopDictionaryOwnKeywordByName
TkwPopDictionaryCheckWord = {final} class(TtfwClassLike)
{* Слово скрипта pop:Dictionary:CheckWord }
private
function CheckWord(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:CheckWord }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopDictionaryCheckWord
function TkwPopDictionaryWordsIterator.WordsIterator(const aCtx: TtfwContext;
aDictionary: TtfwDictionary): ItfwValueList;
{* Реализация слова скрипта pop:Dictionary:WordsIterator }
//#UC START# *55E7083D03A8_55E7083D03A8_4DAEECD90016_Word_var*
//#UC END# *55E7083D03A8_55E7083D03A8_4DAEECD90016_Word_var*
begin
//#UC START# *55E7083D03A8_55E7083D03A8_4DAEECD90016_Word_impl*
Result := TtfwMembersIterator.Make(aDictionary);
//#UC END# *55E7083D03A8_55E7083D03A8_4DAEECD90016_Word_impl*
end;//TkwPopDictionaryWordsIterator.WordsIterator
class function TkwPopDictionaryWordsIterator.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Dictionary:WordsIterator';
end;//TkwPopDictionaryWordsIterator.GetWordNameForRegister
function TkwPopDictionaryWordsIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwValueList);
end;//TkwPopDictionaryWordsIterator.GetResultTypeInfo
function TkwPopDictionaryWordsIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopDictionaryWordsIterator.GetAllParamsCount
function TkwPopDictionaryWordsIterator.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwDictionary)]);
end;//TkwPopDictionaryWordsIterator.ParamsTypes
procedure TkwPopDictionaryWordsIterator.DoDoIt(const aCtx: TtfwContext);
var l_aDictionary: TtfwDictionary;
begin
try
l_aDictionary := TtfwDictionary(aCtx.rEngine.PopObjAs(TtfwDictionary));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDictionary: TtfwDictionary : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushList(WordsIterator(aCtx, l_aDictionary));
end;//TkwPopDictionaryWordsIterator.DoDoIt
function TkwPopDictionaryKeywordByName.KeywordByName(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:KeywordByName }
//#UC START# *55E728580305_55E728580305_4DAEECD90016_Word_var*
//#UC END# *55E728580305_55E728580305_4DAEECD90016_Word_var*
begin
//#UC START# *55E728580305_55E728580305_4DAEECD90016_Word_impl*
Result := aDictionary.DRbyCName[aName];
//#UC END# *55E728580305_55E728580305_4DAEECD90016_Word_impl*
end;//TkwPopDictionaryKeywordByName.KeywordByName
class function TkwPopDictionaryKeywordByName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Dictionary:KeywordByName';
end;//TkwPopDictionaryKeywordByName.GetWordNameForRegister
function TkwPopDictionaryKeywordByName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeyWord);
end;//TkwPopDictionaryKeywordByName.GetResultTypeInfo
function TkwPopDictionaryKeywordByName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopDictionaryKeywordByName.GetAllParamsCount
function TkwPopDictionaryKeywordByName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwDictionary), @tfw_tiString]);
end;//TkwPopDictionaryKeywordByName.ParamsTypes
procedure TkwPopDictionaryKeywordByName.DoDoIt(const aCtx: TtfwContext);
var l_aDictionary: TtfwDictionary;
var l_aName: Il3CString;
begin
try
l_aDictionary := TtfwDictionary(aCtx.rEngine.PopObjAs(TtfwDictionary));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDictionary: TtfwDictionary : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(KeywordByName(aCtx, l_aDictionary, l_aName));
end;//TkwPopDictionaryKeywordByName.DoDoIt
function TkwPopDictionaryKeyWordsIterator.KeyWordsIterator(const aCtx: TtfwContext;
aDictionary: TtfwDictionary): ItfwValueList;
{* Реализация слова скрипта pop:Dictionary:KeyWordsIterator }
//#UC START# *55ED4C2503C3_55ED4C2503C3_4DAEECD90016_Word_var*
//#UC END# *55ED4C2503C3_55ED4C2503C3_4DAEECD90016_Word_var*
begin
//#UC START# *55ED4C2503C3_55ED4C2503C3_4DAEECD90016_Word_impl*
Result := TtfwKeywordsIterator.Make(aDictionary);
//#UC END# *55ED4C2503C3_55ED4C2503C3_4DAEECD90016_Word_impl*
end;//TkwPopDictionaryKeyWordsIterator.KeyWordsIterator
class function TkwPopDictionaryKeyWordsIterator.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Dictionary:KeyWordsIterator';
end;//TkwPopDictionaryKeyWordsIterator.GetWordNameForRegister
function TkwPopDictionaryKeyWordsIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(ItfwValueList);
end;//TkwPopDictionaryKeyWordsIterator.GetResultTypeInfo
function TkwPopDictionaryKeyWordsIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopDictionaryKeyWordsIterator.GetAllParamsCount
function TkwPopDictionaryKeyWordsIterator.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwDictionary)]);
end;//TkwPopDictionaryKeyWordsIterator.ParamsTypes
procedure TkwPopDictionaryKeyWordsIterator.DoDoIt(const aCtx: TtfwContext);
var l_aDictionary: TtfwDictionary;
begin
try
l_aDictionary := TtfwDictionary(aCtx.rEngine.PopObjAs(TtfwDictionary));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDictionary: TtfwDictionary : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushList(KeyWordsIterator(aCtx, l_aDictionary));
end;//TkwPopDictionaryKeyWordsIterator.DoDoIt
function TkwPopDictionaryOwnKeywordByName.OwnKeywordByName(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:OwnKeywordByName }
//#UC START# *5613A27E03D0_5613A27E03D0_4DAEECD90016_Word_var*
//#UC END# *5613A27E03D0_5613A27E03D0_4DAEECD90016_Word_var*
begin
//#UC START# *5613A27E03D0_5613A27E03D0_4DAEECD90016_Word_impl*
Result := aDictionary.OwnDRbyCName(aName);
//#UC END# *5613A27E03D0_5613A27E03D0_4DAEECD90016_Word_impl*
end;//TkwPopDictionaryOwnKeywordByName.OwnKeywordByName
class function TkwPopDictionaryOwnKeywordByName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Dictionary:OwnKeywordByName';
end;//TkwPopDictionaryOwnKeywordByName.GetWordNameForRegister
function TkwPopDictionaryOwnKeywordByName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeyWord);
end;//TkwPopDictionaryOwnKeywordByName.GetResultTypeInfo
function TkwPopDictionaryOwnKeywordByName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopDictionaryOwnKeywordByName.GetAllParamsCount
function TkwPopDictionaryOwnKeywordByName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwDictionary), @tfw_tiString]);
end;//TkwPopDictionaryOwnKeywordByName.ParamsTypes
procedure TkwPopDictionaryOwnKeywordByName.DoDoIt(const aCtx: TtfwContext);
var l_aDictionary: TtfwDictionary;
var l_aName: Il3CString;
begin
try
l_aDictionary := TtfwDictionary(aCtx.rEngine.PopObjAs(TtfwDictionary));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDictionary: TtfwDictionary : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(OwnKeywordByName(aCtx, l_aDictionary, l_aName));
end;//TkwPopDictionaryOwnKeywordByName.DoDoIt
function TkwPopDictionaryCheckWord.CheckWord(const aCtx: TtfwContext;
aDictionary: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:Dictionary:CheckWord }
//#UC START# *57F5350E025B_57F5350E025B_4DAEECD90016_Word_var*
//#UC END# *57F5350E025B_57F5350E025B_4DAEECD90016_Word_var*
begin
//#UC START# *57F5350E025B_57F5350E025B_4DAEECD90016_Word_impl*
Result := aDictionary.CheckWord(aName);
//#UC END# *57F5350E025B_57F5350E025B_4DAEECD90016_Word_impl*
end;//TkwPopDictionaryCheckWord.CheckWord
class function TkwPopDictionaryCheckWord.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Dictionary:CheckWord';
end;//TkwPopDictionaryCheckWord.GetWordNameForRegister
function TkwPopDictionaryCheckWord.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeyWord);
end;//TkwPopDictionaryCheckWord.GetResultTypeInfo
function TkwPopDictionaryCheckWord.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopDictionaryCheckWord.GetAllParamsCount
function TkwPopDictionaryCheckWord.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwDictionary), @tfw_tiString]);
end;//TkwPopDictionaryCheckWord.ParamsTypes
procedure TkwPopDictionaryCheckWord.DoDoIt(const aCtx: TtfwContext);
var l_aDictionary: TtfwDictionary;
var l_aName: Il3CString;
begin
try
l_aDictionary := TtfwDictionary(aCtx.rEngine.PopObjAs(TtfwDictionary));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDictionary: TtfwDictionary : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(CheckWord(aCtx, l_aDictionary, l_aName));
end;//TkwPopDictionaryCheckWord.DoDoIt
initialization
TkwPopDictionaryWordsIterator.RegisterInEngine;
{* Регистрация pop_Dictionary_WordsIterator }
TkwPopDictionaryKeywordByName.RegisterInEngine;
{* Регистрация pop_Dictionary_KeywordByName }
TkwPopDictionaryKeyWordsIterator.RegisterInEngine;
{* Регистрация pop_Dictionary_KeyWordsIterator }
TkwPopDictionaryOwnKeywordByName.RegisterInEngine;
{* Регистрация pop_Dictionary_OwnKeywordByName }
TkwPopDictionaryCheckWord.RegisterInEngine;
{* Регистрация pop_Dictionary_CheckWord }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwDictionary));
{* Регистрация типа TtfwDictionary }
TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwValueList));
{* Регистрация типа ItfwValueList }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeyWord));
{* Регистрация типа TtfwKeyWord }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Il3CString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
/// Dynamic arrays based on JavaScript Array functionality.
/// author: Tomasz Tyrakowski (t.tyrakowski@sol-system.pl)
/// license: public domain
unit DynArr;
interface
uses SysUtils, System.Generics.Collections, System.Generics.Defaults;
type
/// Raw array of values of type T.
TRawArr<T> = array of T;
/// Boxed value of type S.
/// Required for reduce to work properly in Delphi 10.4, where
/// returning a parametrizing type S results in access violation
/// (compiler can't handle a generic return type S in a generic
/// record parametrized with another type T).
TBoxed<S> = record
value: S;
constructor from(const val: S);
end;
/// Dynamic JS-like array of values of type T.
TDynArr<T> = record
type
Ptr = ^T;
private
_items: TRawArr<T>;
// property accessors
function getLength(): Integer;
procedure setLength(newLength: Integer);
function getItem(itemNo: Integer): T;
procedure setItem(itemNo: Integer; const newValue: T);
function getLastIndex(): Integer;
function getLastItem(): T;
function getPtr(itemNo: Integer): Ptr;
procedure setPtr(itemNo: Integer; const newPtr: Ptr);
public
/// Create an array with the initial length as specified.
constructor create(const initialLength: Integer);
/// An alias for create.
constructor new(const initialLength: Integer);
/// Creates an array from a raw array
constructor from(const a: TRawArr<T>; startIndex: Integer = -1; endIndex: Integer = -1); overload;
/// Creates an array from another TDynArr
constructor from(const a: TDynArr<T>); overload;
/// Creates an array of length initialLength,
/// the second variant also filling it with the value initialVal
/// (the first one fills it with System.Default(T).
constructor from(const initialLength: Integer); overload;
constructor from(const initialLength: Integer; const initialVal: T); overload;
/// The length of the array.
property length: Integer read getLength write setLength;
/// Access individual items of the array.
property items[itemNo: Integer]: T read getItem write setItem; default;
/// Access pointers to individual items of the array.
property ptrTo[itemNo: Integer]: Ptr read getPtr write setPtr;
/// Get a raw array of values.
property raw: TRawArr<T> read _items write _items;
/// Get the last valid index number of this array.
property lastIndex: Integer read getLastIndex;
/// Get the last value of this array. Raises an exception if used
/// on an empty array.
property lastItem: T read getLastItem;
/// Array manipulation routines.
/// Append a new item to the end of the array.
procedure append(const item: T); overload;
/// Append all items to the end of the array.
procedure append(const fromHere: TDynArr<T>); overload;
/// Insert an item at index idx in the array.
procedure insert(const item: T; const idx: Integer);
/// Clear the array.
procedure clear();
/// Joins two or more arrays, and returns a copy of the joined arrays.
function concat(const a: TDynArr<T>): TDynArr<T>;
/// Removes the item at the specified index.
procedure delete(const idx: Integer; const howMany: Integer = 1);
/// Fill the elements in an array with a static value.
procedure fill(const val: T);
/// Creates a new array with every item in an array that pass a test.
/// Where is just an alias.
function filter(test: TFunc<T, Boolean>): TDynArr<T>; overload;
function filter(test: TFunc<T, Integer, Boolean>): TDynArr<T>; overload;
function where(test: TFunc<T, Boolean>): TDynArr<T>;
function ptrFilter(test: TFunc<Ptr, Boolean>): TDynArr<T>; overload;
function ptrFilter(test: TFunc<Ptr, Integer, Boolean>): TDynArr<T>; overload;
function ptrWhere(test: TFunc<Ptr, Boolean>): TDynArr<T>;
/// Returns the value of the first item in an array that pass a test.
/// Raises an exception if there are no items passing the test.
function find(test: TFunc<T, Boolean>): T; overload;
function find(test: TFunc<T, Boolean>; const fallback: T): T; overload;
/// Returns the pointer to the first item in an array that pass a test.
/// If no such item exists, returns nil.
function ptrFind(test: TFunc<Ptr, Boolean>): Ptr; overload;
/// Returns the index of the first element in an array that pass a test.
function findIndex(test: TFunc<T, Boolean>): Integer;
function ptrFindIndex(test: TFunc<Ptr, Boolean>): Integer;
/// Calls a function for each array element.
/// The second version also passes the item index.
procedure forEach(process: TProc<T>); overload;
procedure forEach(process: TProc<T, Integer>); overload;
procedure ptrForEach(process: TProc<Ptr>); overload;
procedure ptrForEach(process: TProc<Ptr, Integer>); overload;
/// Check if an array contains the specified element.
function includes(const val: T): Boolean;
/// Search the array for an element and returns its position.
function indexOf(const val: T): Integer;
/// Is this array empty (length is 0)?
function _isEmpty(): Boolean;
function _isNotEmpty(): Boolean;
property isEmpty: Boolean read _isEmpty;
property isNotEmpty: Boolean read _isNotEmpty;
/// Joins all elements of an array into a string.
function join(mapper: TFunc<T, string>; const separator: string = ''): string;
/// Search the array for an element, starting at the end, and returns its position.
function lastIndexOf(const val: T): Integer;
/// Creates a new array with the result of calling a function for each array element.
/// In the second variant the mapper receives the index of an item in addition to the item.
function map<S>(mapper: TFunc<T, S>): TDynArr<S>; overload;
function map<S>(mapper: TFunc<T, Integer, S>): TDynArr<S>; overload;
function ptrMap<S>(mapper: TFunc<Ptr, S>): TDynArr<S>; overload;
function ptrMap<S>(mapper: TFunc<Ptr, Integer, S>): TDynArr<S>; overload;
/// Removes the last element of an array, and returns that element.
function pop(): T;
/// Adds new elements to the end of an array, and returns the new length.
function push(const val: T): Integer;
/// Reduce the values of an array to a single value (going left-to-right).
function reduce<S>(reducer: TFunc<S, T, Integer, S>; const initialValue: S): TBoxed<S>; overload;
function reduce<S>(reducer: TFunc<S, T, S>; const initialValue: S): TBoxed<S>; overload;
function ptrReduce<S>(reducer: TFunc<S, Ptr, Integer, S>; const initialValue: S): TBoxed<S>; overload;
function ptrReduce<S>(reducer: TFunc<S, Ptr, S>; const initialValue: S): TBoxed<S>; overload;
/// Reverses the order of the elements in an array.
procedure reverse();
function reversed(): TDynArr<T>;
/// Removes the first element of an array, and returns that element.
function shift(): T;
/// Selects a part of an array, and returns the new array.
function slice(const startIndex, endIndex: Integer): TDynArr<T>;
/// Checks if any of the elements in the array pass a test.
function some(test: TFunc<T, Integer, Boolean>): Boolean; overload;
function some(test: TFunc<T, Boolean>): Boolean; overload;
function ptrSome(test: TFunc<Ptr, Integer, Boolean>): Boolean; overload;
function ptrSome(test: TFunc<Ptr, Boolean>): Boolean; overload;
function any(test: TFunc<T, Integer, Boolean>): Boolean; overload;
function any(test: TFunc<T, Boolean>): Boolean; overload;
function ptrAny(test: TFunc<Ptr, Integer, Boolean>): Boolean; overload;
function ptrAny(test: TFunc<Ptr, Boolean>): Boolean; overload;
/// Checks if all of the elements in the array pass a test.
function all(test: TFunc<T, Integer, Boolean>): Boolean; overload;
function all(test: TFunc<T, Boolean>): Boolean; overload;
function every(test: TFunc<T, Integer, Boolean>): Boolean; overload;
function every(test: TFunc<T, Boolean>): Boolean; overload;
function ptrAll(test: TFunc<Ptr, Integer, Boolean>): Boolean; overload;
function ptrAll(test: TFunc<Ptr, Boolean>): Boolean; overload;
function ptrEvery(test: TFunc<Ptr, Integer, Boolean>): Boolean; overload;
function ptrEvery(test: TFunc<Ptr, Boolean>): Boolean; overload;
/// Sorts the elements of an array.
procedure sort(compare: TComparison<T>);
function sorted(compare: TComparison<T>): TDynArr<T>;
/// Adds/removes items to/from an array, and returns the removed item(s).
function splice(const startIndex, howMany: Integer; const newItems: TDynArr<T>): TDynArr<T>; overload;
function splice(const startIndex, howMany: Integer): TDynArr<T>; overload;
/// Converts an array to a string, and returns the result.
function toString(mapper: TFunc<T, string>): string;
/// Adds new elements to the beginning of an array, and returns the new length.
function unshift(const toAdd: TDynArr<T>): Integer;
/// Clones the array (returns an array with copies of items)
function clone(): TDynArr<T>;
/// Swaps items with indices i and j
procedure swapItems(const i, j: Integer);
/// Operators
/// Implicit cast, e.g. const a: TDynArr<Integer> := [1, 2, 3];
class operator Implicit(a: TRawArr<T>): TDynArr<T>;
/// Explicit cast, e.g. a := TDynArr<Integer>([1, 2, 3]);
class operator Explicit(a: TRawArr<T>): TDynArr<T>;
/// Addition (concatenation), e.g. c := a + b;
class operator Add(const a1, a2: TDynArr<T>): TDynArr<T>;
/// Multiply an array by an integer, creating an array with
/// n copies of a.
class operator Multiply(const a: TDynArr<T>; const n: Integer): TDynArr<T>;
/// Check arrays for equality.
class operator Equal(const a1, a2: TDynArr<T>): Boolean;
/// BitwiseAnd - return an array consisting of items common
/// to a1 and a2
class operator BitwiseAnd(const a1, a2: TDynArr<T>): TDynArr<T>;
/// Checks whether two items of type T are equal (uses CompareMem).
class function itemsEqual(const i1, i2: T): Boolean; static;
/// Swaps the values of two items of type T.
class procedure swap(var i1, i2: T); static;
/// Returns an empty DynArray<T>.
class function empty(): TDynArr<T>; static;
end;
/// Return a range array, i.e. the array with values min, min+1, ..., max-1,
/// optionally with the given step.
/// The upper bound is always exclusive (like in Python).
/// Allows to do things like range(4).forEach(...) // exec for 0, 1, 2, 3
/// or range(10, 2, -2).forEach(...) // exec for 10, 8, 6, 4
function range(const upperBound: Integer): TDynArr<Integer>; overload;
function range(const lowerBound, upperBound: Integer; const step: Integer = 1): TDynArr<Integer>; overload;
type _Pstring = ^string;
implementation
uses TypInfo;
class operator TDynArr<T>.Add(const a1, a2: TDynArr<T>): TDynArr<T>;
begin
Result := a1.concat(a2);
end;
function TDynArr<T>.all(test: TFunc<T, Boolean>): Boolean;
begin
Result := not any(
function(itm: T): Boolean
begin
Result := not test(itm);
end
);
end;
function TDynArr<T>.all(test: TFunc<T, Integer, Boolean>): Boolean;
begin
Result := any(
function(itm: T; idx: Integer): Boolean
begin
Result := not test(itm, idx);
end
);
end;
function TDynArr<T>.any(test: TFunc<T, Boolean>): Boolean;
begin
Result := some(test);
end;
procedure TDynArr<T>.append(const fromHere: TDynArr<T>);
begin
if fromHere.isNotEmpty then
begin
var l := self.length;
self.length := self.length + fromHere.length;
for var i := 0 to fromHere.length-1 do
self._items[i + l] := fromHere[i];
end;
end;
function TDynArr<T>.any(test: TFunc<T, Integer, Boolean>): Boolean;
begin
Result := some(test);
end;
procedure TDynArr<T>.append(const item: T);
begin
self.length := self.length + 1;
self._items[self.length - 1] := item;
end;
class operator TDynArr<T>.BitwiseAnd(const a1, a2: TDynArr<T>): TDynArr<T>;
begin
Result := a1.filter(
function(it: T): Boolean
begin
Result := a2.includes(it);
end
);
end;
procedure TDynArr<T>.clear;
begin
self.length := 0;
end;
function TDynArr<T>.clone: TDynArr<T>;
begin
Result := TDynArr<T>.from(self);
end;
function TDynArr<T>.concat(const a: TDynArr<T>): TDynArr<T>;
var
i: Integer;
begin
Result := TDynArr<T>.create(self.length + a.length);
for i := 0 to self.length - 1 do
Result[i] := self._items[i];
for i := 0 to a.length - 1 do
Result[i + self.length] := a[i];
end;
constructor TDynArr<T>.create(const initialLength: Integer);
begin
System.SetLength(self._items, initialLength);
end;
procedure TDynArr<T>.delete(const idx: Integer; const howMany: Integer = 1);
begin
if (idx < 0) or (idx >= length) then
raise ERangeError.CreateFmt('Index %d out of range. Array length is %d.', [idx, length]);
System.Delete(_items, idx, howMany);
end;
constructor TDynArr<T>.new(const initialLength: Integer);
begin
create(initialLength);
end;
class function TDynArr<T>.empty: TDynArr<T>;
begin
Result := TDynArr<T>.create(0);
end;
class operator TDynArr<T>.Equal(const a1, a2: TDynArr<T>): Boolean;
var
i: Integer;
begin
if a1.length = a2.length then
Result := a1.every(
function(it: T; idx: Integer): Boolean
begin
Result := TDynArr<T>.itemsEqual(it, a2[idx]);
end
)
else
Result := false;
end;
function TDynArr<T>.every(test: TFunc<T, Integer, Boolean>): Boolean;
begin
Result := self.all(test);
end;
function TDynArr<T>.every(test: TFunc<T, Boolean>): Boolean;
begin
Result := self.all(test);
end;
class operator TDynArr<T>.Explicit(a: TRawArr<T>): TDynArr<T>;
begin
Result := TDynArr<T>.from(a);
end;
procedure TDynArr<T>.fill(const val: T);
var
i: Integer;
begin
for i := 0 to self.length - 1 do
self._items[i] := val;
end;
function TDynArr<T>.filter(test: TFunc<T, Boolean>): TDynArr<T>;
begin
Result := self.filter(
function(it: T; _: Integer): Boolean
begin
Result := test(it);
end
);
end;
function TDynArr<T>.filter(test: TFunc<T, Integer, Boolean>): TDynArr<T>;
var
i, ii: Integer;
begin
Result := TDynArr<T>.create(self.length);
ii := 0;
for i := 0 to self.length - 1 do
if test(self._items[i], i) then
begin
Result[ii] := self._items[i];
ii := ii + 1;
end;
Result.length := ii;
end;
function TDynArr<T>.find(test: TFunc<T, Boolean>): T;
var
ii: Integer;
begin
ii := self.findIndex(test);
if ii >= 0 then
Result := self._items[ii]
else
raise Exception.Create('The value is not present in the TDynArr.');
end;
function TDynArr<T>.find(test: TFunc<T, Boolean>; const fallback: T): T;
var
ii: Integer;
begin
ii := self.findIndex(test);
if ii >= 0 then
Result := self._items[ii]
else
Result := fallback;
end;
function TDynArr<T>.findIndex(test: TFunc<T, Boolean>): Integer;
var
i: Integer;
begin
for i := 0 to self.length - 1 do
if test(self._items[i]) then
begin
Result := i;
Exit;
end;
Result := -1;
end;
procedure TDynArr<T>.forEach(process: TProc<T>);
var
i: Integer;
begin
for i := 0 to self.length - 1 do
process(self._items[i]);
end;
procedure TDynArr<T>.forEach(process: TProc<T, Integer>);
var
i: Integer;
begin
for i := 0 to self.length - 1 do
process(self._items[i], i);
end;
constructor TDynArr<T>.from(const a: TDynArr<T>);
var
i: Integer;
begin
System.SetLength(self._items, a.length);
for i := 0 to a.length - 1 do
self._items[i] := a[i];
end;
constructor TDynArr<T>.from(const initialLength: Integer);
begin
from(initialLength, System.Default(T));
end;
constructor TDynArr<T>.from(const initialLength: Integer; const initialVal: T);
begin
create(initialLength);
fill(initialVal);
end;
constructor TDynArr<T>.from(const a: TRawArr<T>; startIndex: Integer = -1; endIndex: Integer = -1);
var
l, i: Integer;
begin
l := System.Length(a);
if startIndex < 0 then
startIndex := 0;
if endIndex < 0 then
endIndex := l;
if endIndex > l then
endIndex := l;
System.SetLength(self._items, endIndex - startIndex);
for i := startIndex to endIndex - 1 do
self._items[i - startIndex] := a[i];
end;
function TDynArr<T>.getItem(itemNo: Integer): T;
begin
if itemNo < self.length then
Result := self._items[itemNo]
else
raise ERangeError.CreateFmt(
'DynArr item index out of range: %d (max allowed: %d)',
[itemNo, self.lastIndex]);
end;
function TDynArr<T>.getLastIndex: Integer;
begin
Result := self.length - 1;
end;
function TDynArr<T>.getLastItem: T;
begin
if self.isEmpty then
raise ERangeError.Create('Cannot access the last item of an empty array.');
Result := self._items[self.lastIndex];
end;
function TDynArr<T>.getLength: Integer;
begin
Result := System.Length(self._items);
end;
function TDynArr<T>.getPtr(itemNo: Integer): Ptr;
begin
if itemNo < self.length then
Result := @(self._items[itemNo])
else
raise ERangeError.CreateFmt(
'DynArr item index out of range: %d (max allowed: %d)',
[itemNo, self.lastIndex]);
end;
class operator TDynArr<T>.Implicit(a: TRawArr<T>): TDynArr<T>;
begin
Result := TDynArr<T>.from(a);
end;
function TDynArr<T>.includes(const val: T): Boolean;
begin
Result := self.indexOf(val) >= 0;
end;
function TDynArr<T>.indexOf(const val: T): Integer;
var
i: Integer;
begin
for i := 0 to self.length - 1 do
if TDynArr<T>.itemsEqual(self._items[i], val) then
begin
Result := i;
Exit;
end;
Result := -1;
end;
procedure TDynArr<T>.insert(const item: T; const idx: Integer);
begin
if (idx < 0) then
raise ERangeError.CreateFmt(
'Invalid insertion point: %d.', [idx]);
if idx >= self.length then
self.append(item)
else
begin
self.length := self.length + 1;
for var i := self.length - 2 downto idx do
// shift everything right by one, from idx to the end of the array
self._items[i + 1] := self._items[i];
self._items[idx] := item;
end;
end;
function TDynArr<T>._isEmpty: Boolean;
begin
Result := self.length = 0;
end;
function TDynArr<T>._isNotEmpty: Boolean;
begin
Result := not self._isEmpty();
end;
class function TDynArr<T>.itemsEqual(const i1, i2: T): Boolean;
var
t_info: PTypeInfo;
begin
t_info := System.TypeInfo(T);
if (t_info <> nil) and ((t_info^.Kind in [tkString, tkWString, tkUString])) then
// this is a special case for comparing strings, CompareMem doesn't
// work properly with strings
Result := string((_Pstring(@i1))^) = string((_Pstring(@i2))^)
else
// for all other types we use the brute CompareMem function
Result := CompareMem(@i1, @i2, SizeOf(T));
end;
function TDynArr<T>.join(mapper: TFunc<T, string>; const separator: string = ''): string;
var
i: Integer;
begin
Result := '';
for i := 0 to self.length - 1 do
begin
if Result <> '' then
Result := Result + separator + mapper(self._items[i])
else
Result := Result + mapper(self._items[i]);
end;
end;
function TDynArr<T>.lastIndexOf(const val: T): Integer;
var
i: Integer;
begin
for i := self.length - 1 downto 0 do
if TDynArr<T>.itemsEqual(self._items[i], val) then
begin
Result := i;
Exit;
end;
Result := -1;
end;
function TDynArr<T>.map<S>(mapper: TFunc<T, S>): TDynArr<S>;
var
i: Integer;
begin
Result := TDynArr<S>.Create(self.length);
for i := Low(_items) to High(_items) do
Result[i] := mapper(_items[i]);
end;
function TDynArr<T>.map<S>(mapper: TFunc<T, Integer, S>): TDynArr<S>;
var
i: Integer;
begin
Result := TDynArr<S>.Create(self.length);
for i := Low(_items) to High(_items) do
Result[i] := mapper(_items[i], i);
end;
class operator TDynArr<T>.Multiply(const a: TDynArr<T>;
const n: Integer): TDynArr<T>;
var
i, j: Integer;
begin
Result := TDynArr<T>.Create(n * a.length);
for i := 0 to a.length - 1 do
for j := 0 to n - 1 do
Result[j * a.length + i] := a[i];
end;
function TDynArr<T>.pop: T;
begin
if self.length > 0 then
begin
Result := self._items[self.length - 1];
System.Delete(self._items, self.length - 1, 1);
end
else
raise Exception.Create('Cannot pop an item from and empty TDynArr.');
end;
function TDynArr<T>.ptrAll(test: TFunc<Ptr, Integer, Boolean>): Boolean;
begin
Result := not ptrAny(
function(itm: Ptr; idx: Integer): Boolean
begin
Result := not test(itm, idx);
end
);
end;
function TDynArr<T>.ptrAll(test: TFunc<Ptr, Boolean>): Boolean;
begin
Result := ptrAny(
function(itm: Ptr): Boolean
begin
Result := not test(itm);
end
);
end;
function TDynArr<T>.ptrAny(test: TFunc<Ptr, Integer, Boolean>): Boolean;
begin
Result := ptrSome(test);
end;
function TDynArr<T>.ptrAny(test: TFunc<Ptr, Boolean>): Boolean;
begin
Result := ptrSome(test);
end;
function TDynArr<T>.ptrEvery(test: TFunc<Ptr, Integer, Boolean>): Boolean;
begin
Result := self.ptrAll(test);
end;
function TDynArr<T>.ptrEvery(test: TFunc<Ptr, Boolean>): Boolean;
begin
Result := self.ptrAll(test);
end;
function TDynArr<T>.ptrFilter(test: TFunc<Ptr, Boolean>): TDynArr<T>;
begin
Result := self.ptrFilter(
function(it: Ptr; _: Integer): Boolean
begin
Result := test(it);
end
);
end;
function TDynArr<T>.ptrFilter(test: TFunc<Ptr, Integer, Boolean>): TDynArr<T>;
var
i, ii: Integer;
begin
Result := TDynArr<T>.create(self.length);
ii := 0;
for i := 0 to self.length - 1 do
if test(@(self._items[i]), i) then
begin
Result[ii] := self._items[i];
ii := ii + 1;
end;
Result.length := ii;
end;
function TDynArr<T>.ptrFind(test: TFunc<Ptr, Boolean>): Ptr;
var
ii: Integer;
begin
ii := self.ptrFindIndex(test);
if ii >= 0 then
Result := @(self._items[ii])
else
Result := nil;
end;
function TDynArr<T>.ptrFindIndex(test: TFunc<Ptr, Boolean>): Integer;
var
i: Integer;
begin
for i := 0 to self.length - 1 do
if test(@(self._items[i])) then
begin
Result := i;
Exit;
end;
Result := -1;
end;
procedure TDynArr<T>.ptrForEach(process: TProc<Ptr, Integer>);
var
i: Integer;
begin
for i := 0 to self.length - 1 do
process(@(self._items[i]), i);
end;
function TDynArr<T>.ptrMap<S>(mapper: TFunc<Ptr, Integer, S>): TDynArr<S>;
var
i: Integer;
begin
Result := TDynArr<S>.Create(self.length);
for i := Low(_items) to High(_items) do
Result[i] := mapper(@(_items[i]), i);
end;
function TDynArr<T>.ptrReduce<S>(reducer: TFunc<S, Ptr, S>;
const initialValue: S): TBoxed<S>;
begin
Result := self.ptrReduce<S>(
function(accumulated: S; it: Ptr; index: Integer): S
begin
Result := reducer(accumulated, it);
end,
initialValue
);
end;
function TDynArr<T>.ptrReduce<S>(reducer: TFunc<S, Ptr, Integer, S>;
const initialValue: S): TBoxed<S>;
var
i: Integer;
r: S;
begin
r := initialValue;
for i := 0 to self.length - 1 do
r := reducer(r, @(self._items[i]), i);
Result := TBoxed<S>.from(r);
end;
function TDynArr<T>.ptrMap<S>(mapper: TFunc<Ptr, S>): TDynArr<S>;
var
i: Integer;
begin
Result := TDynArr<S>.Create(self.length);
for i := Low(_items) to High(_items) do
Result[i] := mapper(@(_items[i]));
end;
function TDynArr<T>.ptrSome(test: TFunc<Ptr, Integer, Boolean>): Boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to self.length - 1 do
if test(@(self._items[i]), i) then
Exit;
Result := false;
end;
function TDynArr<T>.ptrSome(test: TFunc<Ptr, Boolean>): Boolean;
begin
Result := self.ptrSome(
function(val: Ptr; idx: Integer): Boolean
begin
Result := test(val);
end
);
end;
function TDynArr<T>.ptrWhere(test: TFunc<Ptr, Boolean>): TDynArr<T>;
begin
Result := self.ptrFilter(test);
end;
procedure TDynArr<T>.ptrForEach(process: TProc<Ptr>);
var
i: Integer;
begin
for i := 0 to self.length - 1 do
process(@(self._items[i]));
end;
function TDynArr<T>.push(const val: T): Integer;
begin
self.length := self.length + 1;
self._items[self.length - 1] := val;
end;
function TDynArr<T>.reduce<S>(reducer: TFunc<S, T, S>; const initialValue: S): TBoxed<S>;
begin
Result := self.reduce<S>(
function(accumulated: S; it: T; index: Integer): S
begin
Result := reducer(accumulated, it);
end,
initialValue
);
end;
function TDynArr<T>.reduce<S>(reducer: TFunc<S, T, Integer, S>;
const initialValue: S): TBoxed<S>;
var
i: Integer;
r: S;
begin
r := initialValue;
for i := 0 to self.length - 1 do
r := reducer(r, self._items[i], i);
Result := TBoxed<S>.from(r);
end;
procedure TDynArr<T>.reverse;
var
i: Integer;
tmp: T;
begin
for i := 0 to self.length div 2 do
TDynArr<T>.swap(self._items[i], self._items[self.length - i - 1]);
end;
function TDynArr<T>.reversed: TDynArr<T>;
begin
Result := TDynArr<T>.from(self);
Result.reverse();
end;
procedure TDynArr<T>.setItem(itemNo: Integer; const newValue: T);
begin
if itemNo < self.length then
self._items[itemNo] := newValue
else
raise ERangeError.CreateFmt(
'DynArr item index out of range: %d (max allowed: %d)',
[itemNo, self.lastIndex]);
end;
procedure TDynArr<T>.setLength(newLength: Integer);
begin
if newLength <> self.length then
System.SetLength(_items, newLength);
end;
procedure TDynArr<T>.setPtr(itemNo: Integer; const newPtr: Ptr);
begin
if itemNo < self.length then
self._items[itemNo] := newPtr^
else
raise ERangeError.CreateFmt(
'DynArr item index out of range: %d (max allowed: %d)',
[itemNo, self.lastIndex]);
end;
function TDynArr<T>.shift: T;
begin
if self.length > 0 then
begin
Result := self._items[0];
System.Delete(self._items, 0, 1);
end
else
raise Exception.Create('Cannot shift an empty TDynArr');
end;
function TDynArr<T>.slice(const startIndex, endIndex: Integer): TDynArr<T>;
begin
Result := TDynArr<T>.from(self._items, startIndex, endIndex);
end;
function TDynArr<T>.some(test: TFunc<T, Boolean>): Boolean;
begin
Result := self.some(
function(val: T; idx: Integer): Boolean
begin
Result := test(val);
end
);
end;
function TDynArr<T>.some(test: TFunc<T, Integer, Boolean>): Boolean;
var
i: Integer;
begin
Result := true;
for i := 0 to self.length - 1 do
if test(self._items[i], i) then
Exit;
Result := false;
end;
procedure TDynArr<T>.sort(compare: TComparison<T>);
var
cmp: IComparer<T>;
begin
if self.length > 1 then
begin
cmp := TDelegatedComparer<T>.Create(compare);
TArray.Sort<T>(_items, cmp);
end;
end;
function TDynArr<T>.sorted(compare: TComparison<T>): TDynArr<T>;
begin
Result := TDynArr<T>.from(self);
Result.sort(compare);
end;
function TDynArr<T>.splice(const startIndex, howMany: Integer;
const newItems: TDynArr<T>): TDynArr<T>;
begin
Result := self.slice(startIndex, startIndex + howMany);
System.Delete(self._items, startIndex, howMany);
if newItems.length > 0 then
System.Insert(newItems.raw, self._items, startIndex);
end;
function TDynArr<T>.splice(const startIndex, howMany: Integer): TDynArr<T>;
begin
Result := self.splice(startIndex, howMany, TDynArr<T>.empty);
end;
class procedure TDynArr<T>.swap(var i1, i2: T);
var
tmp: T;
begin
tmp := i1;
i1 := i2;
i2 := tmp;
end;
procedure TDynArr<T>.swapItems(const i, j: Integer);
begin
if (i < 0) or (i >= length) or (j < 0) or (j >= length) then
raise Exception.CreateFmt('Swap: invalid indices %d and %d', [i, j]);
var tmp: T := items[i];
items[i] := items[j];
items[j] := tmp;
end;
function TDynArr<T>.toString(mapper: TFunc<T, string>): string;
begin
Result := self.join(mapper, ', ');
end;
function TDynArr<T>.unshift(const toAdd: TDynArr<T>): Integer;
begin
System.Insert(toAdd.raw, self._items, 0);
Result := self.length;
end;
function TDynArr<T>.where(test: TFunc<T, Boolean>): TDynArr<T>;
begin
Result := self.filter(test);
end;
function range(const upperBound: Integer): TDynArr<Integer>;
var
i: Integer;
begin
if upperBound <= 0 then
Result.length := 0
else
begin
Result.length := upperBound;
for i := 0 to upperBound - 1 do
Result.raw[i] := i;
end;
end;
function range(const lowerBound, upperBound: Integer; const step: Integer = 1): TDynArr<Integer>;
var
i, ii: Integer;
begin
if
((step > 0) and (upperBound <= lowerBound))
or ((step < 0) and (upperBound >= lowerBound))
or (step = 0)
then
Result.length := 0
else
begin
Result.length := upperBound - lowerBound;
ii := 0;
i := lowerBound;
while i < upperBound do
begin
Result.raw[ii] := i;
ii := ii + 1;
i := i + step;
end;
end;
end;
{ TBoxed<S> }
constructor TBoxed<S>.from(const val: S);
begin
self.value := val;
end;
end.
|
unit ext_global;
interface
const
PCKT_TYPE = $01;
PCKT_WRITE_TIME = $02;
PCKT_READ_TIME = $03;
PCKT_WRITE_DATA = $04;
PCKT_CURRENT = $05;
PCKT_STATE_ARCHIVE = $06;
PCKT_GET_ARCHIVE = $07;
PCKT_OPER = $09;
PCKT_WRITE_BLOCK_DATA = $0B;
PCKT_READ_BLOCK_DATA = $0C;
PCKT_VERSION = $0D;
PCKT_WRITE_ROM_Dev = $0E;
PCKT_READ_ROM_Dev = $0F;
// рассчитать CRC для полного пакета
function GET_CRC (TA : TArray<Byte>; Len : Integer) : Byte;
// рассчитать CRC и записать в буфер
procedure CRC (TA : TArray<Byte>;Len : Integer);
// установка бита
procedure SetBit(var Src: Byte; bit: Integer);
// сброс бита
procedure ResetBit(var Src : Byte; bit: Integer);
// провека бита
function GetBit(Src : Byte; bit: Integer) : Integer;
function IsBitSet(Src : Byte; bit: Integer) : Boolean;
implementation
function GET_CRC (TA : TArray<Byte>;Len : Integer) : Byte;
var
B : Byte;
I : Integer;
begin
B := 0;
for i := 0 to Len - 2 do
B := B + TA[i];
Result := $100-B;
end;
procedure CRC (TA : TArray<Byte>;Len : Integer);
begin
TA[Len-1] := GET_CRC(TA,Len);
end;
procedure SetBit(var Src : Byte; bit: Integer);
begin
Src := Src or (1 shl bit);
end;
procedure ResetBit(var Src : Byte; bit: Integer);
begin
Src := Src and not (1 shl Bit);
end;
function GetBit(Src : Byte; bit: Integer) : Integer;
begin
Result := (Src shr bit) and $01;
end;
function IsBitSet (Src : Byte; bit: Integer) : Boolean;
begin
IsBitSet := False;
if (Src shr bit) and $01 = 1 then
IsBitSet := True;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmPreferences;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit,
cxLabel, ExtCtrls, ComCtrls, StdCtrls, cxButtons, cxTreeView;
type
TPreferencesFrm = class(TForm)
Panel1: TPanel;
pc: TPageControl;
Panel2: TPanel;
btnCancel: TcxButton;
btnOK: TcxButton;
tsVisiual: TTabSheet;
Panel3: TPanel;
imgToolBar: TImage;
imgObject: TImage;
lblObjectName: TcxLabel;
cxTreeView1: TcxTreeView;
private
{ Private declarations }
public
{ Public declarations }
end;
var
PreferencesFrm: TPreferencesFrm;
implementation
{$R *.dfm}
end.
|
unit MessagesForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DBGridEh, StdCtrls, Mask, DBCtrlsEh, ComCtrls,
ToolWin, frxClass, frxDBSet, DB, FIBDataSet, pFIBDataSet, Menus,
ActnList, GridsEh, ExtCtrls, Buttons, DBGridEhImpExp, FIBQuery,
DBGridEhGrouping, MemTableDataEh, DataDriverEh, pFIBDataDriverEh,
MemTableEh, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh,
System.Actions, PrjConst, EhLibVCL, System.UITypes, DynVarsEh,
CnErrorProvider, DBLookupEh;
type
TMessagesForm = class(TForm)
pnlAll: TPanel;
dbgMessages: TDBGridEh;
alGuide: TActionList;
actNew: TAction;
actPayDocSearch: TAction;
actMessSetPeriod: TAction;
actPrintDoc: TAction;
actQuickFilter: TAction;
gridPopUp: TPopupMenu;
ppmCopy: TMenuItem;
ppmSelectAll: TMenuItem;
MenuItem1: TMenuItem;
ppmSaveSelection: TMenuItem;
dsMessages: TpFIBDataSet;
srcMessages: TDataSource;
frxDBMessages: TfrxDBDataset;
tlbMain: TToolBar;
ToolButton14: TToolButton;
ToolButton16: TToolButton;
ToolButton4: TToolButton;
ToolButton3: TToolButton;
ToolButton5: TToolButton;
ToolButton1: TToolButton;
ToolButton27: TToolButton;
pmPeriod: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
MainMenu1: TMainMenu;
N5: TMenuItem;
N6: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
N10: TMenuItem;
N12: TMenuItem;
N15: TMenuItem;
chkGroup: TCheckBox;
actGroup: TAction;
N13: TMenuItem;
mtMessages: TMemTableEh;
drvMessages: TpFIBDataDriverEh;
N7: TMenuItem;
actDel: TAction;
N11: TMenuItem;
btnSendSMS: TToolButton;
btn2: TToolButton;
actSendSMS: TAction;
btnDel: TToolButton;
btnEdit: TToolButton;
actEdit: TAction;
N14: TMenuItem;
N16: TMenuItem;
actFilterCustomer: TAction;
btnFilterCustomer: TToolButton;
ToolButton2: TToolButton;
pnlEdit: TPanel;
CnErrors: TCnErrorProvider;
pnl1: TPanel;
lbl3: TLabel;
pnlOkCancel: TPanel;
btnCancelLink: TBitBtn;
btnSaveLink: TBitBtn;
pnl2: TPanel;
pnlHead: TPanel;
lbl2: TLabel;
dsMessType: TpFIBDataSet;
srcMessType: TDataSource;
lbl4: TLabel;
edtReciver: TDBEditEh;
mmoMessage: TDBMemoEh;
edtHEAD: TDBEditEh;
cbbTYPE: TDBLookupComboboxEh;
lblSMScount: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ppmSaveSelectionClick(Sender: TObject);
procedure ppmSelectAllClick(Sender: TObject);
procedure ppmCopyClick(Sender: TObject);
procedure actMessSetPeriodExecute(Sender: TObject);
procedure actQuickFilterExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure actPayDocEditExecute(Sender: TObject);
procedure bbDownClick(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure actPrintDocExecute(Sender: TObject);
procedure frxDBMessagesCheckEOF(Sender: TObject; var Eof: Boolean);
procedure frxDBMessagesFirst(Sender: TObject);
procedure frxDBMessagesNext(Sender: TObject);
procedure actNewExecute(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure actGroupExecute(Sender: TObject);
procedure dbgMessagesDataGroupGetRowText(Sender: TCustomDBGridEh; GroupDataTreeNode: TGroupDataTreeNodeEh;
var GroupRowText: string);
procedure actDelExecute(Sender: TObject);
procedure actSendSMSExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure N16Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actFilterCustomerExecute(Sender: TObject);
procedure btnSaveLinkClick(Sender: TObject);
procedure btnCancelLinkClick(Sender: TObject);
procedure dbgMessagesDblClick(Sender: TObject);
procedure lcbMessTypeChange(Sender: TObject);
procedure mmoMessageChange(Sender: TObject);
procedure cbbTYPEChange(Sender: TObject);
procedure dbgMessagesGetFooterParams(Sender: TObject; DataCol, Row: Integer;
Column: TColumnEh; AFont: TFont; var Background: TColor;
var Alignment: TAlignment; State: TGridDrawState; var Text: string);
private
FFirstOpen : Boolean; // Первое открытие Формы
CanEdit: Boolean;
CanCreate: Boolean;
inEditMode: Boolean;
fStartDate: TDateTime;
fEndDate: TDateTime;
fShowNotSended: Boolean;
fCanSave: Boolean;
fSelectedRow: Integer; // выделенная строка в таблице платежей
procedure SetMessagesFilter;
procedure StartEdit(const New: Boolean = False);
procedure StopEdit(const Cancel: Boolean);
public
{ Public declarations }
end;
var
MessagesForm: TMessagesForm;
implementation
uses DM, MAIN, AtrCommon, PeriodForma, PaymentDocForma, AtrStrUtils, ReportPreview,
apiSMS, CF, pFIBQuery;
{$R *.dfm}
procedure TMessagesForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if fCanSave then
dbgMessages.SaveColumnsLayoutIni(A4MainForm.GetIniFileName, 'dbgMessages', true);
if srcMessages.DataSet.Active then
srcMessages.DataSet.Close;
dsMessages.Close;
MessagesForm := nil;
Action := caFree;
end;
procedure TMessagesForm.ppmSaveSelectionClick(Sender: TObject);
var
ExpClass: TDBGridEhExportClass;
Ext: String;
begin
A4MainForm.SaveDialog.FileName := rsPayments;
if (ActiveControl is TDBGridEh) then
if A4MainForm.SaveDialog.Execute then
begin
case A4MainForm.SaveDialog.FilterIndex of
1:
begin
ExpClass := TDBGridEhExportAsUnicodeText;
Ext := 'txt';
end;
2:
begin
ExpClass := TDBGridEhExportAsCSV;
Ext := 'csv';
end;
3:
begin
ExpClass := TDBGridEhExportAsHTML;
Ext := 'htm';
end;
4:
begin
ExpClass := TDBGridEhExportAsRTF;
Ext := 'rtf';
end;
5:
begin
ExpClass := TDBGridEhExportAsOLEXLS;
Ext := 'xls';
end;
else
ExpClass := nil;
Ext := '';
end;
if ExpClass <> nil then
begin
if AnsiUpperCase(Copy(A4MainForm.SaveDialog.FileName, Length(A4MainForm.SaveDialog.FileName) - 2, 3)) <>
AnsiUpperCase(Ext) then
A4MainForm.SaveDialog.FileName := A4MainForm.SaveDialog.FileName + '.' + Ext;
SaveDBGridEhToExportFile(ExpClass, TDBGridEh(ActiveControl), A4MainForm.SaveDialog.FileName, False);
end;
end;
end;
procedure TMessagesForm.ppmSelectAllClick(Sender: TObject);
begin
if (ActiveControl is TDBGridEh) then
with TDBGridEh(ActiveControl) do
if CheckSelectAllAction and (geaSelectAllEh in EditActions) then
Selection.SelectAll;
end;
procedure TMessagesForm.ppmCopyClick(Sender: TObject);
var
dbg: TDBGridEh;
begin
if (ActiveControl is TDBGridEh) then
begin
dbg := (ActiveControl as TDBGridEh);
if (geaCopyEh in dbg.EditActions) then
if dbg.CheckCopyAction then
DBGridEh_DoCopyAction(dbg, False)
else
StrToClipbrd(dbg.SelectedField.AsString);
end;
end;
procedure TMessagesForm.actMessSetPeriodExecute(Sender: TObject);
var
bDate, eDate: TDateTime;
begin
bDate := fStartDate;
eDate := fEndDate;
if ChangePeriod(bDate, eDate) then
begin
fStartDate := bDate;
fEndDate := eDate;
SetMessagesFilter;
end;
end;
procedure TMessagesForm.actQuickFilterExecute(Sender: TObject);
begin
actQuickFilter.Checked := not actQuickFilter.Checked;
dbgMessages.STFilter.Visible := actQuickFilter.Checked;
end;
procedure TMessagesForm.SetMessagesFilter;
begin
dsMessages.Close;
dsMessages.ParamByName('StartDate').AsDate := fStartDate;
dsMessages.ParamByName('EndDate').AsDate := fEndDate;
if fShowNotSended then
dsMessages.ParamByName('ShowNotSended').AsInteger := 1
else
dsMessages.ParamByName('ShowNotSended').AsInteger := 0;
Caption := Format(rsMessagesPeriod, [DateToStr(fStartDate), DateToStr(fEndDate)]);
dsMessages.Open;
end;
procedure TMessagesForm.FormShow(Sender: TObject);
begin
dbgMessages.RestoreColumnsLayoutIni(A4MainForm.GetIniFileName, 'dbgMessages',
[crpColIndexEh, crpColWidthsEh, crpColVisibleEh]);
fEndDate := now;
fStartDate := MonthFirstDay(dmMain.CurrentMonth);
SetMessagesFilter;
CanEdit := (dmMain.AllowedAction(rght_Messages_add) or dmMain.AllowedAction(rght_Customer_full));
CanCreate := (dmMain.AllowedAction(rght_Messages_add) or dmMain.AllowedAction(rght_Customer_full));
// права пользователей
actNew.Visible := CanEdit;
actDel.Visible := CanEdit;
actEdit.Visible := CanEdit;
dsMessages.Open;
inEditMode := False;
end;
procedure TMessagesForm.N1Click(Sender: TObject);
begin
fStartDate := now;
fEndDate := now;
SetMessagesFilter;
end;
procedure TMessagesForm.N2Click(Sender: TObject);
begin
fStartDate := now - 7;
fEndDate := now;
SetMessagesFilter;
end;
procedure TMessagesForm.dbgMessagesDataGroupGetRowText(Sender: TCustomDBGridEh; GroupDataTreeNode: TGroupDataTreeNodeEh;
var GroupRowText: string);
var
s: string;
i: Integer;
begin
s := GroupDataTreeNode.DisplayValue;
i := Pos(s, GroupRowText);
GroupRowText := Copy(GroupRowText, i, Length(GroupRowText));
end;
procedure TMessagesForm.actPayDocEditExecute(Sender: TObject);
begin
// if dsMessages.FieldByName('mes_id').IsNull
// then exit;
//
end;
procedure TMessagesForm.bbDownClick(Sender: TObject);
begin
pmPeriod.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
end;
procedure TMessagesForm.N3Click(Sender: TObject);
begin
fStartDate := MonthFirstDay(now);
fEndDate := MonthLastDay(now);
SetMessagesFilter;
end;
procedure TMessagesForm.N4Click(Sender: TObject);
begin
fStartDate := (now - 1);
fEndDate := (now - 1);
SetMessagesFilter;
end;
procedure TMessagesForm.actPrintDocExecute(Sender: TObject);
var
bm: TBookMark;
begin
dsMessages.DisableControls;
bm := dsMessages.GetBookmark;
ShowReport('Messages');
dsMessages.GotoBookmark(bm);
dsMessages.EnableControls;
end;
procedure TMessagesForm.frxDBMessagesCheckEOF(Sender: TObject; var Eof: Boolean);
begin
if dbgMessages.SelectedRows.Count > 0 then
Eof := (fSelectedRow > dbgMessages.SelectedRows.Count)
end;
procedure TMessagesForm.frxDBMessagesFirst(Sender: TObject);
begin
if dbgMessages.SelectedRows.Count > 0 then
begin
fSelectedRow := 1;
dbgMessages.DataSource.DataSet.Bookmark := dbgMessages.SelectedRows[0];
end
end;
procedure TMessagesForm.frxDBMessagesNext(Sender: TObject);
begin
if (dbgMessages.SelectedRows.Count > 0) then
begin
if fSelectedRow < dbgMessages.SelectedRows.Count then
dbgMessages.DataSource.DataSet.Bookmark := dbgMessages.SelectedRows[fSelectedRow];
inc(fSelectedRow);
end
end;
procedure TMessagesForm.actDelExecute(Sender: TObject);
var
i: Integer;
begin
if dsMessages.RecordCount = 0 then
exit;
if (MessageDlg(rsDeleteSelectedRecords, mtConfirmation, [mbYes, mbNo], 0) = mrNo) then
exit;
if (dbgMessages.SelectedRows.Count > 1) then
begin
try
Screen.Cursor := crHourGlass;
for i := 0 to (dbgMessages.SelectedRows.Count - 1) do
begin
dbgMessages.DataSource.DataSet.GotoBookmark(pointer(dbgMessages.SelectedRows.Items[i]));
dbgMessages.DataSource.DataSet.Delete;
end;
finally
Screen.Cursor := crDefault;
end
end
else
begin
dbgMessages.DataSource.DataSet.Delete;
end;
dsMessages.CloseOpen(true);
end;
procedure TMessagesForm.actGroupExecute(Sender: TObject);
var
Crsr: TCursor;
begin
actGroup.Checked := not actGroup.Checked;
Crsr := Screen.Cursor;
Screen.Cursor := crSqlWait;
if actGroup.Checked then
begin
srcMessages.DataSet := mtMessages;
dbgMessages.DataGrouping.GroupPanelVisible := true;
// dbgMessages.DataGrouping.GroupLevels.Clear;
dbgMessages.DataGrouping.Active := true;
srcMessages.DataSet.Active := true;
fCanSave := False;
end
else
begin
dbgMessages.DataGrouping.Active := False;
// dbgMessages.DataGrouping.GroupLevels.Clear;
dbgMessages.DataGrouping.GroupPanelVisible := False;
srcMessages.DataSet := dsMessages;
mtMessages.Active := False;
srcMessages.DataSet.Active := true;
end;
Screen.Cursor := Crsr;
end;
procedure TMessagesForm.actNewExecute(Sender: TObject);
begin
{ TODO:добавление сообщения }
StartEdit(true);
end;
procedure TMessagesForm.FormActivate(Sender: TObject);
var
i: integer;
filter: string;
inFilter: Boolean;
begin
if FFirstOpen then begin
FFirstOpen := False;
Exit;
end;
if not((dsMessages.Active) and (dsMessages.RecordCount > 0) and
(not dsMessages.FieldByName('MES_ID').IsNull)) then
dsMessages.CloseOpen(True)
else begin
inFilter := dsMessages.Filtered;
filter := dsMessages.filter;
i := dsMessages['MES_ID'];
dsMessages.CloseOpen(true);
if inFilter then
begin
dsMessages.filter := filter;
dsMessages.Filtered := inFilter;
if dbgMessages.SearchPanel.SearchingText <> '' then
dbgMessages.SearchPanel.ApplySearchFilter;
end;
dsMessages.Locate('MES_ID', i, []);
end;
end;
procedure TMessagesForm.actSendSMSExecute(Sender: TObject);
var
g: TSMSapi;
balance: Integer;
ForSendCount: Integer;
ErrorText: String;
rSMS: TpFIBQuery;
// trR : TpFIBTransaction;
// trW : TpFIBTransaction;
begin
rSMS := TpFIBQuery.Create(nil);
try
rSMS.DataBase := dmMain.dbTV;
rSMS.Transaction := dmMain.trReadQ;
rSMS.SQL.Add('select count(m.reciver) as CNT from messages m where m.mes_result = 0 and m.Mes_Type = ''SMS'' ');
rSMS.Transaction.StartTransaction;
rSMS.ExecQuery;
ForSendCount := rSMS.fn('CNT').AsInteger;
rSMS.Transaction.Commit;
finally
rSMS.Free;
end;
g := TSMSapi.Create(dmMain.GetSettingsValue('A4LOGIN'), dmMain.GetSettingsValue('A4APIKEY'),
dmMain.GetSettingsValue('FORMATN'));
try
ErrorText := '';
balance := g.balance;
if (balance - ForSendCount) < 0 then
begin
MessageDlg(Format(rsSMScountLess, [ForSendCount, balance]), mtWarning, [mbOK], 0);
end
else
begin
if (MessageBox(0, PWideChar(Format(rsSMSSend, [ForSendCount, balance])), '', MB_ICONQUESTION or MB_OKCANCEL or
MB_APPLMODAL or MB_DEFBUTTON2) = idOk) then
begin
ErrorText := g.ErrorText;
if balance > 0 then
begin
g.SendAll(ErrorText);
balance := g.balance;
ErrorText := g.ErrorText;
// TODO: Сделать проверку статуса СМС
//g.CheckAll;
ErrorText := g.ErrorText;
if balance <> -1 then
ShowMessage(Format(rsSMSBalance, [balance]))
else
ShowMessage(ErrorText);
end;
end
end;
finally
g.Free;
end;
dsMessages.Close;
dsMessages.Open;
end;
procedure TMessagesForm.actEditExecute(Sender: TObject);
begin
{ TODO:Редактирование сообщения }
StartEdit(False);
end;
procedure TMessagesForm.N16Click(Sender: TObject);
begin
fShowNotSended := not fShowNotSended;
N16.Checked := fShowNotSended;
SetMessagesFilter;
end;
procedure TMessagesForm.FormCreate(Sender: TObject);
begin
FFirstOpen := True;
fShowNotSended := true;
fCanSave := true;
end;
procedure TMessagesForm.actFilterCustomerExecute(Sender: TObject);
var
i: Integer;
b: TBookMark;
customers: TStringList;
s: string;
begin
customers := TStringList.Create;
customers.Sorted := true;
customers.Duplicates := dupIgnore;
if (dbgMessages.SelectedRows.Count = 0) then
begin
if not dbgMessages.DataSource.DataSet.FieldByName('CUSTOMER_ID').IsNull then
customers.Add(IntToStr(dbgMessages.DataSource.DataSet['CUSTOMER_ID']));
end
else
begin
b := dbgMessages.DataSource.DataSet.GetBookmark;
dbgMessages.DataSource.DataSet.DisableControls;
dbgMessages.DataSource.DataSet.First;
for i := 0 to dbgMessages.SelectedRows.Count - 1 do
begin
dbgMessages.DataSource.DataSet.Bookmark := dbgMessages.SelectedRows[i];
if not dbgMessages.DataSource.DataSet.FieldByName('CUSTOMER_ID').IsNull then
customers.Add(IntToStr(dbgMessages.DataSource.DataSet['CUSTOMER_ID']));
end;
dbgMessages.DataSource.DataSet.GotoBookmark(b);
dbgMessages.DataSource.DataSet.EnableControls;
end;
if (customers.Count > 0) then
s := customers.CommaText
else
s := '';
FreeAndNil(customers);
if (s <> '') then
ShowCustomers(7, s);
end;
procedure TMessagesForm.btnSaveLinkClick(Sender: TObject);
begin
StopEdit(False);
end;
procedure TMessagesForm.cbbTYPEChange(Sender: TObject);
var
show: Boolean;
begin
show := False;
if not dsMessType.FieldByName('O_NUMERICFIELD').IsNull then
show := (dsMessType['O_NUMERICFIELD'] = 1);
pnlHead.Visible := show;
end;
procedure TMessagesForm.btnCancelLinkClick(Sender: TObject);
begin
StopEdit(true);
end;
procedure TMessagesForm.StartEdit(const New: Boolean = False);
begin
if not CanEdit then
exit;
if (not New) and (dsMessages.RecordCount = 0) then
exit;
if (not New) and (dsMessages['MES_RESULT'] <> 0) then
exit;
cbbTYPE.Enabled := New;
dsMessType.Open;
edtReciver.Text := '';
edtHEAD.Text := '';
mmoMessage.Lines.Text := '';
if New then
begin
cbbTYPE.KEyValue := 'SMS';
edtReciver.Tag := -1;
end
else
begin
cbbTYPE.KEyValue := dsMessages['MES_TYPE'];
if (not dsMessages.FieldByName('RECIVER').IsNull) then
edtReciver.Text := dsMessages['RECIVER'];
edtReciver.Tag := 0;
if (not dsMessages.FieldByName('MES_HEAD').IsNull) then
edtHEAD.Text := dsMessages['MES_HEAD'];
if (not dsMessages.FieldByName('MES_TEXT').IsNull) then
mmoMessage.Lines.Text := dsMessages['MES_TEXT'];
end;
pnlEdit.Visible := true;
dbgMessages.Enabled := False;
tlbMain.Enabled := False;
pnlEdit.SetFocus;
PostMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0);
inEditMode := true;
end;
procedure TMessagesForm.StopEdit(const Cancel: Boolean);
begin
pnlEdit.Visible := False;
dbgMessages.Enabled := true;
tlbMain.Enabled := true;
// New
if (edtReciver.Tag = 0) then
begin
dsMessages.Edit;
dsMessages['RECIVER'] := edtReciver.Text;
dsMessages['MES_HEAD'] := edtHEAD.Text;
dsMessages['MES_TEXT'] := mmoMessage.Lines.Text;
dsMessages.Post;
end
else
begin
dsMessages.Insert;
dsMessages['MES_TYPE'] := cbbTYPE.KEyValue;
dsMessages['RECIVER'] := edtReciver.Text;
dsMessages['MES_HEAD'] := edtHEAD.Text;
dsMessages['MES_TEXT'] := mmoMessage.Lines.Text;
dsMessages['MES_RESULT'] := 0;
dsMessages.Post;
end;
dbgMessages.SetFocus;
dsMessType.Close;
inEditMode := False;
end;
procedure TMessagesForm.dbgMessagesDblClick(Sender: TObject);
begin
if dsMessages.RecordCount > 0 then
begin
if not(actEdit.Enabled and actEdit.Visible) then
exit;
actEdit.Execute;
end
else
begin
if not(actNew.Enabled and actNew.Visible) then
exit;
actNew.Execute;
end;
end;
procedure TMessagesForm.dbgMessagesGetFooterParams(Sender: TObject; DataCol,
Row: Integer; Column: TColumnEh; AFont: TFont; var Background: TColor;
var Alignment: TAlignment; State: TGridDrawState; var Text: string);
var
i: Integer;
begin
if (DataCol = 1) and (Row = 0) then begin
i := (Sender as TDBGridEh).SelectedRows.Count;
if i > 1 then
Text := IntToStr(i);
end;
end;
procedure TMessagesForm.lcbMessTypeChange(Sender: TObject);
var
show: Boolean;
begin
show := False;
if not dsMessType.FieldByName('O_NUMERICFIELD').IsNull then
show := (dsMessType['O_NUMERICFIELD'] = 1);
pnlHead.Visible := show;
end;
procedure TMessagesForm.mmoMessageChange(Sender: TObject);
var
i, s: Integer;
begin
i := Length(mmoMessage.Lines.Text);
s := 6;
if (i <= 70) then
s := 1
else if ((i > 70) and (i < 134)) then
s := 2
else if ((i >= 134) and (i < 201)) then
s := 3
else if ((i >= 201) and (i < 268)) then
s := 4
else if ((i >= 268) and (i < 335)) then
s := 5;
lblSMScount.Caption := Format(rsSMScount, [i, s]);
end;
end.
|
unit IdHTTPWebsocketClient;
interface
uses
IdHTTP, IdHashSHA1;
type
TIdHTTPWebsocketClient = class(TIdHTTP)
private
FWSResourceName: string;
FHash: TIdHashSHA1;
protected
procedure InternalUpgradeToWebsocket(aRaiseException: Boolean; out aFailedReason: string);
public
procedure AfterConstruction;override;
destructor Destroy; override;
function TryUpgradeToWebsocket: Boolean;
procedure UpgradeToWebsocket;
published
property Host;
property Port;
property WSResourceName: string read FWSResourceName write FWSResourceName;
end;
implementation
uses
Classes, IdCoderMIME, SysUtils, IdIOHandlerWebsocket;
{ TIdHTTPWebsocketClient }
procedure TIdHTTPWebsocketClient.AfterConstruction;
begin
inherited;
FHash := TIdHashSHA1.Create;
IOHandler := TIdIOHandlerWebsocket.Create(nil);
end;
destructor TIdHTTPWebsocketClient.Destroy;
begin
FHash.Free;
inherited;
end;
function TIdHTTPWebsocketClient.TryUpgradeToWebsocket: Boolean;
var
sError: string;
begin
InternalUpgradeToWebsocket(False{no raise}, sError);
Result := (sError = '');
end;
procedure TIdHTTPWebsocketClient.UpgradeToWebsocket;
var
sError: string;
begin
InternalUpgradeToWebsocket(True{raise}, sError);
end;
procedure TIdHTTPWebsocketClient.InternalUpgradeToWebsocket(aRaiseException: Boolean; out aFailedReason: string);
var
sURL: string;
strmResponse: TMemoryStream;
i: Integer;
sKey, sResponseKey: string;
begin
Assert(not (IOHandler as TIdIOHandlerWebsocket).IsWebsocket);
Request.Clear;
//http://www.websocket.org/aboutwebsocket.html
(* GET ws://echo.websocket.org/?encoding=text HTTP/1.1
Origin: http://websocket.org
Cookie: __utma=99as
Connection: Upgrade
Host: echo.websocket.org
Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==
Upgrade: websocket
Sec-WebSocket-Version: 13 *)
//Connection: Upgrade
Request.Connection := 'upgrade';
//Upgrade: websocket
Request.CustomHeaders.Add('Upgrade: websocket');
//Sec-WebSocket-Key
sKey := '';
for i := 1 to 16 do
sKey := sKey + Char(Random(127-32) + 32);
//base64 encoded
sKey := TIdEncoderMIME.EncodeString(sKey);
Request.CustomHeaders.AddValue('Sec-WebSocket-Key', sKey);
//Sec-WebSocket-Version: 13
Request.CustomHeaders.AddValue('Sec-WebSocket-Version', '13');
strmResponse := TMemoryStream.Create;
try
Request.Host := Format('Host: %s:%d',[Host,Port]);
//ws://host:port/<resourcename>
//about resourcename, see: http://dev.w3.org/html5/websockets/ "Parsing WebSocket URLs"
sURL := Format('ws://%s:%d/%s', [Host, Port, WSResourceName]);
Get(sURL, strmResponse, [101]);
//http://www.websocket.org/aboutwebsocket.html
(* HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: Upgrade
Server: Kaazing Gateway
Upgrade: WebSocket
Access-Control-Allow-Origin: http://websocket.org
Access-Control-Allow-Credentials: true
Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=
Access-Control-Allow-Headers: content-type *)
//'HTTP/1.1 101 Switching Protocols'
if ResponseCode <> 101 then
begin
aFailedReason := Format('Error while upgrading: "%d: %s"',[ResponseCode, ResponseText]);
if aRaiseException then
raise EIdWebSocketHandleError.Create(aFailedReason);
end;
//connection: upgrade
if not SameText(Response.Connection, 'upgrade') then
begin
aFailedReason := Format('Connection not upgraded: "%s"',[Response.Connection]);
if aRaiseException then
raise EIdWebSocketHandleError.Create(aFailedReason);
end;
//upgrade: websocket
if not SameText(Response.RawHeaders.Values['upgrade'], 'websocket') then
begin
aFailedReason := Format('Not upgraded to websocket: "%s"',[Response.RawHeaders.Values['upgrade']]);
if aRaiseException then
raise EIdWebSocketHandleError.Create(aFailedReason);
end;
//check handshake key
sResponseKey := Trim(sKey) + //... "minus any leading and trailing whitespace"
'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; //special GUID
sResponseKey := TIdEncoderMIME.EncodeBytes( //Base64
FHash.HashString(sResponseKey) ); //SHA1
if not SameText(Response.RawHeaders.Values['sec-websocket-accept'], sResponseKey) then
begin
aFailedReason := 'Invalid key handshake';
if aRaiseException then
raise EIdWebSocketHandleError.Create(aFailedReason);
end;
//upgrade succesful
(IOHandler as TIdIOHandlerWebsocket).IsWebsocket := True;
aFailedReason := '';
finally
Request.Clear;
strmResponse.Free;
end;
end;
end.
|
unit simpsons_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,konami,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,sound_engine,ym_2151,k052109,k053260,eepromser,timer_engine,
k053251,k053246_k053247_k055673;
function iniciar_simpsons:boolean;
implementation
const
simpsons_rom:array[0..3] of tipo_roms=(
(n:'072-g02.16c';l:$20000;p:0;crc:$580ce1d6),(n:'072-p01.17c';l:$20000;p:$20000;crc:$07ceeaea),
(n:'072-013.13c';l:$20000;p:$40000;crc:$8781105a),(n:'072-012.15c';l:$20000;p:$60000;crc:$244f9289));
simpsons_sound:tipo_roms=(n:'072-g03.6g';l:$20000;p:0;crc:$76c1850c);
simpsons_tiles:array[0..1] of tipo_roms=(
(n:'072-b07.18h';l:$80000;p:0;crc:$ba1ec910),(n:'072-b06.16h';l:$80000;p:2;crc:$cf2bbcab));
simpsons_sprites:array[0..3] of tipo_roms=(
(n:'072-b08.3n';l:$100000;p:0;crc:$7de500ad),(n:'072-b09.8n';l:$100000;p:2;crc:$aa085093),
(n:'072-b10.12n';l:$100000;p:4;crc:$577dbd53),(n:'072-b11.16l';l:$100000;p:6;crc:$55fab05d));
simpsons_k053260:array[0..1] of tipo_roms=(
(n:'072-d05.1f';l:$100000;p:0;crc:$1397a73b),(n:'072-d04.1d';l:$40000;p:$100000;crc:$78778013));
simpsons_eeprom:tipo_roms=(n:'simpsons2p.12c.nv';l:$80;p:0;crc:$fbac4e30);
var
tiles_rom,sprite_rom,k053260_rom:pbyte;
sprite_colorbase,bank0_bank,bank2000_bank,rom_bank1,sound_bank,snd_timer,sprite_timer_dmaon,sprite_timer_dmaoff:byte;
layer_colorbase,layerpri:array[0..2] of byte;
rom_bank:array[0..$3f,0..$1fff] of byte;
sound_rom_bank:array[0..7,0..$3fff] of byte;
firq_enabled:boolean;
sprite_ram:array[0..$7ff] of word;
procedure simpsons_sprite_cb(var code:dword;var color:word;var priority_mask:word);
var
pri:integer;
begin
pri:=(color and $0f80) shr 6; // ???????
if (pri<=layerpri[2]) then priority_mask:=0
else if ((pri>layerpri[2]) and (pri<=layerpri[1])) then priority_mask:=1
else if ((pri>layerpri[1]) and (pri<=layerpri[0])) then priority_mask:=2
else priority_mask:=3;
color:=sprite_colorbase+(color and $001f);
end;
procedure simpsons_cb(layer,bank:word;var code:dword;var color:word;var flags:word;var priority:word);
begin
code:=code or (((color and $3f) shl 8) or (bank shl 14));
color:=layer_colorbase[layer]+((color and $c0) shr 6);
end;
procedure simpsons_sprites_dmaon;
begin
timers.enabled(sprite_timer_dmaon,false);
timers.enabled(sprite_timer_dmaoff,true);
if firq_enabled then konami_0.change_firq(ASSERT_LINE);
end;
procedure simpsons_sprites_dmaoff;
begin
timers.enabled(sprite_timer_dmaoff,false);
konami_0.change_firq(CLEAR_LINE);
end;
procedure update_video_simpsons;
var
bg_colorbase:byte;
sorted_layer:array[0..2] of byte;
begin
bg_colorbase:=k053251_0.get_palette_index(K053251_CI0);
sprite_colorbase:=k053251_0.get_palette_index(K053251_CI1);
layer_colorbase[0]:=k053251_0.get_palette_index(K053251_CI2);
layer_colorbase[1]:=k053251_0.get_palette_index(K053251_CI3);
layer_colorbase[2]:=k053251_0.get_palette_index(K053251_CI4);
sorted_layer[0]:=0;
layerpri[0]:=k053251_0.get_priority(K053251_CI2);
sorted_layer[1]:=1;
layerpri[1]:=k053251_0.get_priority(K053251_CI3);
sorted_layer[2]:=2;
layerpri[2]:=k053251_0.get_priority(K053251_CI4);
konami_sortlayers3(@sorted_layer,@layerpri);
if k053251_0.dirty_tmap[K053251_CI2] then begin
k052109_0.clean_video_buffer_layer(0);
k053251_0.dirty_tmap[K053251_CI2]:=false;
end;
if k053251_0.dirty_tmap[K053251_CI3] then begin
k052109_0.clean_video_buffer_layer(1);
k053251_0.dirty_tmap[K053251_CI3]:=false;
end;
if k053251_0.dirty_tmap[K053251_CI4] then begin
k052109_0.clean_video_buffer_layer(2);
k053251_0.dirty_tmap[K053251_CI4]:=false;
end;
fill_full_screen(4,bg_colorbase*16);
k052109_0.draw_tiles;
k053246_0.k053247_update_sprites;
k053246_0.k053247_draw_sprites(3);
k052109_0.draw_layer(sorted_layer[0],4);
k053246_0.k053247_draw_sprites(2);
k052109_0.draw_layer(sorted_layer[1],4);
k053246_0.k053247_draw_sprites(1);
k052109_0.draw_layer(sorted_layer[2],4);
k053246_0.k053247_draw_sprites(0);
actualiza_trozo_final(112,16,288,224,4);
end;
procedure eventos_simpsons;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $Fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $F7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
//P2
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80);
//System
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
end;
end;
procedure simpsons_objdma;
var
dst,src:pword;
inac,count:word;
begin
dst:=k053246_0.k053247_get_ram;
src:=@sprite_ram[0];
inac:=256;
count:=256;
repeat
if (((src^ and $8000)<>0) and ((src^ and $ff)<>0)) then begin
copymemory(dst,src,$10);
inc(dst,8);
inac:=inac-1;
end;
inc(src,8);
count:=count-1;
until (count=0);
if (inac<>0) then repeat
dst^:=0;
inc(dst,8);
inac:=inac-1;
until (inac=0);
end;
procedure simpsons_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=konami_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 263 do begin
//main
konami_0.run(frame_m);
frame_m:=frame_m+konami_0.tframes-konami_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=223 then begin
if k052109_0.is_irq_enabled then konami_0.change_irq(HOLD_LINE);
if k053246_0.is_irq_enabled then begin
simpsons_objdma;
timers.enabled(sprite_timer_dmaon,true);
end;
update_video_simpsons;
end;
end;
eventos_simpsons;
video_sync;
end;
end;
//Main CPU
function simpsons_getbyte(direccion:word):byte;
var
tempw:word;
begin
case direccion of
0..$fff:if bank0_bank=1 then simpsons_getbyte:=buffer_paleta[direccion]
else simpsons_getbyte:=k052109_0.read(direccion);
$1000..$1fff:case direccion of
$1f80:simpsons_getbyte:=marcade.in2; //coin
$1f81:simpsons_getbyte:=$cf+(er5911_do_read shl 4)+(er5911_ready_read shl 5); //eeprom+service
$1f90:simpsons_getbyte:=marcade.in0; //p1
$1f91:simpsons_getbyte:=marcade.in1; //p2
$1f92:simpsons_getbyte:=$ff; //p3
$1f93:simpsons_getbyte:=$ff; //p4
$1fc4:begin
simpsons_getbyte:=0;
z80_0.change_irq(HOLD_LINE);
end;
$1fc6..$1fc7:simpsons_getbyte:=k053260_0.main_read(direccion and $1);
$1fc8..$1fc9:simpsons_getbyte:=k053246_0.read(direccion and 1);
$1fca:; //Watchdog
else simpsons_getbyte:=k052109_0.read(direccion)
end;
$2000..$3fff:if bank2000_bank=0 then simpsons_getbyte:=k052109_0.read(direccion)
else if (direccion>$2fff) then simpsons_getbyte:=memoria[direccion]
else begin //k053247
tempw:=(direccion and $fff) shr 1;
//simpsons_getbyte:=(sprite_ram[tempw] shr ((not(direccion) and 1)*8)) and $ff;
if (direccion and 1)<>0 then simpsons_getbyte:=sprite_ram[tempw] and $ff
else simpsons_getbyte:=sprite_ram[tempw] shr 8;
end;
$4000..$5fff,$8000..$ffff:simpsons_getbyte:=memoria[direccion];
$6000..$7fff:simpsons_getbyte:=rom_bank[rom_bank1,direccion and $1fff];
end;
end;
procedure simpsons_putbyte(direccion:word;valor:byte);
var
tempw:word;
procedure cambiar_color(pos:word);
var
color:tcolor;
valor:word;
begin
valor:=(buffer_paleta[pos*2] shl 8)+buffer_paleta[(pos*2)+1];
color.b:=pal5bit(valor shr 10);
color.g:=pal5bit(valor shr 5);
color.r:=pal5bit(valor);
set_pal_color_alpha(color,pos);
k052109_0.clean_video_buffer;
end;
begin
case direccion of
0..$fff:if bank0_bank=1 then begin
if buffer_paleta[direccion]<>valor then begin
buffer_paleta[direccion]:=valor;
cambiar_color(direccion shr 1);
end;
end else k052109_0.write(direccion,valor);
$1000..$1fff:case direccion of
$1fa0..$1fa7:k053246_0.write(direccion and $7,valor);
$1fb0..$1fbf:k053251_0.write(direccion and $f,valor);
$1fc0:begin
if (valor and 8)<>0 then k052109_0.set_rmrd_line(ASSERT_LINE)
else k052109_0.set_rmrd_line(CLEAR_LINE);
if (valor and $20)=0 then k053246_0.set_objcha_line(ASSERT_LINE)
else k053246_0.set_objcha_line(CLEAR_LINE);
end;
$1fc2:if (valor<>$ff) then begin
er5911_di_write((valor shr 7) and 1);
er5911_cs_write((valor shr 3) and 1);
er5911_clk_write((valor shr 4) and 1);
bank0_bank:=valor and 1;
bank2000_bank:=(valor shr 1) and 1;
firq_enabled:=(valor and $4)<>0;
end;
$1fc6..$1fc7:k053260_0.main_write(direccion and 1,valor);
else k052109_0.write(direccion,valor);
end;
$2000..$3fff:if bank2000_bank=0 then k052109_0.write(direccion,valor)
else if (direccion>$2fff) then memoria[direccion]:=valor
else begin //k053247
tempw:=(direccion and $fff) shr 1;
if (direccion and 1)<>0 then sprite_ram[tempw]:=(sprite_ram[tempw] and $ff00) or valor
else sprite_ram[tempw]:=(sprite_ram[tempw] and $ff) or (valor shl 8);
end;
$4000..$5fff:memoria[direccion]:=valor;
$6000..$ffff:; //ROM
end;
end;
procedure simpsons_bank(valor:byte);
begin
rom_bank1:=valor and $3f;
end;
//Audio CPU
function simpsons_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$f000..$f7ff:simpsons_snd_getbyte:=mem_snd[direccion];
$8000..$bfff:simpsons_snd_getbyte:=sound_rom_bank[sound_bank,direccion and $3fff];
$f801:simpsons_snd_getbyte:=ym2151_0.status;
$fc00..$fc2f:simpsons_snd_getbyte:=k053260_0.read(direccion and $3f);
end;
end;
procedure simpsons_nmi;
begin
timers.enabled(snd_timer,false);
z80_0.change_nmi(CLEAR_LINE);
end;
procedure simpsons_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$bfff:; //ROM
$f000..$f7ff:mem_snd[direccion]:=valor;
$f800:ym2151_0.reg(valor);
$f801:ym2151_0.write(valor);
$fa00:begin
z80_0.change_nmi(ASSERT_LINE);
timers.enabled(snd_timer,true);
end;
$fc00..$fc2f:k053260_0.write(direccion and $3f,valor);
$fe00:sound_bank:=valor and $7;
end;
end;
procedure simpsons_sound_update;
begin
ym2151_0.update;
k053260_0.update;
end;
//Main
procedure reset_simpsons;
begin
konami_0.reset;
z80_0.reset;
k052109_0.reset;
k053251_0.reset;
k053246_0.reset;
k053260_0.reset;
ym2151_0.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
bank0_bank:=0;
bank2000_bank:=0;
rom_bank1:=0;
sound_bank:=0;
firq_enabled:=false;
end;
procedure cerrar_simpsons;
begin
if sprite_rom<>nil then freemem(sprite_rom);
if tiles_rom<>nil then freemem(tiles_rom);
if k053260_rom<>nil then freemem(k053260_rom);
sprite_rom:=nil;
tiles_rom:=nil;
k053260_rom:=nil;
end;
function iniciar_simpsons:boolean;
var
temp_mem:array[0..$7ffff] of byte;
f:byte;
begin
llamadas_maquina.close:=cerrar_simpsons;
llamadas_maquina.reset:=reset_simpsons;
llamadas_maquina.bucle_general:=simpsons_principal;
llamadas_maquina.fps_max:=59.185606;
iniciar_simpsons:=false;
//Pantallas para el K052109
screen_init(1,512,256,true);
screen_init(2,512,256,true);
screen_mod_scroll(2,512,512,511,256,256,255);
screen_init(3,512,256,true);
screen_mod_scroll(3,512,512,511,256,256,255);
screen_init(4,1024,1024,false,true);
iniciar_video(288,224,true);
iniciar_audio(true);
//cargar roms y ponerlas en su sitio...
if not(roms_load(@temp_mem,simpsons_rom)) then exit;
copymemory(@memoria[$8000],@temp_mem[$78000],$8000);
for f:=0 to $3f do copymemory(@rom_bank[f,0],@temp_mem[f*$2000],$2000);
//cargar sonido
if not(roms_load(@temp_mem,simpsons_sound)) then exit;
copymemory(@mem_snd,@temp_mem,$8000);
for f:=0 to 7 do copymemory(@sound_rom_bank[f,0],@temp_mem[f*$4000],$4000);
//Main CPU
konami_0:=cpu_konami.create(3000000,264);
konami_0.change_ram_calls(simpsons_getbyte,simpsons_putbyte);
konami_0.change_set_lines(simpsons_bank);
//Sound CPU
z80_0:=cpu_z80.create(3579545,264);
z80_0.change_ram_calls(simpsons_snd_getbyte,simpsons_snd_putbyte);
z80_0.init_sound(simpsons_sound_update);
snd_timer:=timers.init(z80_0.numero_cpu,90,simpsons_nmi,nil,false);
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
getmem(k053260_rom,$140000);
if not(roms_load(k053260_rom,simpsons_k053260)) then exit;
k053260_0:=tk053260_chip.create(3579545,k053260_rom,$140000,0.70);
//eeprom
eepromser_init(ER5911,8);
if not(roms_load(@temp_mem,simpsons_eeprom)) then exit;
eepromser_load_data(@temp_mem,$80);
//Prioridades
k053251_0:=k053251_chip.create;
//Iniciar video
getmem(tiles_rom,$100000);
if not(roms_load32b(tiles_rom,simpsons_tiles)) then exit;
k052109_0:=k052109_chip.create(1,2,3,0,simpsons_cb,tiles_rom,$100000);
getmem(sprite_rom,$400000);
if not(roms_load64b(sprite_rom,simpsons_sprites)) then exit;
k053246_0:=k053246_chip.create(4,simpsons_sprite_cb,sprite_rom,$400000);
sprite_timer_dmaon:=timers.init(konami_0.numero_cpu,256,simpsons_sprites_dmaon,nil,false);
sprite_timer_dmaoff:=timers.init(konami_0.numero_cpu,2048,simpsons_sprites_dmaoff,nil,false);
k053246_0.k053247_start(0,16);
//final
reset_simpsons;
iniciar_simpsons:=true;
end;
end.
|
unit SortIndex;
interface
uses System.Generics.Collections, System.SysUtils;
type
TxnQuickSort = class
type
TGetter = reference to function(const aIndex: integer): string;
TComparer = reference to function(const aLeft, aRight: string): integer;
strict private
fGetter: TGetter;
fComparer: TComparer;
public
constructor Create(aGetter: TGetter; aComparer: TComparer);
procedure Sort(var aData: TList<integer>; aLo, aHi: integer); overload;
procedure Sort(var aData: TList<integer>); overload;
end;
implementation
procedure TxnQuickSort.Sort(var aData: TList<integer>; aLo, aHi: integer);
var
iLo: integer;
iHi: integer;
iPivot: string;
function Get(aIndex: integer): string;
begin
Result := fGetter(aData[aIndex])
end;
begin
iLo := aLo;
iHi := aHi;
iPivot := Get((iLo + iHi) div 2);
repeat
while (fComparer(Get(iLo), iPivot) < 0) do
Inc(iLo);
while (fComparer(Get(iHi), iPivot) > 0) do
Dec(iHi);
if iLo <= iHi then
begin
if iLo <> iHi then
aData.Exchange(iLo, iHi);
Inc(iLo);
Dec(iHi);
end;
until iLo > iHi;
if iHi > aLo then
Sort(aData, aLo, iHi);
if iLo < aHi then
Sort(aData, iLo, aHi);
end;
constructor TxnQuickSort.Create(aGetter: TGetter; aComparer: TComparer);
begin
inherited Create;
fGetter := aGetter;
fComparer := aComparer;
end;
procedure TxnQuickSort.Sort(var aData: TList<integer>);
begin
Sort(aData, 0, aData.Count - 1);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Contnrs, StdCtrls, ExtCtrls;
type
TValue = class
Score: single;
constructor Create(S: Single);
end;
TForm1 = class(TForm)
Button1: TButton;
Image1: TImage;
Image2: TImage;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private-Deklarationen }
procedure OutputIm(c: TCanvas);
public
{ Public-Deklarationen }
Pool: TObjectList;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TDataArray = array of TValue;
function Merge(ll, rl: TDataArray): TDataArray;
var
p, l, r, i: integer;
begin
SetLength(Result, length(ll) + length(rl));
p := 0;
l := 0;
r := 0;
while (length(ll) > l) and (length(rl) > r) do
begin
if TValue(ll[l]).Score >= TValue(rl[r]).Score then
begin
Result[p] := ll[l];
inc(l);
end
else
begin
Result[p] := rl[r];
inc(r);
end;
inc(p);
end;
for i := l to high(ll) do
begin
Result[p] := ll[i];
inc(p);
end;
for i := r to high(rl) do
begin
Result[p] := rl[i];
inc(p);
end;
end;
function MergeSort(L: TDataArray): TDataArray;
var
ll, rl: TDataArray;
begin
SetLength(ll, 0);
SetLength(rl, 0);
if Length(L) <= 1 then
Result := copy(L, 0, length(L))
else
begin
ll := copy(L, 0, length(L) div 2);
rl := copy(L, length(L) div 2, maxint);
Result := Merge(MergeSort(ll), MergeSort(rl));
end;
end;
procedure MergeSortList(L: TObjectList);
var
A: TDataArray;
I: integer;
OldOO: boolean;
begin
Setlength(A, L.Count);
for i := 0 to high(A) do
A[i] := TValue(L[i]);
A := MergeSort(A);
OldOO := L.OwnsObjects;
try
L.OwnsObjects := false;
for i := 0 to high(A) do
L.Items[i] := A[i];
finally
L.OwnsObjects := OldOO;
end;
end;
{ TValue }
constructor TValue.Create(S: Single);
begin
inherited Create;
Score := S;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Pool := TObjectList.Create(true);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
begin
Pool.Clear;
for i := 0 to 800 - 1 do
Pool.Add(TValue.Create(random * 100));
OutputIm(Image1.Canvas);
end;
procedure TForm1.OutputIm(c: TCanvas);
var
i: integer;
begin
C.Brush.Color := clWhite;
C.FillRect(Rect(0, 0, 500, Pool.Count));
for i := 0 to Pool.Count - 1 do
begin
C.Pen.Color := round(Tvalue(Pool[i]).Score / 100 * 255);
C.MoveTo(0, i);
C.LineTo(round(Tvalue(Pool[i]).Score * 2), i);
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MergeSortList(Pool);
OutputIm(Image2.Canvas);
Image2.Canvas.Pen.Color := clLime;
Image2.Canvas.MoveTo(200, 0);
Image2.Canvas.LineTo(0, Pool.Count - 1);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Button1.Click;
Button2.Click;
end;
end.
|
unit Dialogs.Controllers.Method.SaveDialogs;
interface
uses
{$IF FireMonkeyVersion}
FMX.Dialogs,
{$ELSE}
Vcl.Dialogs,
{$ENDIF}
Dialogs.Controllers.Method.Interfaces, System.Classes;
type
TSaveDialogs = class(TInterfacedObject, iDialogs, iDialogParams,
iDialogFilter, iDialogOption)
private
FSaveDialog: TSaveDialog;
FFilter: TStringList;
FOptions: TOpenOptions;
public
function Title(Value: String): iDialogParams;
function InitialDir(Value: String): iDialogParams;
function FilterIndex(Value: Integer): iDialogParams;
function ReadOnly: iDialogOption;
function AllowMultiSelect: iDialogOption;
function FileMustExist: iDialogOption;
function EndOptions: iDialogParams;
function AddXML: iDialogFilter;
function AddPDF: iDialogFilter;
function AddTXT: iDialogFilter;
function AddAll: iDialogFilter;
function AddFilter: iDialogFilter;
function AddOption: iDialogOption;
function EndFilter: iDialogParams;
function Params: iDialogParams;
function EndParams: iDialogs;
function Execute(var pNameFile: TStrings): Boolean;
constructor Create;
destructor Destroy; override;
class function New: iDialogs;
end;
implementation
{ TSaveDialogs }
constructor TSaveDialogs.Create;
begin
FSaveDialog := TSaveDialog.Create(nil);
FSaveDialog.Filter := '';
FFilter := TStringList.Create;
end;
destructor TSaveDialogs.Destroy;
begin
FSaveDialog.DisposeOf;
FFilter.DisposeOf;
inherited;
end;
class function TSaveDialogs.New: iDialogs;
begin
Result := Self.Create;
end;
function TSaveDialogs.AddAll: iDialogFilter;
begin
Result := Self;
FFilter.Add('Todos os Arquivos (*.*) | * .*|');
end;
function TSaveDialogs.AddPDF: iDialogFilter;
begin
Result := Self;
FFilter.Add('Arquivos PDF (*.pdf) | * .pdf|');
end;
function TSaveDialogs.AddTXT: iDialogFilter;
begin
Result := Self;
FFilter.Add('Arquivos TXT (*.txt) | * .txt|');
end;
function TSaveDialogs.AddXML: iDialogFilter;
begin
Result := Self;
FFilter.Add('Arquivos XML (*.xml) | * .xml|');
end;
function TSaveDialogs.AddFilter: iDialogFilter;
begin
Result := Self;
end;
function TSaveDialogs.AddOption: iDialogOption;
begin
Result := Self;
end;
function TSaveDialogs.EndFilter: iDialogParams;
begin
Result := Self;
FSaveDialog.Filter := FFilter.Text;
end;
function TSaveDialogs.EndParams: iDialogs;
begin
Result := Self;
end;
function TSaveDialogs.Execute(var pNameFile: TStrings): Boolean;
begin
Result := FSaveDialog.Execute;
pNameFile := FSaveDialog.Files;
end;
function TSaveDialogs.FilterIndex(Value: Integer): iDialogParams;
begin
Result := Self;
FSaveDialog.FilterIndex := Value;
end;
function TSaveDialogs.InitialDir(Value: String): iDialogParams;
begin
Result := Self;
FSaveDialog.InitialDir := Value;
end;
function TSaveDialogs.Title(Value: String): iDialogParams;
begin
Result := Self;
FSaveDialog.Title := Value;
end;
function TSaveDialogs.Params: iDialogParams;
begin
Result := Self;
end;
function TSaveDialogs.EndOptions: iDialogParams;
begin
Result := Self;
FSaveDialog.Options := FOptions;
end;
function TSaveDialogs.AllowMultiSelect: iDialogOption;
begin
Result := Self;
FOptions := [ofAllowMultiSelect];
end;
function TSaveDialogs.FileMustExist: iDialogOption;
begin
Result := Self;
FOptions := FOptions + [ofFileMustExist];
end;
function TSaveDialogs.ReadOnly: iDialogOption;
begin
Result := Self;
FOptions := FOptions + [ofReadOnly];
end;
end.
|
unit MFichas.Model.Conexao.Interfaces;
interface
uses
System.Generics.Collections,
System.Bluetooth,
ORMBR.Factory.Interfaces,
FireDAC.Comp.Client;
type
iModelConexaoSQL = interface;
iModelConexaoBluetooth = interface;
iModelConexaoFactory = interface;
iModelConexaoSQL = interface
['{42CC2F84-B965-4DE1-A8F0-44EFD15D7DCE}']
function Conn: iDBConnection;
function Query: TFDQuery;
end;
iModelConexaoBluetooth = interface
['{94DB15EA-C87E-454C-BFC2-59A8FA25285A}']
function ListarDispositivos(var AList: TList<String>): iModelConexaoBluetooth;
function ConectarDispositivo(var ASocket: TBluetoothSocket): iModelConexaoBluetooth;
procedure LimparSocketPosImpressao;
end;
iModelConexaoFactory = interface
['{F2D21153-EE55-4E8F-99A9-0FBD8D144E1A}']
function ConexaoSQL : iModelConexaoSQL;
function ConexaoBluetooth: iModelConexaoBluetooth;
end;
implementation
end.
|
unit UserLoginDlg;
{$I defines.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ActnList, Buttons, DBCtrlsEh, Mask, Grids, pngimage,
System.Actions, PrjConst;
{$IFDEF Scale4k}
const
WM_DPICHANGED = 736; // 0x02E0
{$ENDIF}
type
TUserLoginDialog = class(TForm)
ActionList: TActionList;
actLogin: TAction;
Timer1: TTimer;
pnlLogin: TPanel;
AppIcon: TImage;
Image1: TImage;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
cbSERVER: TDBComboBoxEh;
mbbOk: TBitBtn;
mbbCancel: TBitBtn;
xLabel1: TLabel;
edUser: TDBEditEh;
edPassword: TDBEditEh;
actEditDB: TAction;
lblLANG: TLabel;
lblCAPS: TLabel;
procedure actLoginUpdate(Sender: TObject);
procedure actLoginExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure mbbCancelClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure cbSERVERNotInList(Sender: TObject; NewText: String;
var RecheckInList: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure actEditDBExecute(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure edUserExit(Sender: TObject);
private
FDatabases: TStringList;
procedure UpdateKbdState;
procedure LoadListOfDataBases;
procedure SetDataBase(const Value: string);
function GetDataBase: string;
{$IFDEF Scale4k}
procedure WMDpiChanged(var Message: TMessage); message WM_DPICHANGED;
{$ENDIF}
public
{ Public declarations }
procedure CreateParams(VAR Params: TCreateParams);
property DataBase: string read GetDataBase write SetDataBase;
end;
function LoginDialog(var ADatabaseName, AUserName, APassword: string): Boolean;
// Возвращает базу пароль логин и алиас (название) базы
function LoginDialogA(var ADatabaseName, AUserName, APassword,
ADatabaseAlias: string): Boolean;
implementation
{$R *.DFM}
uses
ShellApi, Commctrl, ShlObj, IniFiles, DBEditor, DM, MAIN, atrCmdUtils;
function LoginDialog(var ADatabaseName, AUserName, APassword: string): Boolean;
var
LoginDlg: TUserLoginDialog;
begin
LoginDlg := TUserLoginDialog.Create(nil);
with LoginDlg do
try
DataBase := ADatabaseName;
edUser.Text := AUserName;
Result := ShowModal = mrOk;
if Result then
begin
ADatabaseName := DataBase;
AUserName := edUser.Text;
APassword := edPassword.Text;
end;
finally
Free;
end
end;
function LoginDialogA(var ADatabaseName, AUserName, APassword,
ADatabaseAlias: string): Boolean;
var
LoginDlg: TUserLoginDialog;
begin
LoginDlg := TUserLoginDialog.Create(nil);
with LoginDlg do
try
DataBase := ADatabaseName;
edUser.Text := AUserName;
edPassword.Text := APassword;
Result := ShowModal = mrOk;
if Result then
begin
ADatabaseName := DataBase;
AUserName := edUser.Text;
APassword := edPassword.Text;
ADatabaseAlias := cbSERVER.Text;
end;
finally
Free;
end
end;
{$IFDEF Scale4k}
procedure TUserLoginDialog.WMDpiChanged(var Message: TMessage);
{$IFDEF DELPHI_STYLE_SCALING}
function FontHeightAtDpi(aDPI, aFontSize: integer): integer;
var
tmpCanvas: TCanvas;
begin
tmpCanvas := TCanvas.Create;
try
tmpCanvas.Handle := GetDC(0);
tmpCanvas.Font.Assign(self.Font);
tmpCanvas.Font.PixelsPerInch := aDPI; // must be set BEFORE size
tmpCanvas.Font.size := aFontSize;
Result := tmpCanvas.TextHeight('0');
finally
tmpCanvas.Free;
end;
end;
{$ENDIF}
begin
inherited;
{$IFDEF DELPHI_STYLE_SCALING}
ChangeScale(FontHeightAtDpi(LOWORD(Message.wParam), self.Font.size),
FontHeightAtDpi(self.PixelsPerInch, self.Font.size));
{$ELSE}
ChangeScale(LOWORD(Message.wParam), self.PixelsPerInch);
{$ENDIF}
self.PixelsPerInch := LOWORD(Message.wParam);
end;
{$ENDIF}
procedure TUserLoginDialog.SetDataBase(const Value: string);
var
i: integer;
begin
i := FDatabases.IndexOf(Value);
if i < 0 then
cbSERVER.Text := Value
else
cbSERVER.Text := cbSERVER.Items[i];
end;
function TUserLoginDialog.GetDataBase: string;
var
i: integer;
begin
i := cbSERVER.Items.IndexOf(cbSERVER.Text);
if i >= 0 then
Result := FDatabases[i]
else
Result := '';
end;
procedure TUserLoginDialog.LoadListOfDataBases;
var
AppIni: TIniFile;
i: integer;
begin
cbSERVER.Items.Clear;
FDatabases.Clear;
AppIni := TIniFile.Create(ChangeFileExt(Application.ExeName, '.INI'));
try
AppIni.ReadSection('DATABASES', cbSERVER.Items);
for i := 0 to cbSERVER.Items.Count - 1 do
FDatabases.Add(AppIni.ReadString('DATABASES', cbSERVER.Items[i], ''));
finally
AppIni.Free;
end;
end;
procedure TUserLoginDialog.UpdateKbdState;
var
Buf: array [0 .. KL_NAMELENGTH] of char;
Pk: PChar;
C, i: integer;
begin
GetKeyboardLayoutName(@Buf);
Pk := @Buf;
Val(StrPas(Pk), i, C);
case i of
409:
lblLANG.Caption := 'EN';
419:
lblLANG.Caption := 'RU';
422:
lblLANG.Caption := 'UA';
10437:
lblLANG.Caption := 'ქარ';
42:
lblLANG.Caption := 'HY';
else
lblLANG.Caption := IntToStr(i);
end;
lblCAPS.Visible := (GetKeyState(VK_CAPITAL) and $01) = 1;
end;
procedure TUserLoginDialog.actLoginUpdate(Sender: TObject);
begin
actLogin.Enabled := (edUser.Text > '') and (cbSERVER.Text > '');
end;
procedure TUserLoginDialog.actEditDBExecute(Sender: TObject);
var
lzForm: TfmDBEditor;
AppIni: TIniFile;
i, j: integer;
c1, c2: string;
begin
Screen.Cursor := crHourGlass;
lzForm := TfmDBEditor.Create(Application);
try
lzForm.Left := Left + Width + 2;
lzForm.Top := Top;
lzForm.temp.Open;
AppIni := TIniFile.Create(ChangeFileExt(Application.ExeName, '.INI'));
try
AppIni.ReadSection('DATABASES', cbSERVER.Items);
for i := 0 to cbSERVER.Items.Count - 1 do
begin
lzForm.temp.Append;
lzForm.temp.FieldByName('NAME').Value := cbSERVER.Items[i];
c1 := AppIni.ReadString('DATABASES', cbSERVER.Items[i], '');
for j := 1 to Length(c1) do
begin
c2 := Copy(c1, j, 1);
if (c2 = ':') and (Copy(c1, j + 1, 1) <> '\') then
begin
lzForm.temp.FieldByName('IP').Value := Copy(c1, 1, j - 1);
lzForm.temp.FieldByName('WAY').Value := Copy(c1, j + 1);
Break;
end;
end;
if ((j - 1) = Length(c1)) then
lzForm.temp.FieldByName('WAY').Value := c1;
lzForm.temp.Post;
end;
lzForm.temp.First;
Screen.Cursor := crDefault;
lzForm.ShowModal;
Screen.Cursor := crHourGlass;
try
AppIni.EraseSection('DATABASES');
lzForm.temp.First;
while (not lzForm.temp.Eof) do
begin
if (lzForm.temp.FieldByName('IP').AsString <> '') then
c1 := lzForm.temp.FieldByName('IP').AsString + ':' +
lzForm.temp.FieldByName('WAY').AsString
else
c1 := lzForm.temp.FieldByName('WAY').AsString;
AppIni.WriteString('DATABASES', lzForm.temp.FieldByName('NAME')
.AsString, c1);
lzForm.temp.Next;
end;
except
ShowMessage(format(rsIniWriteError, [AppIni.FileName]));
end;
finally
AppIni.Free;
end;
lzForm.temp.Close;
finally
lzForm.Free;
end;
LoadListOfDataBases;
Screen.Cursor := crDefault;
end;
procedure TUserLoginDialog.actLoginExecute(Sender: TObject);
begin
// MessageBox(Handle, 'Неверно введена подсистема.', 'Внимание', MB_OK or MB_ICONEXCLAMATION);
// edSubSystem.SetFocus;
//
// MessageBox(Handle, 'Неверно введен пользователь.', 'Внимание', MB_OK or MB_ICONEXCLAMATION);
// edUser.SetFocus;
//
// MessageBox(Handle, 'Неверно введен пароль.', 'Внимание', MB_OK or MB_ICONEXCLAMATION);
// edPassword.SetFocus;
ModalResult := mrOk;
end;
procedure TUserLoginDialog.FormDestroy(Sender: TObject);
begin
FDatabases.Free;
end;
procedure TUserLoginDialog.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
actLoginExecute(Sender);
end;
procedure TUserLoginDialog.FormActivate(Sender: TObject);
begin
Left := (Screen.Monitors[0].Width - Width) div 2;
Top := (Screen.Monitors[0].Height - Height) div 2;
if cbSERVER.Text <> '' then
begin
if edUser.Text <> '' then
edPassword.SetFocus
else
edUser.SetFocus;
end
else
cbSERVER.SetFocus;
end;
procedure TUserLoginDialog.FormCreate(Sender: TObject);
begin
FDatabases := TStringList.Create;
LoadListOfDataBases;
end;
procedure TUserLoginDialog.mbbCancelClick(Sender: TObject);
begin
// Halt;
ModalResult := mrCancel;
end;
procedure TUserLoginDialog.Timer1Timer(Sender: TObject);
begin
UpdateKbdState;
end;
procedure TUserLoginDialog.cbSERVERNotInList(Sender: TObject; NewText: String;
var RecheckInList: Boolean);
var
InputString: string;
AppIni: TIniFile;
begin
if NewText = 'A4ON' then
Exit;
if NewText = '' then
begin
if cbSERVER.Items.Count > 0 then
cbSERVER.Text := cbSERVER.Items[0];
Exit;
end;
InputString := InputBox(rsDataBaseAlias, rsLabelName + ' ' + NewText, '');
if InputString <> '' then
begin
AppIni := TIniFile.Create(ChangeFileExt(Application.ExeName, '.INI'));
try
AppIni.WriteString('DATABASES', InputString, NewText);
finally
AppIni.Free;
end;
end;
RecheckInList := False;
LoadListOfDataBases;
cbSERVER.Text := InputString;
end;
procedure TUserLoginDialog.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params); { CreateWindowEx }
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
Params.WndParent := GetDesktopWindow; // дочерняя форма рабочего стола
end;
procedure TUserLoginDialog.edUserExit(Sender: TObject);
var
pass: String;
begin
pass := GetEnvVarValue('A4ON_' + edUser.Text);
if not pass.isEmpty then
edPassword.Text := pass;
end;
end.
|
unit HistoryFrame;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls;
type
TFrameHistory = class(TFrame)
private
fSplitter: TSplitter;
procedure SetSplitter(value: TSplitter);
{ Private declarations }
protected
procedure Notification(aComponent: TComponent; operation: TOperation); override;
public
{ Public declarations }
procedure AddLine(Xs,Xe,Y: Integer);
procedure ClearLines;
procedure HideWithSplitter;
procedure ShowWithSplitter;
published
PaintBox1: TPaintBox;
procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure FormPaint(Sender: TObject);
property Splitter: TSplitter read fSplitter write SetSplitter;
end;
TLineRec=record
Xs,Xe,Y: Integer;
end;
var
Lines: array of TLineRec;
implementation
{$R *.dfm}
procedure TFrameHistory.AddLine(Xs,Xe,Y: Integer);
var l: Integer;
begin
l:=Length(Lines);
SetLength(Lines,l+1);
Lines[l].Xs:=Xs;
Lines[l].Xe:=Xe;
Lines[l].Y:=Y;
end;
procedure TFrameHistory.ClearLines;
begin
SetLength(Lines,0);
end;
procedure TFrameHistory.FormPaint(Sender: TObject);
var i,x,y: Integer;
begin
y:=self.VertScrollBar.Position;
x:=self.HorzScrollBar.Position;
with Paintbox1.Canvas do begin
FillRect(self.BoundsRect);
pen.Width:=2;
pen.Color:=clBlack;
pen.Style:=psSolid;
for i:=0 to Length(Lines)-1 do begin
MoveTo(Lines[i].Xs-x,Lines[i].Y-y);
LineTo(Lines[i].Xe-x,Lines[i].Y-y);
LineTo(Lines[i].Xe-5-x,Lines[i].Y-5-y);
MoveTo(Lines[i].Xe-x,Lines[i].Y-y);
LineTo(Lines[i].Xe-5-x,Lines[i].Y+5-y);
end;
end;
end;
procedure TFrameHistory.FormMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if Shift=[] then with VertScrollBar do
Position:=Position-increment
else if Shift=[ssShift] then with HorzScrollBar do
Position:=Position-increment
end;
procedure TFrameHistory.FormMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
if Shift=[] then with VertScrollBar do
Position:=Position+increment
else if Shift=[ssShift] then with HorzScrollBar do
Position:=Position+increment
end;
procedure TFrameHistory.SetSplitter(value: TSplitter);
begin
if Assigned(fSplitter) then
fSplitter.RemoveFreeNotification(self);
fSplitter:=value;
if Assigned(fSplitter) then
fSplitter.FreeNotification(self);
end;
procedure TFrameHistory.Notification(aComponent: TComponent; operation: TOperation);
begin
inherited;
if (aComponent=fSplitter) and (operation=opRemove) then
fSplitter:=nil;
end;
procedure TFrameHistory.HideWithSplitter;
begin
if Assigned(splitter) then splitter.Visible:=false;
visible:=false;
end;
procedure TFrameHistory.ShowWithSplitter;
begin
Left:=0;
Visible:=true;
if Assigned(splitter) then begin
splitter.Left:=Left-1;
splitter.Visible:=true;
end;
end;
end. |
unit xStrUtils;
interface
uses Classes, SysUtils;
type
TCharSet = set of AnsiChar;
function DelChars(const S: AnsiString; C: AnsiChar): AnsiString;
function DelCharsEx(const S: AnsiString; Chars: TCharSet): AnsiString;
function WordCount(const S: AnsiString; const WordDelims: TSysCharSet): Integer;
function ExtractWord(N: Integer; const S: AnsiString; const WordDelims: TSysCharSet): AnsiString;
procedure StrToList(const S: AnsiString; AList: TStringList; const WordDelims: TSysCharSet);
function ListToStr(AList: TStringList; const Delim: AnsiChar): AnsiString;
function ReplaceStr(const S, Srch, Replace: AnsiString): AnsiString;
function StreamToHexStr(AStream: TStream): AnsiString;
procedure HexStrToStream(AStream: TStream; AStr: AnsiString);
function HexToDec(AHex: AnsiString): Byte;
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses Math;
//==============================================================================================
function DelCharsEx(const S: AnsiString; Chars: TCharSet): AnsiString;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
if not (S[i] in Chars) then Result := Result + S[i];
end;
//==============================================================================================
function HexToDec(AHex: AnsiString): Byte;
var
i: Integer;
b: Byte;
begin
Result := 0;
for i := 1 downto 0 do begin
case AHex[i + 1] of
'A': b := 10;
'B': b := 11;
'C': b := 12;
'D': b := 13;
'E': b := 14;
'F': b := 15
else b := StrToInt(AHex[i + 1]);
end;
Result := Result + Trunc(b*IntPower(16, 1 - i));
end;
end;
//==============================================================================================
procedure HexStrToStream(AStream: TStream; AStr: AnsiString);
var
i, j: Integer;
b: Byte;
begin
with AStream do begin
Size := Length(AStr) div 2;
j := 1;
Position := 0;
for i := 1 to Length(AStr) div 2 do begin
b := HexToDec(AStr[j] + AStr[j + 1]);
Write(b, 1);
inc(j, 2);
end;
end;
end;
//==============================================================================================
function StreamToHexStr(AStream: TStream): AnsiString;
var
i: Integer;
b: Byte;
begin
Result := EmptyStr;
with AStream do begin
Seek(0, soFromBeginning);
for i := 1 to Size do begin
Read(b, 1);
Result := Result + IntToHex(b, 2);
end;
end;
end;
//==============================================================================================
function ReplaceStr(const S, Srch, Replace: AnsiString): AnsiString;
var
I: Integer;
Source: AnsiString;
begin
Source := S;
Result := '';
repeat
I := Pos(Srch, Source);
if I > 0 then begin
Result := Result + Copy(Source, 1, I - 1) + Replace;
Source := Copy(Source, I + Length(Srch), MaxInt);
end
else Result := Result + Source;
until I <= 0;
end;
//==============================================================================================
function DelChars(const S: AnsiString; C: AnsiChar): AnsiString;
var i: integer;
begin
Result := '';
for i := 1 to Length(S) do
if S[i]<>C then Result := Result+S[i];
end;
//==============================================================================================
function WordCount(const S: AnsiString; const WordDelims: TSysCharSet): Integer;
var
i: integer;
begin
Result := 1;
for i := 1 to Length(S) do
if S[i] in WordDelims then inc(Result);
end;
//==============================================================================================
function ExtractWord(N: Integer; const S: AnsiString; const WordDelims: TSysCharSet): AnsiString;
var
i, wpos: Integer;
begin
Result := '';
WPos := 1;
for i := 1 to Length(S) do
if S[i] in WordDelims then begin
if WPos=N then Exit;
inc(WPos);
Result := '';
end
else Result := Result+S[i];
end;
//==============================================================================================
procedure StrToList(const S: AnsiString; AList: TStringList; const WordDelims: TSysCharSet);
var
i: integer;
begin
with AList do begin
Clear;
for i := 1 to WordCount(S, WordDelims) do
AList.Add(ExtractWord(i, S, WordDelims));
end;
end;
//==============================================================================================
function ListToStr(AList: TStringList; const Delim: AnsiChar): AnsiString;
var
i: integer;
begin
Result := '';
for i := 0 to AList.Count-1 do
Result := Result+AList[i]+Delim;
if Result<>'' then System.Delete(Result, Length(Result), 1);
end;
end.
|
unit ClasseCliente;
interface
uses
System.Classes, Conexao.MySQL, Interfaces;
type
TClasseAmiga = class // Caso esteja na mesma Unit, as classes compartilham de objetos privados
strict private // usado para encapsular dentro da mesma Unit com classes diferentes
Teste : String;
public
procedure TesteSoftware;
end;
type
TPessoa = class
strict private // usado para encapsular dentro da mesma Unit com classes diferentes
FDataNascimento: TDateTime;
FDataNascimentoPP: TDateTime;
FNome2: String; // property criada Get
FFEndereco : String;
FTelefone2 : String; //Criado FTelefone, mas não um para o Set separado, ou seja
// Gerenciando ambos
// Conexao : TConexaoMySQL; Usando Interfaces deixa de usar a conexaoMysql Aula 16
Conexao : IConexao;
procedure SetDataNascimentoPP(const Value: TDateTime);
procedure SetNome2(const Value: String);
function GetEndereco: String;
procedure SetEndereco(const Value: String); // property criada Set
public
Nome: String;
Telefone: String;
Endereco : String;
Cidade: String;
UF: String;
//DataNascimento: TDateTime;
Saldo: Currency;
// constructor Create; // Alterado na implentação da Interfaces - Aula 16
constructor Create(aConexao : IConexao);
procedure Cadastrar;
procedure CriarFinanceiro;
function Idade : Integer;
procedure SetDataNascimento(aValue : String);
//property DataNascimentoPP : TDateTime - ctrl+shift+c ele cria o resto
// read Get - write Set
property DataNascimentoPP : TDateTime read FDataNascimentoPP write SetDataNascimentoPP;
property Nome2 :String read FNome2 write SetNome2;
// Criando na mãe, é possível dar problema
property Telefone2 : String read FTelefone2 write FTelefone2;
// Criando os Gets e Sets na linha abaixo e dando o ctrl+shift+c ele vai criar no padrão
property Endereco2 : String read GetEndereco write SetEndereco;
end;
implementation
uses
System.SysUtils;
procedure TPessoa.Cadastrar;
var
Lista : TStringList;
begin
Lista := TStringList.Create;
try
Lista.Add('Nome: ' + Nome);
Lista.Add('Telefone: ' + Telefone);
Lista.Add('Nome: ' + Nome);
Lista.Add('End: ' + Endereco);
Lista.Add('Cidade: ' + Cidade);
Lista.Add('UF: ' + UF);
Lista.SaveToFile(Nome + '_Cliente.txt');
Conexao.Gravar;
finally
Lista.Free;
end;
end;
constructor TPessoa.Create(aConexao : IConexao);
begin
// Toda vez que criar a classe, executa o Create Aula 16
// Conexao := TConexaoMySQL.Create;
// Removemido a linha acima na implementação da Interfaces
// Aula 16 - Fim
Conexao := aConexao;
UF := 'SP';
Saldo := 1000;
end;
procedure TPessoa.CriarFinanceiro;
var
Lista : TStringList;
begin
Lista := TStringList.Create;
try
Lista.Add('Nome: ' + Nome);
Lista.Add('Saldo: ' + CurrToStr(Saldo));
Lista.SaveToFile(Nome + '_Financeiro.txt');
finally
Lista.Free;
end;
end;
function TPessoa.GetEndereco: String;
begin
Result := FFEndereco + 'Teste Apai';
end;
function TPessoa.Idade: Integer;
begin
Result := Trunc((Now - FDataNascimento) / 365.25) ;
end;
procedure TPessoa.SetDataNascimento(aValue: String);
var
aClasse : TClasseAmiga;
begin
//aClasse.Teste;
// Aqui é possível a função acessando o objeto privado de outra classe
if not TryStrToDateTime(aValue, FDataNascimento) then
raise Exception.Create('A Data é Inválida');
FDataNascimento := StrToDateTime(aValue);
end;
procedure TPessoa.SetDataNascimentoPP(const Value: TDateTime);
begin
FDataNascimentoPP := Value;
end;
procedure TPessoa.SetEndereco(const Value: String);
begin
FFEndereco := Value;
end;
procedure TPessoa.SetNome2(const Value: String);
begin
if Value='' then
raise Exception.Create('Nome não pode ser vazio');
FNome2 := Value;
end;
{ TClasseAmiga }
procedure TClasseAmiga.TesteSoftware;
var
aClasse : TPessoa;
begin
// aClasse.FDataNascimento;// Objeto privado acessado na classe amiga
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
Androidapi.JNI.Location, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os, FMX.Layouts, FMX.ListBox, FMX.StdCtrls;
type
TLocationListener = class;
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
procedure Button1Click(Sender: TObject);
{ Private declarations }
private
FLocationManager : JLocationManager;
locationListener : TLocationListener;
public
destructor Destroy; override;
{ Public declarations }
procedure onLocationChanged(location: JLocation);
end;
TLocationListener = class(TJavaLocal, JLocationListener)
private
[weak]
FParent : TForm1;
public
constructor Create(AParent : TForm1);
procedure onLocationChanged(location: JLocation); cdecl;
procedure onProviderDisabled(provider: JString); cdecl;
procedure onProviderEnabled(provider: JString); cdecl;
procedure onStatusChanged(provider: JString; status: Integer; extras: JBundle); cdecl;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText;
{ TLocationListener }
constructor TLocationListener.Create(AParent: TForm1);
begin
inherited Create;
FParent := AParent;
end;
procedure TLocationListener.onLocationChanged(location: JLocation);
begin
FParent.onLocationChanged(location);
end;
procedure TLocationListener.onProviderDisabled(provider: JString);
begin
end;
procedure TLocationListener.onProviderEnabled(provider: JString);
begin
end;
procedure TLocationListener.onStatusChanged(provider: JString; status: Integer;
extras: JBundle);
begin
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
LocationManagerService: JObject;
iter : JIterator;
location : JLocation;
begin
if not Assigned(FLocationManager) then
begin
LocationManagerService := SharedActivityContext.getSystemService(TJContext.JavaClass.LOCATION_SERVICE);
FLocationManager := TJLocationManager.Wrap((LocationManagerService as ILocalObject).GetObjectID);
if not Assigned(locationListener) then
locationListener := TLocationListener.Create(self);
FLocationManager.requestLocationUpdates(TJLocationManager.JavaClass.GPS_PROVIDER, 10000, 10, locationListener,
TJLooper.JavaClass.getMainLooper);
end;
iter := FLocationManager.GetAllProviders.Iterator;
ListBox1.Clear;
while iter.hasNext do
begin
ListBox1.Items.Add(JStringToString(iter.next.ToString));
end;
CheckBox1.IsChecked := FLocationManager.isProviderEnabled(TJLocationManager.JavaClass.GPS_PROVIDER);
CheckBox2.IsChecked := FLocationManager.isProviderEnabled(TJLocationManager.JavaClass.NETWORK_PROVIDER);
location := FLocationManager.getLastKnownLocation(TJLocationManager.JavaClass.GPS_PROVIDER);
onLocationChanged(location);
end;
destructor TForm1.Destroy;
begin
if Assigned(locationListener) then
FLocationManager.removeUpdates(locationListener);
inherited;
end;
procedure TForm1.onLocationChanged(location: JLocation);
begin
Label4.Text := location.getLatitude.ToString;
Label5.Text := location.getLongitude.ToString;
Label6.Text := location.getAltitude.ToString;
end;
end.
|
unit tipoCombustivelDao;
interface
uses
TipoCombustivel, DB, DM, IBQuery, IBDataBase, Classes;
type
T_TipoCombustivelDao = class(TObject)
private
F_Qr: TIBQuery;
F_Lista: TList;
public
// Os tipos de combustível são fixos, portanto só atualizam preço e imposto
constructor Create(db: TIBDataBase);
destructor Destroy();
procedure atualizar(tipoCombustivel: T_TipoCombustivel);
function listarTudo(): TList;
function get(id: Integer): T_TipoCombustivel;
end;
implementation
const
SQL_ATUALIZAR =
'UPDATE TIPOCOMBUSTIVEL '#13#10 +
'SET '#13#10 +
' ValorPorLitro = :valorporlitro , '#13#10 +
' PercentualDeImposto = :percentualdeimposto '#13#10 +
'WHERE Id = :id '#13#10;
SQL_LISTARTUDO =
'SELECT * FROM TIPOCOMBUSTIVEL ORDER BY Nome ';
SQL_GET =
'SELECT * FROM TIPOCOMBUSTIVEL WHERE ID = :id ';
constructor T_TipoCombustivelDao.Create(db: TIBDataBase);
begin
F_Qr := TIBQuery.Create(db);
F_Qr.Database := db;
F_QR.Transaction := db.DefaultTransaction;
F_Lista := TList.Create();
end;
destructor T_TipoCombustivelDao.Destroy();
begin
F_Lista.Free();
end;
procedure T_TipoCombustivelDao.atualizar(tipoCombustivel: T_TipoCombustivel);
begin
F_Qr.SQL.Text := SQL_ATUALIZAR;
F_Qr.ParamByName('id').Value := tipoCombustivel.Id;
F_Qr.ParamByName('valorporlitro').Value := tipoCombustivel.ValorPorLitro;
F_Qr.ParamByName('percentualdeimposto').Value := tipoCombustivel.PercentualDeImposto;
F_Qr.ExecSQL();
end;
function T_TipoCombustivelDao.listarTudo(): TList;
var
a: T_TipoCombustivel;
begin
F_Qr.SQL.Text := SQL_LISTARTUDO;
F_Qr.Open();
result := TList.Create();
if result = nil then
result := F_Lista.Create();
F_Qr.First();
while not F_Qr.Eof do
begin
result.Add(
T_TipoCombustivel.Create(
F_Qr.FieldByName('Id').AsInteger,
F_Qr.FieldByName('Nome').AsString,
F_Qr.FieldByName('ValorPorLitro').AsInteger,
F_Qr.FieldByName('PercentualDeImposto').AsFloat)
);
F_Qr.Next();
end;
if F_Qr.Active then
F_Qr.Close();
end;
function T_TipoCombustivelDao.get(id: Integer): T_TipoCombustivel;
begin
result := nil;
F_Qr.SQL.Text := SQL_GET;
F_Qr.ParamByName('id').Value := id;
F_Qr.Open();
if not F_Qr.Eof then
begin
result :=
T_TipoCombustivel.Create(
F_Qr.FieldByName('Id').AsInteger,
F_Qr.FieldByName('Nome').AsString,
F_Qr.FieldByName('ValorPorLitro').AsInteger,
F_Qr.FieldByName('PercentualDeImposto').AsFloat);
end;
if F_Qr.Active then
F_Qr.Close();
end;
end.
|
unit TokyoScript.Main;
{
TokyoScript (c)2018 Execute SARL
http://www.execute.Fr
}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SynEditHighlighter, SynHighlighterPas,
SynEdit, Vcl.StdCtrls, Vcl.ExtCtrls,
TokyoScript.Parser,
TokyoScript.Compiler,
TokyoScript.Runtime;
type
TMain = class(TForm)
SynEdit: TSynEdit;
SynPasSyn1: TSynPasSyn;
Panel1: TPanel;
btRun: TButton;
mmLog: TMemo;
cbSource: TComboBox;
spLog: TSplitter;
mmDump: TMemo;
Splitter1: TSplitter;
procedure btRunClick(Sender: TObject);
procedure cbSourceChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Déclarations privées }
FConsole: Boolean;
procedure OnLog(Sender: TObject; const Msg: string);
procedure OnWriteStr(Sender: TObject; const Msg: string);
procedure Dump(ByteCode: TByteCode);
public
{ Déclarations publiques }
end;
var
Main: TMain;
implementation
{$R *.dfm}
function GetConsoleWindow: HWnd; stdcall; external 'kernel32.dll';
procedure ClearConsole;
var
hConsole: THandle;
Coord: TCoord;
Info: TConsoleScreenBufferInfo;
Count: Cardinal;
begin
hConsole := GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, Info);
Coord.X := 0;
Coord.Y := 0;
FillConsoleOutputCharacter(hConsole, ' ', Info.dwSize.X * Info.dwSize.Y, Coord, Count);
SetConsoleCursorPosition(hConsole, Coord);
BringWindowToTop(GetConsoleWindow);
end;
procedure TMain.btRunClick(Sender: TObject);
var
Compiler: TCompiler;
Runtime : TRuntime;
begin
mmLog.Clear;
spLog.Hide;
mmLog.Hide;
Compiler := TCompiler.Create;
try
try
Compiler.OnLog := OnLog;
Compiler.Compile(SynEdit.Lines);
Compiler.ByteCode.SaveToFile('output.tks');
except
on e: ESourceError do
begin
SynEdit.CaretX := e.Col;
SynEdit.CaretY := e.Row;
SynEdit.SetFocus;
OnLog(Self, e.Message);
Abort;
end;
on e: Exception do
begin
OnLog(Self, e.Message);
Abort;
end;
end;
Dump(Compiler.ByteCode);
OnLog(Self, 'Start');
OnLog(Self, '');
FConsole := (Compiler.ByteCode.Flags and FLAG_CONSOLE) <> 0;
if FConsole then
begin
AllocConsole;
ClearConsole;
end;
Runtime := TRuntime.Create;
try
Runtime.OnWriteStr := OnWriteStr;
try
Runtime.Execute(Compiler.ByteCode);
except
on e: Exception do
OnLog(Self, e.Message);
end;
finally
Runtime.Free;
end;
OnLog(Self, 'Done.');
finally
Compiler.Free;
end;
end;
procedure TMain.cbSourceChange(Sender: TObject);
var
Index: Integer;
Stream: TResourceStream;
begin
Index := cbSource.ItemIndex + 1;
Stream := TResourceStream.Create(hInstance, 'DEMO' + IntToStr(Index), RT_RCDATA);
try
SynEdit.Lines.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TMain.Dump(ByteCode: TByteCode);
var
St: string;
PC: Integer;
Lbl : TArray<Integer>;
Ends: Integer;
Next: Integer;
function GetByte: Byte;
begin
Result := ByteCode.Code[PC];
Inc(PC);
end;
function GetWord: Word;
begin
Move(ByteCode.Code[PC], Result, SizeOf(Result));
Inc(PC, SizeOf(Result));
end;
function GetLong: Integer;
begin
Move(ByteCode.Code[PC], Result, SizeOf(Result));
Inc(PC, SizeOf(Result));
end;
function GetVarLen: Integer;
begin
Result := GetByte;
case Result of
254: Result := GetWord;
255: Result := GetLong;
end;
end;
function GetLabels: Integer;
var
Save: Integer;
Index: Integer;
begin
Save := PC;
PC := Ends;
for Index := 0 to Length(Lbl) - 1 do
Lbl[Index] := GetVarLen;
Result := PC;
PC := Save;
end;
procedure Add(const Str: string);
begin
mmDump.Lines.Add(St + Str);
end;
function Reg: string;
begin
Result := 'r' + IntToStr(GetVarLen);
end;
function Str: string;
begin
Result := ByteCode.Strings[GetVarLen];
Result := StringReplace(Result, #13, '\r', [rfReplaceAll]);
Result := StringReplace(Result, #10, '\n', [rfReplaceAll]);
end;
function Val: string;
begin
Result := IntToStr(ByteCode.Values[GetVarLen]);
end;
function Adr: string;
begin
Result := '@' + IntToHex(Lbl[GetVarLen], 4);
end;
begin
mmDump.Clear;
PC := 0;
while PC < Length(ByteCode.Code) do
begin
St := '';
Add('// Format: ' + IntToStr(GetByte));
Add('// Regs : ' + IntToSTr(GetVarLen));
SetLength(Lbl, GetVarLen);
Add('// Labels: ' + IntToSTr(Length(Lbl)));
Ends := GetLong;
Add('// Ends : $' + IntToHex(Ends, 4));
Next := GetLabels();
Add('// Next : $' + IntToHex(Next, 4));
while PC < Ends do
begin
St := IntToHex(PC, 4) + ' ';
case TOpCode(GetByte) of
opReturn : Add('opReturn');
opGotoLabel: Add('opGoto ' + Adr);
opJumpiEQ : Add('opJumpiEQ ' + Reg + ', ' + Reg + ', '+ Adr);
opJumpTrue : Add('opJumpTrue ' + Reg + ', ' + Adr);
opLoadInt : Add('opLoadInt ' + Reg + ', ' + Val);
opLoadStr : Add('opLoadStr ' + Reg + ', ' + Str);
opWriteInt : Add('opWriteInt ' + Reg);
opWriteStr : Add('opWriteStr ' + Reg);
opAssign : Add('opAssign ' + Reg + ', ' + Reg);
opiIncr : Add('opiIncr ' + Reg);
opiLT : Add('opiLT ' + Reg + ', ' + Reg + ', ' + Reg);
else
Add(IntToStr(ByteCode.Code[PC - 1]) + '?');
break;
end;
end;
PC := Next;
end;
end;
procedure TMain.FormCreate(Sender: TObject);
var
Index : Integer;
Demo : string;
begin
Index := 1;
Demo := 'DEMO1';
while FindResource(hInstance, PChar(Demo), RT_RCDATA) <> 0 do
begin
cbSource.Items.Add('Demo' + IntToStr(Index) + '.pas');
Inc(Index);
Demo := 'DEMO' + IntToStr(Index);
end;
cbSource.ItemIndex := 0;
cbSourceChange(Self);
end;
procedure TMain.OnLog(Sender: TObject; const Msg: string);
begin
mmLog.Lines.Add(Msg);
mmLog.Show;
spLog.Show;
end;
procedure TMain.OnWriteStr(Sender: TObject; const Msg: string);
var
Index: Integer;
begin
if FConsole then
Write(Msg)
else begin
if Msg = #13#10 then
mmLog.Lines.Add('')
else begin
Index := mmLog.Lines.Count - 1;
if Index < 0 then
mmLog.Lines.Add(Msg)
else
mmLog.Lines[Index] := mmLog.Lines[Index] + Msg;
end;
end;
end;
end.
|
unit Control.PlanilhaEntradaDIRECT;
interface
uses Model.PlanilhaEntradaDIRECT;
type
TPlanilhaEntradaDIRECTControl = class
private
FPlanilha: TPlanilhaEntradaDIRECT;
public
constructor Create();
destructor Destroy(); override;
function GetPlanilha(sFile: String): boolean;
property Planilha: TPlanilhaEntradaDIRECT read FPlanilha write FPlanilha;
end;
implementation
{ TPlanilhaEntradaDIRECTControl }
constructor TPlanilhaEntradaDIRECTControl.Create;
begin
FPlanilha := TPlanilhaEntradaDIRECT.Create;
end;
destructor TPlanilhaEntradaDIRECTControl.Destroy;
begin
FPlanilha.Create;
inherited;
end;
function TPlanilhaEntradaDIRECTControl.GetPlanilha(sFile: String): Boolean;
begin
Result := FPlanilha.GetPlanilha(sFile);
end;
end.
|
unit vulgus_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,main_engine,controls_engine,ay_8910,gfx_engine,rom_engine,pal_engine,
sound_engine,timer_engine;
function iniciar_vulgus:boolean;
implementation
const
vulgus_rom:array[0..4] of tipo_roms=(
(n:'vulgus.002';l:$2000;p:0;crc:$e49d6c5d),(n:'vulgus.003';l:$2000;p:$2000;crc:$51acef76),
(n:'vulgus.004';l:$2000;p:$4000;crc:$489e7f60),(n:'vulgus.005';l:$2000;p:$6000;crc:$de3a24a8),
(n:'1-8n.bin';l:$2000;p:$8000;crc:$6ca5ca41));
vulgus_snd_rom:tipo_roms=(n:'1-11c.bin';l:$2000;p:0;crc:$3bd2acf4);
vulgus_pal:array[0..5] of tipo_roms=(
(n:'e8.bin';l:$100;p:0;crc:$06a83606),(n:'e9.bin';l:$100;p:$100;crc:$beacf13c),
(n:'e10.bin';l:$100;p:$200;crc:$de1fb621),(n:'d1.bin';l:$100;p:$300;crc:$7179080d),
(n:'j2.bin';l:$100;p:$400;crc:$d0842029),(n:'c9.bin';l:$100;p:$500;crc:$7a1f0bd6));
vulgus_char:tipo_roms=(n:'1-3d.bin';l:$2000;p:0;crc:$8bc5d7a5);
vulgus_sprites:array[0..3] of tipo_roms=(
(n:'2-2n.bin';l:$2000;p:0;crc:$6db1b10d),(n:'2-3n.bin';l:$2000;p:$2000;crc:$5d8c34ec),
(n:'2-4n.bin';l:$2000;p:$4000;crc:$0071a2e3),(n:'2-5n.bin';l:$2000;p:$6000;crc:$4023a1ec));
vulgus_tiles:array[0..5] of tipo_roms=(
(n:'2-2a.bin';l:$2000;p:0;crc:$e10aaca1),(n:'2-3a.bin';l:$2000;p:$2000;crc:$8da520da),
(n:'2-4a.bin';l:$2000;p:$4000;crc:$206a13f1),(n:'2-5a.bin';l:$2000;p:$6000;crc:$b6d81984),
(n:'2-6a.bin';l:$2000;p:$8000;crc:$5a26b38f),(n:'2-7a.bin';l:$2000;p:$a000;crc:$1e1ca773));
//Dip
vulgus_dip_a:array [0..3] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$1;dip_name:'1'),(dip_val:$2;dip_name:'2'),(dip_val:$3;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1c;name:'Coin B';number:8;dip:((dip_val:$10;dip_name:'5C 1C'),(dip_val:$8;dip_name:'4C 1C'),(dip_val:$18;dip_name:'3C 1C'),(dip_val:$4;dip_name:'2C 1C'),(dip_val:$1c;dip_name:'1C 1C'),(dip_val:$c;dip_name:'1C 2C'),(dip_val:$14;dip_name:'1C 3C'),(dip_val:$0;dip_name:'Invalid'),(),(),(),(),(),(),(),())),
(mask:$e0;name:'Coin A';number:8;dip:((dip_val:$80;dip_name:'5C 1C'),(dip_val:$40;dip_name:'4C 1C'),(dip_val:$c0;dip_name:'3C 1C'),(dip_val:$20;dip_name:'2C 1C'),(dip_val:$e0;dip_name:'1C 1C'),(dip_val:$60;dip_name:'1C 2C'),(dip_val:$a0;dip_name:'1C 3C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),())),());
vulgus_dip_b:array [0..4] of def_dip=(
(mask:$4;name:'Demo Music';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$4;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$70;name:'Bonus Life';number:8;dip:((dip_val:$30;dip_name:'10K 50K'),(dip_val:$50;dip_name:'10K 60K'),(dip_val:$10;dip_name:'10K 70K'),(dip_val:$70;dip_name:'20K 60K'),(dip_val:$60;dip_name:'20K 70K'),(dip_val:$20;dip_name:'20K 80K'),(dip_val:$40;dip_name:'30K 70K'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),())),
(mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
scroll_x,scroll_y:word;
sound_command,palette_bank:byte;
procedure update_video_vulgus;
var
f,color,nchar,x,y:word;
attr,row:byte;
begin
for f:=$3ff downto 0 do begin
//tiles
if gfx[2].buffer[f] then begin
x:=f mod 32;
y:=31-(f div 32);
attr:=memoria[$dc00+f];
nchar:=memoria[$d800+f]+((attr and $80) shl 1);
color:=((attr and $1f)+($20*palette_bank)) shl 3;
put_gfx_flip(x*16,y*16,nchar,color,2,2,(attr and $40)<>0,(attr and $20)<>0);
gfx[2].buffer[f]:=false;
end;
//Chars
if gfx[0].buffer[f] then begin
x:=f div 32;
y:=31-(f mod 32);
attr:=memoria[f+$d400];
color:=(attr and $3f) shl 2;
nchar:=memoria[f+$d000]+((attr and $80) shl 1);
put_gfx_mask(x*8,y*8,nchar,color,3,0,$2f,$3f);
gfx[0].buffer[f]:=false;
end;
end;
scroll_x_y(2,1,scroll_x and $1ff,256-(scroll_y and $1ff));
//sprites
for f:=$1f downto 0 do begin
attr:=memoria[$cc01+(f*4)];
nchar:=memoria[$cc00+(f*4)];
color:=(attr and $f) shl 4;
x:=memoria[$cc02+(f*4)];
y:=240-memoria[$cc03+(f*4)];
if y=240 then continue;
row:=(attr and $c0) shr 6;
case row of
0:begin //16x16
put_gfx_sprite(nchar,color,false,false,1);
actualiza_gfx_sprite(x,y,1,1);
end;
1:begin //32x16
put_gfx_sprite_diff(nchar+1,color,false,false,1,16,0);
put_gfx_sprite_diff(nchar,color,false,false,1,0,0);
actualiza_gfx_sprite_size(x,y,1,32,16);
end;
2:begin //64x16
put_gfx_sprite_diff(nchar+3,color,false,false,1,48,0);
put_gfx_sprite_diff(nchar+2,color,false,false,1,32,0);
put_gfx_sprite_diff(nchar+1,color,false,false,1,16,0);
put_gfx_sprite_diff(nchar,color,false,false,1,0,0);
actualiza_gfx_sprite_size(x,y,1,64,16);
end;
end;
end;
actualiza_trozo(0,0,256,256,3,0,0,256,256,1);
actualiza_trozo_final(16,0,224,256,1);
end;
procedure eventos_vulgus;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
//P2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
//system
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
end;
end;
procedure vulgus_principal;
var
f:byte;
frame_m,frame_s:single;
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_s:=z80_1.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//snd
z80_1.run(frame_s);
frame_s:=frame_s+z80_1.tframes-z80_1.contador;
if f=239 then begin
z80_0.change_irq(HOLD_LINE);
update_video_vulgus;
end;
end;
eventos_vulgus;
video_sync;
end;
end;
function vulgus_getbyte(direccion:word):byte;
begin
case direccion of
$0..$9fff,$cc00..$cc7f,$d000..$efff:vulgus_getbyte:=memoria[direccion];
$c000:vulgus_getbyte:=marcade.in0;
$c001:vulgus_getbyte:=marcade.in1;
$c002:vulgus_getbyte:=marcade.in2;
$c003:vulgus_getbyte:=marcade.dswa;
$c004:vulgus_getbyte:=marcade.dswb;
$c802:vulgus_getbyte:=scroll_x and $ff;
$c803:vulgus_getbyte:=scroll_y and $ff;
$c902:vulgus_getbyte:=scroll_x shr 8;
$c903:vulgus_getbyte:=scroll_y shr 8;
end;
end;
procedure vulgus_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$9fff:;
$c800:sound_command:=valor;
$c802:scroll_x:=(scroll_x and $ff00) or valor;
$c803:scroll_y:=(scroll_y and $ff00) or valor;
$c804:main_screen.flip_main_screen:=(valor and $80)<>0;
$c805:if palette_bank<>(valor and 3) then begin
palette_bank:=valor and 3;
fillchar(gfx[2].buffer[0],$400,1);
end;
$c902:scroll_x:=(scroll_x and $ff) or (valor shl 8);
$c903:scroll_y:=(scroll_y and $ff) or (valor shl 8);
$cc00..$cc7f,$e000..$efff:memoria[direccion]:=valor;
$d000..$d7ff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$d800..$dfff:if memoria[direccion]<>valor then begin
gfx[2].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
end;
end;
function vulgus_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$1fff,$4000..$47ff:vulgus_snd_getbyte:=mem_snd[direccion];
$6000:vulgus_snd_getbyte:=sound_command;
end;
end;
procedure vulgus_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$1fff:;
$4000..$47ff:mem_snd[direccion]:=valor;
$8000:ay8910_0.Control(valor);
$8001:ay8910_0.Write(valor);
$c000:ay8910_1.Control(valor);
$c001:ay8910_1.Write(valor);
end;
end;
procedure vulgus_sound_update;
begin
ay8910_0.update;
ay8910_1.update;
end;
procedure vulgus_snd_irq;
begin
z80_1.change_irq(HOLD_LINE);
end;
//Main
procedure reset_vulgus;
begin
z80_0.reset;
z80_0.im0:=$d7; //rst 10
z80_1.reset;
ay8910_0.reset;
ay8910_1.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
scroll_x:=0;
scroll_y:=0;
sound_command:=0;
palette_bank:=0;
end;
function iniciar_vulgus:boolean;
var
colores:tpaleta;
f:word;
memoria_temp:array[0..$bfff] of byte;
bit0,bit1,bit2,bit3:byte;
const
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3,
32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3);
ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16);
pt_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7);
pt_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8);
begin
llamadas_maquina.bucle_general:=vulgus_principal;
llamadas_maquina.reset:=reset_vulgus;
llamadas_maquina.fps_max:=59.59;
iniciar_vulgus:=false;
iniciar_audio(false);
screen_init(1,512,512,false,true);
screen_init(2,512,512);
screen_mod_scroll(2,512,256,511,512,256,511);
screen_init(3,256,256,true);
iniciar_video(224,256);
//Main CPU
z80_0:=cpu_z80.create(3000000,256);
z80_0.change_ram_calls(vulgus_getbyte,vulgus_putbyte);
//Sound CPU
z80_1:=cpu_z80.create(3000000,256);
z80_1.change_ram_calls(vulgus_snd_getbyte,vulgus_snd_putbyte);
z80_1.init_sound(vulgus_sound_update);
//IRQ Sound CPU
timers.init(z80_1.numero_cpu,3000000/(8*60),vulgus_snd_irq,nil,true);
//Sound Chips
ay8910_0:=ay8910_chip.create(1500000,AY8910,0.5);
ay8910_1:=ay8910_chip.create(1500000,AY8910,0.5);
//cargar y desencriptar las ROMS
if not(roms_load(@memoria,vulgus_rom)) then exit;
//cargar ROMS sonido
if not(roms_load(@mem_snd,vulgus_snd_rom)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,vulgus_char)) then exit;
init_gfx(0,8,8,$200);
gfx[0].trans[0]:=true;
gfx_set_desc_data(2,0,16*8,4,0);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,true);
//convertir sprites
if not(roms_load(@memoria_temp,vulgus_sprites)) then exit;
init_gfx(1,16,16,$100);
gfx[1].trans[15]:=true;
gfx_set_desc_data(4,0,64*8,$4000*8+4,$4000*8+0,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,true);
//tiles
if not(roms_load(@memoria_temp,vulgus_tiles)) then exit;
init_gfx(2,16,16,$200);
gfx_set_desc_data(3,0,32*8,0,$4000*8,$4000*8*2);
convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,true);
//poner la paleta
if not(roms_load(@memoria_temp,vulgus_pal)) then exit;
for f:=0 to 255 do begin
bit0:=(memoria_temp[f] shr 0) and $01;
bit1:=(memoria_temp[f] shr 1) and $01;
bit2:=(memoria_temp[f] shr 2) and $01;
bit3:=(memoria_temp[f] shr 3) and $01;
colores[f].r:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3;
bit0:=(memoria_temp[f+$100] shr 0) and $01;
bit1:=(memoria_temp[f+$100] shr 1) and $01;
bit2:=(memoria_temp[f+$100] shr 2) and $01;
bit3:=(memoria_temp[f+$100] shr 3) and $01;
colores[f].g:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3;
bit0:=(memoria_temp[f+$200] shr 0) and $01;
bit1:=(memoria_temp[f+$200] shr 1) and $01;
bit2:=(memoria_temp[f+$200] shr 2) and $01;
bit3:=(memoria_temp[f+$200] shr 3) and $01;
colores[f].b:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3;
end;
set_pal(colores,256);
//crear la tabla de colores
for f:=0 to $ff do gfx[0].colores[f]:=memoria_temp[$300+f]+32;
for f:=0 to $ff do gfx[1].colores[f]:=memoria_temp[$400+f]+16;
for f:=0 to $ff do begin
gfx[2].colores[0*32*8+f]:=memoria_temp[$500+f];
gfx[2].colores[1*32*8+f]:=memoria_temp[$500+f]+64;
gfx[2].colores[2*32*8+f]:=memoria_temp[$500+f]+128;
gfx[2].colores[3*32*8+f]:=memoria_temp[$500+f]+192;
end;
//Dip
marcade.dswa:=$ff;
marcade.dswb:=$7f;
marcade.dswa_val:=@vulgus_dip_a;
marcade.dswb_val:=@vulgus_dip_b;
//final
reset_vulgus;
iniciar_vulgus:=true;
end;
end.
|
unit Trade;
interface
uses
Protocol, Kernel, Standards, CacheCommon;
const
TradeCenterPrice = 200;
TradeCenterQuality = 40;
const
tidFacilityKind_TradeCenter = 'TradeCenter';
procedure RegisterTradeCenter( aClusterName, anId : string; aVisualClass : TVisualClassId; axSize, aySize : integer );
procedure RegisterBackup;
implementation
uses
Collection, SysUtils, Logs, ClassStorage, BackupInterfaces, ConnectedBlock, BasicAccounts;
type
TUnlimitedPullOutput =
class( TPullOutput )
protected
constructor Create( aMetaGate : TMetaGate; aBlock : TBlock ); override;
public
procedure ValuePulled( Value : TFluidValue; Input : TInput; Idx, tick : integer ); override;
procedure Slice ( Value : TFluidValue ); override;
function GetSliceFor( Input : TInput; Idx : integer ) : TFluidValue; override;
public
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
end;
TMetaTradeCenter =
class( TMetaBlock )
public
constructor Create( anId : string; aBlockClass : CBlock );
end;
// TUnlimitedPullOutput
const
pulloutputIlimited : TOutputData = (Q : qIlimited; K : TradeCenterQuality);
constructor TUnlimitedPullOutput.Create( aMetaGate : TMetaGate; aBlock : TBlock );
begin
inherited;
SetFluidData( @pulloutputIlimited );
PricePerc := TradeCenterPrice;
end;
procedure TUnlimitedPullOutput.ValuePulled( Value : TFluidValue; Input : TInput; Idx, tick : integer );
begin
end;
procedure TUnlimitedPullOutput.Slice( Value : TFluidValue );
begin
end;
function TUnlimitedPullOutput.GetSliceFor( Input : TInput; Idx : integer ) : TFluidValue;
begin
if Idx = noIndex
then
if ConnectTo( Input ) = cnxValid
then
begin
Logs.Log( 'Survival', 'Unknown Input found x:' + IntToStr(Input.Block.xPos) + ' y:' + IntToStr(Input.Block.yPos));
Idx := vConnections.IndexOf( Input );
end;
if (Idx <> noIndex) and not Connections[Idx].Block.Facility.CriticalTrouble and TSlice(vSlices[Idx]).ExtraConnectionInfo.Connected and TPullInput(Input).TransferAllowed( self )
then result := qIlimited
else result := 0;
end;
procedure TUnlimitedPullOutput.LoadFromBackup( Reader : IBackupReader );
begin
inherited;
SetFluidData( @pulloutputIlimited );
end;
procedure TUnlimitedPullOutput.StoreToBackup( Writer : IBackupWriter );
begin
inherited;
end;
// TMetaTradeCenter
constructor TMetaTradeCenter.Create( anId : string; aBlockClass : CBlock );
var
MetaFluid : TMetaFluid;
i : integer;
OutputClass : COutput;
begin
inherited Create( anId, accIdx_None, accIdx_None, aBlockClass );
for i := 0 to pred(TheClassStorage.ClassCount[tidClassFamily_Fluids]) do
begin
MetaFluid := TMetaFluid(TheClassStorage.ClassByIdx[tidClassFamily_Fluids, i]);
if (mfTradeable in MetaFluid.Options) and (mfImportable in MetaFluid.Options)
then
begin
OutputClass := MetaFluid.OutputClass;
if OutputClass = nil
then OutputClass := TUnlimitedPullOutput;
MetaOutputs.Insert(
TMetaOutput.Create(
MetaFluid.Id,
fluidIlimited,
OutputClass,
MetaFluid,
1000,
[mgoptCacheable],
sizeof(TOutputData),
-1 ));
end;
end;
end;
// RegisterTradeCenter
procedure RegisterTradeCenter( aClusterName, anId : string; aVisualClass : TVisualClassId; axSize, aySize : integer );
var
MetaBlock : TMetaBlock;
MetaFacility : TMetaFacility;
begin
with TFacilityKind.Create(aClusterName + tidFacilityKind_TradeCenter) do
begin
Name := 'Trade Center';
SuperType := tidSuperFacKind_TradeCenter;
ClusterName := aClusterName;
Role := rolImporter;
Cacheable := false;
Register( tidClassFamily_FacilityKinds );
end;
MetaBlock := TMetaTradeCenter.Create( anId, TConnectedBlock );
MetaFacility := TMetaFacility.Create( anId, 'Trade Center', aVisualClass, TFacility );
with MetaFacility do
begin
xSize := axSize;
ySize := aySize;
Options := [mfcShowCompanyInText, mfcStopDisabled, mfcIgnoreZoning, mfcForbiddenRename, mfcAceptsNoOwner];
Cacheable := false;
ClusterName := aClusterName;
NeedsBudget := false;
FacilityKind := aClusterName + tidFacilityKind_TradeCenter;
end;
MetaFacility.EvlStages.Insert( TEvlStage.Create( '', '', '', MetaBlock ));
MetaBlock.Register( tidClassFamily_Blocks );
MetaFacility.Register( tidClassFamily_Facilities );
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TUnlimitedPullOutput );
end;
end.
|
unit KM_Terrain;
interface
uses
System.SysUtils,
ExtAISharedInterface;
type
// Dummy class (in KP it store all terrain data, aswell terrain routines)
TKMTerrain = class
private
fMapX: Word;
fMapY: Word;
public
Passability: TBoolArr;
Fertility: TBoolArr;
constructor Create;
property MapX: Word read fMapX;
property MapY: Word read fMapY;
end;
var
// Terrain is a globally accessible resource
gTerrain: TKMTerrain;
implementation
{ TKMTerrain }
constructor TKMTerrain.Create;
begin
Inherited;
fMapX := 128;
fMapY := 256;
SetLength(Passability, fMapX*fMapY);
SetLength(Fertility, fMapX*fMapY);
end;
end.
|
unit InventoryDM;
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,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Phys.FB, FireDAC.Phys.FBDef,
System.IniFiles, Vcl.Dialogs, System.UITypes;
type
TdmInventory = class(TDataModule)
dbInventory: TFDConnection;
qryStationaryStocks: TFDQuery;
qryItems: TFDQuery;
procedure DataModuleCreate(Sender: TObject);
private
FConnectionSuccessful: boolean;
function GetDatabaseFromPath(const ADBPath: string): string;
function GetServerFromPath(const AFirebirdDatabasePath: string): string;
{ Private declarations }
public
{ Public declarations }
procedure SetupConnection(const AIni: TIniFile);
procedure Connect;
function InitialiseDatabaseConnection: boolean;
property ConnectionSuccessful: boolean read FConnectionSuccessful write FConnectionSuccessful;
end;
var
dmInventory: TdmInventory;
function GetNewInventoryQuery: TFDQuery;
function NextInventorySequenceValue(const ASequenceName: string): integer;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmInventory.SetupConnection(const AIni: TIniFile);
var
LDBConnection: TFDConnection;
LFBDatabasePath: string;
LServerName: string;
LDatabasePath: string;
LPos: integer;
begin
LDBConnection := dbInventory;
LDBConnection.Connected := False;
LDBConnection.Params.Values['USER NAME'] := 'SYSDBA';
LDBConnection.Params.Values['PASSWORD'] := 'xyzzy';
LFBDatabasePath := AIni.ReadString('Server', 'DatabaseName', '');
LDatabasePath := GetDatabaseFromPath(LFBDatabasePath);
LServerName := UpperCase(AIni.ReadString('Server', 'ServerName', GetServerFromPath(LFBDatabasePath)));
LFBDatabasePath := LServerName + ':' + LDatabasePath;
LPos := pos('/', LServerName);
if LPos > 0 then
LServerName := Copy(LServerName, 1, LPos - 1);
LDBConnection.Params.Values['SERVER'] := LServerName;
LDBConnection.Params.Values['DATABASE'] := LDatabasePath;
end;
procedure TdmInventory.Connect;
begin
dbInventory.Open;
end;
function TdmInventory.GetServerFromPath(const AFirebirdDatabasePath: string): string;
var
LPos: integer;
begin
result := '';
LPos := Pos(':', AFirebirdDatabasePath);
if LPos > 1 then
result := Copy(AFirebirdDatabasePath, 1, LPos - 1);
end;
procedure TdmInventory.DataModuleCreate(Sender: TObject);
begin
try
FConnectionSuccessful := InitialiseDatabaseConnection;
except
on E: exception do
MessageDlg('Error connecting to Database. ' + #13#10 + E.Message,
mtError, [mbOK], 0);
end;
end;
function TdmInventory.GetDatabaseFromPath(const ADBPath: string): string;
var
LPos: integer;
begin
result := ADBPath;
LPos := Pos(':', ADBPath);
if LPos > 1 then
result := Copy(ADBPath, LPos + 1, MAXINT);
end;
function TdmInventory.InitialiseDatabaseConnection: boolean;
var
LIniFile : TIniFile;
begin
result := false;
LIniFile := TIniFile.Create('.\InventorySystem.ini');
try
SetupConnection(LIniFile);
connect;
result := true;
finally
LIniFile.Free;
end;
end;
function GetNewInventoryQuery: TFDQuery;
begin
result := TFDQuery.Create(nil);
result.Connection := dmInventory.dbInventory;
end;
function NextInventorySequenceValue(const ASequenceName: string): integer;
var
LQry: TFDQuery;
begin
LQry := GetNewInventoryQuery;
try
LQry.SQL.Text := 'SELECT NEXT VALUE FOR ' + ASequenceName + ' as new_id from RDB$DATABASE';
LQry.Open;
result := LQry.FieldByName('new_id').AsInteger;
finally
LQry.Free;
end;
end;
end.
|
unit Abastecimento;
interface
uses
Bomba;
type
TAbastecimento = class
private
FId: Integer;
FQuantidade: Double;
FValor: Double;
FBomba: TBomba;
function GetBomba: TBomba;
function GetId: Integer;
function GetQuantidade: Double;
function GetValor: Double;
procedure SetBomba(const Value: TBomba);
procedure SetId(const Value: Integer);
procedure SetQuantidade(const Value: Double);
procedure SetValor(const Value: Double);
public
constructor create;
destructor destroy;
property Id: Integer read GetId write SetId;
property Quantidade: Double read GetQuantidade write SetQuantidade;
property Valor: Double read GetValor write SetValor;
property Bomba: TBomba read GetBomba write SetBomba;
end;
implementation
{ TAbastecimento }
constructor TAbastecimento.create;
begin
FBomba := TBomba.Create;
end;
destructor TAbastecimento.destroy;
begin
FBomba.Destroy;
end;
function TAbastecimento.GetBomba: TBomba;
begin
Result := FBomba;
end;
function TAbastecimento.GetId: Integer;
begin
Result := FId;
end;
function TAbastecimento.GetQuantidade: Double;
begin
Result := FQuantidade;
end;
function TAbastecimento.GetValor: Double;
begin
Result := FValor;
end;
procedure TAbastecimento.SetBomba(const Value: TBomba);
begin
FBomba := Value;
end;
procedure TAbastecimento.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TAbastecimento.SetQuantidade(const Value: Double);
begin
FQuantidade := Value;
end;
procedure TAbastecimento.SetValor(const Value: Double);
begin
FValor := Value;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uBaseSecurityService.pas }
{ Описание: Абстрактная базовая реализация ISecurityService }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uBaseSecurityService;
interface
uses
uServices, uMultiCastEvent, classes;
type
TBaseSecurityService = class(TInterfacedObject, ISecurityService)
private
FAccessGrantedByDefault: Boolean;
FAfterLogin: IMultiCastEvent;
FAfterLogout: IMultiCastEvent;
FBeforeLogin: IMultiCastEvent;
FBeforeLogout: IMultiCastEvent;
FOnCheckAccess: IMultiCastEvent;
FPermissions: IInterfaceList;
FCurrentAppUser: IAppUser;
protected
function InternalLogin(ALoginName, APassword: String): IAppUser; virtual;
abstract;
public
function AccessGranted(ATokenName: String; AAccessType: TAccessType;
AContext: IInterface = nil; AAppUser: IAppUser = nil): Boolean;
overload; virtual; stdcall;
function AccessGranted(AComponent: TComponent; AAccessType: TAccessType;
AContext: IInterface = nil; AAppUser: IAppUser = nil): Boolean;
overload; virtual; stdcall;
procedure AfterConstruction; override;
function AfterLogin: IMultiCastEvent; stdcall;
function AfterLogout: IMultiCastEvent; stdcall;
function BeforeLogin: IMultiCastEvent; stdcall;
function BeforeLogout: IMultiCastEvent; stdcall;
procedure ClearPermissions; stdcall;
function CurrentAppUser: IAppUser; stdcall;
function CurrentUserFio: string; stdcall;
function CurrentUserId: Variant; stdcall;
function GetAccessGrantedByDefault: Boolean; stdcall;
function GetComponentToken(AComponent: TComponent): string; stdcall;
function IsLoggedIn: Boolean; stdcall;
function Login(ALoginName, APassword: string): Boolean; stdcall;
procedure Logout; stdcall;
function OnCheckAccess: IMultiCastEvent; stdcall;
procedure RegisterPermission(APermission: IPermission); stdcall;
function SelectTokenPermissions(ATokenName: String): IInterfaceList;
procedure SetAccessGrantedByDefault(Value: Boolean); stdcall;
property AccessGrantedByDefault: Boolean read GetAccessGrantedByDefault
write SetAccessGrantedByDefault;
end;
implementation
uses
StrUtils, Variants, SysUtils, uCheckAccessParameters, Forms,
uMultiCastEventImpl;
{
***************************** TBaseSecurityService *****************************
}
function TBaseSecurityService.AccessGranted(ATokenName: String; AAccessType:
TAccessType; AContext: IInterface = nil; AAppUser: IAppUser = nil): Boolean;
var
CheckAccessParameters: TCheckAccessParameters;
I: Integer;
J: Integer;
Permission: IPermission;
TokenPermissions: IInterfaceList;
begin
Result := AccessGrantedByDefault;
if ATokenName <> EmptyStr then
begin
if AAppUser = nil then
AAppUser := CurrentAppUser;
CheckAccessParameters := TCheckAccessParameters.Create(ATokenName,
AAccessType, AContext, AAppUser);
try
CheckAccessParameters.AccessGranted := Result;
TokenPermissions := SelectTokenPermissions(ATokenName);
for I := 0 to TokenPermissions.Count-1 do
begin
if Supports(TokenPermissions[I], IPermission, Permission) then
begin
for J := 0 to Permission.Roles.Count-1 do
begin
if (AAppUser <> nil) and AAppUser.InRole(Permission.Roles[J]) then
begin
if Permission.AccessType in [AAccessType, atyFull] then
begin
CheckAccessParameters.AccessGranted := Permission.Granted;
end;
end;
end;
end;
end;
FOnCheckAccess.Broadcast(CheckAccessParameters);
Result := CheckAccessParameters.AccessGranted;
finally
CheckAccessParameters.Free;
end;
end;
end;
function TBaseSecurityService.AccessGranted(AComponent: TComponent;
AAccessType: TAccessType; AContext: IInterface = nil; AAppUser: IAppUser =
nil): Boolean;
begin
Result := AccessGranted(GetComponentToken(AComponent),
AAccessType, AContext, AAppUser);
end;
procedure TBaseSecurityService.AfterConstruction;
begin
inherited;
FPermissions := TInterfaceList.Create;
FAfterLogin := CreateMultiCastEvent();
FBeforeLogout := CreateMultiCastEvent();
FAfterLogout := CreateMultiCastEvent();
FBeforeLogin := CreateMultiCastEvent();
FOnCheckAccess := CreateMultiCastEvent();
FAccessGrantedByDefault := True;
end;
function TBaseSecurityService.AfterLogin: IMultiCastEvent;
begin
Result := FAfterLogin;
end;
function TBaseSecurityService.AfterLogout: IMultiCastEvent;
begin
Result := FAfterLogout;
end;
function TBaseSecurityService.BeforeLogin: IMultiCastEvent;
begin
Result := BeforeLogin;
end;
function TBaseSecurityService.BeforeLogout: IMultiCastEvent;
begin
Result := FBeforeLogout;
end;
procedure TBaseSecurityService.ClearPermissions;
begin
FPermissions.Clear;
end;
function TBaseSecurityService.CurrentAppUser: IAppUser;
begin
Result := FCurrentAppUser;
end;
function TBaseSecurityService.CurrentUserFio: string;
begin
Result := 'Неаутентифицированный пользователь';
if FCurrentAppUser <> nil then
Result := FCurrentAppUser.Fio;
end;
function TBaseSecurityService.CurrentUserId: Variant;
begin
Result := Null;
if FCurrentAppUser <> nil then
Result := FCurrentAppUser.Id;
end;
function TBaseSecurityService.GetAccessGrantedByDefault: Boolean;
begin
Result := FAccessGrantedByDefault;
end;
function TBaseSecurityService.GetComponentToken(AComponent: TComponent): string;
begin
Result := '';
if AComponent <> nil then
begin
Result := GetComponentToken(AComponent.Owner);
Result := IfThen(Result <> EmptyStr, '.', '') +
IfThen(AComponent is TCustomForm, AComponent.ClassName, AComponent.Name);
end;
end;
function TBaseSecurityService.IsLoggedIn: Boolean;
begin
Result := FCurrentAppUser <> nil;
end;
function TBaseSecurityService.Login(ALoginName, APassword: string): Boolean;
begin
FCurrentAppUser := InternalLogin(ALoginName, APassword);
Result := FCurrentAppUser <> nil;
if Result then
FAfterLogin.Broadcast(Self);
end;
procedure TBaseSecurityService.Logout;
begin
FBeforeLogout.Broadcast(Self);
FCurrentAppUser := nil;
end;
function TBaseSecurityService.OnCheckAccess: IMultiCastEvent;
begin
Result := FOnCheckAccess;
end;
procedure TBaseSecurityService.RegisterPermission(APermission: IPermission);
begin
FPermissions.Add(APermission);
end;
function TBaseSecurityService.SelectTokenPermissions(ATokenName: String):
IInterfaceList;
var
I: Integer;
Permission: IPermission;
begin
Result := TInterfaceList.Create;
for I := 0 to FPermissions.Count-1 do
begin
if Supports(FPermissions[I], IPermission, Permission) then
begin
if AnsiSameText(Permission.TokenName, ATokenName) then
Result.Add(Permission)
end;
end;
end;
procedure TBaseSecurityService.SetAccessGrantedByDefault(Value: Boolean);
begin
if FAccessGrantedByDefault <> Value then
begin
FAccessGrantedByDefault := Value;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.0 12/8/2004 8:45:02 AM JPMugaas
}
unit IdFTPListParseUnisysClearPath;
{
Unisys ClearPath (MCP and OS/2)
DIRECTORY_FORMAT=NATIVE
Much of this is based on:
ClearPath Enterprise Servers
FTP Services for ClearPath
OS 2200 User's Guide
ClearPath OS 2200 Release 8.0 January 2003
© 2003 Unisys Corporation.
All rights reserved.
and
ClearPath Enterprise Servers
TCP/IP Distributed Systems Services Operations Guide
ClearPath MCP Release 9.0 April 2004
© 2004 Unisys Corporation.
All rights reserved.
With a sample showing a multiline response from:
http://article.gmane.org/gmane.text.xml.cocoon.devel/24912
This parses data in this form:
===
Report for: (UC)A ON PACK
A SEQDATA 84 03/08/1998 15:32
A/B SEQDATA 84 06/09/1998 12:03
A/B/C SEQDATA 84 06/09/1998 12:03
A/C SEQDATA 84 06/09/1998 12:03
A/C/C SEQDATA 84 06/09/1998 12:04
A/C/C/D SEQDATA 84 06/09/1998 12:04
6 Files 504 Octets
===
The parserm only support DIRECTORY_FORMAT=NATIVE which is the default on that server.
DIRECTORY_FORMAT=STANDARD does not need be supported because that is probably listed
in Unix format. If not, we'll deal with it given some data samples.
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
type
TIdUnisysClearPathFTPListItem = class(TIdCreationDateFTPListItem)
protected
FFileKind : String;
public
property FileKind : String read FFileKind write FFileKind;
end;
TIdFTPLPUnisysClearPath = class(TIdFTPListBaseHeader)
protected
class function IsContinuedLine(const AData: String): Boolean;
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function IsHeader(const AData: String): Boolean; override;
class function IsFooter(const AData : String): Boolean; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function ParseListing(AListing : TStrings; ADir : TIdFTPListItems) : Boolean; override;
class function GetIdent : String; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseUnisysClearPath"'*)
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils;
{ TIdFTPLPUnisysClearPath }
class function TIdFTPLPUnisysClearPath.GetIdent: String;
begin
Result := 'Unisys Clearpath'; {Do not localize}
end;
class function TIdFTPLPUnisysClearPath.IsContinuedLine(const AData: String): Boolean;
begin
Result := TextStartsWith(AData, ' '); {Do not localize}
end;
class function TIdFTPLPUnisysClearPath.IsFooter(const AData: String): Boolean;
var
s : TStrings;
begin
Result := False;
s := TStringList.Create;
try
SplitColumns(AData, s);
if s.Count = 4 then
begin
if (s[1] = 'Files') or (s[1] = 'File') then begin {Do not localize}
Result := (s[3] = 'Octets') or (s[3] = 'Octet'); {Do not localize}
end;
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPUnisysClearPath.IsHeader(const AData: String): Boolean;
var
s : TStrings;
begin
Result := False;
s := TStringList.Create;
try
SplitColumns(AData, s);
if s.Count > 2 then begin
Result := (s[0] = 'Report') and (s[1] = 'for:');
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPUnisysClearPath.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdUnisysClearPathFTPListItem.Create(AOwner);
end;
class function TIdFTPLPUnisysClearPath.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
s : TStrings;
LI : TIdUnisysClearPathFTPListItem;
begin
Result := False;
LI := AItem as TIdUnisysClearPathFTPListItem;
LI.ItemType := ditFile;
s := TStringList.Create;
try
SplitColumns(LI.Data, s);
if s.Count > 4 then
begin
LI.FileName := s[0];
LI.FileKind := s[1];
//size
if IsNumeric(s[2]) then
begin
LI.Size := IndyStrToInt(s[2], 0);
AItem.SizeAvail := True;
//creation date
if IsMMDDYY(s[3], '/') then {Do not localize}
begin
LI.CreationDate := DateMMDDYY(s[3]);
if IsHHMMSS(s[4], ':') then {Do not localize}
begin
LI.CreationDate := LI.CreationDate + TimeHHMMSS(s[4]);
Result := True;
end;
end;
end;
s.Clear;
//remove path from localFileName
SplitColumns(LI.FileName, s, '/'); {Do not localize}
if s.Count > 0 then begin
LI.LocalFileName := s[s.Count-1];
end else begin
Result := False;
end;
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPUnisysClearPath.ParseListing(AListing: TStrings;
ADir: TIdFTPListItems): Boolean;
var
i : Integer;
LItem : TIdFTPListItem;
begin
for i := 0 to AListing.Count-1 do
begin
if not IsWhiteString(AListing[i]) then
begin
if not (IsHeader(AListing[i]) or IsFooter(AListing[i])) then
begin
if (not IsContinuedLine(AListing[i])) then //needed because some VMS computers return entries with multiple lines
begin
LItem := MakeNewItem(ADir);
LItem.Data := UnfoldLines(AListing[i], i, AListing);
Result := ParseLine(LItem);
if not Result then begin
FreeAndNil(LItem);
Exit;
end;
end;
end;
end;
end;
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPUnisysClearPath);
finalization
UnRegisterFTPListParser(TIdFTPLPUnisysClearPath);
end.
|
unit ufrmLapKartuStock;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefaultLaporan, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu,
Vcl.Menus, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, System.ImageList, Vcl.ImgList,
Datasnap.DBClient, Datasnap.Provider, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, cxCheckBox,
cxGridLevel, cxClasses, cxGridCustomView, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox,
Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC, dxStatusBar,
uDBUtils, ClientModule, uModel, ClientClassesUnit, uAppUtils,
Data.FireDACJSONReflect, uDMReport, cxCurrencyEdit;
type
TfrmLapKartuStock = class(TfrmDefaultLaporan)
cbbBarang: TcxExtLookupComboBox;
Label1: TLabel;
pnlfOOTER: TPanel;
edtOTAL: TcxCurrencyEdit;
lblTotal: TLabel;
procedure ActionRefreshExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FCDSS: TFDJSONDataSets;
procedure InisialisasiCBBBarang;
{ Private declarations }
public
procedure CetakSlip; override;
{ Public declarations }
end;
var
frmLapKartuStock: TfrmLapKartuStock;
implementation
{$R *.dfm}
procedure TfrmLapKartuStock.ActionRefreshExecute(Sender: TObject);
var
dTotal: double;
lBarang: TBarang;
lDS: TClientDataSet;
lGudang: TGudang;
begin
inherited;
lBarang := TBarang.CreateID(cbbBarang.EditValue);
lGudang := TGudang.CreateID(cbbGudang.EditValue);
FCDSS := ClientDataModule.ServerLaporanClient.LaporanKartok(dtpAwal.Date, dtpAkhir.Date,lBarang, lGudang);
lDS := TDBUtils.DSToCDS(TDataSet(TFDJSONDataSetsReader.GetListValue(FCDSS, 1)), Self);
cxGridDBTableOverview.SetDataset(lDS, True);
cxGridDBTableOverview.ApplyBestFit();
cxGridDBTableOverview.SetVisibleColumns(['urutan'], False);
dTotal := 0;
while not lDS.Eof do
begin
dTotal := dTotal + lDS.FieldByName('qtyin').AsFloat - lDS.FieldByName('qtyout').AsFloat;
lDS.Next;
end;
edtOTAL.Value := dTotal;
end;
procedure TfrmLapKartuStock.CetakSlip;
var
lBarang: TBarang;
lGudang: TGudang;
begin
inherited;
lBarang := TBarang.CreateID(cbbBarang.EditValue);
lGudang := TGudang.CreateID(cbbGudang.EditValue);
FCDSS := ClientDataModule.ServerLaporanClient.LaporanKartok(dtpAwal.Date, dtpAkhir.Date,lBarang, lGudang);
with dmReport do
begin
AddReportVariable('UserCetak', UserAplikasi.UserName);
ExecuteReport( 'Reports/Lap_Kartok' ,
FCDSS
);
end;
end;
procedure TfrmLapKartuStock.FormShow(Sender: TObject);
begin
inherited;
InisialisasiCBBBarang;
end;
procedure TfrmLapKartuStock.InisialisasiCBBBarang;
var
lCDSBarang: TClientDataSet;
sSQL: string;
begin
sSQL := 'select id,Nama,SKU from TBarang';
lCDSBarang := TDBUtils.OpenDataset(sSQL);
cbbBarang.Properties.LoadFromCDS(lCDSBarang,'ID','Nama',['ID'],Self);
cbbBarang.Properties.SetMultiPurposeLookup;
end;
end.
|
unit D_DateCalc;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BottomBtnDlg, StdCtrls, Buttons, ExtCtrls, vtSpin, Mask,
vtCombo, vtDateEdit,
l3Date;
type
TDateCalcDlg = class(TBottomBtnDlg)
Label3: TLabel;
Label4: TLabel;
Label1: TLabel;
Label5: TLabel;
edtInitialDate: TvtDateEdit;
edtlDateDelta: TvtSpinEdit;
edtResultDate: TvtDateEdit;
cbLogModificator: TComboBox;
cbDeltaKind: TComboBox;
procedure Calculate;
procedure edtInitialDateChange(Sender: TObject);
procedure edtlDateDeltaChange(Sender: TObject);
procedure cbDeltaKindChange(Sender: TObject);
procedure cbLogModificatorChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetCalculateDate(var aDate : TStDate) : Boolean;
implementation
{$R *.dfm}
uses
l3MinMax;
function GetCalculateDate(var aDate : TStDate) : Boolean;
begin
with TDateCalcDlg.Create(nil) do
try
edtInitialDate.StDate := aDate;
Result := Execute;
if Result then
aDate := edtResultDate.StDate;
finally
Free;
end;
end;
(*
From: Денис А. Кузякин
To: Соловьев Саша ; Дудко Дима ; Бабанин Вова ; Подключение
Sent: Wednesday, June 13, 2007 3:57 PM
Subject: Калькулятор дат
Вованыч!
Надо сделать, чтобы подсчет в калькуляторе для МЕСЯЦЕВ осуществлялся следующим образом:
"По истечении Х месяцев со дня опубликования"
1. Определяется начало срока - ДЕНЬ ОПУБЛИКОВАНИЯ - число Y
2. От месяца начала срока определяется месяц окончания срока
3. Смотрится есть ли в этом месяце это число Y. Если есть, то берется оно, если нет - берется 1-е число следующего месяца
Например, Док опубликован 30 января 2007. Вступает по истечении 1 месяца со дня опубликования.
1. Начало срока - 30 января
2. Месяц окончания - февраль
3. В феврале нет 30-го числа, значит вступает - с 1 марта
Пример 2:
Док опубликован 30 января 2007. Вступает по истечении 3 месяцев со дня опубликования.
1. Начало срока - 30 января
2. Месяц окончания - апрель
3. В апреле есть 30-е число, значит вступает - с 30 апреля
"По истечении Х месяцев после дня опубликования"
1. Определяется начало срока - ДЕНЬ ОПУБЛИКОВАНИЯ ПЛЮС ОДИН ДЕНЬ - число Z
2. От месяца начала срока определяется месяц окончания срока
3. Смотрится есть ли в этом месяце это число Z. Если есть, то берется оно, если нет - берется 1-е число следующего месяца
Например, Док опубликован 30 января 2007. Вступает по истечении 1 месяца после дня опубликования.
1. Начало срока - 30 января + 1 = 31 января
2. Месяц окончания - февраль
3. В феврале нет 31-го числа, значит вступает - с 1 марта
Пример 2:
Док опубликован 31 января 2007. Вступает по истечении 3 месяцев со дня опубликования.
1. Начало срока - 31 января + 1 = 1 февраля
2. Месяц окончания - май
3. 1 мая
____________________________________
С уважением, Кузякин Денис
*)
procedure TDateCalcDlg.Calculate;
var
Day, Month, Year : Integer;
lDate : TStDate;
lDinM : Integer;
procedure MonthYearRecalc;
begin
Year := Year + (Month - 1) div 12;
Month := ((Month-1) mod 12) + 1;
end;
begin
if edtInitialDate.IsValid then
begin
lDate := edtInitialDate.StDate + cbLogModificator.ItemIndex;
if cbDeltaKind.ItemIndex = 0 then //дней
edtResultDate.StDate := lDate + edtlDateDelta.AsInteger
else
begin
StDateToDMY(lDate, Day, Month, Year);
if cbDeltaKind.ItemIndex = 1 then //месяцев
Month := Month + edtlDateDelta.AsInteger
else //лет
Month := Month + edtlDateDelta.AsInteger * 12;
MonthYearRecalc;
lDinM := DaysInMonth(Month, Year);
if Day > lDinM then
begin
Day := Day - lDinM;
Inc(Month);
MonthYearRecalc;
end;
edtResultDate.StDate := DMYToStDate(Day, Month, Year);
end;
end
else
edtResultDate.ClearDate;
end;
procedure TDateCalcDlg.edtInitialDateChange(Sender: TObject);
begin
Calculate;
end;
procedure TDateCalcDlg.edtlDateDeltaChange(Sender: TObject);
begin
Calculate;
end;
procedure TDateCalcDlg.cbDeltaKindChange(Sender: TObject);
begin
Calculate;
end;
procedure TDateCalcDlg.cbLogModificatorChange(Sender: TObject);
begin
Calculate;
end;
end.
|
unit streamable_component_list;
interface
uses classes,introspectionLib, streaming_class_lib;
type
TComponentClass=class of TComponent;
TStreamableComponentList=class(TIntrospectedStreamingClass)
private
fResolved: boolean;
fList: TStrings;
fOwnsObjects: boolean;
fUseNotifications: boolean;
procedure SetList(writer: TWriter);
procedure GetList(reader: TReader);
procedure SetOwnsObjects(value: Boolean);
function GetItem(index: Integer): TStreamingClass;
function GetCount: Integer;
protected
procedure Loaded; override;
procedure DefineProperties(Filer: TFiler); override;
procedure Notification(aComponent: TComponent; operation: TOperation); override;
public
procedure ResolveNames;
constructor Create(owner: TComponent); override;
destructor Destroy; override;
procedure Add(component: TComponent);
procedure XAdd(component: TComponent); //если нет - добавим, если есть-удалим
procedure Delete(component: TComponent);
procedure Remove(index: Integer); overload;
procedure Remove(component: TComponent); overload;
procedure Clear; override;
procedure Assign(source: TPersistent); override;
procedure TakeFromList(source: TStreamableComponentList); //с парам. OwnsObjects
procedure SetObjectsOwner(value: TComponent);
function IndexOf(component: TComponent): Integer;
function Exist(component: Tcomponent): Boolean;
function NamesAsString: string;
property Count: Integer read GetCount;
property Item[index: Integer]: TStreamingClass read GetItem; default;
published
property OwnsObjects: boolean read fOwnsObjects write SetOwnsObjects default false;
property UseNotifications: boolean read fUseNotifications write fUseNotifications default false;
end;
implementation
uses SysUtils;
constructor TStreamableComponentList.Create(owner: TComponent);
begin
inherited Create(owner);
fList:=TStringList.Create;
fResolved:=true;
end;
destructor TStreamableComponentList.Destroy;
begin
Clear; //снять notification если объекты не принадлежат
FreeAndNil(fList);
inherited Destroy;
end;
procedure TStreamableComponentList.Add(component: TComponent);
begin
fList.AddObject(component.Name,component);
if OwnsObjects then begin
if Assigned(component.Owner) then component.Owner.RemoveComponent(component);
InsertComponent(component);
end
else if UseNotifications then
component.FreeNotification(self);
end;
procedure TStreamableComponentList.XAdd(component: TComponent);
begin
if Exist(component) then Remove(component)
else Add(component);
end;
procedure TStreamableComponentList.ResolveNames;
var i: Integer;
begin
if OwnsObjects then
for i:=0 to ComponentCount-1 do
fList.AddObject(components[i].Name,components[i])
else
for i:=0 to fList.Count-1 do begin
fList.Objects[i]:=FindNestedComponent(FindOwner,fList.Strings[i]);
if UseNotifications then (fList.Objects[i] as TComponent).FreeNotification(self);
end;
fResolved:=true;
end;
procedure TStreamableComponentList.Loaded;
begin
ResolveNames; //если списка вообще не было, значит fResolved так и не сбросился в false
// if not fResolved then ResolveNames;
end;
procedure TStreamableComponentList.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty('data',GetList,SetList,(Count>0) and not ownsObjects);
end;
procedure TStreamableComponentList.SetList(writer: TWriter);
var i: Integer;
Component: TComponent;
LookupRoot: TComponent;
s: string;
begin
if not fResolved then ResolveNames;
LookupRoot:=writer.LookupRoot;
if fList.Count>1 then writer.WriteListBegin;
for i:=0 to fList.Count-1 do begin
Component:=flist.objects[i] as TComponent;
s:=GetComponentValue(Component,LookupRoot);
writer.WriteIdent(s);
end;
if fList.Count>1 then writer.WriteListEnd;
end;
procedure TStreamableComponentList.GetList(reader: TReader);
begin
if reader.NextValue=vaList then begin
reader.ReadListBegin;
while not reader.EndOfList do begin
fList.Add(reader.ReadIdent);
end;
reader.ReadListEnd;
end
else fList.Add(reader.ReadIdent);
fResolved:=false;
end;
function TStreamableComponentList.GetItem(index: Integer): TStreamingClass;
begin
if not fResolved then ResolveNames;
Result:=fList.Objects[index] as TStreamingClass;
if Result=nil then Raise Exception.CreateFmt('%s.GetItem: incorrect index %d (length %d)',[name,index,count]);
end;
function TStreamableComponentList.GetCount: Integer;
begin
if not fResolved then ResolveNames;
Result:=fList.Count;
end;
function TStreamableComponentList.IndexOf(component: TComponent): Integer;
begin
if fList=nil then Result:=-1
else begin
if not fResolved then ResolveNames;
Result:=fList.IndexOfObject(component);
end;
end;
function TStreamableComponentList.Exist(component: TComponent): Boolean;
begin
Result:=(IndexOf(component)>=0);
end;
procedure TStreamableComponentList.Clear;
var i: Integer;
begin
if OwnsObjects then
for i:=0 to Count-1 do
Item[i].Free
else if UseNotifications then
for i:=0 to Count-1 do
Item[i].RemoveFreeNotification(self);
fList.Clear;
fResolved:=true;
end;
procedure TStreamableComponentList.Delete(component: TCOmponent);
var i: Integer;
begin
i:=IndexOf(component);
if i>=0 then begin
if (not OwnsObjects) and UseNotifications then component.RemoveFreeNotification(self);
fList.delete(i);
component.Free;
end;
end;
procedure TStreamableComponentList.Remove(Index: Integer);
begin
if (not OwnsObjects) and UseNotifications then Item[Index].RemoveFreeNotification(self);
fList.Delete(index);
end;
procedure TStreamableComponentList.Remove(component: TComponent);
begin
Remove(IndexOf(component));
end;
procedure TStreamableComponentList.TakeFromList(source: TStreamableComponentList);
var cl: TStreamingClassClass;
i: Integer;
comp: TComponent;
begin
flist.Assign(source.fList);
if OwnsObjects then begin
DestroyComponents;
for i:=0 to source.Count-1 do begin
cl:=TStreamingClassClass(source.Item[i].ClassType);
comp:=cl.Clone(source.item[i],self);
fList.Objects[i]:=comp;
end;
end
else if UseNotifications then
for i:=0 to Count-1 do
Item[i].FreeNotification(self);
end;
procedure TStreamableComponentList.Assign(source: TPersistent);
var f: TStreamableComponentList absolute source;
cl: TStreamingClassClass;
i: Integer;
comp: TComponent;
begin
if source is TStreamableComponentList then begin
//если "наш" лист держит компоненты внутри себя, то сделает копию компонентов,
//иначе просто сошлется на те же самые компоненты
fList.Assign(f.fList);
fResolved:=f.fResolved;
fOwnsObjects:=f.fOwnsObjects; //иначе не будет работать Clone как надо
if OwnsObjects then begin
DestroyComponents;
for i:=0 to f.Count-1 do begin
cl:=TStreamingClassClass(f.Item[i].ClassType);
comp:=cl.Clone(f.item[i],self);
fList.Objects[i]:=comp;
end;
end
else if UseNotifications then
for i:=0 to Count-1 do
Item[i].FreeNotification(self);
end
else inherited Assign(source);
end;
function TStreamableComponentList.NamesAsString: string;
var i: Integer;
begin
If Count=0 then Result:='{}'
else begin
Result:='{'+Item[0].Name;
for i:=1 to Count-1 do
Result:=Result+';'+Item[i].Name;
Result:=Result+'}';
end;
end;
procedure TStreamableComponentList.Notification(aComponent: TComponent; operation: TOperation);
begin
if UseNotifications and (operation=opRemove) and Exist(aComponent) then
fList.Delete(IndexOf(aComponent));
inherited Notification(aComponent,operation);
end;
procedure TStreamableComponentList.SetObjectsOwner(value: TComponent);
var i: Integer;
begin
for i:=0 to Count-1 do
if Item[i].Owner<>value then begin
if Assigned(Item[i].Owner) then Item[i].Owner.RemoveComponent(Item[i]);
if Assigned(value) then value.InsertComponent(Item[i]);
end;
fOwnsObjects:=(value=self);
end;
procedure TStreamableComponentList.SetOwnsObjects(value: Boolean);
begin
if not fResolved then ResolveNames;
fOwnsObjects:=value;
if value then SetObjectsOwner(self);
// else SetObjectsOwner(nil);
end;
initialization
RegisterClass(TStreamableComponentList);
end.
|
unit SysVars;
{
本单元包含系统全部的全局变量
}
interface
uses
//自编模块
SysRecords,SysConsts,
//
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
var
//----------------------------基本变量-------------------------------------------------------//
gsMainDir : string; //系统的初始运行目录
//----------------------------程序块---------------------------------------------------------//
giOldBlockID : Integer=-1; //保存上次的程序块数组
//----------------------------编辑器设置-----------------------------------------------------//
giTabStops : Integer=5; //代码缩进量
giRightMargin : Integer=80; //代码右边界显示位置
//----------------------------流程图设置-----------------------------------------------------//
giColor_Line : TColor; //流程图中线和颜色
giColor_If : TColor; //判断框的颜色
giColor_Fill : TColor; //框的填充颜色
giColor_Try : TColor; //Try框的颜色
giColor_Select : TColor; //选择时的颜色
giColor_Font : TColor; //字体颜色
giColor_Flow : TColor=clGreen; //动态流程的颜色
giFontName : String='Small Fonts'; //字体名称
giFontSize : Byte=6; //字体大小,默认为6
giBaseWidth : Integer=60; //基本框的宽度的一半(为了便于绘图控制)
giBaseHeight : Integer=20; //基本框的高度
giSpaceH : Integer=10; //横向间隔
giSpaceV : Integer=20; //纵向间隔
giImgWidth : Integer=200; //流程图的原始宽和高,主要用于流程图缩放
giImgHeight : Integer=200;
grConfig : TWWConfig;
//
giMaxWidth : Integer=4000;//图片最大宽度,用于解决内存不足的问题
giMaxHeight : Integer=8000;//图片最大高度
implementation
end.
|
unit NewDisk;
{
Inno Setup
Copyright (C) 1997-2005 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
New Disk form
$jrsoftware: issrc/Projects/NewDisk.pas,v 1.34 2010/10/22 10:33:26 mlaan Exp $
}
interface
{$I VERSION.INC}
uses
Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs,
SetupForm, StdCtrls, ExtCtrls, NewStaticText, BitmapImage, BidiCtrls;
type
TNewDiskForm = class(TSetupForm)
DiskBitmapImage: TBitmapImage;
SelectDiskLabel: TNewStaticText;
PathLabel: TNewStaticText;
PathEdit: TEdit;
BrowseButton: TNewButton;
OKButton: TNewButton;
CancelButton: TNewButton;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure BrowseButtonClick(Sender: TObject);
private
{ Private declarations }
Filename: string;
function GetSanitizedPath: String;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
end;
function SelectDisk(const DiskNumber: Integer; const AFilename: String; var Path: String): Boolean;
implementation
uses
Msgs, MsgIDs, PathFunc, CmnFunc, CmnFunc2, BrowseFunc,
Main, Wizard;
{$R *.DFM}
function SelectDisk(const DiskNumber: Integer; const AFilename: String;
var Path: String): Boolean;
begin
with TNewDiskForm.Create(Application) do
try
Filename := AFilename;
SelectDiskLabel.Caption := FmtSetupMessage(msgSelectDiskLabel2, [IntToStr(DiskNumber)]);
PathEdit.Text := Path;
MessageBeep(0);
Result := ShowModal = mrOK;
if Result then
Path := GetSanitizedPath;
finally
Free;
end;
end;
{ TNewDiskForm }
constructor TNewDiskForm.Create(AOwner: TComponent);
begin
inherited;
InitializeFont;
{ WizardForm will not exist yet if we're being called from [Code]'s
ExtractTemporaryFile in InitializeSetup }
if Assigned(WizardForm) then
CenterInsideControl(WizardForm, False)
else
Center;
Caption := SetupMessages[msgChangeDiskTitle];
PathLabel.Caption := SetupMessages[msgPathLabel];
BrowseButton.Caption := SetupMessages[msgButtonBrowse];
OKButton.Caption := SetupMessages[msgButtonOK];
CancelButton.Caption := SetupMessages[msgButtonCancel];
DiskBitmapImage.Bitmap.Handle := LoadBitmap(HInstance, 'DISKIMAGE'); {don't localize};
DiskBitmapImage.ReplaceColor := clBlue;
DiskBitmapImage.ReplaceWithColor := Color;
TryEnableAutoCompleteFileSystem(PathEdit.Handle);
end;
function TNewDiskForm.GetSanitizedPath: String;
begin
Result := PathExpand(RemoveBackslashUnlessRoot(Trim(PathEdit.Text)));
end;
procedure TNewDiskForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
Path: String;
begin
case ModalResult of
mrOK: begin
Path := GetSanitizedPath;
if (Path = '') or not NewFileExists(AddBackslash(Path) + Filename) then begin
CanClose := False;
LoggedMsgBox(FmtSetupMessage(msgFileNotInDir2, [Filename, Path]),
'', mbError, MB_OK, False, 0);
end;
end;
mrCancel: CanClose := ExitSetupMsgBox;
end;
end;
procedure TNewDiskForm.BrowseButtonClick(Sender: TObject);
var
Dir: String;
begin
Dir := GetSanitizedPath;
if BrowseForFolder(SetupMessages[msgSelectDirectoryLabel], Dir, Handle, False) then
PathEdit.Text := Dir;
end;
end.
|
unit l3ControlFontService;
// Модуль: "w:\common\components\rtl\Garant\L3\l3ControlFontService.pas"
// Стереотип: "Service"
// Элемент модели: "Tl3ControlFontService" MUID: (556F24A80035)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
{$If NOT Defined(NoVCL)}
uses
l3IntfUses
, l3ProtoObject
, l3Interfaces
, Controls
, l3CProtoObject
;
type
Tl3ControlFontInfo = class(Tl3CProtoObject, Il3FontInfo)
private
f_Control: TControl;
protected
function Get_Size: Integer;
function Get_Name: TFontName;
function Get_Bold: Boolean;
function Get_Italic: Boolean;
function Get_Underline: Boolean;
function Get_Strikeout: Boolean;
function Get_ForeColor: Tl3Color;
function Get_BackColor: Tl3Color;
function Get_Pitch: TFontPitch;
function Get_Index: Tl3FontIndex;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aControl: TControl); reintroduce;
class function Make(aControl: TControl): Il3FontInfo; reintroduce;
end;//Tl3ControlFontInfo
(*
Ml3ControlFontService = interface
{* Контракт сервиса Tl3ControlFontService }
function GetFont(aControl: TControl): Il3FontInfo;
end;//Ml3ControlFontService
*)
Il3ControlFontService = interface
{* Интерфейс сервиса Tl3ControlFontService }
function GetFont(aControl: TControl): Il3FontInfo;
end;//Il3ControlFontService
Tl3ControlFontService = {final} class(Tl3ProtoObject)
private
f_Alien: Il3ControlFontService;
{* Внешняя реализация сервиса Il3ControlFontService }
protected
procedure pm_SetAlien(const aValue: Il3ControlFontService);
procedure ClearFields; override;
public
function GetFont(aControl: TControl): Il3FontInfo;
class function Instance: Tl3ControlFontService;
{* Метод получения экземпляра синглетона Tl3ControlFontService }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property Alien: Il3ControlFontService
write pm_SetAlien;
{* Внешняя реализация сервиса Il3ControlFontService }
end;//Tl3ControlFontService
{$IfEnd} // NOT Defined(NoVCL)
implementation
{$If NOT Defined(NoVCL)}
uses
l3ImplUses
, SysUtils
, l3Base
, Graphics
{$If NOT Defined(NoScripts)}
, FontWordsPack
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *556F24A80035impl_uses*
//#UC END# *556F24A80035impl_uses*
;
type
TControlFriend = {abstract} class(TControl)
{* Друг к классу TControl }
end;//TControlFriend
var g_Tl3ControlFontService: Tl3ControlFontService = nil;
{* Экземпляр синглетона Tl3ControlFontService }
procedure Tl3ControlFontServiceFree;
{* Метод освобождения экземпляра синглетона Tl3ControlFontService }
begin
l3Free(g_Tl3ControlFontService);
end;//Tl3ControlFontServiceFree
constructor Tl3ControlFontInfo.Create(aControl: TControl);
//#UC START# *556F25D20367_556F25860097_var*
//#UC END# *556F25D20367_556F25860097_var*
begin
//#UC START# *556F25D20367_556F25860097_impl*
inherited Create;
f_Control := aControl;
//#UC END# *556F25D20367_556F25860097_impl*
end;//Tl3ControlFontInfo.Create
class function Tl3ControlFontInfo.Make(aControl: TControl): Il3FontInfo;
var
l_Inst : Tl3ControlFontInfo;
begin
l_Inst := Create(aControl);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tl3ControlFontInfo.Make
function Tl3ControlFontInfo.Get_Size: Integer;
//#UC START# *46A60D7A02E4_556F25860097get_var*
//#UC END# *46A60D7A02E4_556F25860097get_var*
begin
//#UC START# *46A60D7A02E4_556F25860097get_impl*
Result := TControlFriend(f_Control).Font.Size;
//#UC END# *46A60D7A02E4_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Size
function Tl3ControlFontInfo.Get_Name: TFontName;
//#UC START# *46A60E2802E4_556F25860097get_var*
//#UC END# *46A60E2802E4_556F25860097get_var*
begin
//#UC START# *46A60E2802E4_556F25860097get_impl*
Result := TControlFriend(f_Control).Font.Name;
//#UC END# *46A60E2802E4_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Name
function Tl3ControlFontInfo.Get_Bold: Boolean;
//#UC START# *46A60E58013F_556F25860097get_var*
//#UC END# *46A60E58013F_556F25860097get_var*
begin
//#UC START# *46A60E58013F_556F25860097get_impl*
Result := (fsBold in TControlFriend(f_Control).Font.Style);
//#UC END# *46A60E58013F_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Bold
function Tl3ControlFontInfo.Get_Italic: Boolean;
//#UC START# *46A60E740045_556F25860097get_var*
//#UC END# *46A60E740045_556F25860097get_var*
begin
//#UC START# *46A60E740045_556F25860097get_impl*
Result := (fsItalic in TControlFriend(f_Control).Font.Style);
//#UC END# *46A60E740045_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Italic
function Tl3ControlFontInfo.Get_Underline: Boolean;
//#UC START# *46A60EA6032C_556F25860097get_var*
//#UC END# *46A60EA6032C_556F25860097get_var*
begin
//#UC START# *46A60EA6032C_556F25860097get_impl*
Result := (fsUnderline in TControlFriend(f_Control).Font.Style);
//#UC END# *46A60EA6032C_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Underline
function Tl3ControlFontInfo.Get_Strikeout: Boolean;
//#UC START# *46A60EBF03BE_556F25860097get_var*
//#UC END# *46A60EBF03BE_556F25860097get_var*
begin
//#UC START# *46A60EBF03BE_556F25860097get_impl*
Result := (fsStrikeout in TControlFriend(f_Control).Font.Style);
//#UC END# *46A60EBF03BE_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Strikeout
function Tl3ControlFontInfo.Get_ForeColor: Tl3Color;
//#UC START# *46A60ED90325_556F25860097get_var*
//#UC END# *46A60ED90325_556F25860097get_var*
begin
//#UC START# *46A60ED90325_556F25860097get_impl*
Result := TControlFriend(f_Control).Font.Color;
//#UC END# *46A60ED90325_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_ForeColor
function Tl3ControlFontInfo.Get_BackColor: Tl3Color;
//#UC START# *46A60EF300C9_556F25860097get_var*
//#UC END# *46A60EF300C9_556F25860097get_var*
begin
//#UC START# *46A60EF300C9_556F25860097get_impl*
Result := TControlFriend(f_Control).Color;
//#UC END# *46A60EF300C9_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_BackColor
function Tl3ControlFontInfo.Get_Pitch: TFontPitch;
//#UC START# *46A60F63035F_556F25860097get_var*
//#UC END# *46A60F63035F_556F25860097get_var*
begin
//#UC START# *46A60F63035F_556F25860097get_impl*
Result := TControlFriend(f_Control).Font.Pitch;
//#UC END# *46A60F63035F_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Pitch
function Tl3ControlFontInfo.Get_Index: Tl3FontIndex;
//#UC START# *46A60F89031E_556F25860097get_var*
//#UC END# *46A60F89031E_556F25860097get_var*
begin
//#UC START# *46A60F89031E_556F25860097get_impl*
Result := l3_fiNone;
//#UC END# *46A60F89031E_556F25860097get_impl*
end;//Tl3ControlFontInfo.Get_Index
procedure Tl3ControlFontInfo.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_556F25860097_var*
//#UC END# *479731C50290_556F25860097_var*
begin
//#UC START# *479731C50290_556F25860097_impl*
f_Control := nil;
inherited;
//#UC END# *479731C50290_556F25860097_impl*
end;//Tl3ControlFontInfo.Cleanup
procedure Tl3ControlFontService.pm_SetAlien(const aValue: Il3ControlFontService);
begin
Assert((f_Alien = nil) OR (aValue = nil));
f_Alien := aValue;
end;//Tl3ControlFontService.pm_SetAlien
function Tl3ControlFontService.GetFont(aControl: TControl): Il3FontInfo;
//#UC START# *556F24D50369_556F24A80035_var*
//#UC END# *556F24D50369_556F24A80035_var*
begin
//#UC START# *556F24D50369_556F24A80035_impl*
Result := nil;
if (f_Alien <> nil) then
Result := f_Alien.Getfont(aControl);
if (Result = nil) then
Result := Tl3ControlFontInfo.Make(aControl);
//#UC END# *556F24D50369_556F24A80035_impl*
end;//Tl3ControlFontService.GetFont
class function Tl3ControlFontService.Instance: Tl3ControlFontService;
{* Метод получения экземпляра синглетона Tl3ControlFontService }
begin
if (g_Tl3ControlFontService = nil) then
begin
l3System.AddExitProc(Tl3ControlFontServiceFree);
g_Tl3ControlFontService := Create;
end;
Result := g_Tl3ControlFontService;
end;//Tl3ControlFontService.Instance
class function Tl3ControlFontService.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_Tl3ControlFontService <> nil;
end;//Tl3ControlFontService.Exists
procedure Tl3ControlFontService.ClearFields;
begin
Alien := nil;
inherited;
end;//Tl3ControlFontService.ClearFields
{$IfEnd} // NOT Defined(NoVCL)
end.
|
{**************************************************************}
{ }
{ This is a part of Morphine v2.7 by Holy_Father && Ratter/29A }
{ }
{**************************************************************}
unit uCode;
interface
procedure GenerateRubbishCode(AMem: Pointer; ASize, AVirtAddr: Cardinal); stdcall;
implementation
const
REG_EAX = 0;
REG_ECX = 1;
REG_EDX = 2;
REG_EBX = 3;
REG_ESP = 4;
REG_EBP = 5;
REG_ESI = 6;
REG_EDI = 7;
REG_NON = 255;
Reg8Count = 8;
Reg16Count = 8;
Reg32Count = 8;
type
PByte = ^Byte;
PWord = ^Word;
PCardinal = ^Cardinal;
procedure GenerateRandomBuffer(ABuf: PByte; ASize: Cardinal);
var
LI:Integer;
begin
for LI:= 0 to ASize-1 do
begin
ABuf^:= Random($FE)+1;
Inc(ABuf);
end;
end;
procedure PutRandomBuffer(var AMem: PByte; ASize: Cardinal);
begin
GenerateRandomBuffer(AMem, ASize);
Inc(AMem, ASize);
end;
function RandomReg32All: Byte;
begin
Result:= Random(Reg32Count);
end;
function RandomReg16All: Byte;
begin
Result:= Random(Reg16Count);
end;
function RandomReg8ABCD: Byte;
begin
Result:= Random(Reg8Count);
end;
function RandomReg32Esp: Byte;
begin
Result:= Random(Reg32Count-1);
if Result = REG_ESP then Result:= 7;
end;
function RandomReg32EspEbp: Byte;
begin
Result:= Random(Reg32Count-2);
if Result = REG_ESP then
Result:= 6
else
if Result = REG_EBP then Result:= 7;
end;
procedure ThrowTheDice(var ADice: Cardinal; ASides: Cardinal = 6); overload;
begin
ADice:= Random(ASides) + 1;
end;
procedure ThrowTheDice(var ADice: Word; ASides: Word = 6); overload;
begin
ADice:= Random(ASides) + 1;
end;
procedure ThrowTheDice(var ADice: Byte; ASides: Byte = 6); overload;
begin
ADice:= Random(ASides) + 1;
end;
function Bswap(var AMem: PByte; AReg: Byte): Byte;
begin
Result:= 2;
AMem^:= $0F;
Inc(AMem);
AMem^:= $C8 + AReg;
Inc(AMem);
end;
function Pushad(var AMem: PByte): Byte;
begin
Result:= 1;
AMem^:= $60;
Inc(AMem);
end;
function Stosd(var AMem: PByte): Byte;
begin
Result:= 1;
AMem^:= $AB;
Inc(AMem);
end;
function Movsd(var AMem:PByte): Byte;
begin
Result:= 1;
AMem^:= $A5;
Inc(AMem);
end;
function Ret(var AMem: PByte): Byte;
begin
Result:= 1;
AMem^:= $C3;
Inc(AMem);
end;
procedure Ret16(var AMem: PByte; AVal: Word);
begin
AMem^:= $C2;
Inc(AMem);
PWord(AMem)^:= AVal;
Inc(AMem,2);
end;
procedure RelJmpAddr32(var AMem: PByte; AAddr: Cardinal);
begin
AMem^:= $E9;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure RelJmpAddr8(var AMem: PByte; AAddr: Byte);
begin
AMem^:= $EB;
Inc(AMem);
AMem^:= AAddr;
Inc(AMem);
end;
procedure RelJzAddr32(var AMem: PByte; AAddr: Cardinal);
begin
AMem^:= $0F;
Inc(AMem);
AMem^:= $84;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure RelJnzAddr32(var AMem: PByte; AAddr: Cardinal);
begin
AMem^:= $0F;
Inc(AMem);
AMem^:= $85;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure RelJbAddr32(var AMem: PByte; AAddr: Cardinal);
begin
AMem^:= $0F;
Inc(AMem);
AMem^:= $82;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure RelJzAddr8(var AMem: PByte; AAddr: Byte);
begin
AMem^:= $74;
Inc(AMem);
AMem^:= AAddr;
Inc(AMem);
end;
procedure RelJnzAddr8(var AMem: PByte; AAddr: Byte);
begin
AMem^:= $75;
Inc(AMem);
AMem^:= AAddr;
Inc(AMem);
end;
function JmpRegMemIdx8(var AMem: PByte; AReg, AIdx: Byte): Byte;
begin
Result:= 3;
AMem^:= $FF;
Inc(AMem);
AMem^:= $60+AReg;
InC(AMem);
if AReg = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
AMem^:= AIdx;
Inc(AMem);
end;
function PushRegMem(var AMem: PByte; AReg: Byte): Byte;
begin
Result:= 2;
AMem^:= $FF;
Inc(AMem);
if AReg = REG_EBP then
begin
Inc(Result);
AMem^:=$75;
Inc(AMem);
AMem^:=$00;
end else AMem^:= $30 + AReg;
Inc(AMem);
if AReg = REG_ESP then
begin
Inc(Result);
AMem^:=$24;
Inc(AMem);
end;
end;
procedure PushReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $50 + AReg;
Inc(AMem);
end;
function PushReg32Rand(var AMem: PByte): Byte;
begin
Result:= RandomReg32Esp;
PushReg32(AMem,Result);
end;
procedure PopReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $58 + AReg;
Inc(AMem);
end;
function PopReg32Idx(var AMem: PByte; AReg: Byte; AIdx: Cardinal): Byte;
begin
Result:= 6;
AMem^:= $8F;
Inc(AMem);
AMem^:= $80 + AReg;
Inc(AMem);
if AReg = REG_ESP then
begin
AMem^:= $24;
Inc(AMem);
Inc(Result);
end;
PCardinal(AMem)^:= AIdx;
InC(AMem,4);
end;
procedure RelCallAddr(var AMem: PByte; AAddr: Cardinal);
begin
AMem^:= $E8;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure MovReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte);
begin
AMem^:= $89;
Inc(AMem);
AMem^:= AReg2*8 + AReg1 + $C0;
Inc(AMem);
end;
procedure AddReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte);
begin
AMem^:= $01;
Inc(AMem);
AMem^:= AReg2*8 + AReg1 + $C0;
Inc(AMem);
end;
function AddReg32RegMem(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $03;
Inc(AMem);
if AReg2 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg1*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg1*8 + AReg2;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
function AddRegMemReg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $01;
Inc(AMem);
if AReg1 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg2*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg2*8 + AReg1;
Inc(AMem);
if AReg1 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
procedure AddReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $83;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure MovReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $B8 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
function MovReg32IdxNum32(var AMem: PByte; AReg: Byte; AIdx, ANum: Cardinal): Byte;
begin
Result:= 10;
AMem^:= $C7;
Inc(AMem);
AMem^:= $80 + AReg;
Inc(AMem);
if AReg = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
PCardinal(AMem)^:= AIdx;
Inc(AMem,4);
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
procedure MovReg32Reg32IdxNum32(var AMem: PByte; AReg1, AReg2: Byte; ANum: Cardinal);
begin
if AReg1 = REG_ESP then
begin
AReg1:= AReg2;
AReg2:= REG_ESP;
end;
if AReg2 = REG_EBP then
begin
AReg2:= AReg1;
AReg1:= REG_EBP;
end;
AMem^:= $C7;
Inc(AMem);
AMem^:= $04;
Inc(AMem);
AMem^:= AReg1*8 + AReg2;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
function MovReg32RegMem(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $8B;
Inc(AMem);
if AReg2 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg1*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg1*8 + AReg2;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
function MovRegMemReg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $89; //mov
Inc(AMem);
if AReg1 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg2*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg2*8 + AReg1;
Inc(AMem);
if AReg1 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
function MovReg32RegMemIdx8(var AMem: PByte; AReg1, AReg2, AIdx: Byte): Byte;
begin
Result:= 3;
AMem^:= $8B;
Inc(AMem);
AMem^:= AReg1*8 + AReg2 + $40;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
AMem^:= AIdx;
Inc(AMem);
end;
procedure PushNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $68;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
procedure JmpReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $FF;
Inc(AMem);
AMem^:= $E0 + AReg;
Inc(AMem);
end;
procedure CallReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $FF;
Inc(AMem);
AMem^:= $D0 + AReg;
Inc(AMem);
end;
procedure Cld(var AMem: PByte);
begin
AMem^:= $FC;
Inc(AMem);
end;
procedure Std(var AMem: PByte);
begin
AMem^:= $FD;
Inc(AMem);
end;
procedure Nop(var AMem: PByte);
begin
AMem^:= $90;
Inc(AMem);
end;
procedure Stc(var AMem: PByte);
begin
AMem^:= $F9;
Inc(AMem);
end;
procedure Clc(var AMem: PByte);
begin
AMem^:= $F8;
Inc(AMem);
end;
procedure Cmc(var AMem: PByte);
begin
AMem^:= $F5;
Inc(AMem);
end;
procedure XchgReg32Rand(var AMem: PByte);
begin
AMem^:= $87;
Inc(AMem);
AMem^:= $C0 + RandomReg32All*9;
Inc(AMem);
end;
function XchgReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
if AReg2 = REG_EAX then
begin
AReg2:= AReg1;
AReg1:= REG_EAX;
end;
if AReg1 = REG_EAX then
ThrowTheDice(Result, 2)
else
Result:= 2;
if Result = 2 then
begin
AMem^:= $87;
Inc(AMem);
AMem^:= $C0 + AReg2*8 + AReg1;
end else
AMem^:= $90 + AReg2;
Inc(AMem);
end;
procedure MovReg32Rand(var AMem: PByte);
begin
AMem^:= $8B;
Inc(AMem);
AMem^:= $C0 + RandomReg32All*9;
Inc(AMem);
end;
procedure IncReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $40 + AReg;
Inc(AMem);
end;
procedure DecReg32(var AMem: PByte; AReg: Byte);
begin
AMem^:= $48 + AReg;
Inc(AMem);
end;
function IncReg32Rand(var AMem: PByte): Byte;
begin
Result:= RandomReg32All;
IncReg32(AMem, Result);
end;
function DecReg32Rand(var AMem: PByte): Byte;
begin
Result:= RandomReg32All;
DecReg32(AMem, Result);
end;
function LeaReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $8D;
Inc(AMem);
if AReg2 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg1*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg1*8 + AReg2;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
function LeaReg32Reg32MemIdx8(var AMem: PByte; AReg1, AReg2, AIdx: Byte): Byte;
begin
Result:= 3;
AMem^:= $8D;
Inc(AMem);
AMem^:= $40 + AReg1*8 + AReg2;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
AMem^:= AIdx;
Inc(AMem);
end;
procedure LeaReg32Rand(var AMem: PByte);
begin
AMem^:= $8D;
Inc(AMem);
AMem^:= $00 + RandomReg32EspEbp*9;
Inc(AMem);
end;
procedure LeaReg32Addr32(var AMem: PByte; AReg, AAddr: Cardinal);
begin
AMem^:= $8D;
Inc(AMem);
AMem^:= $05 + AReg*8;
Inc(AMem);
PCardinal(AMem)^:= AAddr;
Inc(AMem,4);
end;
procedure TestReg32Rand(var AMem: PByte);
begin
AMem^:= $85;
Inc(AMem);
AMem^:= $C0 + RandomReg32All*9;
Inc(AMem);
end;
procedure OrReg32Rand(var AMem: PByte);
begin
AMem^:= $0B;
Inc(AMem);
AMem^:= $C0 + RandomReg32All*9;
Inc(AMem);
end;
procedure AndReg32Rand(var AMem: PByte);
begin
AMem^:= $23;
Inc(AMem);
AMem^:= $C0 + RandomReg32All*9;
Inc(AMem);
end;
procedure TestReg8Rand(var AMem: PByte);
var
LReg8: Byte;
begin
LReg8:= RandomReg8ABCD;
AMem^:= $84;
Inc(AMem);
AMem^:= $C0 + LReg8*9;
Inc(AMem);
end;
procedure OrReg8Rand(var AMem: PByte);
var
LReg8: Byte;
begin
LReg8:= RandomReg8ABCD;
AMem^:= $0A;
Inc(AMem);
AMem^:= $C0 + LReg8*9;
Inc(AMem);
end;
procedure AndReg8Rand(var AMem: PByte);
var
LReg8: Byte;
begin
LReg8:= RandomReg8ABCD;
AMem^:= $22;
Inc(AMem);
AMem^:= $C0 + LReg8*9;
Inc(AMem);
end;
procedure CmpRegRegNum8Rand(var AMem: PByte);
var
LRnd: Byte;
begin
LRnd:= Random(3);
AMem^:= $3A + LRnd;
Inc(AMem);
if LRnd < 2 then
LRnd:= Random($40) + $C0
else
LRnd:= Random($100);
AMem^:= LRnd;
Inc(AMem);
end;
function CmpReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $39;
Inc(AMem);
AMem^:= $C0 + AReg1 + AReg2*8;
Inc(AMem);
end;
procedure CmpReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $83;
Inc(AMem);
AMem^:= $F8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure CmpReg32RandNum8(var AMem: PByte; AReg: Byte);
begin
CmpReg32Num8(AMem, AReg, Random($100));
end;
procedure CmpRandReg32RandNum8(var AMem: PByte);
begin
CmpReg32RandNum8(AMem, RandomReg32All);
end;
procedure JmpNum8(var AMem: PByte; ANum: Byte);
var
LRnd: Byte;
begin
LRnd:= Random(16);
if LRnd = 16 then
AMem^:= $EB
else
AMem^:= $70 + LRnd;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure SubReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte);
begin
AMem^:= $29;
Inc(AMem);
AMem^:= AReg2*8 + AReg1 + $C0;
Inc(AMem);
end;
procedure SubReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $83;
Inc(AMem);
AMem^:= $E8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
function SubReg32Num8Rand(var AMem: PByte; ANum: Byte): Byte;
begin
Result:= RandomReg32All;
SubReg32Num8(AMem, Result, ANum);
end;
function AddReg32Num8Rand(var AMem: PByte; ANum: Byte): Byte;
begin
Result:= RandomReg32All;
AddReg32Num8(AMem, Result, ANum);
end;
procedure SubAlNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $2C;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure TestAlNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $A8;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure TestAlNum8Rand(var AMem: PByte);
begin
TestAlNum8(AMem, Random($100));
end;
procedure SubReg8Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:=$80;
Inc(AMem);
AMem^:=$E8 + AReg;
Inc(AMem);
AMem^:=ANum;
Inc(AMem);
end;
procedure SubReg8Num8Rand(var AMem: PByte; ANum: Byte);
var
LReg8: Byte;
begin
LReg8:= RandomReg8ABCD;
SubReg8Num8(AMem, LReg8, ANum);
end;
procedure TestReg8Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $F6;
Inc(AMem);
AMem^:= $C0+AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure TestReg8Num8Rand(var AMem: PByte);
begin
TestReg8Num8(AMem, RandomReg8ABCD, Random($100));
end;
procedure AddReg8Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $80;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure AddReg8Num8Rand(var AMem: PByte; ANum: Byte);
var
LReg8: Byte;
begin
LReg8:= RandomReg8ABCD;
AddReg8Num8(AMem, LReg8, ANum);
end;
procedure AddAlNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $04;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure FNop(var AMem: PByte);
begin
AMem^:= $D9;
Inc(AMem);
AMem^:= $D0;
Inc(AMem);
end;
procedure OrReg16Rand(var AMem:PByte);
var
LReg16: Byte;
begin
LReg16:= RandomReg16All;
AMem^:= $66;
Inc(AMem);
AMem^:= $0B;
Inc(AMem);
AMem^:= $C0 + LReg16*9;
Inc(AMem);
end;
procedure TestReg16Rand(var AMem: PByte);
var
LReg16: Byte;
begin
LReg16:= RandomReg16All;
AMem^:= $66;
Inc(AMem);
AMem^:= $85;
Inc(AMem);
AMem^:= $C0 + LReg16*9;
Inc(AMem);
end;
procedure AndReg16Rand(var AMem: PByte);
var
LReg16: Byte;
begin
LReg16:= RandomReg16All;
AMem^:= $66;
Inc(AMem);
AMem^:= $23;
Inc(AMem);
AMem^:= $C0 + LReg16*9;
Inc(AMem);
end;
procedure Cdq(var AMem:PByte);
begin
AMem^:= $99;
Inc(AMem);
end;
procedure ShlReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $E0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure ShlReg32RandNum8FullRand(var AMem: PByte);
begin
ShlReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure ShrReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $E8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure ShrReg32RandNum8FullRand(var AMem: PByte);
begin
ShrReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure SalReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $F0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure SalReg32RandNum8FullRand(var AMem: PByte);
begin
SalReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure SarReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $F8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure SarReg32RandNum8FullRand(var AMem: PByte);
begin
SarReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure RolReg8Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C0;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RolReg8RandNum8FullRand(var AMem: PByte);
begin
RolReg8Num8(AMem, RandomReg8ABCD, Random($20)*8);
end;
procedure RorReg8Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C0;
Inc(AMem);
AMem^:= $C8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RorReg8RandNum8FullRand(var AMem: PByte);
begin
RorReg8Num8(AMem, RandomReg8ABCD, Random($20)*8);
end;
procedure RolReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RolReg32RandNum8FullRand(var AMem: PByte);
begin
RolReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure RorReg32Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $C1;
Inc(AMem);
AMem^:= $C8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RorReg32RandNum8FullRand(var AMem: PByte);
begin
RorReg32Num8(AMem, RandomReg32All, Random(8)*$20);
end;
procedure TestAxNum16(var AMem: PByte; ANum: Word);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $A9;
Inc(AMem);
PWord(AMem)^:= ANum;
Inc(AMem,2);
end;
procedure TestAxNum16Rand(var AMem: PByte);
begin
TestAxNum16(AMem, Random($10000));
end;
procedure CmpAxNum16(var AMem: PByte; ANum: Word);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $3D;
Inc(AMem);
PWord(AMem)^:= ANum;
Inc(AMem,2);
end;
procedure CmpAxNum16Rand(var AMem: PByte);
begin
TestAxNum16(AMem, Random($10000));
end;
procedure PushNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $6A;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure PushNum8Rand(var AMem: PByte);
begin
PushNum8(AMem, Random($100));
end;
function XorRand(var AMem: PByte): Word;
var
LRnd: Byte;
LRes: PWord;
begin
LRes:= Pointer(AMem);
LRnd:= Random(5);
AMem^:= $30 + LRnd;
Inc(AMem);
if LRnd = 4 then
AMem^:= Random($100)
else
AMem^:= Random(7)*9 + Random(8) + 1 + $C0;
Inc(AMem);
Result:= LRes^;
end;
procedure InvertXor(var AMem: PByte; AXor: Word);
begin
PWord(AMem)^:= AXor;
Inc(AMem,2);
end;
procedure DoubleXorRand(var AMem: PByte);
begin
InvertXor(AMem, XorRand(AMem));
end;
function NotReg32(var AMem: PByte; AReg: Byte): Byte;
begin
Result:= 2;
AMem^:= $F7;
Inc(AMem);
AMem^:= $D0 + AReg;
Inc(AMem);
end;
function NegReg32(var AMem: PByte; AReg: Byte): Byte;
begin
Result:= 2;
AMem^:= $F7;
Inc(AMem);
AMem^:= $D8 + AReg;
Inc(AMem);
end;
function NotRand(var AMem: PByte): Word;
var
LRes: PWord;
begin
LRes:= Pointer(AMem);
AMem^:= $F6 + Random(1);
Inc(AMem);
AMem^:= $D0 + Random(8);
Inc(AMem);
Result:= LRes^;
end;
procedure InvertNot(var AMem: PByte; ANot: Word);
begin
PWord(AMem)^:= ANot;
Inc(AMem,2);
end;
procedure DoubleNotRand(var AMem: PByte);
begin
InvertNot(AMem, NotRand(AMem));
end;
function NegRand(var AMem: PByte): Word;
var
LRes: PWord;
begin
LRes:= Pointer(AMem);
AMem^:= $F6 + Random(1);
Inc(AMem);
AMem^:= $D8 + Random(8);
Inc(AMem);
Result:= LRes^;
end;
procedure InvertNeg(var AMem: PByte; ANeg: Word);
begin
PWord(AMem)^:= ANeg;
Inc(AMem,2);
end;
procedure DoubleNegRand(var AMem: PByte);
begin
InvertNeg(AMem, NegRand(AMem));
end;
procedure AddReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure AddReg16Num8Rand(var AMem: PByte; ANum: Byte);
begin
AddReg16Num8(AMem, RandomReg16All, ANum);
end;
procedure OrReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $C8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure OrReg16Num8Rand(var AMem: PByte; ANum: Byte);
begin
OrReg16Num8(AMem, RandomReg16All, ANum);
end;
procedure AndReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $E0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure AndReg16Num8Rand(var AMem: PByte; ANum: Byte);
begin
AndReg16Num8(AMem, RandomReg16All, ANum);
end;
procedure SubReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $E8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure SubReg16Num8Rand(var AMem: PByte; ANum: Byte);
begin
SubReg16Num8(AMem, RandomReg16All, ANum);
end;
procedure XorReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $F0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure XorReg16Num8Rand(var AMem: PByte; ANum: Byte);
begin
XorReg16Num8(AMem, RandomReg16All, ANum);
end;
procedure CmpReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $83;
Inc(AMem);
AMem^:= $F8 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure CmpReg16Num8RandRand(var AMem: PByte);
begin
CmpReg16Num8(AMem, RandomReg16All, Random($100));
end;
procedure RolReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $C1;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RolReg16RandNum8FullRand(var AMem: PByte);
begin
RolReg16Num8(AMem, RandomReg16All, Random($10)*$10);
end;
procedure RorReg16Num8(var AMem: PByte; AReg, ANum: Byte);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $C1;
Inc(AMem);
AMem^:= $C1 + AReg;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure RorReg16RandNum8FullRand(var AMem: PByte);
begin
RorReg16Num8(AMem, RandomReg16All, Random($10)*$10);
end;
function XchgRand(var AMem: PByte): Word;
var
LRes: PWord;
LRnd: Byte;
begin
LRes:= Pointer(AMem);
LRnd:= Random(4);
case LRnd of
0,1: AMem^:= $66 + LRnd;
2,3: AMem^:= $86 + LRnd - 2;
end;
Inc(AMem);
case LRnd of
0,1: AMem^:= $90 + Random(8);
2,3: AMem^:= $C0 + Random($10);
end;
Inc(AMem);
Result:= LRes^;
end;
procedure InvertXchg(var AMem: PByte; AXchg: Word);
begin
PWord(AMem)^:= AXchg;
Inc(AMem,2);
end;
procedure DoubleXchgRand(var AMem: PByte);
begin
InvertXchg(AMem, XchgRand(AMem));
end;
procedure LoopNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $E2;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure JecxzNum8(var AMem: PByte; ANum: Byte);
begin
AMem^:= $E3;
Inc(AMem);
AMem^:= ANum;
Inc(AMem);
end;
procedure MovzxEcxCl(var AMem: PByte);
begin
AMem^:= $0F;
Inc(AMem);
AMem^:= $B6;
Inc(AMem);
AMem^:= $C9;
Inc(AMem);
end;
procedure MovReg32Reg32Rand(var AMem: PByte; AReg: Byte);
begin
AMem^:= $8B;
Inc(AMem);
AMem^:= $C0 + 8*AReg + RandomReg32All;
Inc(AMem);
end;
procedure CmpEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $3D;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure CmpEaxNum32Rand(var AMem: PByte);
begin
CmpEaxNum32(AMem, Random($FFFFFFFF));
end;
procedure TestEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $A9;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure TestEaxNum32Rand(var AMem: PByte);
begin
TestEaxNum32(AMem, Random($FFFFFFFF));
end;
procedure SubEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $2D;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure AddEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $05;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure AndEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $25;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure OrEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $0D;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure XorEaxNum32(var AMem: PByte; ANum: Cardinal);
begin
AMem^:= $35;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure AddReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure OrReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $C8 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure AndReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $E0 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure SubReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $E8 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure XorReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $F0 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end;
procedure XorReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte);
begin
AMem^:= $31;
Inc(AMem);
AMem^:= $C0+AReg2*8 + AReg1;
Inc(AMem);
end;
function XorReg32RegMem(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $33;
Inc(AMem);
if AReg2 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg1*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg1*8 + AReg2;
Inc(AMem);
if AReg2 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
function XorRegMemReg32(var AMem: PByte; AReg1, AReg2: Byte): Byte;
begin
Result:= 2;
AMem^:= $31; //xor
Inc(AMem);
if AReg1 = REG_EBP then
begin
Inc(Result);
AMem^:= AReg2*8 + $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg2*8 + AReg1;
Inc(AMem);
if AReg1 = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
end;
procedure CmpReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal);
begin
AMem^:= $81;
Inc(AMem);
AMem^:= $F8 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
function TestReg32Num32(var AMem: PByte; AReg: Byte; ANum: Cardinal): Byte;
begin
if AReg = REG_EAX then
ThrowTheDice(Result, 2)
else
Result:= 2;
Inc(Result, 4);
if Result = 6 then
begin
AMem^:= $F7;
Inc(AMem);
AMem^:= $C0 + AReg;
Inc(AMem);
PCardinal(AMem)^:= ANum;
Inc(AMem, 4);
end else
TestEaxNum32(AMem, ANum);
end;
procedure TestReg32Reg32(var AMem: PByte; AReg1, AReg2: Byte);
begin
AMem^:= $85;
Inc(AMem);
AMem^:= AReg2*8 + AReg1 + $C0;
Inc(AMem);
end;
function TestRegMemNum32(var AMem: PByte; AReg: Byte; ANum: Cardinal): Byte;
begin
Result:= 6;
AMem^:= $F7;
Inc(AMem);
if AReg = REG_EBP then
begin
Inc(Result);
AMem^:= $45;
Inc(AMem);
AMem^:= $00;
end else
AMem^:= AReg;
Inc(AMem);
if AReg = REG_ESP then
begin
Inc(Result);
AMem^:= $24;
Inc(AMem);
end;
PCardinal(AMem)^:= ANum;
Inc(AMem,4);
end;
procedure AddReg32RandNum32(var AMem: PByte; ANum: Cardinal);
begin
AddReg32Num32(AMem, RandomReg32All, ANum);
end;
procedure OrReg32RandNum32(var AMem: PByte; ANum: Cardinal);
begin
OrReg32Num32(AMem, RandomReg32All, ANum);
end;
procedure AndReg32RandNum32(var AMem: PByte; ANum: Cardinal);
begin
AndReg32Num32(AMem, RandomReg32All, ANum);
end;
procedure SubReg32RandNum32(var AMem: PByte; ANum: Cardinal);
begin
SubReg32Num32(AMem, RandomReg32All, ANum);
end;
procedure XorReg32RandNum32(var AMem: PByte; ANum: Cardinal);
begin
XorReg32Num32(AMem, RandomReg32All, ANum);
end;
procedure CmpReg32RandNum32Rand(var AMem: PByte);
begin
CmpReg32Num32(AMem, RandomReg32All, Random($FFFFFFFF));
end;
procedure TestReg32RandNum32Rand6(var AMem: PByte);
var
LLen: Byte;
begin
LLen:= TestReg32Num32(AMem, RandomReg32All, Random($FFFFFFFF));
if LLen = 5 then
begin
AMem^:= $90;
Inc(AMem);
end;
end;
procedure MovReg32Num32Rand(var AMem: PByte; AReg: Byte);
begin
MovReg32Num32(AMem, AReg, Random($FFFFFFFF));
end;
procedure MovReg16Num16(var AMem: PByte; AReg: Byte; ANum: Word);
begin
AMem^:= $66;
Inc(AMem);
AMem^:= $B8 + AReg;
Inc(AMem);
PWord(AMem)^:= ANum;
Inc(AMem,2);
end;
procedure MovReg16Num16Rand(var AMem: PByte; AReg: Byte);
begin
MovReg16Num16(AMem, AReg, Random($10000));
end;
procedure GenerateRubbishCode(AMem: Pointer; ASize, AVirtAddr: Cardinal); stdcall;
procedure InsertRandomInstruction(var AMem:PByte; ALength: Byte; var ARemaining: Cardinal);
var
LRegAny: Byte;
LMaxDice,LXRem: Cardinal;
begin
case ALength of
1:
begin
ThrowTheDice(LMaxDice, 50);
case LMaxDice of
001..010: Cld(AMem);
011..020: Nop(AMem);
021..030: Stc(AMem);
031..040: Clc(AMem);
041..050: Cmc(AMem);
end;
end;
2:
begin
ThrowTheDice(LMaxDice, 145);
case LMaxDice of
001..010: XchgReg32Rand(AMem);
011..020: MovReg32Rand(AMem);
021..030:
begin
LRegAny:= IncReg32Rand(AMem);
DecReg32(AMem, LRegAny);
end;
031..040:
begin
LRegAny:= DecReg32Rand(AMem);
IncReg32(AMem, LRegAny);
end;
041..050:
begin
LRegAny:= PushReg32Rand(AMem);
PopReg32(AMem, LRegAny);
end;
051..060: LeaReg32Rand(AMem);
061..070: TestReg32Rand(AMem);
071..080: OrReg32Rand(AMem);
081..090: AndReg32Rand(AMem);
091..100: TestReg8Rand(AMem);
101..110: OrReg8Rand(AMem);
111..120: AndReg8Rand(AMem);
121..130: CmpRegRegNum8Rand(AMem);
131..132:
begin
Std(AMem);
Cld(AMem);
end;
133..134: JmpNum8(AMem, 0);
135..138: SubAlNum8(AMem, 0);
139..140: TestAlNum8Rand(AMem);
141..142: AddAlNum8(AMem, 0);
143..145: FNop(AMem);
end;
end;
3:
begin
ThrowTheDice(LMaxDice, 205);
case LMaxDice of
001..010:
begin
JmpNum8(AMem, 1);
InsertRandomInstruction(AMem, 1, LXRem);
end;
011..020: SubReg32Num8Rand(AMem, 0);
021..030: AddReg32Num8Rand(AMem, 0);
031..040:
begin
LRegAny:= PushReg32Rand(AMem);
IncReg32(AMem, LRegAny);
PopReg32(AMem, LRegAny);
end;
041..050:
begin
LRegAny:= PushReg32Rand(AMem);
DecReg32(AMem, LRegAny);
PopReg32(AMem, LRegAny);
end;
051..060: CmpRandReg32RandNum8(AMem);
061..070: TestReg8Num8Rand(AMem);
071..080: SubReg8Num8Rand(AMem,0);
081..090: AddReg8Num8Rand(AMem,0);
091..100: AndReg16Rand(AMem);
101..110: TestReg16Rand(AMem);
111..120: OrReg16Rand(AMem);
121..130: ShlReg32RandNum8FullRand(AMem);
131..140: ShrReg32RandNum8FullRand(AMem);
141..150: SalReg32RandNum8FullRand(AMem);
151..160: SarReg32RandNum8FullRand(AMem);
161..170: RolReg8RandNum8FullRand(AMem);
171..180: RorReg8RandNum8FullRand(AMem);
181..190: RolReg32RandNum8FullRand(AMem);
191..200: RorReg32RandNum8FullRand(AMem);
201..203:
begin
PushReg32(AMem, REG_EDX);
Cdq(AMem);
PopReg32(AMem, REG_EDX);
end;
204..205:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 1, LXRem);
PopReg32(AMem, LRegAny);
end;
end;
end;
4:
begin
ThrowTheDice(LMaxDice, 170);
case LMaxDice of
001..020:
begin
JmpNum8(AMem, 2);
InsertRandomInstruction(AMem, 2, LXRem);
end;
021..040:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 2, LXRem);
PopReg32(AMem, LRegAny);
end;
041..050: TestAxNum16Rand(AMem);
051..060: CmpAxNum16Rand(AMem);
061..063: DoubleXorRand(AMem);
064..066: DoubleNegRand(AMem);
067..070: DoubleNotRand(AMem);
071..080: AddReg16Num8Rand(AMem, 0);
081..090: OrReg16Num8Rand(AMem, 0);
091..100: AndReg16Num8Rand(AMem, $FF);
101..110: SubReg16Num8Rand(AMem, 0);
111..120: XorReg16Num8Rand(AMem, 0);
121..130: CmpReg16Num8RandRand(AMem);
131..140: RolReg16RandNum8FullRand(AMem);
141..150: RorReg16RandNum8FullRand(AMem);
151..155: DoubleXchgRand(AMem);
156..160:
begin
LRegAny:= PushReg32Rand(AMem);
MovReg32Reg32Rand(AMem,LRegAny);
PopReg32(AMem, LRegAny);
end;
161..170:
begin
PushReg32Rand(AMem);
AddReg32Num8(AMem, REG_ESP, 4);
end;
end;
end;
5:
begin
ThrowTheDice(LMaxDice, 150);
case LMaxDice of
001..030:
begin
JmpNum8(AMem, 3);
InsertRandomInstruction(AMem, 3, LXRem);
end;
031..060:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 3, LXRem);
PopReg32(AMem, LRegAny);
end;
061..070:
begin
LRegAny:= PushReg32Rand(AMem);
PushNum8Rand(AMem);
PopReg32(AMem, LRegAny);
PopReg32(AMem, LRegAny);
end;
071..080:
begin
PushNum8Rand(AMem);
AddReg32Num8(AMem, REG_ESP, 4);
end;
081..090: AddEaxNum32(AMem, 0);
091..100: OrEaxNum32(AMem, 0);
101..110: AndEaxNum32(AMem, $FFFFFFFF);
111..120: SubEaxNum32(AMem, 0);
121..130: XorEaxNum32(AMem, 0);
131..140: CmpEaxNum32Rand(AMem);
141..150: TestEaxNum32Rand(AMem);
end;
end;
6:
begin
ThrowTheDice(LMaxDice, 161);
case LMaxDice of
001..040:
begin
JmpNum8(AMem, 4);
InsertRandomInstruction(AMem, 4, LXRem);
end;
041..080:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 4, LXRem);
PopReg32(AMem, LRegAny);
end;
081..090: AddReg32RandNum32(AMem, 0);
091..100: OrReg32RandNum32(AMem, 0);
101..110: AndReg32RandNum32(AMem, $FFFFFFFF);
111..120: SubReg32RandNum32(AMem, 0);
121..130: XorReg32RandNum32(AMem, 0);
131..140: CmpReg32RandNum32Rand(AMem);
141..150: TestReg32RandNum32Rand6(AMem);
151..161:
begin
LRegAny:= PushReg32Rand(AMem);
MovReg16Num16Rand(AMem, LRegAny);
PopReg32(AMem, LRegAny);
end;
end;
end;
7:
begin
ThrowTheDice(LMaxDice, 110);
case LMaxDice of
001..050:
begin
JmpNum8(AMem, 5);
InsertRandomInstruction(AMem, 5, LXRem);
end;
051..100:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 5, LXRem);
PopReg32(AMem, LRegAny);
end;
101..110:
begin
LRegAny:= PushReg32Rand(AMem);
MovReg32Num32Rand(AMem, LRegAny);
PopReg32(AMem, LRegAny);
end;
end;
end;
8:
begin
ThrowTheDice(LMaxDice, 120);
case LMaxDice of
001..060:
begin
JmpNum8(AMem, 6);
InsertRandomInstruction(AMem, 6, LXRem);
end;
061..120:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, 6, LXRem);
PopReg32(AMem, LRegAny);
end;
end;
end;
9..10:
begin
ThrowTheDice(LMaxDice, 200);
case LMaxDice of
001..100:
begin
JmpNum8(AMem, ALength - 2);
InsertRandomInstruction(AMem, ALength - 2, LXRem);
end;
101..200:
begin
LRegAny:= PushReg32Rand(AMem);
InsertRandomInstruction(AMem, ALength - 2, LXRem);
PopReg32(AMem, LRegAny);
end;
end;
end;
end;
if ALength < 11 then Dec(ARemaining, ALength);
end;
var
LPB: PByte;
LReg: Byte;
LDice, LDecSize, LSize, LAddr: Cardinal;
begin
LPB:= AMem;
LSize:= ASize;
while LSize > 0 do
begin
ThrowTheDice(LDice, 6);
if LSize < 32 then LDice:= 1;
if AVirtAddr = 0 then LDice:= 1;
if LDice < 6 then
begin
ThrowTheDice(LDice, LSize*100);
if LSize = 1 then LDice:= 1;
case LDice of
001..002: InsertRandomInstruction(LPB, 1, LSize);
101..104: InsertRandomInstruction(LPB, 2, LSize);
201..208: InsertRandomInstruction(LPB, 3, LSize);
301..316: InsertRandomInstruction(LPB, 4, LSize);
401..432: InsertRandomInstruction(LPB, 5, LSize);
501..564: InsertRandomInstruction(LPB, 6, LSize);
else InsertRandomInstruction(LPB, (LDice + 99) div 100, LSize);
end;
end else begin
ThrowTheDice(LDice, 63);
if LDice < 57 then
LDecSize:= LSize
else
LDecSize:= 0;
case LDice of
1..18:
begin
RelJmpAddr32(LPB, LSize - 5);
PutRandomBuffer(LPB, LSize - 5);
end;
19..37:
begin
LReg:= PushReg32Rand(LPB);
ThrowTheDice(LDice);
if LDice > 3 then
LAddr:= LSize - 8
else
LAddr:= LSize - 10;
RelCallAddr(LPB,LAddr);
PutRandomBuffer(LPB,LAddr);
if LDice > 3 then
PopReg32(LPB, LReg)
else
AddReg32Num8(LPB, REG_ESP, 4);
PopReg32(LPB, LReg);
end;
38..56:
begin
if LSize-3 < $7D then
LAddr:= LSize - 4
else
LAddr:= $7C;
LAddr:= Random(LAddr) + 2;
LoopNum8(LPB, LAddr);
JecxzNum8(LPB, LAddr - 2);
PutRandomBuffer(LPB, LAddr - 2);
IncReg32(LPB, REG_ECX);
LDecSize:= LAddr + 3;
end;
57..63:
begin
if LSize - 7 < $7D then
LAddr:= LSize - 7
else
LAddr:= $75;
LAddr:= Random(LAddr) + 3;
PushReg32(LPB, REG_ECX);
MovzxEcxCl(LPB);
GenerateRubbishCode(LPB, LAddr - 3, 0);
Inc(LPB, LAddr - 3);
LoopNum8(LPB, $FE - LAddr);
PopReg32(LPB, REG_ECX);
LDecSize:= LAddr + 4;
end;
end;
Dec(LSize, LDecSize);
end;
end;
end;
initialization
Randomize;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.