text stringlengths 14 6.51M |
|---|
{ A unit to watch the heap, i.e. check if all pointers that were
allocated are released again. It is meant as a debugging help to
detect memory leaks.
Use it in the main program before all other units. When, at the
end of the program, some pointers that were allocated, have not
been released, the unit writes a report to StdErr or another file
(see below). Only pointers allocated via the Pascal mechanisms
(New, GetMem) are tracked, not pointers allocated with direct libc
calls or from C code. After a runtime error, pointers are not
checked.
Note that many units and libraries allocate memory for their own
purposes and don't always release it at the end. Therefore, the
usefulness of this unit is rather limited.
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal 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, or (at your
option) any later version.
GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
unit HeapMon;
interface
uses GPC;
{ This unit is automatically activated when used. The following
declarations are only needed for special purposes. }
{ The report generated at the end can be redirected to a certain
file by pointing HeapMonOutput to it. If not set, the report will
be printed to the error messages file given with `--gpc-rts'
options if given, and StdErr otherwise. }
var
HeapMonOutput: ^Text = nil;
{ HeapMonReport can be used to print a report on non-released memory
blocks at an arbitrary point during a program run to the file f.
It is invoked automatically at the end, so usually you don't have
to call it. Returns True if any non-released blocks were found,
False otherwise. }
function HeapMonReport (var f: Text; DoRestoreTerminal: Boolean) = Res: Boolean; attribute (ignorable);
implementation
var
HeapMonitorMark: Pointer = nil;
function HeapMonReport (var f: Text; DoRestoreTerminal: Boolean) = Res: Boolean;
var
Count: Integer;
Size: SizeType;
procedure CountBlock (aPointer: Pointer; aSize: SizeType; aCaller: Pointer);
begin
if not Res then
begin
Res := True;
if DoRestoreTerminal then RestoreTerminal (True);
WriteLn (f, 'Heap monitor: Pointers not disposed (caller, size):');
WriteLn (f, ReturnAddr2Hex (aCaller))
end;
Inc (Count);
Inc (Size, aSize);
WriteLn (f, ReturnAddr2Hex (aCaller), ' ', aSize, ' address: ', PtrCard (aPointer))
end;
begin
Res := False;
Count := 0;
Size := 0;
ForEachMarkedBlock (HeapMonitorMark, CountBlock);
if Res then WriteLn (f, 'Total: ', Count, ' pointers, total size: ', Size)
end;
to begin do
Mark (HeapMonitorMark);
to end do
if (HeapMonitorMark <> nil) and (ErrorAddr = nil) then
begin
var TmpFile: Text;
if HeapMonOutput = nil then
if WriteErrorMessage ('', False) then
begin
var p: Pointer;
p := SuspendMark;
AssignHandle (TmpFile, RTSErrorFD, True);
ResumeMark (p);
Rewrite (TmpFile);
HeapMonOutput := @TmpFile
end
else
HeapMonOutput := @StdErr;
var Res: Boolean = HeapMonReport (HeapMonOutput^, True);
Close (TmpFile);
if Res then Halt (7)
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name:
Author: Roman
Purpose: Базовый класс для всех трейдеров. Реализует интерфейс IStockTrader
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Trader.Base;
{$I Compiler.inc}
{$DEFINE IGNORE_UNKNOWN_PROPERTIES}
{$DEFINE USE_NONCACHED_RECALCULATION} //Для оптимизации. Во включенном режиме удаляет пре-расчет и кеширование у индикаторов
interface
uses
Classes, Math,Contnrs, Controls, SysUtils, BaseUtils, ActnList, Forms, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Indicators, StockChart.Definitions.Drawing,
Serialization, FC.Definitions, FC.Trade.Properties;
type
{ TStockTrader }
TStockTraderBase = class;
TStockTraderClass = class of TStockTraderBase;
TLastOrderType = (lotNone,lotBuy,lotSell);
TLogRecord = class
public
DateTime: TDateTime;
Text : string;
end;
//Псевдо-интерфейс, необходимый для генерации уникального GUID
//Будем использовать его в ExternalData экспертов, чтобы отличить
//где наш эксперта, а где не наш
IStockTraderExternalIdentifier = interface (ISCAttribute)
['{40DE82A4-840E-4AA3-A89C-78BBE85691D0}']
function GetIdentification: string;
function GetTraderIID: TGUID;
end;
//... и собственно класс, его реализующий
TStockTraderExternalIdentifier = class (TNameValuePersistentObjectRefCounted,IStockTraderExternalIdentifier,ISCAttribute)
private
FTraderIID: TGUID;
FIdentification: string;
procedure SetIdentification(const Value: string);
function GetIdentification: string;
function GetTraderIID: TGUID;
protected
procedure OnDefineValues; override;
property Identification: string read FIdentification write SetIdentification;
property TraderIID: TGUID read FTraderIID write FTraderIID;
constructor Create; virtual;
end;
TStockTraderExternalIdentifierClass = class of TStockTraderExternalIdentifier;
TStockBrokerEventHandler = class;
//Базовый
TStockTraderBase = class (TNameValuePersistentObjectRefCounted,IStockTrader,IPropertyChangeHandler)
private
FExperts : ISCIndicatorCollection;
FExternalIdentifiers: TInterfaceList; //of IStockTraderExternalIdentifier
FExternalIdentifierClass: TStockTraderExternalIdentifierClass;
FIID : TGUID;
FCategory : string;
FName : string;
FOrders : IStockOrderCollection;
FHandlers : TInterfaceList;
FLastTime : TDateTime;
FBroker : IStockBroker;
//FMessages : IStockTraderMessageCollection;
FProject : IStockProject;
FState : TSCIndicatorStates;
FBrokerEventHandler : TStockBrokerEventHandler;
//
FTestBenchDialog: TForm;
FTestBenchDialogAction: TAction;
//Свойства (настраиваемые)
FPropMaxSubsidence : TPropertyInt;
FPropTrailingStop : TPropertyInt;
FPropTrailingStopDescend: TPropertyReal;
FPropEnoughProfit : TPropertyInt;
//Способ минимизации рисков
FMinimizationRiskType : TPropertyMinimizationLossType;
FPropLotDefaultRateSize : TPropertyReal;
FPropLotDynamicRate : TPropertyYesNo;
FPropLotDynamicRateSize : TPropertyReal;
FCachedPropMaxSubsidence: TStockRealNumber;
FCachedPropTrailingStop : TStockRealNumber;
FCachedPropEnoughProfit : TStockRealNumber;
FCachedPropTrailingStopDescend: TStockRealNumber;
FVisibleProperties: TPropertyList;
function GetExternalIdentifier(index: integer): IStockTraderExternalIdentifier;
function GetEventHandler(index: integer): IStockTraderEventHandler;
procedure CachePropertyValues;
procedure OnTestBenchActionUpdate(Sender: TObject);
procedure OnTestBenchActionExecute(Sender: TObject);
protected
FID : TGUID;
//Сериализация (TNameValuePersistentObjectRefCounted)
procedure OnDefineValues; override;
procedure OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); override;
procedure OnWriteValues(const aWriter: INameValueDataWriter); override;
//Вспомогательная функция для находждения "наших" индикаторов на указанном чарте
//Если таковой не находится - мы его создаем. Параметр aIndicatorIdentification должен быть
//уникален для каждого создаваемого индикатора
//Параметр aRegister указывает, регистрировать ли созданный индикатор в трейдере (назначить ему атрибут
//ExternalId трейдера). По регистрации см. также OnAddObject
function CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean=true): ISCIndicator; overload;
function CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean; out aCreated: boolean): ISCIndicator; overload;
//Установка Trailing Stop на основании свойств трейдера
procedure SetTrailingStopAccordingProperty(aOrder: IStockOrder); virtual;
//Установка Stop Stop на основании свойств трейдера
procedure SetStopLossAccordingProperty(aOrder: IStockOrder); virtual;
//Считает, на какой цене сработает Stop Loss или опередивший его Trailing Stop
//Если Trailing Stop не задан, то фукнция просто вернет значение StopLoss
function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber;
//Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop (что быстрее)
//Возвращает знак наоборот: плюс, если действительно есть лосс, и минус, если стоп стоит уже на
//профитной стороне
function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber;
//проверяет, можно ли установить ордеру указанный стоп. Невозможность установки может возникнуть
//из-за близости маркет-цены, установокй не с той стороны и т.д.
function CanSetStopLoss(const aOrder: IStockOrder; aStopLevel:TStockRealNumber): boolean;
//подсчитывает, какойстоп лосс можно поставить для ордера, чтобы он был как можно
//ближе к маркет цене, стандартное использование: подтянуть стоп как можно ближе, чтобы
//он сразу же сработал, если цена двинется в отрицаетельном направлении
function GetNearestStopLossToMarketPrice(const aOrder: IStockOrder): TStockRealNumber;
function IsLevelTooCloseToCurrentPrice(aPriceKind: TStockBrokerPriceKind;aLevel: TSCRealNumber): boolean;
//двигает StopLoss в сторону безубыточности ордера на заданное значение
//При этом проверяется, чтобы
//1) Указанный SL не был хуже текущего
//2) Указанный SL не противоречил текущей цене брокера
function MoveStopLossCloser(const aOrder: IStockOrder; const aSL: TStockRealNumber):boolean;
//возвращает рекомедуемое кол-во лотов
function GetRecommendedLots: TStockOrderLots; virtual;
//Создает пустой экзмепдяр ордера, никуда не открытого.
//Просто создается экзмепляр и регистрирурется в внутр. списке
function CreateEmptyOrder: IStockOrder; virtual;
//Специальные методы-обработчики для наследников, определяющие начало и конец работы треедра
//Вызываются при инициализации трейдера брокером (см. SetBroker)
procedure OnBeginWorkSession; virtual;
procedure OnEndWorkSession; virtual;
procedure OnAddObject(const aIndicator:ISCIndicator; aIndicatorIdentification: string); virtual;
procedure OnRemoveObject(const aIndicator:ISCIndicator); virtual;
procedure OnPropertyChanged(aNotifier:TProperty); virtual;
procedure OnPropertyCreated(aNotifier:TProperty); virtual;
//Оставлено для потомков. Методы, в которых нужно создавать и удалять свои объекты
procedure OnCreateObjects; virtual;
procedure OnReleaseObjects; virtual;
//Событие на изменение "нашего" ордера (который был создан функциями OpenOrder.... или CreateEmptyOrder)
procedure OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); virtual;
procedure GetProperties(aList: TPropertyList); overload; virtual;
function GetProperties: IPropertyCollection; overload;
procedure RegisterProperties(aProperties: array of TProperty);
procedure UnRegisterProperties(aProperties: array of TProperty);
property State : TSCIndicatorStates read FState;
property ExternalIdentifierClass: TStockTraderExternalIdentifierClass read FExternalIdentifierClass write FExternalIdentifierClass;
function ExternalIdentifierCount: integer;
property ExternalIdentifiers[index: integer]: IStockTraderExternalIdentifier read GetExternalIdentifier;
//Найти наш идентификатор в указанном индикаторе. Если нет, возврашает nil;
function FindExternalIdentifier(const aIndicator:ISCIndicator; aIndicatorIdentification: string): IStockTraderExternalIdentifier;
//Добавить на все чарты значок
procedure AddMarkToCharts(const aTime: TDateTime; const aPrice: TStockRealNumber;
const aMarkType: TSCChartMarkKind;
const aMessage: string);
//Добавить на указанный чарт значок
procedure AddMarkToChart( const aTimeInterval: TStockTimeInterval;
const aTime: TDateTime; const aPrice: TStockRealNumber;
const aMarkType: TSCChartMarkKind;
const aMessage: string);
//Выдает НЕмодальный диалог с кнопкой "ПРодолжить". Останавливает процесс, пока виден этот диалог
procedure Pause(const aMessage: string);
//форма для тестирования
function TestBenchDialogClass: TClass; virtual; //TClass = TfmTestBenchDialogClass
property PropMaxSubsidence : TPropertyInt read FPropMaxSubsidence;
property CachedPropMaxSubsidence: TStockRealNumber read FCachedPropMaxSubsidence;
property PropTrailingStop : TPropertyInt read FPropTrailingStop;
property PropTrailingStopDescend: TPropertyReal read FPropTrailingStopDescend;
property PropEnoughProfit : TPropertyInt read FPropEnoughProfit;
property PropLotDefaultRateSize : TPropertyReal read FPropLotDefaultRateSize;
property PropLotDynamicRate : TPropertyYesNo read FPropLotDynamicRate;
property PropLotDynamicRateSize : TPropertyReal read FPropLotDynamicRateSize;
property PropMinimizationRiskType : TPropertyMinimizationLossType read FMinimizationRiskType;
constructor Create; virtual;
public
procedure OnCloseTestBenchDialog(aDialog: TForm); virtual;
//from IPersistentObject
procedure ReadData(const aReader: IDataReader); override;
//from IStockTrader
function GetCategory: string;
function GetName: string;
procedure SetCategory(const aValue: string);
procedure SetName(const aValue : string);
function GetSymbol: string;
function GetID: TGUID;
function GetBroker: IStockBroker;
procedure SetBroker(const aBroker: IStockBroker); virtual;
function GetProject: IStockProject;
procedure SetProject(const aValue : IStockProject); virtual;
//Посчитать
procedure IStockTrader.Update = UpdateStep1;
procedure UpdateStep1(const aTime: TDateTime); virtual;
procedure UpdateStep2(const aTime: TDateTime); virtual; abstract;
procedure Invalidate;
procedure AddEventHandler(const aHandler: IStockTraderEventHandler);
procedure RemoveEventHandler(const aHandler: IStockTraderEventHandler);
procedure AddExpert(const aExpert: ISCExpert);
function RemoveExpert(const aExpert: ISCExpert): integer;
procedure DeleteExpert(index: integer);
function ExpertCount: integer;
function GetExpert(aIndex: integer): ISCExpert;
function IndexOfExpert(const aExpert:ISCExpert): integer;
function GetOrders: IStockOrderCollection;
function ShowPropertyWindow: boolean;
function IsThis(const aTrader: IStockTrader): boolean;
//end of IStockTrader
property IID: TGUID read FIID write FIID;
//Немедленное открытие ордера по текущей цене брокера
//Значения Rate, Take Profit, Stop Loss, Trailing Stop устанавливаются автоматически, в соответствии
//с настройками трейдера
function OpenOrder(aKind: TStockOrderKind; const aComment: string=''): IStockOrder; overload;
//Немедленное открытие ордера по текущей цене брокера
//Значения Rate, Take Profit, Stop Loss, Trailing Stop указываются вручную
function OpenOrder(aKind: TStockOrderKind;
aLots:TStockOrderLots;
aStopLoss, aTakeProfit,aTrailingStop: TSCRealNumber;
const aComment: string=''): IStockOrder; overload;
//открытие Limit или Stop ордера по запрошенной цене
//Значения Rate, Take Profit, Stop Loss, Trailing Stop устанавливаются автоматически, в соответствии
//с настройками трейдера
function OpenOrderAt(aKind: TStockOrderKind;aPrice: TStockRealNumber; const aComment: string=''): IStockOrder; overload;
//открытие Limit или Stop ордера по запрошенной цене
//Значения Rate, Take Profit, Stop Loss, Trailing Stop указываются вручную
function OpenOrderAt(aKind: TStockOrderKind;aPrice: TStockRealNumber;
aLots:TStockOrderLots;
aStopLoss, aTakeProfit,aTrailingStop: TSCRealNumber;
const aComment: string=''): IStockOrder; overload;
//Немедленное закрытие ордера
procedure CloseOrder(const aOrder: IStockOrder;const aComment: string);
//Немедленное закрытие последнего ордера в списке ордера по текущей цене брокера
procedure CloseLastOrder(const aComment: string);
procedure CloseAllSellOrders(const aComment: string);
procedure CloseAllBuyOrders(const aComment: string);
//Брокер может закрывать ордера самостоятельно по TakeProfit или StopLoss
//Чтобы они не болтались в нашем списке, их можно удалить с помощтью данной функции
procedure RemoveClosedOrders;
//Если в списке есть ордера, возвращает тип последнего. Если ордеров нет, возвращает lotNone
function LastOrderType: TLastOrderType;
//Если в списке есть ордера, возвращает статус последнего. Если ордеров нет, возвращает osNothing
function LastOrderState: TStockOrderState;
//Ищет первый ордер, совпадающий по состоянию с указанным. Поиск можно вести как
//с начала в конец, так и с конца в начало (aForward);
function FindOrderByState(aState:TStockOrderState; aForward: boolean):IStockOrder;
function EventHandlerCount: integer;
property EventHandler[index:integer]:IStockTraderEventHandler read GetEventHandler;
procedure Dispose; virtual;
constructor CreateNaked; override;
destructor Destroy; override;
end;
TStockBrokerEventHandler = class (TInterfacedObject,IStockBrokerEventHandler)
private
FOwner: TStockTraderBase;
public
constructor Create (aOwner: TStockTraderBase);
destructor Destroy; override;
procedure OnStart (const aSender: IStockBroker);
procedure OnNewOrder (const aSender: IStockBroker; const aOrder: IStockOrder);
procedure OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
procedure OnNewData (const aSender: IStockBroker; const aSymbol: string);
procedure OnNewMessage (const aSender: IStockBroker; const aMessage: IStockBrokerMessage); overload;
procedure OnNewMessage (const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); overload;
end;
implementation
uses FC.Trade.OrderCollection, FC.Singletons, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.DataUtils, StockChart.Obj,
FC.fmUIDataStorage,Application.Definitions,FC.Trade.Trader.TestBenchDialog_B,
ufmResume;
{ TStockTraderBase }
constructor TStockTraderBase.CreateNaked;
begin
FState:=[isReading];
inherited;
Create;
Exclude(FState,isReading);
end;
constructor TStockTraderBase.Create;
begin
inherited Create;
FBrokerEventHandler:=TStockBrokerEventHandler.Create(self);
IInterface(FBrokerEventHandler)._AddRef;
FExternalIdentifiers:=TInterfaceList.Create;
FOrders:=TStockOrderCollection.Create;
FHandlers:=TInterfaceList.Create;
FExperts:=TSCIndicatorCollection.Create;
//FMessages:=TStockTraderMessageCollection.Create;
FExternalIdentifierClass:=TStockTraderExternalIdentifier;
CreateGUID(FID);
FLastTime:=-1;
FPropMaxSubsidence:=TPropertyInt.Create('Method','Max Subsidence',self);
FPropMaxSubsidence.Value:=30;
FPropTrailingStop:=TPropertyInt.Create('Method','Trailing stop',self);
FPropTrailingStop.Value:=30;
FPropTrailingStopDescend:=TPropertyReal.Create('Method','Trailing Stop Descend Koeff',self);
FPropTrailingStopDescend.HelpString:='Decreases trailing stop while profit grows. '#13#10+'RealTS = TS-k*(Profit-TS)'+#13#10+'where TS-trailing stop, k-descend';
FPropTrailingStopDescend.Value:=0;
FPropEnoughProfit:=TPropertyInt.Create('Method','Enough Profit',self);
FPropEnoughProfit.Value:=300;
FPropLotDefaultRateSize:= TPropertyReal.Create('Lots','Static Value',self);
FPropLotDefaultRateSize.Value:=0.1;
FPropLotDynamicRate := TPropertyYesNo.Create('Lots\Dynamic','Enable',self);
FPropLotDynamicRate.Value:=False;
FPropLotDynamicRateSize:= TPropertyReal.Create('Lots\Dynamic','Percent of Balace',self);
FPropLotDynamicRateSize.Value:=5;
FMinimizationRiskType:=TPropertyMinimizationLossType.Create(self);
RegisterProperties([FPropMaxSubsidence,FPropTrailingStop,FPropTrailingStopDescend,FPropEnoughProfit,
FPropLotDefaultRateSize,FPropLotDynamicRate,FPropLotDynamicRateSize,FMinimizationRiskType]);
CachePropertyValues;
StockBrokerConnectionRegistry.AddBrokerEventHandler(FBrokerEventHandler);
if TestBenchDialogClass<>nil then
begin
FTestBenchDialogAction:=(Workspace.MainFrame as IStockMainFrame).AddMenuItem(UIDataStorage.acTradingTail,false);
FTestBenchDialogAction.Caption:=self.GetName+' - Test Bench';
FTestBenchDialogAction.OnExecute:=OnTestBenchActionExecute;
FTestBenchDialogAction.OnUpdate:=OnTestBenchActionUpdate;
end;
end;
destructor TStockTraderBase.Destroy;
begin
FBrokerEventHandler.FOwner:=nil;
StockBrokerConnectionRegistry.RemoveBrokerEventHandler(FBrokerEventHandler);
IInterface(FBrokerEventHandler)._Release;
FBrokerEventHandler:=nil;
FOrders:=nil;
FExperts:=nil;
//FMessages:=nil;
FreeAndNil(FHandlers);
FreeAndNil(FVisibleProperties);
FreeAndNil(FExternalIdentifiers);
inherited;
end;
procedure TStockTraderBase.Dispose;
var
i: integer;
begin
FreeAndNil(FTestBenchDialog);
if FTestBenchDialogAction<>nil then
(Workspace.MainFrame as IStockMainFrame).RemoveMenuItem(FTestBenchDialogAction);
FreeAndNil(FTestBenchDialogAction);
if FOrders<>nil then
FOrders.Clear;
if FExperts<>nil then
begin
for i:=0 to ExpertCount-1 do
OnRemoveObject(GetExpert(i));
FExperts.Clear;
end;
FreeAndNil(FPropMaxSubsidence);
FreeAndNil(FPropTrailingStop);
FreeAndNil(FPropTrailingStopDescend);
FreeAndNil(FPropEnoughProfit);
FreeAndNil(FPropLotDefaultRateSize);
FreeAndNil(FPropLotDynamicRate);
FreeAndNil(FPropLotDynamicRateSize);
FreeAndNil(FMinimizationRiskType);
if FVisibleProperties<>nil then
FVisibleProperties.Clear;
FBroker:=nil;
end;
function TStockTraderBase.GetID: TGUID;
begin
result:=FID;
end;
procedure TStockTraderBase.Invalidate;
var
i: integer;
begin
FLastTime:=-1;
FOrders.Clear;
for i:=0 to EventHandlerCount-1 do
EventHandler[i].OnInvalidate(self);
end;
function TStockTraderBase.GetCategory: string;
begin
result:=FCategory;
end;
function TStockTraderBase.GetName: string;
begin
result:=FName;
end;
function TStockTraderBase.GetNearestStopLossToMarketPrice(const aOrder: IStockOrder): TStockRealNumber;
var
aMarketPrice: TStockRealNumber;
aStopDelta: TStockRealNumber;
begin
//Берем +1, чтобы наверняка
aStopDelta:=GetBroker.PointToPrice(aOrder.GetSymbol,GetBroker.GetMarketInfo(aOrder.GetSymbol).StopLevel+1);
aStopDelta:=GetBroker.RoundPrice(aOrder.GetSymbol,aStopDelta);
if aOrder.GetKind= okBuy then
begin
aMarketPrice:=GetBroker.GetCurrentPrice(aOrder.GetSymbol,bpkBid);
result:=aMarketPrice+aStopDelta;//Для ордера вверх добавляем (а не отнимаем) к цене спред, чтобы стремится к меньшим потерям
end
else begin
aMarketPrice:=GetBroker.GetCurrentPrice(aOrder.GetSymbol,bpkAsk);
result:=aMarketPrice-aStopDelta; //Для ордера вниз отнимаем от цены спред, чтобы стремится к меньшим потерям
end;
Assert(CanSetStopLoss(aOrder,result));
end;
procedure TStockTraderBase.UpdateStep1(const aTime: TDateTime);
var
i: integer;
begin
if FLastTime>=aTime then
exit;
//Нужно минимизировать риски
if FMinimizationRiskType.Value<>mltNone then
for i:=0 to GetOrders.Count-1 do
SetStopLossAccordingProperty(GetOrders[i]);
//Если установлен динамический Trailing Stop, то нужно обежать все ордера
//и модифицировать его
for i:=0 to GetOrders.Count-1 do
SetTrailingStopAccordingProperty(GetOrders[i]);
{$IFDEF USE_NONCACHED_RECALCULATION}
for i:=0 to ExpertCount-1 do
GetExpert(i).SetCalculationMode(icmMinPrecache);
{$ENDIF}
try
try
UpdateStep2(aTime);
except
on E:EAbort do;
end;
finally
{$IFDEF USE_NONCACHED_RECALCULATION}
for i:=0 to ExpertCount-1 do
GetExpert(i).SetCalculationMode(icmMaxPrecache);
{$ENDIF}
end;
FLastTime:=aTime;
end;
function TStockTraderBase.GetOrders: IStockOrderCollection;
begin
result:=FOrders;
end;
procedure TStockTraderBase.OnDefineValues;
begin
inherited;
DefValGUID('ID',FID);
DefValString('Category',FCategory);
DefValString('Name',FName);
end;
procedure TStockTraderBase.OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
end;
procedure TStockTraderBase.OnWriteValues(const aWriter: INameValueDataWriter);
var
aPropList: TPropertyList;
i: integer;
aList: TInterfaceList;
begin
inherited;
aList:=TInterfaceList.Create;
try
for i := 0 to FExperts.Count-1 do
aList.Add(FExperts.Items[i]);
aWriter.WriteObjects('Experts',aList);
finally
aList.Free;
end;
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
for i:=0 to aPropList.Count-1 do
aWriter.WriteVariant('Property:'+aPropList[i].Category+'\'+aPropList[i].Name,aPropList[i].Value);
finally
aPropList.Free;
end;
end;
procedure TStockTraderBase.OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean);
var
aPropList: TPropertyList;
i,j: integer;
s: string;
v: variant;
aList: TInterfaceList;
begin
inherited;
if (aName = 'Experts') then
begin
aHandled:=true;
aList:=TInterfaceList.Create;
try
aReader.ReadObjects(aList);
for i := 0 to aList.Count - 1 do
AddExpert(aList[i] as ISCExpert);
finally
aList.Free;
end;
end
else if StrIsInLeft('Property:',pchar(aName)) then
begin
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
for i:=0 to aPropList.Count-1 do
begin
s:='Property:'+aPropList[i].Category+'\'+aPropList[i].Name;
if s=aName then
aHandled:=true;
//Устаревшие названия
if not aHandled and (aPropList[i].ObsoleteNames<>nil) then
for j:=0 to aPropList[i].ObsoleteNames.Count-1 do
begin
s:='Property:'+aPropList[i].Category+'\'+aPropList[i].ObsoleteNames[j];
if s=aName then
begin
aHandled:=true;
end
end;
//Если имя подходит - считываем
if (aHandled) then
begin
aReader.ReadVariant(v);
aPropList[i].Value:=v;
break;
end;
end;
finally
aPropList.Free;
end;
CachePropertyValues;
{$IFDEF IGNORE_UNKNOWN_PROPERTIES}
if not aHandled then
begin
aHandled:=true;
aReader.ReadVariant(v);
end;
{$ENDIF}
end
end;
procedure TStockTraderBase.OnCloseTestBenchDialog(aDialog: TForm);
begin
FTestBenchDialog:=nil;
end;
procedure TStockTraderBase.OnCreateObjects;
begin
end;
procedure TStockTraderBase.OnReleaseObjects;
begin
end;
procedure TStockTraderBase.AddEventHandler(const aHandler: IStockTraderEventHandler);
begin
if FHandlers.IndexOf(aHandler)<>-1 then
raise ESCItemAlreadyExists.Create;
FHandlers.Add(aHandler);
end;
procedure TStockTraderBase.RemoveClosedOrders;
var
i: integer;
begin
for i:=FOrders.Count-1 downto 0 do
if GetOrders[i].GetState in [osClosed,osNothing] then
FOrders.Delete(i);
end;
procedure TStockTraderBase.RemoveEventHandler(const aHandler: IStockTraderEventHandler);
begin
FHandlers.Remove(aHandler);
end;
procedure TStockTraderBase.CloseAllBuyOrders(const aComment: string);
var
i: integer;
aOrder: IStockOrder;
begin
for i:=FOrders.Count-1 downto 0 do
begin
aOrder:=FOrders[FOrders.Count-1];
if (aOrder.GetState<>osClosed) and (aOrder.GetKind=okBuy) then
begin
aOrder.Close(aComment);
aOrder:=nil;
FOrders.Delete(i);
end;
end;
end;
procedure TStockTraderBase.CloseAllSellOrders(const aComment: string);
var
i: integer;
aOrder: IStockOrder;
begin
for i:=FOrders.Count-1 downto 0 do
begin
aOrder:=FOrders[FOrders.Count-1];
if (aOrder.GetState<>osClosed) and (aOrder.GetKind=okSell) then
begin
aOrder.Close(aComment);
aOrder:=nil;
FOrders.Delete(i);
end;
end;
end;
procedure TStockTraderBase.CloseLastOrder(const aComment: string);
var
aOrder: IStockOrder;
begin
if FOrders.Count=0 then
raise ESCError.Create('Нет открытых ордеров');
aOrder:=FOrders[FOrders.Count-1];
if aOrder.GetState<>osClosed then
aOrder.Close(aComment);
aOrder:=nil;
FOrders.Delete(FOrders.Count-1);
end;
procedure TStockTraderBase.CloseOrder(const aOrder: IStockOrder; const aComment: string);
begin
aOrder.Close(aComment);
FOrders.Remove(aOrder);
end;
function TStockTraderBase.LastOrderState: TStockOrderState;
begin
if FOrders.Count=0 then
result:=osNothing
else
result:=FOrders[FOrders.Count-1].GetState;
end;
function TStockTraderBase.LastOrderType: TLastOrderType;
begin
if FOrders.Count=0 then
result:=lotNone
else if FOrders[FOrders.Count-1].GetKind=okBuy then
result:=lotBuy
else
result:=lotSell;
end;
function TStockTraderBase.MoveStopLossCloser(const aOrder: IStockOrder; const aSL: TStockRealNumber):boolean;
var
aRes: TStockRealNumber;
begin
result:=false;
//Сравниваем с текущим SL
if aOrder.GetKind=okBuy then
begin
aRes:=max(aOrder.GetStopLoss,aSL);
//Смотрим, чтобы не слишком близко к Market-цене
aRes:=min(aRes,GetNearestStopLossToMarketPrice(aOrder));
//Смотрим, что получилось, и если SL стал лучше, ставим
if aRes>aOrder.GetStopLoss then
begin
aOrder.SetStopLoss(aRes);
result:=true;
end;
end
else begin
aRes:=min(aOrder.GetStopLoss,aSL);
//Смотрим, чтобы не слишком близко к Market-цене
aRes:=max(aRes,GetNearestStopLossToMarketPrice(aOrder));
//Смотрим, что получилось, и если SL стал лучше, ставим
if aRes<aOrder.GetStopLoss then
begin
aOrder.SetStopLoss(aRes);
result:=true;
end;
end;
end;
function TStockTraderBase.CreateEmptyOrder: IStockOrder;
begin
if FBroker=nil then
raise ESCError.Create('Broker is not defined for trader');
if FLastTime>FBroker.GetCurrentTime then
raise ESCError.Create('The indicated time is less than in previous order');
FLastTime:=FBroker.GetCurrentTime;
result:=FBroker.CreateOrder(self);
//добавляем себя в список
FOrders.Add(result);
end;
function TStockTraderBase.OpenOrder(aKind: TStockOrderKind;const aComment: string=''): IStockOrder;
var
aLots : TStockOrderLots;
begin
result:=nil;
aLots:=GetRecommendedLots;
if aLots=0 then
raise EStockError.CreateFmt('Deposit too small to open order (Type=%s)', [OrderKindNames[aKind]]);
result:=CreateEmptyOrder;
//открываемся
result.Open(GetSymbol, aKind,aLots,aComment);
//Выставляем TakeProfit и StopLoss
case aKind of
okBuy: begin
if FCachedPropMaxSubsidence>0 then
result.SetStopLoss(result.GetOpenPrice-FCachedPropMaxSubsidence);
if FCachedPropEnoughProfit>0 then
result.SetTakeProfit(result.GetOpenPrice+FCachedPropEnoughProfit);
end;
okSell: begin
if FCachedPropMaxSubsidence>0 then
result.SetStopLoss(result.GetOpenPrice+FCachedPropMaxSubsidence);
if FCachedPropEnoughProfit>0 then
result.SetTakeProfit(result.GetOpenPrice-FCachedPropEnoughProfit);
end;
else
raise EAlgoError.Create;
end;
//Выставляем trailing stop
SetTrailingStopAccordingProperty(result);
//result.AddMessage('Order opened');
end;
function TStockTraderBase.OpenOrder(aKind: TStockOrderKind; aLots:TStockOrderLots; aStopLoss, aTakeProfit,
aTrailingStop: TSCRealNumber; const aComment: string): IStockOrder;
begin
result:=nil;
result:=CreateEmptyOrder;
try
//открываемся
result.Open(GetSymbol, aKind,aLots,aComment);
result.SetStopLoss(aStopLoss);
result.SetTakeProfit(aTakeProfit);
//Выставляем trailing stop
result.SetTrailingStop(aTrailingStop);
except
FOrders.Remove(result);
raise;
end;
end;
function TStockTraderBase.OpenOrderAt(aKind: TStockOrderKind; aPrice: TStockRealNumber;
aLots:TStockOrderLots; aStopLoss, aTakeProfit, aTrailingStop: TSCRealNumber;
const aComment: string): IStockOrder;
begin
result:=nil;
result:=CreateEmptyOrder;
//открываемся
result.OpenAt(GetSymbol, aKind,aPrice,aLots,aComment);
result.SetStopLoss(aStopLoss);
result.SetTakeProfit(aTakeProfit);
//Выставляем trailing stop
result.SetTrailingStop(aTrailingStop);
end;
procedure TStockTraderBase.Pause(const aMessage: string);
begin
with TfmResume.Create(nil) do
begin
laText.Caption:=aMessage;
Show;
while Visible do
Forms.Application.ProcessMessages;
Free;
end;
end;
function TStockTraderBase.OpenOrderAt(aKind: TStockOrderKind; aPrice: TStockRealNumber; const aComment: string): IStockOrder;
var
aLots : TStockOrderLots;
begin
result:=nil;
aLots:=GetRecommendedLots;
if aLots=0 then
raise EStockError.CreateFmt('Deposit too small to open order (Type=%s)', [OrderKindNames[aKind]]);
result:=CreateEmptyOrder;
//открываемся
result.OpenAt(GetSymbol, aKind,aPrice,aLots,aComment);
//Выставляем TakeProfit и StopLoss
case aKind of
okBuy: begin
result.SetStopLoss(result.GetPendingOpenPrice-FCachedPropMaxSubsidence);
result.SetTakeProfit(result.GetPendingOpenPrice+FCachedPropEnoughProfit);
end;
okSell: begin
result.SetStopLoss(result.GetPendingOpenPrice+FCachedPropMaxSubsidence);
result.SetTakeProfit(result.GetPendingOpenPrice-FCachedPropEnoughProfit);
end;
else
raise EAlgoError.Create;
end;
//Выставляем trailing stop
SetTrailingStopAccordingProperty(result);
end;
function TStockTraderBase.GetEventHandler(index: integer): IStockTraderEventHandler;
begin
result:=IStockTraderEventHandler(FHandlers[index]);
end;
function TStockTraderBase.EventHandlerCount: integer;
begin
result:=FHandlers.Count;
end;
procedure TStockTraderBase.SetName(const aValue: string);
begin
FName:=aValue;
OnPropertyChanged(nil);
end;
procedure TStockTraderBase.SetCategory(const aValue: string);
begin
FCategory:=aValue;
OnPropertyChanged(nil);
end;
procedure TStockTraderBase.AddExpert(const aExpert: ISCExpert);
begin
FExperts.Add(aExpert);
end;
procedure TStockTraderBase.AddMarkToChart(const aTimeInterval: TStockTimeInterval; const aTime: TDateTime;
const aPrice: TStockRealNumber; const aMarkType: TSCChartMarkKind; const aMessage: string);
begin
if aMarkType=mkNone then
raise EStockError.Create('mkNone is prohibited to use');
FProject.GetStockChart(aTimeInterval).OnTraderSetMark(self,aTime,aPrice,aMarkType,aMessage);
end;
procedure TStockTraderBase.AddMarkToCharts(const aTime: TDateTime; const aPrice: TStockRealNumber;
const aMarkType: TSCChartMarkKind; const aMessage: string);
var
aInterval: TStockTimeInterval;
begin
if aMarkType=mkNone then
raise EStockError.Create('mkNone is prohibited to use');
for aInterval:=low(TStockTimeInterval) to high(TStockTimeInterval) do
FProject.GetStockChart(aInterval).OnTraderSetMark(self,aTime,aPrice,aMarkType,aMessage);
end;
function TStockTraderBase.ExpertCount: integer;
begin
result:=FExperts.Count;
end;
function TStockTraderBase.ExternalIdentifierCount: integer;
begin
result:=FExternalIdentifiers.Count;
end;
function TStockTraderBase.FindExternalIdentifier(const aIndicator: ISCIndicator; aIndicatorIdentification: string): IStockTraderExternalIdentifier;
var
i: integer;
begin
//Ищем, нет ли такого атриубута у индикатора уже
for i := 0 to aIndicator.GetAttributes.Count-1 do
if (Supports (aIndicator.GetAttributes.Items[i],IStockTraderExternalIdentifier,result)) and
(IsEqualGUID(result.GetTraderIID,FIID)) then
begin
if result.GetIdentification=aIndicatorIdentification then
exit; //Уже идентифицирован
end;
result:=nil;
end;
function TStockTraderBase.FindOrderByState(aState: TStockOrderState; aForward: boolean): IStockOrder;
var
i: integer;
begin
result:=nil;
if aForward then
begin
for i := 0 to FOrders.Count - 1 do
if FOrders[i].GetState=aState then
begin
result:=FOrders[i];
break;
end;
end
else begin
for i := FOrders.Count - 1 downto 0 do
if FOrders[i].GetState=aState then
begin
result:=FOrders[i];
break;
end;
end;
end;
function TStockTraderBase.GetExternalIdentifier(index: integer): IStockTraderExternalIdentifier;
begin
result:=FExternalIdentifiers[index] as IStockTraderExternalIdentifier;
end;
function TStockTraderBase.GetExpert(aIndex: integer): ISCExpert;
begin
result:=FExperts[aIndex] as ISCExpert;
end;
procedure TStockTraderBase.ReadData(const aReader: IDataReader);
begin
Include(FState,isReading);
inherited;
Exclude(FState,isReading);
end;
procedure TStockTraderBase.OnAddObject(const aIndicator:ISCIndicator; aIndicatorIdentification: string);
var
aId : IStockTraderExternalIdentifier;
aIdImpl: TStockTraderExternalIdentifier;
i: integer;
begin
aIndicator.AddUsing('Trader "'+GetName+'"');
//Ищем, не создавали ли мы раньше такой идентификатор
aId:=FindExternalIdentifier(aIndicator,aIndicatorIdentification);
//Если не нашли
if aId=nil then
begin
//Проверка. Идентификатор не должен повторяться. Поэтому если у нас такой идентификатор
//зарегистрирован, то скорее, это ошибка в наследниках - пытаются использовать один и тот же Id
for i := 0 to ExternalIdentifierCount - 1 do
begin
if ExternalIdentifiers[i].GetIdentification=aIndicatorIdentification then
raise EStockError.Create('Duplicate identification string');
end;
Assert(FExternalIdentifierClass<>nil);
aIdImpl:=FExternalIdentifierClass.Create;
aIdImpl.Identification:=aIndicatorIdentification;
aIdImpl.FTraderIID:=FIID;
aId:=aIdImpl;
//Добавляем в коллекцию
FExternalIdentifiers.Add(aId);
//Нужно дописать свои идентификационные данные к индикатору
Assert(aId<>nil);
Assert(aId.GetIdentification=aIndicatorIdentification);
aIndicator.GetAttributes.Add(aId);
end;
end;
procedure TStockTraderBase.OnBeginWorkSession;
begin
CachePropertyValues;
end;
procedure TStockTraderBase.OnEndWorkSession;
begin
end;
procedure TStockTraderBase.OnRemoveObject(const aIndicator:ISCIndicator);
var
i: integer;
aId : IStockTraderExternalIdentifier;
aOurs : boolean;
begin
aIndicator.RemoveUsing('Trader "'+GetName+'"');
aOurs:=false;
//Удаляем свои идентификационные данные
for i := aIndicator.GetAttributes.Count-1 downto 0 do
if (Supports (aIndicator.GetAttributes.Items[i],IStockTraderExternalIdentifier,aId)) and
(IsEqualGUID(aId.GetTraderIID,FIID)) then
begin
aIndicator.GetAttributes.Remove(aId);
aOurs:=true;
end;
if aOurs then
if GetParentStockChart(aIndicator)<>nil then
GetParentStockChart(aIndicator).DeleteIndicator(aIndicator);
end;
procedure TStockTraderBase.OnTestBenchActionExecute(Sender: TObject);
begin
if FTestBenchDialog=nil then
begin
FTestBenchDialog:=TfmTestBenchDialogClass(TestBenchDialogClass).Create(self);
FTestBenchDialog.Show;
end
end;
procedure TStockTraderBase.OnTestBenchActionUpdate(Sender: TObject);
begin
TAction(Sender).Caption:=self.GetName+' - Test Bench';
TAction(Sender).Checked:=FTestBenchDialog<>nil;
end;
function TStockTraderBase.ShowPropertyWindow: boolean;
var
aDialog: TSCIndicatorPropertiesDialog;
aPropList: TPropertyList;
begin
result:=false;
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
aDialog:=TSCIndicatorPropertiesDialog.Create(aPropList,GetName);
try
if aDialog.ShowModal=mrOk then
result:=true;
finally
aDialog.Free;
end;
finally
aPropList.Free;
end;
end;
procedure TStockTraderBase.GetProperties(aList: TPropertyList);
var
i: integer;
begin
if FVisibleProperties<>nil then
for i:=0 to FVisibleProperties.Count-1 do
aList.Add(FVisibleProperties[i]);
end;
procedure TStockTraderBase.OnPropertyChanged(aNotifier: TProperty);
var
i: integer;
begin
for i:=0 to EventHandlerCount-1 do
EventHandler[i].OnPropertiesChanged(self);
CachePropertyValues;
end;
procedure TStockTraderBase.OnPropertyCreated(aNotifier: TProperty);
begin
end;
function TStockTraderBase.GetProperties: IPropertyCollection;
var
aCollection: TPropertyCollection;
begin
aCollection:=TPropertyCollection.Create;
GetProperties(aCollection.List);
result:=aCollection;
end;
function TStockTraderBase.GetRecommendedLots: TStockOrderLots;
begin
if FPropLotDynamicRate.Value then
result:=(FBroker.GetEquity/FBroker.GetMargin*(FPropLotDynamicRateSize.Value/100))/10
else
result:=FPropLotDefaultRateSize.Value;
end;
procedure TStockTraderBase.RegisterProperties(aProperties: array of TProperty);
var
i: integer;
begin
if Length(aProperties)=0 then
exit;
if FVisibleProperties=nil then
FVisibleProperties:=TPropertyList.Create;
for i:=0 to High(aProperties) do
begin
if FVisibleProperties.IndexOf(aProperties[i])=-1 then
FVisibleProperties.Add(aProperties[i]);
end;
end;
procedure TStockTraderBase.UnRegisterProperties(aProperties: array of TProperty);
var
i: integer;
begin
if Length(aProperties)=0 then
exit;
if FVisibleProperties=nil then
exit;
for i:=0 to High(aProperties) do
FVisibleProperties.Remove(aProperties[i]);
end;
procedure TStockTraderBase.CachePropertyValues;
begin
if FBroker=nil then
exit;
if FPropMaxSubsidence<>nil then
FCachedPropMaxSubsidence:=GetBroker.PointToPrice(GetSymbol,FPropMaxSubsidence.Value);
if FPropTrailingStop<>nil then
FCachedPropTrailingStop:=GetBroker.PointToPrice(GetSymbol,FPropTrailingStop.Value);
if FPropTrailingStopDescend<>nil then
FCachedPropTrailingStopDescend:=FPropTrailingStopDescend.Value;
if FPropEnoughProfit<>nil then
FCachedPropEnoughProfit:=GetBroker.PointToPrice(GetSymbol,FPropEnoughProfit.Value);
end;
function TStockTraderBase.CanSetStopLoss(const aOrder: IStockOrder; aStopLevel: TStockRealNumber): boolean;
var
aMarketPrice: TStockRealNumber;
begin
result:=true;
if aOrder.GetKind= okBuy then
aMarketPrice:=GetBroker.GetCurrentPrice(aOrder.GetSymbol,bpkBid)
else
aMarketPrice:=GetBroker.GetCurrentPrice(aOrder.GetSymbol,bpkAsk);
//Проверим, чтобы SL не был слшиком близко к маркет-цене
if Abs(GetBroker.PriceToPoint(aOrder.GetSymbol,aStopLevel-aMarketPrice))<GetBroker.GetMarketInfo(aOrder.GetSymbol).StopLevel then
result:=false;
end;
procedure TStockTraderBase.SetBroker(const aBroker: IStockBroker);
begin
if aBroker=FBroker then
exit;
//Если брокера сняли, считаем, что конец текущий работы
if (aBroker=nil) then
OnEndWorkSession;
FBroker:=aBroker;
if (FBroker<>nil) then
OnBeginWorkSession;
end;
function TStockTraderBase.GetBroker: IStockBroker;
begin
result:=FBroker;
end;
function TStockTraderBase.GetSymbol: string;
begin
result:=FProject.GetStockSymbol;
end;
function TStockTraderBase.TestBenchDialogClass: TClass;
begin
result:=nil;
end;
procedure TStockTraderBase.SetProject(const aValue: IStockProject);
begin
if GetProject=aValue then
exit;
if FProject<>nil then
OnReleaseObjects;
FProject:=aValue;
if FProject<>nil then
OnCreateObjects;
end;
procedure TStockTraderBase.SetStopLossAccordingProperty(aOrder: IStockOrder);
var
aMinimizationRisksType : TMinimizationLossType;
aStopLoss: TStockRealNumber;
begin
if aOrder.GetState in [osClosed,osNothing] then
exit;
aMinimizationRisksType:=FMinimizationRiskType.Value;
//Нужно перевести в безубыточное состояние ордер, поэтому
//как только появится возможность поставить стоп с безубыточной стороны - делаем это
if (aMinimizationRisksType<>mltNone) and (GetExpectedLoss(aOrder)>0) then
begin
if (aMinimizationRisksType=mltFixAtZeroPoint) and (CanSetStopLoss(aOrder,aOrder.GetOpenPrice)) then
begin
aOrder.SetStopLoss(aOrder.GetOpenPrice);
GetBroker.AddMessage(aOrder,'Zero stop loss ('+PriceToStr(aOrder,aOrder.GetOpenPrice)+') was set');
end
//безубыточного стоп лоса нет, но хотя бы подвинем его как можно ближе
else if aMinimizationRisksType=mltMinimizeAll then
begin
aStopLoss:=max(aOrder.GetStopLoss,GetNearestStopLossToMarketPrice(aOrder));
if (CanSetStopLoss(aOrder,aStopLoss)) then
aOrder.SetStopLoss(aStopLoss);
end;
end;
end;
procedure TStockTraderBase.SetTrailingStopAccordingProperty(aOrder: IStockOrder);
var
aK : TStockRealNumber;
begin
if aOrder.GetState in [osClosed,osNothing] then
exit;
if FCachedPropTrailingStop>0 then
begin
//Динамический Trailing Stop
aK:=max(0,FCachedPropTrailingStop-max(0,FCachedPropTrailingStopDescend*(aOrder.GetBestProfit-FCachedPropTrailingStop)));
aK:=max(aK,GetBroker.PointToPrice(aOrder.GetSymbol,GetBroker.GetMarketInfo(GetSymbol).StopLevel));
aK:=GetBroker.RoundPrice(aOrder.GetSymbol,aK);
aOrder.SetTrailingStop(aK);
end;
end;
function TStockTraderBase.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber;
begin
if aOrder.GetKind=okBuy then
result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder)
else
result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice;
end;
function TStockTraderBase.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber;
begin
result:=aOrder.GetStopLoss;
if (aOrder.GetState=osOpened) and (aOrder.GetTrailingStop>0) then
if aOrder.GetKind=okBuy then
result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop)
else
result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop);
end;
function TStockTraderBase.GetProject: IStockProject;
begin
result:=FProject;
end;
function TStockTraderBase.IndexOfExpert(const aExpert: ISCExpert): integer;
var
i: integer;
begin
result:=-1;
for i:=0 to ExpertCount-1 do
if GetExpert(i).IsThis(aExpert) then
begin
result:=i;
break;
end;
end;
function TStockTraderBase.RemoveExpert(const aExpert: ISCExpert):integer;
begin
result:=IndexOfExpert(aExpert);
if result<>-1 then
DeleteExpert(result);
end;
procedure TStockTraderBase.DeleteExpert(index: integer);
begin
OnRemoveObject(GetExpert(index));
FExperts.Delete(index);
end;
function TStockTraderBase.IsLevelTooCloseToCurrentPrice(aPriceKind: TStockBrokerPriceKind; aLevel: TSCRealNumber): boolean;
var
aPrice: TSCRealNumber;
aStopDelta: TStockRealNumber;
begin
//Берем +1, чтобы наверняка
aStopDelta:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).StopLevel+1);
aPrice:=GetBroker.GetCurrentPrice(GetSymbol,aPriceKind);
result:=Abs(aPrice-aLevel)>=aStopDelta;
end;
function TStockTraderBase.IsThis(const aTrader: IStockTrader): boolean;
begin
result:=IsEqualGUID(aTrader.GetID,self.GetID);
end;
function TStockTraderBase.CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean=true): ISCIndicator;
var
aRes: boolean;
begin
result:=CreateOrFindIndicator(aChart,aIID,aIndicatorIdentification,aRegister, aRes);
end;
function TStockTraderBase.CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean; out aCreated: boolean): ISCIndicator;
var
aIndicators: ISCIndicatorCollection;
aId: IStockTraderExternalIdentifier;
i: integer;
begin
//Ищем среди уже существующих
aIndicators:=aChart.FindIndicators(aIID);
aId:=nil;
result:=nil;
for i := 0 to aIndicators.Count- 1 do
begin
aId:=FindExternalIdentifier(aIndicators.Items[i],aIndicatorIdentification);
if aId<>nil then
begin
result:=aIndicators.Items[i];
break;
end;
end;
//Итак, нашли среди существующих
if result<>nil then
begin
aCreated:=false;
end
//Если нет - тогда создаем
else begin
result:=aChart.CreateIndicator(IndicatorFactory.GetIndicatorInfo(aIID),false);
aCreated:=true;
end;
//Регистрируем индикатор
if aRegister then
OnAddObject(result,aIndicatorIdentification);
end;
{ TStockTraderExternalIdentifier }
constructor TStockTraderExternalIdentifier.Create;
begin
inherited Create;
end;
function TStockTraderExternalIdentifier.GetIdentification: string;
begin
result:=FIdentification;
end;
function TStockTraderExternalIdentifier.GetTraderIID: TGUID;
begin
result:=FTraderIID;
end;
procedure TStockTraderExternalIdentifier.OnDefineValues;
begin
inherited;
DefValString('Identification',FIdentification);
end;
procedure TStockTraderExternalIdentifier.SetIdentification(const Value: string);
begin
FIdentification := Value;
end;
{ TStockBrokerEventHandler }
constructor TStockBrokerEventHandler.Create(aOwner: TStockTraderBase);
begin
inherited Create;
FOwner:=aOwner;
end;
destructor TStockBrokerEventHandler.Destroy;
begin
Assert(FOwner=nil);
inherited;
end;
procedure TStockBrokerEventHandler.OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
if (FOwner<>nil) and (IStockTrader(FOwner)=aOrder.GetTrader) then
FOwner.OnModifyOrder(aOrder,aModifyEventArgs);
end;
procedure TStockBrokerEventHandler.OnNewData(const aSender: IStockBroker; const aSymbol: string);
begin
end;
procedure TStockBrokerEventHandler.OnNewMessage(const aSender: IStockBroker; const aMessage: IStockBrokerMessage);
begin
end;
procedure TStockBrokerEventHandler.OnNewMessage(const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage);
begin
end;
procedure TStockBrokerEventHandler.OnNewOrder(const aSender: IStockBroker; const aOrder: IStockOrder);
begin
end;
procedure TStockBrokerEventHandler.OnStart(const aSender: IStockBroker);
begin
end;
initialization
Serialization.TClassFactory.RegisterClass(TStockTraderExternalIdentifier);
Serialization.TClassFactory.RegisterClass(TStockTraderBase);
end.
|
UNIT ColrCtrl;
(*
--------------------------------------------------------------
Adds a pop-up palette control to any 16 color VGA program
Allows 256K color choices.
created: 2/2/89 by Art Steinmetz / CIS: 76044,3204
Use at will but please leave my name in. Thanks.
Intructions: Call PaletteControl while in any VGA mode.
Up/Down arrows scroll through palette entries.
F1/F2 Increase/Decrease Red level.
F3/F4 Increase/Decrease Green level.
F5/F6 Increase/Decrease Blue level.
Shift-F(1..6) Increase/Decrease Color level
for all palette entries (useful for monitor
color correction )
Esc to restore original VGA colors.
G to invoke grey scale.
<End> to accept changes and exit.
Change global variables XOffset and YOffset to adjust palette
control position.
-----------------------------------------------------------------
*)
interface
USES
Graph { Bar, GetImage, GetPalette, ImageSize, OutTextXY,
PaletteType, PutImage, Rectangle, SetColor,
SetFillStyle, SetLineStyle, SetRGBPalette,
SetWriteMode }
,
KeyCodes { GetKey, F1,F2,F3,F4,F5,F6,ESC, UpArrow, DownArrow}
{ SF1,SF2,SF3,SF4,SF5,SF6 }
,
DOS { Intr, Registers}
;
CONST
MaxColors = 15;
TYPE
RGBRec = RECORD
RedVal, GreenVal, BlueVal : BYTE;
END;
RGBArray = ARRAY[0..MaxColors] OF RGBRec;
VAR
XOffset,
YOffset : INTEGER;
PROCEDURE PaletteControl;
(* see instructions above *)
PROCEDURE GetOrigPalette;
(*
If you modify the palette outside of user control call this procedure
so the ESC key on the palette control will cause reversion to
that palette
*)
PROCEDURE GetRGBPalette(ColorNum : INTEGER;
VAR RedVal, GreenVal, BlueVal : BYTE);
(* complement of Borland's SetRGBPalette procedure *)
PROCEDURE GetVGAPalette(VAR p : RGBArray);
PROCEDURE GrayScale;
(* Change palette to levels of gray *)
PROCEDURE RestoreDefaultPalette;
(* Revert to original VGA startup colors *)
(*==========================================================*)
implementation
CONST
PenColor = 14;
CONST
DefaultColors : RGBArray = (
(RedVal: 0;GreenVal: 0;BlueVal: 0),
(RedVal: 0;GreenVal: 0;BlueVal:42),
(RedVal: 0;GreenVal:42;BlueVal: 0),
(RedVal: 0;GreenVal:42;BlueVal:42),
(RedVal:42;GreenVal: 0;BlueVal: 0),
(RedVal:42;GreenVal: 0;BlueVal:42),
(RedVal:42;GreenVal:21;BlueVal: 0),
(RedVal:42;GreenVal:42;BlueVal:42),
(RedVal:21;GreenVal:21;BlueVal:21),
(RedVal:21;GreenVal:21;BlueVal:63),
(RedVal:21;GreenVal:63;BlueVal:21),
(RedVal:21;GreenVal:63;BlueVal:63),
(RedVal:63;GreenVal:21;BlueVal:21),
(RedVal:63;GreenVal:21;BlueVal:63),
(RedVal:63;GreenVal:63;BlueVal:21),
(RedVal:63;GreenVal:63;BlueVal:63)
);
MaxColorVal = 63;
increase = TRUE;
decrease = FALSE;
TYPE
RGBSelect = (RED, GREEN, BLUE);
VAR
OrigImage : POINTER;
CharHeight,
BoxHeight,
Size : Word;
OrigColors : RGBArray;
(* ++++++++++++++++++++++++++++++++++++ *)
function Int2Str(L : LongInt) : string;
{ Converts an integer to a string for use with OutText, OutTextXY }
var
S : string;
begin
Str(L, S);
Int2Str := S;
end; { Int2Str }
{ ---------------------------------------------------------------}
FUNCTION max(a,b : INTEGER) : INTEGER;
BEGIN
IF a > b THEN
max := a
ELSE
max := b;
END; {max}
{ ---------------------------------------------------------------}
FUNCTION min(a,b : INTEGER) : INTEGER;
BEGIN
IF a < b THEN
min := a
ELSE
min := b;
END; {max}
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE DisplayPalette;
VAR
pal : PaletteType;
n : WORD;
BEGIN
GetPalette(pal);
FOR n := 0 TO 15 DO
BEGIN
SetFillStyle(SolidFill,n);
Bar(XOffset+8,YOffset+(n*BoxHeight)+2,
XOffset+38, YOffset+trunc(BoxHeight-2)+(n*BoxHeight));
END;
SetLineStyle(SolidLn,0,ThickWidth);
Rectangle(XOffset+4,YOffset,XOffset+42,YOffset+(BoxHeight*16)+(CharHeight*3)+2);
{ put in labels }
OutTextXY(XOffset+8,YOffset+BoxHeight*16+2 ,'R:');
OutTextXY(XOffset+8,YOffset+BoxHeight*16+CharHeight+2,'G:');
OutTextXY(XOffset+8,YOffset+BoxHeight*16+CharHeight*2+2,'B:');
END {DisplayPalette};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE GetRGBPalette(ColorNum : INTEGER;
VAR RedVal, GreenVal, BlueVal : BYTE);
CONST
VGAIntr = $10;
VAR
DAC : WORD;
regs: Registers;
BEGIN
IF (ColorNum > 255) OR (ColorNum < 0) THEN
DAC := 0
ELSE
DAC := ColorNum;
regs.AH := $10; { Get color register function call}
regs.AL := $15; { Get color register function call}
regs.BX := DAC; { Register to retrieve }
Intr(VGAIntr,regs);
RedVal := regs.DH;
GreenVal := regs.CH;
BlueVal := regs.CL;
END {GetRGBPalette};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE GetVGAPalette(VAR p : RGBArray);
var
n : integer;
BEGIN
FOR n := 0 TO MaxColors DO
GetRGBPalette(n,p[n].RedVal,p[n].GreenVal,p[n].BlueVal);
END;
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE RestoreDefaultPalette;
VAR
n : WORD;
palette : PaletteType;
BEGIN
GetPalette(palette);
FOR n := 0 TO MaxColors DO
WITH DefaultColors[n] DO
SetRGBPalette(palette.Colors[n],RedVal,GreenVal,BlueVal);
END {RestoreDefaultPalette};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE GetOrigPalette;
VAR
n : WORD;
palette : PaletteType;
BEGIN
GetPalette(palette);
FOR n := 0 TO MaxColors DO
WITH OrigColors[n] DO
GetRGBPalette(palette.Colors[n],RedVal,GreenVal,BlueVal);
END {GetOrigPalette};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE RestoreOrigPalette;
VAR
n : WORD;
palette : PaletteType;
BEGIN
GetPalette(palette);
FOR n := 0 TO MaxColors DO
WITH OrigColors[n] DO
SetRGBPalette(palette.Colors[n],RedVal,GreenVal,BlueVal);
END {RestoreOrigPalette};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE GrayScale;
VAR
n : WORD;
palette : PaletteType;
BEGIN
GetPalette(palette);
FOR n := 0 TO MaxColors DO
SetRGBPalette(palette.Colors[n],n*4,n*4,n*4);
END {GrayScale};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE ShowColorNums(RedVal, GreenVal, BlueVal : INTEGER);
CONST
pad = #219+#219;
VAR
ColStr : String;
BEGIN
ColStr := Int2Str(RedVal);
SetColor(0);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+2,pad);
SetColor(PenColor);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+2,ColStr);
ColStr := Int2Str(GreenVal);
SetColor(0);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+CharHeight+2,pad);
SetColor(PenColor);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+CharHeight+2,ColStr);
ColStr := Int2Str(BlueVal);
SetColor(0);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+CharHeight*2+2,pad);
SetColor(PenColor);
OutTextXY(XOffset+24,YOffset+BoxHeight*16+CharHeight*2+2,ColStr);
END {ShowColorNums};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE GlobalColorChange(RGB : RGBSelect; change : INTEGER);
VAR
n,
RedVal,
GreenVal,
BlueVal : BYTE;
pal : PaletteType;
BEGIN
GetPalette(pal);
FOR n := 0 TO MaxColors DO
BEGIN
GetRGBPalette(pal.Colors[n],RedVal,GreenVal,BlueVal);
CASE RGB OF
RED : RedVal := max(0,min(RedVal +change,MaxColorVal));
GREEN : GreenVal := max(0,min(GreenVal+change,MaxColorVal));
BLUE : BlueVal := max(0,min(BlueVal +change,MaxColorVal));
END;
SetRGBPalette(pal.Colors[n],RedVal,GreenVal,BlueVal);
END {FOR};
END {GlobalColorChange};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE ModifyColors;
CONST
MaxColorVal = 63;
Step = 1;
VAR
Key : INTEGER;
OldEntry,
n : WORD;
RedVal,
GreenVal,
BlueVal : BYTE;
palette : PaletteType;
BEGIN
GetPalette(palette);
RedVal := 0;
BlueVal := 0;
GreenVal := 0;
SetLineStyle(SolidLn,0,ThickWidth);
n := 0;
OldEntry := 0;
SetWriteMode(XORPut);
WHILE Key <> EndKey DO
BEGIN
SetColor(PenColor);
Rectangle(XOffset+4,YOffset+(n*BoxHeight),
XOffset+42,YOffset+BoxHeight+(n*BoxHeight));
OldEntry := n;
GetRGBPalette(palette.Colors[n],RedVal,GreenVal,BlueVal);
ShowColorNums(RedVal,GreenVal,BlueVal);
Key := GetKey;
CASE Key OF
DownArrow : n := min(n + 1,15);
UpArrow : n := max(n - 1, 0);
F1 : RedVal := min(RedVal + Step,MaxColorVal);
F2 : RedVal := max(RedVal - Step,0);
F3 : GreenVal := min(GreenVal + Step,MaxColorVal);
F4 : GreenVal := max(GreenVal - Step,0);
F5 : BlueVal := min(BlueVal + Step,MaxColorVal);
F6 : BlueVal := max(BlueVal - Step,0);
SF1 : GlobalColorChange(Red,1);
SF2 : GlobalColorChange(Red,-1);
SF3 : GlobalColorChange(Green,1);
SF4 : GlobalColorChange(Green,-1);
SF5 : GlobalColorChange(Blue,1);
SF6 : GlobalColorChange(Blue,-1);
ESC : RestoreOrigPalette;
ord('G') : GrayScale;
ord('g') : GrayScale;
END {CASE};
Rectangle(XOffset+4,YOffset+(OldEntry*BoxHeight),
XOffset+42, YOffset+BoxHeight+(OldEntry*BoxHeight));
IF (Key >= F1) AND (Key < F7) THEN
SetRGBPalette(palette.Colors[n],RedVal,GreenVal,BlueVal);
END {While};
SetWriteMode(CopyPut);
END {ModifyColors};
(* ++++++++++++++++++++++++++++++++++++ *)
PROCEDURE PaletteControl;
BEGIN
IF GetMaxY < 300 THEN
BoxHeight := 8
ELSE
IF GetMaxY < 400 THEN
BoxHeight := 15
ELSE
BoxHeight := 20;
CharHeight := round(TextHeight('X') * 1.25);
Size := ImageSize(XOffset,YOffset-2,
XOffset+44,YOffset+(BoxHeight*16)+(CharHeight*3));
IF MaxAvail >= Size THEN
BEGIN
GetMem(OrigImage,Size);
GetImage(XOffset,YOffset-2,XOffset+44,YOffset+370,OrigImage^);
DisplayPalette;
ModifyColors;
PutImage(XOffset,YOffset-2,OrigImage^,NormalPut);
FreeMem(OrigImage,Size);
END;
END {PaletteControl};
(* ++++++++++++++++++++++++++++++++++++ *)
BEGIN
OrigColors := DefaultColors;
XOffset := 20;
YOffset := 20;
END {ColrCtrl}.
|
{$mode objfpc}
{$m+}
program Queue;
type
Node = record
val : integer;
prev : ^Node;
end;
LinkedListQueue = class
private
first : ^Node;
last : ^Node;
public
function pop(): integer;
procedure push(i : integer);
end;
function LinkedListQueue.pop() : integer;
begin
if first <> nil then
begin
writeln('poping ', first^.val);
pop := first^.val;
first := first^.prev;
end
else
begin
pop := -1;
writeln('nothing left in queue');
end;
end;
procedure LinkedListQueue.push(i : integer);
var
Prev, A : ^Node;
begin
writeln('pushing ', i);
new(A);
A^.val := i;
if first = nil then
begin
first := A;
last := A;
end
else if i < last^.val then
begin
last^.prev := A;
last := A;
end
else
begin
Prev := last;
while (Prev^.prev <> nil) and (i > Prev^.val) do
begin
Prev := Prev^.prev;
end;
A^.prev := Prev^.prev;
Prev^.prev := A;
end;
end;
var
L : LinkedListQueue;
a : integer;
begin
writeln('--LinkedListQueue--');
L := LinkedListQueue.Create();
L.push(1);
L.push(2);
L.push(3);
L.push(1);
L.push(5);
L.push(2);
repeat
a := L.pop();
until a = -1;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 1997-2002 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
{$DENYPACKAGEUNIT}
unit CGIApp;
interface
uses WebBroker, CGIHTTP;
type
TCGIFactory = class;
TCGIApplication = class(TWebApplication)
private
FOutputFileName: string;
FFactory: TCGIFactory;
function NewRequest: TCGIRequest;
function NewResponse(CGIRequest: TCGIRequest): TCGIResponse;
procedure SetFactory(Value: TCGIFactory);
function GetFactory: TCGIFactory;
procedure CGIHandleException(Sender: TObject);
public
destructor Destroy; override;
procedure Run; override;
end;
TCGIFactory = class(TObject)
private
FApplication: TCGIApplication;
function GetOutputFileName: string;
procedure SetOutputFileName(const Value: string);
protected
function NewRequest: TCGIRequest; virtual;
function NewResponse(CGIRequest: TCGIRequest): TCGIResponse; virtual;
property OutputFileName: string read GetOutputFileName write SetOutputFileName;
public
constructor Create;
end;
implementation
uses SysUtils, BrkrConst, Classes, IniFiles, HTTPApp;
{ TCGIApplication }
procedure HandleServerException(E: TObject; const OutputFile: string);
var
ResultText, ResultHeaders, EMsg: string;
OutFile: TStream;
begin
if E is Exception then
EMsg := Exception(E).Message
else
EMsg := '';
ResultText := Format(sInternalServerError, [E.ClassName, EMsg]);
ResultHeaders := Format(
'Status: 500 %s'#13#10+ { do not localize }
'Content-Type: text/html'#13#10 + { do not localize }
'Content-Length: %d'#13#10#13#10, { do not localize }
[EMsg, Length(ResultText)]); { do not localize }
if IsConsole then
begin
FileWrite(TTextRec(Output).Handle, Pointer(ResultHeaders)^, Length(ResultHeaders));
FileWrite(TTextRec(Output).Handle, Pointer(ResultText)^, Length(ResultText));
end else
begin
if FileExists(OutputFile) then
OutFile := TFileStream.Create(OutputFile, fmOpenWrite or fmShareDenyNone)
else OutFile := TFileStream.Create(OutputFile, fmCreate);
try
OutFile.Write(Pointer(ResultHeaders)^, Length(ResultHeaders));
OutFile.Write(Pointer(ResultText)^, Length(ResultText));
finally
OutFile.Free;
end;
end;
end;
destructor TCGIApplication.Destroy;
begin
inherited;
FFactory.Free;
end;
function TCGIApplication.NewRequest: TCGIRequest;
begin
Result := GetFactory.NewRequest;
end;
function TCGIApplication.NewResponse(CGIRequest: TCGIRequest): TCGIResponse;
begin
Result := GetFactory.NewResponse(CGIRequest);
end;
procedure TCGIApplication.Run;
var
HTTPRequest: TCGIRequest;
HTTPResponse: TCGIResponse;
begin
inherited Run;
if IsConsole then
begin
Rewrite(Output);
Reset(Input);
end;
try
HTTPRequest := NewRequest;
try
HTTPResponse := NewResponse(HTTPRequest);
try
HandleRequest(HTTPRequest, HTTPResponse);
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
except
HandleServerException(ExceptObject, FOutputFileName);
end;
end;
procedure InitApplication;
begin
Application := TCGIApplication.Create(nil);
end;
procedure TCGIApplication.SetFactory(Value: TCGIFactory);
begin
Assert(FFactory = nil, 'Duplication CGIFactory'); { do not localize }
FFactory := Value;
end;
function TCGIApplication.GetFactory: TCGIFactory;
begin
if not Assigned(FFactory) then
FFactory := TCGIFactory.Create;
Result := FFactory;
end;
procedure TCGIApplication.CGIHandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
E: TObject;
begin
Handled := False;
if (ExceptObject is Exception) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
begin
E := ExceptObject;
AcquireExceptionObject;
raise E;
end;
end;
{ TCGIFactory }
constructor TCGIFactory.Create;
begin
inherited;
FApplication := Application as TCGIApplication;
FApplication.SetFactory(Self);
Classes.ApplicationHandleException := TCGIApplication(FApplication).CGIHandleException;
end;
function TCGIFactory.GetOutputFileName: string;
begin
Result := FApplication.FOutputFileName;
end;
function TCGIFactory.NewRequest: TCGIRequest;
var
Ini: TIniFile;
begin
if IsConsole then
Result := TCGIRequest.Create
else
begin
Result := TWinCGIRequest.Create(ParamStr(1), ParamStr(2), ParamStr(3));
OutputFileName := ParamStr(3);
if OutputFileName = '' then
begin
Ini := TIniFile.Create(ParamStr(1));
try
OutputFileName := Ini.ReadString('System','Output File',''); {do not localize}
finally
Ini.Free;
end;
end;
end;
end;
function TCGIFactory.NewResponse(CGIRequest: TCGIRequest): TCGIResponse;
begin
if IsConsole then
Result := TCGIResponse.Create(CGIRequest)
else Result := TWinCGIResponse.Create(CGIRequest);
end;
procedure TCGIFactory.SetOutputFileName(const Value: string);
begin
FApplication.FOutputFileName := Value;
end;
initialization
InitApplication;
end.
|
program hanoi1;
procedure hanoi(num, src, dst: integer);
{ num is a quantity of discs }
begin
if num = 1 then
begin
writeln('Move a top disk from ', src, ' to ', dst);
exit;
end;
hanoi(num-1, src, 6-src-dst);
hanoi(1, src, dst);
hanoi(num-1, 6-src-dst, dst);
end;
begin
hanoi(3, 1 ,3);
end.
|
unit ProjectConst;
interface
resourcestring
sMainFormCaption = 'Database';
sSaveAllActionCaption = 'Перезаписать уже имеющиеся';
sSkipAllActionCaption = 'Пропустить уже имеющиеся';
sRecommendedReplacement = 'Recommended Replacement';
sOperatingTemperatureRange = 'Operating Temperature Range';
sDoDescriptionsBind = 'Выполняем прикрепление кратких описаний';
sIsNotEnoughProductAmount = 'Данное значение превышает количество партии товара';
// Категория производителей которые добавляются на склад в ручную или из Excel Файла
sWareHouseDefaultProducerType = 'Склад';
// Папка по умолчанию для хранения документации на складе
sWareHouseFolder = 'Склад';
// Папка по умолчанию для хранения спецификаций компонентов
sComponentsDatasheetFolder = 'Спецификация';
// Папка по умолчанию для хранения схем компонентов
sComponentsDiagramFolder = 'Схема';
// Папка по умолчанию для хранения чертежей компонентов
sComponentsDrawingFolder = 'Чертёж';
// Папка по умолчанию для хранения изображений компонентов
sComponentsImageFolder = 'Изображение';
// Папка по умолчанию для хранения изображений корпусов
sBodyImageFolder = 'Изображение';
// Папка по умолчанию для хранения чертёжей посадочной площадки корпусов
sBodyLandPatternFolder = 'Чертёж посадочной площадки';
// Папка по умолчанию для хранения чертежей корпуса
sBodyOutlineDrawingFolder = 'Чертёж корпуса';
// Папка по умолчанию для хранения JEDEC
sBodyJEDECFolder = 'Чертёж корпуса\JEDEC';
sBodyTypesFilesExt = 'pdf;jpg;png;bmp;gif';
// sDefaultDatabaseFileName = 'database_1.4.db';
// sEmptyDatabaseFileName = 'database_empty_1.4.db';
sDoYouWantToDeleteCategoryParameter =
'Вы действительно хотите убрать выделенные параметры из текущей категории?';
sDoYouWantToDeleteCategorySubParameter =
'Вы действительно хотите удалить выделенные подпараметры?';
sDoYouWantToDeleteFamily =
'Вы действительно хотите удалить выделенные семейства компонентов из текущей категории?';
sDoYouWantToDeleteFamilyFromAll =
'Вы действительно хотите полностью удалить выделенные семейства компонентов из всех категорий?';
sDoYouWantToDeleteComponent =
'Вы действительно хотите удалить выделенные компоненты из семейства?';
sDoYouWantToDelete = 'Вы действительно хотите удалить запись?';
sDatabase = 'Database';
sPleaseWrite = 'Пожалуйста, введите наименование';
sNoExcelSheets = 'В выбранной Excel книге нет ни одного листа';
sDoYouWantToDeleteProducts =
'Вы действительно хотите удалить выделенные компоненты со склада?';
sDoYouWantToSaveChanges = 'Изменения не были сохранены. Сохранить изменения?';
sError = 'Ошибка';
sSaving = 'Сохранение';
sExtraChargeRangeError =
'Поле количество должно содержать диапазон вида 2-10';
sExtraChargeRangeError2 = 'Левая граница диапазона должна быть больше правой';
sLocalizationFileName = 'Localization.ini';
sDriverName = 'SQLite';
sProducerParamTableName = 'Producer';
sPackagePinsParamTableName = 'Package / Pins';
sDatasheetParamTableName = 'Datasheet';
sDiagramParamTableName = 'Diagram';
sDrawingParamTableName = 'Drawing';
sImageParamTableName = 'Image';
sDescriptionParamTableName = 'Description';
sRows = 'строк';
sRecords = 'записей';
sComponents = 'компонентов';
sFiles = 'файлов';
sParameters = 'параметров';
sTreeRootNodeName = 'Структура';
const
DBVersion = 10;
BaseFontSize = 10;
ProgramVersion = 1.6;
DragDropTimeOut = 200; // Защита от случайного перетаскивания
DefaultRate = 60; // Курс доллара к рублю "по умолчанию"
OnReadProcessEventRecordCount = 100;
// Через сколько считанных / записанных записей извещать о прогрессе
OnWriteProcessEventRecordCount = 5;
MinWholeSaleDef = 10; // Минимальная оптовая наценка по "умолчанию"
implementation
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit Data.DbxSybaseASE;
interface
uses
Data.DBXDynalink,
Data.DBXDynalinkNative,
Data.DBXCommon, Data.DbxSybaseASEReadOnlyMetaData, Data.DbxSybaseASEMetaData;
type
TDBXSybaseASEProperties = class(TDBXProperties)
strict private
const StrASETransIsolation = 'ASE TransIsolation';
const StrTDSPacketSize = 'TDS Packet Size';
const StrClientHostName = 'Client HostName';
const StrClientAppName = 'Client AppName';
function GetHostName: string;
function GetPassword: string;
function GetUserName: string;
function GetBlobSize: Integer;
function GetDatabase: string;
function GetTDSPacketSize: Integer;
function GetSybaseASETransIsolation: string;
function GetClientAppName: string;
function GetClientHostName: string;
procedure SetClientAppName(const Value: string);
procedure SetClientHostName(const Value: string);
procedure SetTDSPacketSize(const Value: Integer);
procedure SetBlobSize(const Value: Integer);
procedure SetDatabase(const Value: string);
procedure SetSybaseASETransIsolation(const Value: string);
procedure SetHostName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
public
constructor Create(DBXContext: TDBXContext); override;
published
property HostName: string read GetHostName write SetHostName;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property Database: string read GetDatabase write SetDatabase;
property BlobSize: Integer read GetBlobSize write SetBlobSize;
property SybaseASETransIsolation:string read GetSybaseASETransIsolation write SetSybaseASETransIsolation;
property TDSPacketSize: Integer read GetTDSPacketSize write SetTDSPacketSize;
property ClientHostName: string read GetClientHostName write SetClientHostName;
property ClientAppName: string read GetClientAppName write SetClientAppName;
end;
TDBXSybaseASEDriver = class(TDBXDynalinkDriverNative)
public
constructor Create(DBXDriverDef: TDBXDriverDef); override;
end;
implementation
uses
Data.DBXCommonResStrs, Data.DBXPlatform, System.SysUtils;
const
sDriverName = 'ASE';
{ TDBXSybaseASEDriver }
constructor TDBXSybaseASEDriver.Create(DBXDriverDef: TDBXDriverDef);
var
Props: TDBXSybaseASEProperties;
I, Index: Integer;
begin
Props := TDBXSybaseASEProperties.Create(DBXDriverDef.FDBXContext);
if DBXDriverDef.FDriverProperties <> nil then
begin
for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do
begin
Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]);
if Index > -1 then
Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I];
end;
Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties);
DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties);
end;
inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props);
rcs;
end;
{ TDBXSybaseASEProperties }
constructor TDBXSybaseASEProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
Values[TDBXPropertyNames.DriverUnit] := 'Data.DbxSybaseASE';
Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXSybaseASEDriver' + PackageVersion + '.bpl';
Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXSybaseASEMetaDataCommandFactory,DbxSybaseASEDriver' + PackageVersion + '.bpl';
Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXSybaseASEMetaDataCommandFactory,Borland.Data.DbxSybaseASEDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverASE';
Values[TDBXPropertyNames.LibraryName] := 'dbxase.dll';
Values[TDBXPropertyNames.VendorLib] := 'libct.dll;libcs.dll';
Values[TDBXPropertyNames.VendorLibWin64] := 'libct64.dll;libcs64.dll';
Values[TDBXPropertyNames.HostName] := 'ServerName';
Values[TDBXPropertyNames.Database] := 'Database Name';
Values[TDBXPropertyNames.UserName] := 'user';
Values[TDBXPropertyNames.Password] := 'password';
Values[TDBXPropertyNames.MaxBlobSize] := '-1';
Values[TDBXPropertyNames.ErrorResourceFile] := '';
Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000';
Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted';
Values['TDSPacketSize'] := '512';
Values['ClientHostName'] := '';
Values['ClientAppName'] := '';
end;
function TDBXSybaseASEProperties.GetBlobSize: Integer;
begin
Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1);
end;
function TDBXSybaseASEProperties.GetClientAppName: string;
begin
Result := Values[StrClientAppName];
end;
function TDBXSybaseASEProperties.GetClientHostName: string;
begin
Result := Values[StrClientHostName];
end;
function TDBXSybaseASEProperties.GetDatabase: string;
begin
Result := Values[TDBXPropertyNames.Database];
end;
function TDBXSybaseASEProperties.GetSybaseASETransIsolation: string;
begin
Result := Values[StrASETransIsolation];
end;
function TDBXSybaseASEProperties.GetTDSPacketSize: Integer;
begin
Result := StrToIntDef(Values[StrTDSPacketSize], 512);
end;
function TDBXSybaseASEProperties.GetHostName: string;
begin
Result := Values[TDBXPropertyNames.HostName];
end;
function TDBXSybaseASEProperties.GetPassword: string;
begin
Result := Values[TDBXPropertyNames.Password];
end;
function TDBXSybaseASEProperties.GetUserName: string;
begin
Result := Values[TDBXPropertyNames.UserName];
end;
procedure TDBXSybaseASEProperties.SetBlobSize(const Value: Integer);
begin
Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value);
end;
procedure TDBXSybaseASEProperties.SetClientAppName(const Value: string);
begin
Values[StrClientAppName] := Value;
end;
procedure TDBXSybaseASEProperties.SetClientHostName(const Value: string);
begin
Values[StrClientHostName] := Value;
end;
procedure TDBXSybaseASEProperties.SetDatabase(const Value: string);
begin
Values[TDBXPropertyNames.Database] := Value;
end;
procedure TDBXSybaseASEProperties.SetSybaseASETransIsolation(const Value: string);
begin
Values[StrASETransIsolation] := Value;
end;
procedure TDBXSybaseASEProperties.SetTDSPacketSize(const Value: Integer);
begin
Values[StrTDSPacketSize] := IntToStr(Value);
end;
procedure TDBXSybaseASEProperties.SetHostName(const Value: string);
begin
Values[TDBXPropertyNames.HostName] := Value;
end;
procedure TDBXSybaseASEProperties.SetPassword(const Value: string);
begin
Values[TDBXPropertyNames.Password] := Value;
end;
procedure TDBXSybaseASEProperties.SetUserName(const Value: string);
begin
Values[TDBXPropertyNames.UserName] := Value;
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXSybaseASEDriver);
finalization
TDBXDriverRegistry.UnloadDriver(sDriverName);
end.
|
unit Support.Phison;
interface
uses
SysUtils,
Support, Device.SMART.List;
type
TPhisonNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetSemiSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsHasSATASSDString: Boolean;
function IsHasSAFM0String: Boolean;
function IsProductOfPhison: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TPhisonNSTSupport }
function TPhisonNSTSupport.IsHasSATASSDString: Boolean;
begin
result :=
Pos('SATA SSD', UpperCase(Identify.Model)) = 1;
end;
function TPhisonNSTSupport.IsHasSAFM0String: Boolean;
begin
result :=
Pos('SAFM0', UpperCase(Identify.Firmware)) = 1;
end;
function TPhisonNSTSupport.IsProductOfPhison: Boolean;
begin
result :=
IsHasSATASSDString and IsHasSAFM0String;
end;
function TPhisonNSTSupport.GetSemiSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := false;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TPhisonNSTSupport.GetSupportStatus: TSupportStatus;
begin
FillChar(result, SizeOf(result), #0);
if IsProductOfPhison then
result := GetSemiSupport;
end;
function TPhisonNSTSupport.GetTotalWrite: TTotalWrite;
const
GiBtoMiB = 1024;
IDOfHostWrite = 241;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := RAWValue * GiBtoMiB;
end;
function TPhisonNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfReadError = 1;
IDOfReplacedSector = 170;
IDofUsedHour = 9;
ReplacedSectorThreshold = 50;
ReadErrorThreshold = 10;
HalfOfSMARTBits = 16;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := true;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfReadError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= ReadErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(
IDOfReplacedSector) shr HalfOfSMARTBits;
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
{ 25/05/2007 11:17:03 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 10:37:27 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:32:29 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:32:17 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:16:44 (GMT+0:00) > [Akadamia] checked in }
{ 08/02/2007 14:08:23 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: OCU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Open and Close example to Delphi
Opens and immediately Closes SimConnect
History:
-----------------------------------------------------------------------------}
unit OCU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// The form
TOpenAndCloseForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Connect: TAction;
FileExit: TFileExit;
Memo: TMemo;
procedure ConnectExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
end;
var
OpenAndCloseForm : TOpenAndCloseForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TOpenAndCloseForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: ConnectExecute
Opens the connection for Polled access. If successful closes the connection.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TOpenAndCloseForm.ConnectExecute(Sender: TObject);
var
hr : HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Open And Close', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
Memo.Lines.Add('Connected to Flight Simulator');
hr := SimConnect_Close(hSimConnect);
end
else
Memo.Lines.Add('Failed to connect to Flight Simulator');
StatusBar.Panels[0].Text := 'Not Connected';
end;
end.
|
unit ui200;
interface
uses
Contnrs,
MVCInterfaces,uRegistroEmpresaContabil, uI100 , uNumeroCampo, uTipoDetalhamento, uContaContabil;
type
TI200 = class(TRegistroEmpresaContabil)
private
fID : Integer;
FOnModeloMudou : TModeloMudou;
fNumeroCampo : TNumeroCampo;
fTipoDetalhamento : TTipoDetalhamento;
fValorDetalhado : Real;
fContaContabil : TContaContabil;
fI100: TI100;
procedure SetID(const Value: Integer);
procedure SetOnModeloMudou(const Value: TModeloMudou);
procedure SetNumeroCampo(const Value: TNumeroCampo);
procedure SetTipoDetalhamento(const Value: TTipoDetalhamento);
procedure SetValorDetalhado(const Value: Real);
procedure SetContaContabil(const Value: TContaContabil);
procedure SetI100(const Value: TI100);
public
property ID : Integer read fID write SetID;
property OnModeloMudou : TModeloMudou read FOnModeloMudou write SetOnModeloMudou; // Assim funcionou em Delphi 7
property I100 : TI100 read fI100 write SetI100;
property NumeroCampo : TNumeroCampo read fNumeroCampo write SetNumeroCampo;
property TipoDetalhamento : TTipoDetalhamento read fTipoDetalhamento write SetTipoDetalhamento;
property ValorDetalhado : Real read fValorDetalhado write SetValorDetalhado;
property ContaContabil : TContaContabil read fContaContabil write SetContaContabil;
constructor create();
end;
implementation
uses
UI200BD, UEmpresa;
constructor TI200.create;
begin
Empresa := TEmpresa.create;
I100 := TI100.create;
NumeroCampo := TNumeroCampo.create;
TipoDetalhamento := TTipoDetalhamento.create;
end;
procedure TI200.SetContaContabil(const Value: TContaContabil);
begin
fContaContabil := Value;
end;
procedure TI200.SetI100(const Value: TI100);
begin
fI100 := Value;
end;
procedure TI200.SetID(const Value: Integer);
begin
fID := Value;
end;
procedure TI200.SetNumeroCampo(const Value: TNumeroCampo);
begin
fNumeroCampo := Value;
end;
procedure TI200.SetOnModeloMudou(const Value: TModeloMudou);
begin
FOnModeloMudou := Value;
end;
procedure TI200.SetTipoDetalhamento(const Value: TTipoDetalhamento);
begin
fTipoDetalhamento := Value;
end;
procedure TI200.SetValorDetalhado(const Value: Real);
begin
fValorDetalhado := Value;
end;
end.
|
unit UFrmPaciente;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
, UPACIENTE
, UUtilitarios
, URegraCRUDPaciente, Mask
;
type
TfrmCadPaciente = class(TFrmCRUD)
gbCadastro: TGroupBox;
edCodSus: TLabeledEdit;
edNome: TLabeledEdit;
edEndereco: TLabeledEdit;
edRG: TLabeledEdit;
edEstado: TLabeledEdit;
edFixo: TLabeledEdit;
edCel: TLabeledEdit;
edCidade: TLabeledEdit;
edPai: TLabeledEdit;
edMae: TLabeledEdit;
edSexo: TComboBox;
Label1: TLabel;
edCPF: TMaskEdit;
Label2: TLabel;
edNascimento: TMaskEdit;
Label3: TLabel;
protected
FPACIENTE: TPACIENTE;
FregraCRUDPacienteS: TRegraCRUDPacienteS;
procedure Inicializa; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
frmPaciente: TfrmCadPaciente;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UDialogo;
{$R *.dfm}
{ TfrmPaciente }
procedure TfrmCadPaciente.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbCadastro.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TfrmCadPaciente.Inicializa;
begin
inherited;
DefineEntidade(@FPACIENTE, TPACIENTE);
DefineRegraCRUD(@FregraCRUDPACIENTES, TRegraCRUDPACIENTES);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_CODIGO_SUS)
.AdicionaFiltro(FLD_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_PACIENTE)
.DefineVisao(TBL_PACIENTE));
end;
procedure TfrmCadPaciente.PosicionaCursorPrimeiroCampo;
begin
inherited;
edCodSus.SetFocus;
end;
procedure TfrmCadPaciente.PreencheEntidade;
begin
inherited;
{FPACIENTE.PESSOA_CODIGO := edCodSus.Text ;
FPACIENTE.PESSOA_NOME := edNome.Text ;
FPACIENTE.PESSOA_NASCIMENTO := StrToInt(edNascimento.Text) ;
FPACIENTE.PESSOA_SEXO := edSexo.Text ;
FPACIENTE.PESSOA_ENDERECO := edEndereco.Text ;
FPACIENTE.PESSOA_RG := StrToInt(edRG.Text) ;
FPACIENTE.PESSOA_CPF := edCPF.Text ;
FPACIENTE.PESSOA_ESTADO := edEstado.Text ;
FPACIENTE.PESSOA_TEL_FIXO := StrToInt(edFixo.Text) ;
FPACIENTE.PESSOA_CELULAR := StrToInt(edCel.Text) ;
FPACIENTE.PESSOA_CIDADE := edCidade.Text ;
FPACIENTE.PESSOA_PAI := edPai.Text ;
FPACIENTE.PESSOA_MAE := edMae.Text ; }
end;
procedure TfrmCadPaciente.PreencheFormulario;
begin
inherited;
{edCodSus.Text := FPACIENTE.PESSOA_CODIGO;
edNome.Text := FPACIENTE.PESSOA_NOME;
edNascimento.Text := IntToStr(FPACIENTE.PESSOA_NASCIMENTO);
edSexo.Text := FPACIENTE.PESSOA_SEXO;
edEndereco.Text := FPACIENTE.PESSOA_ENDERECO;
edRG.Text := IntToStr(FPACIENTE.PESSOA_RG);
edCPF.Text := FPACIENTE.PESSOA_CPF;
edEstado.Text := FPACIENTE.PESSOA_ESTADO;
edFixo.Text := IntToStr(FPACIENTE.PESSOA_TEL_FIXO);
edCel.Text := IntToStr(FPACIENTE.PESSOA_CELULAR);
edCidade.Text := FPACIENTE.PESSOA_CIDADE;
edPai.Text := FPACIENTE.PESSOA_PAI;
edMae.Text := FPACIENTE.PESSOA_MAE; }
end;
end.
|
program ReadFile;
type
states = (start, slash, slashSlash, slashStar, slashStarStar, slashStarStarSlash, quote, quoteBackslash);
var
input, outputBuffer: string;
c: char;
currentState: states;
function transitionFunction(state: states; c: char): states;
begin
transitionFunction := state;
case state of
start:
if c = '/' then
transitionFunction := slash
else if c = '"' then
transitionFunction := quote
else
;
slash:
if c = '/' then
transitionFunction := slashSlash
else if c = '*' then
transitionFunction := slashStar
else
transitionFunction := start;
slashSlash:
{Only recognize unix style line endings.}
if c = chr(10) then
transitionFunction := start
else
;{dump all characters until end of line}
slashStar:
if c = '*' then
transitionFunction := slashStarStar
else
;{dump all characters until comment is ended}
slashStarStar:
if c = '/' then
transitionFunction := slashStarStarSlash
else
transitionFunction := slashStar;
slashStarStarSlash:
if c = '/' then
transitionFunction := slash
else if c = '"' then
transitionFunction := quote
else
transitionFunction := start;
quote:
if c = '\' then
transitionFunction := quoteBackslash
else if c = '"' then
transitionFunction := start
else
;
quoteBackslash:
transitionFunction := quote;
end;
end;
procedure handleChar(state: states; c: char; outputBuffer: string);
begin
case state of
start:
begin
if outputBuffer <> '' then
write(outputBuffer);
write(c);
end;
slash:
outputBuffer := outputBuffer + c;
slashSlash, slashStar:
outputBuffer := '';
slashStarStar, slashStarStarSlash:
;
quote:
write(c);
quoteBackslash:
write(c);
end;
end;
begin
currentState := start;
while not eof do
begin
read(c);
currentState := transitionFunction(currentState, c);
handleChar(currentState, c, outputBuffer);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий чтение данных из файла }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.WaveIn;
interface
uses Windows, SysUtils, Classes, SyncObjs, MMSystem,uBaseClasses,
MediaServer.Stream.Source,
MediaProcessing.Definitions,MediaStream.Framer;
type
TMediaServerSourceWaveIn = class;
//Класс, выполняющий непосредственно получение данных (видеопотока)
TMediaServerSourceWaveIn = class (TMediaServerSource)
private
FDeviceID: NativeUInt;
FWaveFormat:TWaveFormatEx;
FWaveInHeader : WAVEHDR;
FWaveInBuff : PAnsiChar;
FWaveInHandleLock: TCriticalSection;
FWaveInHandle : HWAVEIN;
protected
function GetStreamType(aMediaType: TMediaType): TStreamType; override;
procedure OnReceiveData;
public
constructor Create(aChannels,aSamplesPerSec,aBitsPerSample: cardinal; aDeviceID: NativeUInt=INVALID_HANDLE_VALUE);
destructor Destroy; override;
procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
procedure Open(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
property WaveFormat:TWaveFormatEx read FWaveFormat;
end;
implementation
uses Math,Forms,ThreadNames, VFW, MediaServer.Workspace, uTrace,
MediaStream.FramerFactory,MediaStream.UrlFormats;
{ TMediaServerSourceWaveIn }
constructor TMediaServerSourceWaveIn.Create(aChannels,aSamplesPerSec,aBitsPerSample: cardinal; aDeviceID: NativeUInt=INVALID_HANDLE_VALUE);
begin
inherited Create(-1);
FDeviceID:=aDeviceID;
FWaveInHandleLock:=TCriticalSection.Create;
FWaveFormat.wFormatTag:=WAVE_FORMAT_PCM;
FWaveFormat.nChannels :=aChannels;
FWaveFormat.wBitsPerSample:=aBitsPerSample;
FWaveFormat.nSamplesPerSec:=aSamplesPerSec;
FWaveFormat.nBlockAlign:=(FWaveFormat.wBitsPerSample div 8) * FWaveFormat.nChannels;
FWaveFormat.nAvgBytesPerSec:=FWaveFormat.nBlockAlign * FWaveFormat.nSamplesPerSec;
FWaveFormat.cbSize:= 0;
end;
destructor TMediaServerSourceWaveIn.Destroy;
begin
inherited;
FreeAndNil(FWaveInHandleLock);
end;
function TMediaServerSourceWaveIn.DeviceType: string;
begin
result:='Файл';
end;
function TMediaServerSourceWaveIn.Name: string;
begin
result:='Wave In';
end;
procedure waveInProc(hwi: HWAVEIN; uMsg:UINT; dwInstance:DWORD ;dwParam1:DWORD ;dwParam2:DWORD ); stdcall;
var
aInstance : TMediaServerSourceWaveIn;
begin
aInstance:=pointer(dwInstance);
Assert(aInstance<>nil);
if (uMsg=WIM_DATA) then
begin
aInstance.OnReceiveData;
end;
end;
procedure TMediaServerSourceWaveIn.OnFrameReceived(
const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
begin
//Выносим за Lock потому что все операнды - локальные переменные
DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize);
end;
procedure TMediaServerSourceWaveIn.OnReceiveData;
var
aFormat: TMediaStreamDataHeader;
begin
try
// aProcessed:=true;
aFormat.Assign(FWaveFormat);
OnFrameReceived(aFormat,FWaveInBuff,FWaveInHeader.dwBufferLength,nil,0);
FWaveInHandleLock.Enter;
try
//поведение по умолчанию
waveInAddBuffer(FWaveInHandle,@FWaveInHeader,sizeof(FWaveInHeader));
finally
FWaveInHandleLock.Leave;
end;
except
on E:Exception do
begin
end;
end;
end;
procedure TMediaServerSourceWaveIn.Open(aSync: boolean);
var
aWaveInDevCaps: WAVEINCAPS;
res: integer;
aBuffSize: cardinal;
aDenom : cardinal;
begin
if Opened then
exit;
Close;
try
if FDeviceID=INVALID_HANDLE_VALUE then
begin
res:=waveInGetNumDevs;
if res=0 then
raise Exception.Create('Не обнаружено входное Audio-устройство');
res:=waveInGetDevCaps(0,@aWaveInDevCaps,sizeof(aWaveInDevCaps));
end
else begin
res:=waveInGetDevCaps(FDeviceID,@aWaveInDevCaps,sizeof(aWaveInDevCaps));
end;
if(res<>MMSYSERR_NOERROR) then
raise Exception.Create('Не обнаружено входное Audio-устройство');
Win32Check(waveInOpen(@FWaveInHandle,WAVE_MAPPER,@FWaveFormat,dword(@waveInProc),dword(self),CALLBACK_FUNCTION)=MMSYSERR_NOERROR);
//Размер буфера, используемый при записи входного потока аудио (с микрофона, линейного входа и прочее)
{$IFDEF HHNET_LARGE_AUDIO_IN_BUFFER}
aDenom:=12;
{$ELSE}
aDenom:=25;
{$ENDIF}
aBuffSize:=(FWaveFormat.nChannels*FWaveFormat.nSamplesPerSec* FWaveFormat.wBitsPerSample div 8) div aDenom; //Буфер на один кадр видео, должно получиться 640
FWaveInBuff:=pointer(GlobalAlloc(GMEM_FIXED or GMEM_NOCOMPACT or GMEM_NODISCARD, aBuffSize));
if FWaveInBuff=nil then
RaiseLastOSError;
FWaveInHeader.lpData := FWaveInBuff;
FWaveInHeader.dwBufferLength := aBuffSize;
FWaveInHeader.dwFlags:=0;
FWaveInHeader.dwLoops:=0;
Win32Check(waveInPrepareHeader(FWaveInHandle,@FWaveInHeader,sizeof(FWaveInHeader))=MMSYSERR_NOERROR);
if FWaveInHandle=0 then
raise Exception.Create('Не инициализировано входное аудио');
Win32Check(waveInAddBuffer(FWaveInHandle,@FWaveInHeader,sizeof(FWaveInHeader))=MMSYSERR_NOERROR);
Win32Check(waveInStart(FWaveInHandle)=MMSYSERR_NOERROR);
try
DoConnectionOK;
except
//?????
end;
except
on E:Exception do
DoConnectionFailed(E);
end;
end;
procedure TMediaServerSourceWaveIn.DoClose;
begin
if FWaveInHandle<>0 then
begin
FWaveInHandleLock.Enter;
try
waveInStop(FWaveInHandle);
sleep(50);
finally
FWaveInHandleLock.Leave;
end;
end;
if FWaveInHandle<>0 then
begin
Stop;
FWaveInHandleLock.Enter;
try
waveInUnprepareHeader(FWaveInHandle,@FWaveInHeader,sizeof(FWaveInHeader));
waveInClose(FWaveInHandle);
FWaveInHandle:=0;
finally
FWaveInHandleLock.Leave;
end;
end;
if FWaveInBuff<>nil then
GlobalFree(HGLOBAL(FWaveInBuff));
FWaveInBuff:=nil;
end;
function TMediaServerSourceWaveIn.ConnectionString: string;
begin
result:='Wave In';
end;
function TMediaServerSourceWaveIn.Opened: Boolean;
begin
result:=FWaveInHandle<>0;
end;
function TMediaServerSourceWaveIn.StreamInfo: TBytes;
begin
result:=nil;
end;
function TMediaServerSourceWaveIn.GetStreamType(aMediaType: TMediaType): TStreamType;
begin
if aMediaType=mtAudio then
result:=stPCM
else
result:=0;
end;
function TMediaServerSourceWaveIn.PtzSupported: boolean;
begin
result:=false;
end;
procedure TMediaServerSourceWaveIn.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
end;
end.
|
unit UConexao;
interface
uses
IniFiles, SysUtils, Forms, SqlExpr, Dialogs;
type
TConexao = class
private
Path: string;
Host: string;
Porta: integer;
Database: string;
Password: string;
User: string;
VendorLib: string;
LibraryC: string;
GetDriver: string;
Driver: string;
Connection: string;
Secao: string;
Charset: string;
Time: Integer;
FThreadSimultanea: Integer;
FQuality1 : Integer;
FQuality2 : Integer;
FMaxWidth : Integer;
FSeparador: string;
public
constructor Create(Path: string; Secao: string);
procedure LeINI(); virtual;
procedure GravaINI(Usuario, Senha, Servidor, Banco: string); virtual;
procedure Conectar(var Conexao: TSQLConnection); virtual;
property Hostname: string read Host write Host;
property Usuario: string read User write User;
property Senha: string read Password write Password;
property Banco: string read Database write Database;
property TimeOut: Integer read Time write Time;
property Quality1: Integer read FQuality1 write FQuality1;
property MaxWidth: Integer read FMaxWidth write FMaxWidth;
property Separador: string read FSeparador write FSeparador;
end;
implementation
procedure TConexao.Conectar(var Conexao: TSQLConnection);
begin
if (Conexao.DriverName = '') and (Conexao.GetDriverFunc = '') and (Conexao.LibraryName = '') and (Conexao.VendorLib = '') then
begin
try
//Le o arquivo INI e carrega os valores nas respectivas variáveis
LeINI();
//Passa os parâmetros para o objeto Conexão
Conexao.Connected := false;
Conexao.LoginPrompt := false;
Conexao.ParamsLoaded := True;
Conexao.DriverName := Driver;
Conexao.GetDriverFunc := GetDriver;
Conexao.LibraryName := LibraryC;
Conexao.VendorLib := VendorLib;
Conexao.Params.Clear;
Conexao.Params.Add('hostname='+ Host);
Conexao.Params.Add('user_name='+ User);
Conexao.Params.Add('password='+ Password);
Conexao.Params.Add('database='+ Database);
Conexao.Params.Add('connecttimeout='+ IntToStr(TimeOut));
Except
on E:Exception do
ShowMessage('Erro ao carregar parâmetros de conexão!'#13#10 + E.Message);
end;
end;
end;
constructor TConexao.Create(Path: string; Secao: string);
begin
// Verifica se o arquivo INI existe
if FileExists(Path) then
begin
Self.Path := Path;
Self.Secao := Secao;
end
else
raise Exception.Create('Arquivo INI para configuração não encontrado.'#13#10'Aplicação será finalizada.');
end;
procedure TConexao.GravaINI(Usuario, Senha, Servidor, Banco: string);
var
ArqIni : TIniFile;
begin
ArqIni := TIniFile.Create(Path);
try
//Carrega valores para conexão com banco de dados
ArqIni.WriteString(Secao, 'user_name', Usuario);
ArqIni.WriteString(Secao, 'Password', Senha);
ArqIni.WriteString(Secao, 'Database', Banco);
ArqIni.WriteString(Secao, 'Hostname', Servidor);
finally
ArqIni.Free;
end;
end;
procedure TConexao.LeINI();
var
ArqIni : TIniFile;
begin
ArqIni := TIniFile.Create(Path);
try
//Carrega valores para conexão com banco de dados
Host := ArqIni.ReadString(Secao, 'Hostname', '');
Database := ArqIni.ReadString(Secao, 'Database', '');
Password := ArqIni.ReadString(Secao, 'Password', '');
User := ArqIni.ReadString(Secao, 'user_name', '');
VendorLib := ArqIni.ReadString(Secao, 'VendorLib', '');
LibraryC := ArqIni.ReadString(Secao, 'LibraryName', '');
GetDriver := ArqIni.ReadString(Secao, 'GetDriveFunc', '');
Driver := ArqIni.ReadString(Secao, 'drivername', '');
Charset := ArqIni.ReadString(Secao, 'charset', '');
TimeOut := ArqIni.ReadInteger(Secao, 'TimeOut', 0);
//Carrega valores para qualidade das imagens
FQuality1 := ArqIni.ReadInteger('Qualidade', 'Quality1', 0);
// Carrega valor máximo de largura
FMaxWidth := ArqIni.ReadInteger('Dimensao', 'MaxWidth', 0);
// Carrega parâmetro para configuração de separador decimal
FSeparador:= ArqIni.ReadString('Configuracao', 'SeparadorDecimal', '');
finally
ArqIni.Free;
end;
end;
end.
|
{ *******************************************************
Threading utilities for Delphi 2009 and above
Utilidad para programación concurrente.
*******************************************************
2012-2015 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
unit ThreadUtils.Sync;
{
SUMMARY:
- THandleObjectHelper: new primitive MsgWaitFor.
- TEvent2: extended behavior for TEvent
- TLockCondition and TPrecondition: lock thread execution until
some condition is met.
- TSyncPoint: wait until a number of threads have reached an execution point
- TRendezvous: pass data to another thread in a synchronized way
}
interface
uses
SysUtils,
WinAPI.Windows,
SyncObjs;
{ THandleObjectHelper
PURPOUSE:
To add a VCL-safe WaitFor primitive
MsgWaitFor:
Spawns a new thread wich executes WaitFor and then executes
the given callback on the main thread. This way, message queue may be attended
in VCL applications
}
type
TWaitNotifyEvent = procedure(Sender: THandleObject; WaitResult: TWaitResult)
of object;
THandleObjectHelper = class helper for THandleObject
public
procedure MsgWaitFor(Callback: TWaitNotifyEvent;
Timeout: cardinal = INFINITE);
end;
{ TEvent2
PURPOSE:
Extend the behavior of TEvent
GENERAL USAGE:
Once "Cancel" method is called, all pending threads at "WaitFor" will
return wrError. Further calls to WaitFor will also return wrError.
SIGNALANDWAITFOR:
SignalAndWaitFor reproduces the behavior of SignalObjectAndWait Windows
API primitive. ObjToSignal parameter should be TSemaphore, TMutex or TEvent.
PULSEEVENT:
Will release, at least, all pending threads at the moment.
No need to use if ManualReset was set to true at instance creation.
Note: this is not the same as the PulseEvent deprecated Windows primitive.
}
type
TEvent2 = class(TEvent)
protected
FLockedCounter: integer;
FCancelled: boolean;
public
constructor Create(EventAttributes: PSecurityAttributes;
ManualReset, InitialState: boolean; const Name: string;
UseCOMWait: boolean = False); overload;
constructor Create(UseCOMWait: boolean = False); overload;
destructor Destroy; override;
function WaitFor(Timeout: cardinal = INFINITE): TWaitResult; override;
function SignalAndWaitFor(ObjToSignal: THandleObject;
Timeout: cardinal = INFINITE): TWaitResult;
procedure PulseEvent;
procedure Cancel;
end;
{ TLockCondition
PURPOUSE:
To lock any thread until a certain condition is met.
GENERAL USAGE:
- Create a TLockCondition instance
- enter a critical section
- Call TLockCondition.WaitFor
- Leave the critical section
WAITFOR:
Call WaitFor to sleep on the given condition and to release the critical
section specified through the CriticalSection parameter.
The TimeOut parameter sets the time-out interval.
When this interval elapses or the condition is met,
the critical section is reacquired.
This class ensures that the given condition is allways true after the
waiting thread has been unlocked and result is wrSignaled (no need for loops).
WaitFor result is wrError if another thread calls TLockCondition.Cancel
which also cause the waiting thread to be awaken. Further calls to WaitFor
will return wrError, too.
CriticalSection is reacquired as an atomic operation when the locked
thread is awaken.
CONDITIONS:
Conditions are expressed as references to function returning a
boolean value. Such function should return "true" when
the unlocking condition is met.
SIGNALING STATE CHANGES:
Any thread that changes the state of the WaitFor condition must call
TLockCondition.Update.
CANCELLATION:
TLockCondition.Cancel will unlock all waiting threads at WaitFor with
wrAbandoned result. Further calls to WaitFor will result in wrAbandoned too.
Cancellation is provided for smooth instance destruction. Call Cancel,
wait for threads to terminate, then destroy the instance itself.
EXAMPLE:
procedure TMyClass.LockUntilCount(limit: integer);
begin
CriticalSection.Enter;
try
wr := LockCondition.WaitFor(CriticalSection,
function:boolean
begin
result := (self.counter>=limit)
end;
finally
CriticalSection.Leave;
end;
end;
procedure TMyClass.Inc;
begin
CriticalSection.Enter;
inc(self.counter);
CriticalSection.Leave;
LockCondition.Update;
end;
}
type
TLockCondition = class
private
FSync: TConditionVariableCS;
FCancelled: boolean;
public
constructor Create;
destructor Destroy; override;
function WaitFor(CriticalSection: TCriticalSection;
Condition: TFunc<boolean>; Timeout: cardinal = INFINITE)
: TWaitResult; overload;
procedure Update;
procedure Cancel;
property Cancelled: boolean read FCancelled;
end;
{ TPrecondition
PURPOUSE:
To lock any thread until a certain condition is met.
GENERAL USAGE:
Same as TLockCondition
CONDITIONS:
The locking condition is set at instance creation, so it's result should depend
on your object's state alone. Whether such condition depends on external
parameters use TLockCondition instead.
EXAMPLE:
constructor TMyClass.Create;
begin
...
NotEmpty := TPrecondition.Create(
function: boolean
begin
Result := (FBuffer.Count>0);
end);
NotFull := TPrecondition.Create(
function: boolean
begin
Result := (FBuffer.Count<FBuffer.Size);
end);
...
end;
function TmyClass.Consume: TSomeItem;
begin
CriticalSection.Enter;
NotEmpty.WaitFor(CriticalSection);
Result := FBuffer.Extract;
CriticalSection.Leave;
NotEmpty.Update;
NotFull.Update;
end;
procedure TMyClass.Produce(Item: TSomeItem);
begin
CriticalSection.Enter;
NotFull.WaitFor(CriticalSection);
FBuffer.Add(Item);
CriticalSection.Leave;
NotEmpty.Update;
NotFull.Update;
end;
}
type
TPrecondition = class(TLockCondition)
private
FCondition: TFunc<boolean>;
public
constructor Create(Condition: TFunc<boolean>);
function WaitFor(CriticalSection: TCriticalSection;
Timeout: cardinal = INFINITE): TWaitResult;
end;
{ TSyncPoint
PURPOUSE:
Wait until a number of threads have reached certain point of
execution. Mostly used for waiting termination of
all spawned threads, without keeping track of their instance identifiers,
so shared resources are safe to release after that
(including the TsyncPoint instance itself)
GENERAL USAGE:
- Call AddThread every time a new thread is created
(or set a value at instance creation)
- Any thread reaching the required execution point should call Reached
- Call WaitFor to lock until all other threads meet the sync point.
NOTES:
Give every thread a chance to reach the sync point, otherwise a deadlock
may occur.
EXAMPLE:
// assume that "sync" is a shared variable
sync := TSyncPoint.Create(5)
for i := 1 to 5 do
MyThread.Create.Start;
sync.WaitFor;
<<release shared resources>>
sync.Free;
...
procedure MyThread.Execute;
begin
<<do something>>
sync.reached;
end;
}
type
TSyncPoint = class
private
FThreadCount: integer;
Event: TEvent;
public
constructor Create(InitialThreadCount: integer = 0);
destructor Destroy; override;
procedure AddThread;
procedure Reached;
function WaitFor(Timeout: cardinal = INFINITE): TWaitResult;
procedure MsgWaitFor(Callback: TWaitNotifyEvent);
property ThreadCount: integer read FThreadCount;
end;
{ TRendezvous<T>
PURPOUSE:
Pass data to another thread in a synchronized way.
GENERAL USAGE:
- one thread calls "send"
- another thread calls "receive".
If passed data (of type T) can not be copied by value,
"receive" should provide a "copy procedure".
First parameter is the source variable and second parameter is the
destination variable (also returned by "receive").
EXAMPLE (Data passed by value):
R := TRendezvous<integer>.Create;
// Thread 1
R.send(89);
// Thread 2
intValue := R.receive;
EXAMPLE (Data passed by reference):
R := TRendezvous<PByte>.Create;
// Thread 1
R.send(buffer);
buffer[0] := pbyte(8); // this IS SAFE !!!
// Thread 2
buffer := R.Receive(
procedure (source,dest: PByte)
begin
CopyMemory(dest,source,BUFFER_SIZE);
end);
NOTES:
- "send" and "receive" are blocking primitives.
Do not call from the main thread in windows applications
- "send" and "receive" will unlock pending threads and raise
an ESyncObjectException after "cancel" is called. Further
calls will also raise such an exception.
}
type
TRendezvous<T> = class
private
FData: T;
sendReady, receiveReady: TEvent;
sendCS: TCriticalSection;
receiveCS: TCriticalSection;
FCancelled: boolean;
public
constructor Create;
destructor Destroy; override;
procedure Cancel;
function receive(copyProcedure: TProc<T, T>): T; overload;
function receive: T; overload;
procedure send(data: T);
property Cancelled: boolean read FCancelled;
end;
implementation
uses
Classes;
// -----------------------------------------------------------------------------
// THandleObjectHelper
// -----------------------------------------------------------------------------
// Auxiliary type in order to pass data to auxiliary thread
type
TMsgWaitData = record
WaitOn: THandleObject;
Callback: TWaitNotifyEvent;
Timeout: cardinal;
end;
PMsgWaitData = ^TMsgWaitData;
// Auxiliary thread body
function MsgWaitForThread(arg: PMsgWaitData): integer;
var
wr: TWaitResult;
Callback: TWaitNotifyEvent;
hObject: THandleObject;
Timeout: cardinal;
begin
Callback := arg^.Callback;
hObject := arg^.WaitOn;
Timeout := arg^.Timeout;
FreeMem(arg);
wr := hObject.WaitFor(Timeout);
TThread.Synchronize(nil,
procedure
begin
Callback(hObject, wr);
end);
result := 0;
end;
// -----------------------------------------------------------------------------
procedure THandleObjectHelper.MsgWaitFor(Callback: TWaitNotifyEvent;
Timeout: cardinal);
var
th: THandle;
id: cardinal;
data: PMsgWaitData;
begin
if (Assigned(Callback)) then
begin
GetMem(data, sizeof(TMsgWaitData));
data^.WaitOn := self;
data^.Callback := Callback;
data^.Timeout := Timeout;
th := BeginThread(nil, 32, @MsgWaitForThread, data, 0, id);
if (th <> INVALID_HANDLE_VALUE) then
CloseHandle(th)
else
raise ESyncObjectException.Create('Unable to create auxiliary thread');
end;
end;
// -----------------------------------------------------------------------------
// TEvent2
// -----------------------------------------------------------------------------
constructor TEvent2.Create(EventAttributes: PSecurityAttributes;
ManualReset, InitialState: boolean; const Name: string;
UseCOMWait: boolean = False);
begin
FCancelled := False;
FLockedCounter := 0;
inherited Create(EventAttributes, ManualReset, InitialState, Name,
UseCOMWait);
end;
// -----------------------------------------------------------------------------
constructor TEvent2.Create(UseCOMWait: boolean = False);
begin
FCancelled := False;
FLockedCounter := 0;
inherited Create(UseCOMWait);
end;
// -----------------------------------------------------------------------------
destructor TEvent2.Destroy;
begin
if (FHandle <> 0) then
Cancel;
inherited;
end;
// -----------------------------------------------------------------------------
function TEvent2.WaitFor(Timeout: cardinal): TWaitResult;
begin
if (FCancelled) then
result := wrError
else
begin
InterlockedIncrement(FLockedCounter);
result := Inherited WaitFor(Timeout);
InterlockedDecrement(FLockedCounter);
if (result = wrSignaled) and FCancelled then
result := wrError;
end;
end;
// -----------------------------------------------------------------------------
procedure TEvent2.PulseEvent;
begin
while (FLockedCounter > 0) do
SetEvent;
end;
// -----------------------------------------------------------------------------
procedure TEvent2.Cancel;
begin
FCancelled := True;
PulseEvent;
end;
// -----------------------------------------------------------------------------
function TEvent2.SignalAndWaitFor(ObjToSignal: THandleObject;
Timeout: cardinal = INFINITE): TWaitResult;
var
wr: cardinal;
begin
result := wrError;
if (not FCancelled) and (ObjToSignal <> nil) then
begin
InterlockedIncrement(FLockedCounter);
wr := SignalObjectAndWait(ObjToSignal.Handle, FHandle, Timeout, False);
InterlockedDecrement(FLockedCounter);
if (wr = WAIT_OBJECT_0) and (not FCancelled) then
result := wrSignaled
else if (wr = WAIT_TIMEOUT) then
result := wrTimeout
else if (wr = WAIT_ABANDONED) then
result := wrAbandoned;
end;
end;
// -----------------------------------------------------------------------------
// TLockCondition
// -----------------------------------------------------------------------------
constructor TLockCondition.Create;
begin
FSync := TConditionVariableCS.Create;
FCancelled := False;
end;
// -----------------------------------------------------------------------------
destructor TLockCondition.Destroy;
begin
Cancel;
FSync.Destroy;
inherited;
end;
// -----------------------------------------------------------------------------
function TLockCondition.WaitFor(CriticalSection: TCriticalSection;
Condition: TFunc<boolean>; Timeout: cardinal): TWaitResult;
begin
result := wrSignaled;
if (Assigned(Condition)) then
while (not FCancelled) and (result = wrSignaled) and (not Condition()) do
result := FSync.WaitFor(CriticalSection, Timeout)
else
raise ESyncObjectException.Create('TLockCondition: Condition unknown');
if (FCancelled) then
result := wrError;
end;
// -----------------------------------------------------------------------------
procedure TLockCondition.Update;
begin
FSync.ReleaseAll;
end;
// -----------------------------------------------------------------------------
procedure TLockCondition.Cancel;
begin
FCancelled := True;
Update;
end;
// -----------------------------------------------------------------------------
// TPrecondition
// -----------------------------------------------------------------------------
constructor TPrecondition.Create(Condition: TFunc<System.boolean>);
begin
if not Assigned(Condition) then
raise ESyncObjectException.Create('TPrecondition: precondition unknown');
FCondition := Condition;
inherited Create;
end;
// -----------------------------------------------------------------------------
function TPrecondition.WaitFor(CriticalSection: TCriticalSection;
Timeout: cardinal): TWaitResult;
begin
result := inherited WaitFor(CriticalSection, FCondition, Timeout);
end;
// -----------------------------------------------------------------------------
// TSyncPoint
// -----------------------------------------------------------------------------
constructor TSyncPoint.Create(InitialThreadCount: integer);
begin
if (InitialThreadCount < 0) then
InitialThreadCount := 0;
FThreadCount := InitialThreadCount;
Event := TEvent.Create(nil, True, (InitialThreadCount = 0), '');
end;
// -----------------------------------------------------------------------------
destructor TSyncPoint.Destroy;
begin
Event.Free;
inherited;
end;
// -----------------------------------------------------------------------------
procedure TSyncPoint.AddThread;
begin
if (InterlockedIncrement(FThreadCount) = 0) then
Event.SetEvent
else
Event.ResetEvent;
end;
// -----------------------------------------------------------------------------
procedure TSyncPoint.Reached;
begin
if (InterlockedDecrement(FThreadCount) = 0) then
Event.SetEvent;
end;
// -----------------------------------------------------------------------------
function TSyncPoint.WaitFor(Timeout: cardinal): TWaitResult;
begin
try
result := Event.WaitFor(Timeout);
except
result := wrError;
end;
end;
// -----------------------------------------------------------------------------
procedure TSyncPoint.MsgWaitFor(Callback: TWaitNotifyEvent);
begin
Event.MsgWaitFor(Callback);
end;
// -----------------------------------------------------------------------------
// TRendezvous<T>
// -----------------------------------------------------------------------------
constructor TRendezvous<T>.Create;
begin
sendReady := TEvent.Create(nil, False, False, '');
receiveReady := TEvent.Create(nil, False, False, '');
sendCS := TCriticalSection.Create;
receiveCS := TCriticalSection.Create;
FCancelled := false;
end;
destructor TRendezvous<T>.Destroy;
begin
sendReady.Free;
receiveReady.Free;
sendCS.Free;
receiveCS.Free;
end;
procedure TRendezvous<T>.send(data: T);
begin
sendCS.Enter;
try
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
FData := data;
sendReady.SetEvent;
receiveReady.WaitFor;
finally
sendCS.Leave;
end;
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
end;
function TRendezvous<T>.receive: T;
begin
receiveCS.Enter;
try
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
sendReady.WaitFor;
if (not FCancelled) then
begin
result := FData;
receiveReady.SetEvent;
end;
finally
receiveCS.Leave;
end;
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
end;
function TRendezvous<T>.receive(copyProcedure: TProc<T, T>): T;
begin
receiveCS.Enter;
try
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
sendReady.WaitFor;
if (not FCancelled) then
begin
result := FData;
if Assigned(copyProcedure) then
try
copyProcedure(FData, result);
except
end;
receiveReady.SetEvent;
end;
finally
receiveCS.Leave;
end;
if (FCancelled) then
raise ESyncObjectException.Create('Sync object was cancelled');
end;
procedure TRendezvous<T>.Cancel;
begin
FCancelled := True;
receiveReady.SetEvent;
sendReady.SetEvent;
end;
// -----------------------------------------------------------------------------
end.
|
unit xVectorMap;
interface
uses Classes, SysUtils, xVectorLine, XMLIntf,
XMLDoc,Variants, FMX.Graphics, System.UITypes, system.Types, FMX.Types,
FMX.Controls, FMX.StdCtrls, FMX.Objects, xVectorType, xVectorArc;
type
TVectorMap = class
private
FVectorList: TStringList;
FOwner : TComponent;
XMLDocument1: TXMLDocument;
FRect: TRectF;
FText : TText;
FCanvas: TControl;
FBackColor: TAlphaColor;
FRectangle: TRectangle;
FTempVectorA, FTempVectorB, FTempVectorC : TVectorLineInfo;
FLineH, FLineV : TLine;
FArcList: TStringList;
FVectorMapName: string;
FIsCanSelect: Boolean;
FOnSelectVector: TNotifyEvent;
FOnSelectArc: TNotifyEvent;
function GetVectorInfo(nIndex: Integer): TVectorLineInfo;
procedure SetVectorStr(const Value: string);
function GetVectorStr: string;
function GetArcInfo(nIndex: Integer): TVectorArc;
procedure ClearList(slList : TStringList);
function GetMaxWidth : Single;
/// <summary>
/// 获取向量最大长度
/// </summary>
function GetMaxVectorLen(AVType: tTVectorType) : Single;
/// <summary>
/// 根据ID获取向量
/// </summary>
function GetVectorInfoByID(nVID : Integer) : TVectorLineInfo;
procedure SetIsCanSelect(const Value: Boolean);
/// <summary>
/// 向量双击事件
/// </summary>
procedure VectorDblClick(Sender: TObject);
/// <summary>
/// 向量鼠标按下事件
/// </summary>
procedure VectorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
/// <summary>
/// 背景图鼠标按下事件
/// </summary>
procedure MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure SetCanvas(const Value: TControl);
/// <summary>
/// 弧线鼠标按下事件
/// </summary>
procedure ArcMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
public
/// <summary>
/// 向量列表
/// </summary>
property VectorList : TStringList read FVectorList write FVectorList;
property VectorInfo[nIndex : Integer] : TVectorLineInfo read GetVectorInfo;
/// <summary>
/// 设置全部向量处在不选择状态
/// </summary>
procedure SetNoSelect;
procedure SetNoMainSelect;
/// <summary>
/// 添加向量
/// </summary>
function AddVector : TVectorLineInfo;
/// <summary>
/// 删除向量
/// </summary>
procedure DelVector(nVectorID : Integer);
/// <summary>
/// 背景图
/// </summary>
property BackColor : TAlphaColor read FBackColor write FBackColor;
/// <summary>
/// 向量图描述
/// </summary>
property VectorMapName : string read FVectorMapName write FVectorMapName;
/// <summary>
/// 删除选择向量
/// </summary>
procedure DelSelect;
/// <summary>
/// 获取选择的向量图个数
/// </summary>
function GetSelectVectorCount : Integer;
/// <summary>
/// 弧线列表
/// </summary>
property ArcList : TStringList read FArcList write FArcList;
property ArcInfo[nIndex : Integer] : TVectorArc read GetArcInfo;
/// <summary>
/// 添加弧线
/// </summary>
function AddArc : TVectorArc;
function AddVectorArc: TVectorArc;
/// <summary>
/// 删除弧线
/// </summary>
procedure DelArc(nArcID : Integer);
/// <summary>
/// 删除向量相关的弧线
/// </summary>
procedure DelVectorArc(nVectorID : Integer);
/// <summary>
/// 设置全部弧线处在不选择状态
/// </summary>
procedure SetArcNoSelect;
public
constructor Create(Owner : TComponent);
destructor Destroy; override;
/// <summary>
/// 最大电压值
/// </summary>
function GetMaxVolValue : Double;
/// <summary>
/// 最大电流值
/// </summary>
function GetMaxCurValue : Double;
/// <summary>
/// 向量图描述
/// </summary>
property VectorStr : string read GetVectorStr write SetVectorStr;
/// <summary>
/// *画布 必须赋值
/// </summary>
property Canvas : TControl read FCanvas write SetCanvas;
/// <summary>
/// *绘制区域 必须赋值
/// </summary>
property Rect : TRectF read FRect write FRect;
/// <summary>
/// 绘制
/// </summary>
procedure Draw;
/// <summary>
/// 是否允许选择 默认 允许
/// </summary>
property IsCanSelect : Boolean read FIsCanSelect write SetIsCanSelect;
/// <summary>
/// 选择向量事件
/// </summary>
property OnSelectVector : TNotifyEvent read FOnSelectVector write FOnSelectVector;
/// <summary>
/// 选择弧线事件
/// </summary>
property OnSelectArc : TNotifyEvent read FOnSelectArc write FOnSelectArc;
end;
var
AVectorControl : TVectorMap;
implementation
{ TVectorMap }
function TVectorMap.AddArc: TVectorArc;
function GetMaxID : Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to FArcList.Count - 1 do
begin
if ArcInfo[i].VID > Result then
Result := ArcInfo[i].VID;
end;
end;
begin
Result := TVectorArc.Create;
Result.VID := GetMaxID + 1;
Result.ArcR := GetMaxWidth/15*Result.VID+GetMaxWidth/10;
Result.OnMouseDown := ArcMouseDown;
FArcList.AddObject('', Result);
end;
function TVectorMap.AddVectorArc:TVectorArc;
function GetMainVercor(bMain : Boolean) : TVectorLineInfo;
var
i: Integer;
begin
Result := nil;
for i := 0 to FVectorList.Count - 1 do
begin
if (VectorInfo[i].IsMainSelect = bMain) and VectorInfo[i].IsSelected then
begin
Result := VectorInfo[i];
Break;
end;
end;
end;
var
AMain, AOther : TVectorLineInfo;
ACenterPoint : TPointF;
begin
Result := nil;
AMain := GetMainVercor(True);
AOther := GetMainVercor(False);
if Assigned(AMain) and Assigned(AOther) then
begin
ACenterPoint.X := FRect.Width/2;
ACenterPoint.y := FRect.Height/2;
Result := AddArc;
Result.StartVector := AMain;
Result.EndVector := AOther;
Result.CenterPoint := ACenterPoint;
Result.Canvas := FCanvas;
Result.Draw;
Result.FArc.SendToBack;
FRectangle.SendToBack;
end;
end;
function TVectorMap.AddVector: TVectorLineInfo;
function GetMaxID : Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to FVectorList.Count - 1 do
begin
if VectorInfo[i].VID > Result then
Result := VectorInfo[i].VID;
end;
end;
var
ACenterPoint : TPointF;
begin
ACenterPoint.X := FRect.Width/2;
ACenterPoint.y := FRect.Height/2;
Result := TVectorLineInfo.Create;
Result.VID := GetMaxID + 1;
Result.OnDblClick := VectorDblClick;
Result.OnMouseDown := VectorMouseDown;
Result.IsCanSelect := FIsCanSelect;
Result.CenterPoint := ACenterPoint;
Result.Canvas := FCanvas;
if Result.VType = vtVol then
Result.VMaxValue := GetMaxVolValue
else
Result.VMaxValue := GetMaxCurValue;
FVectorList.AddObject('', Result);
end;
procedure TVectorMap.ArcMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
SetArcNoSelect;
TVectorArc(Sender).IsSelected := True;
if Assigned(FOnSelectArc) then
FOnSelectArc(Sender);
end;
procedure TVectorMap.ClearList(slList : TStringList);
var
i: Integer;
begin
for i := slList.Count - 1 downto 0 do
slList.Objects[i].Free;
slList.Clear;
end;
constructor TVectorMap.Create(Owner : TComponent);
begin
FOwner := Owner;
XMLDocument1:= TXMLDocument.Create(FOwner);
FVectorList:= TStringList.Create;
FBackColor := $FFFFFFFF;;
FArcList := TStringList.Create;
FIsCanSelect := True;
end;
procedure TVectorMap.DelArc(nArcID: Integer);
var
i: Integer;
AArc : TVectorArc;
begin
for i := FArcList.Count - 1 downto 0 do
begin
AArc := ArcInfo[i];
if Assigned(AArc) then
begin
if AArc.VID = nArcID then
begin
AArc.Free;
FArcList.Delete(i);
end;
end;
end;
end;
procedure TVectorMap.DelSelect;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
for i := FVectorList.Count - 1 downto 0 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsSelected then
begin
// 删除向量相关的弧线
DelVectorArc(AVLInfo.VID);
// 删除向量图
AVLInfo.Free;
FVectorList.Delete(i);
end;
end;
end;
procedure TVectorMap.DelVector(nVectorID: Integer);
var
i: Integer;
AVLineInfo : TVectorLineInfo;
begin
for i := FVectorList.Count - 1 downto 0 do
begin
AVLineInfo := VectorInfo[i];
if Assigned(AVLineInfo) then
begin
if AVLineInfo.VID = nVectorID then
begin
AVLineInfo.Free;
FVectorList.Delete(i);
end;
end;
end;
end;
procedure TVectorMap.DelVectorArc(nVectorID: Integer);
var
i: Integer;
AArc : TVectorArc;
begin
for i := FArcList.Count - 1 downto 0 do
begin
AArc := ArcInfo[i];
if Assigned(AArc) then
begin
if (AArc.StartVector.VID = nVectorID) or (AArc.EndVector.VID = nVectorID) then
begin
AArc.Free;
FArcList.Delete(i);
end;
end;
end;
end;
destructor TVectorMap.Destroy;
begin
ClearList(FVectorList);
FVectorList.Free;
ClearList(FArcList);
FArcList.Free;
XMLDocument1.Free;
if Assigned(FText) then
FText.Free;
if Assigned(FLineV) then
FLinev.Free;
if Assigned(FLineH) then
FLineH.Free;
if Assigned(FRectangle) then
FRectangle.Free;
if Assigned(FTempVectorA) then
FTempVectorA.Free;
if Assigned(FTempVectorB) then
FTempVectorB.Free;
if Assigned(FTempVectorC) then
FTempVectorC.Free;
inherited;
end;
procedure TVectorMap.Draw;
var
AVector : TVectorLineInfo;
AArc : TVectorArc;
i: Integer;
ACenterPoint : TPointF;
dMaxVolValue, dMaxCurrentValue : Single;
procedure DrawVector( AVec: TVectorLineInfo; dAngle : Double; sName : string);
begin
if not Assigned(AVec) then
AVec := TVectorLineInfo.Create;
AVec.VAngle := dAngle;
AVec.CenterPoint := ACenterPoint;
AVec.Canvas := FCanvas;
AVec.VMaxValue := dMaxVolValue;
AVec.VMaxWidth := GetMaxWidth;
AVec.VColor := $3FC0C0C0;
AVec.VDash := TStrokeDash.Solid;
AVec.VName := sName;
AVec.IsCanSelect := False;
AVec.IsDrawPoint := False;
AVec.Draw;
end;
begin
if not Assigned(FCanvas) then
Exit;
ACenterPoint.X := FRect.Width/2;
ACenterPoint.y := FRect.Height/2;
// 画背景
if not Assigned(FRectangle) then
FRectangle:= TRectangle.Create(FCanvas);
FRectangle.Parent := FCanvas;
FRectangle.OnMouseDown := MouseDown;
FRectangle.Stroke.Dash := TStrokeDash.Dash;
FRectangle.Position.X := 0;
FRectangle.Position.Y := 0;
FRectangle.Width := FRect.Width;
FRectangle.Height := FRect.Height;
FRectangle.Fill.Color := FBackColor;
FRectangle.Stroke.Color := $FFC0C0C0;
FRectangle.Stroke.Thickness := 1;
// 画背景交叉线
if not Assigned(FLineH) then
FLineH := TLine.Create(FRectangle);
FLineH.Parent := FRectangle;
FLineH.Position.X := 0;
FLineH.Position.y := FRectangle.Height/2-1;
FLineH.Width := FRectangle.Width;
FLineH.Height := 1;
FLineH.LineType := TLineType.Top;
FLineH.Stroke.Color := $FFC0C0C0;
FLineH.Stroke.Dash := TStrokeDash.Dash;
if not Assigned(FLineV) then
FLineV := TLine.Create(FRectangle);
FLineV.Parent := FRectangle;
FLineV.Position.X := FRectangle.Width/2;
FLineV.Position.y := 0;
FLineV.Width := 1;
FLineV.Height := FRectangle.Height;
FLineV.LineType := TLineType.Left;
FLineV.Stroke.Color := $FFC0C0C0;
FLineV.Stroke.Dash := TStrokeDash.Dash;
dMaxVolValue := GetMaxVolValue;
dMaxCurrentValue := GetMaxCurValue;
// 画描述
if not Assigned(FText) then
FText := TText.Create(FRectangle);
FText.Parent := FRectangle;
FText.Align := TAlignLayout.Bottom;
FText.Color := FBackColor xor $00C0C0C0;
FText.Text := FVectorMapName;
// 画辅助向量
DrawVector(FTempVectorA, 90, 'Ua');
DrawVector(FTempVectorB, 330, 'Ub');
DrawVector(FTempVectorC, 210, 'Uc');
// 画弧线
for i := 0 to FArcList.Count - 1 do
begin
AArc := ArcInfo[i];
AArc.CenterPoint := ACenterPoint;
AArc.Canvas := FCanvas;
AArc.Draw;
AArc.FArc.SendToBack;
end;
// 画向量
for i := 0 to FVectorList.Count - 1 do
begin
AVector := VectorInfo[i];
AVector.CenterPoint := ACenterPoint;
AVector.Canvas := FCanvas;
if AVector.VType = vtVol then
AVector.VMaxValue := dMaxVolValue
else
AVector.VMaxValue := dMaxCurrentValue;
AVector.VMaxWidth := GetMaxWidth;
AVector.Draw;
end;
FRectangle.SendToBack;
end;
function TVectorMap.GetArcInfo(nIndex: Integer): TVectorArc;
begin
if (nIndex >= 0) and (nIndex < FArcList.Count) then
begin
Result := TVectorArc(FArcList.Objects[nIndex]);
end
else
Result := nil;
end;
function TVectorMap.GetMaxCurValue: Double;
begin
Result := GetMaxVectorLen(vtCurrent)+2;
end;
function TVectorMap.GetMaxVectorLen(AVType: tTVectorType): Single;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
Result := 0;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.VType = AVType then
begin
if AVLInfo.VValue > Result then
Result := AVLInfo.VValue;
end;
end;
end;
function TVectorMap.GetMaxVolValue: Double;
begin
Result := GetMaxVectorLen(vtVol);
end;
function TVectorMap.GetMaxWidth: Single;
begin
if FRect.Height > FRect.Width then
begin
Result := FRect.Width/2-35;
end
else
begin
Result := FRect.Height/2-35;
end;
end;
function TVectorMap.GetSelectVectorCount: Integer;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
Result := 0;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsSelected then
begin
Inc(Result);
end;
end;
end;
function TVectorMap.GetVectorInfo(nIndex: Integer): TVectorLineInfo;
begin
if (nIndex >= 0) and (nIndex < FVectorList.Count) then
begin
Result := TVectorLineInfo(FVectorList.Objects[nIndex]);
end
else
Result := nil;
end;
function TVectorMap.GetVectorInfoByID(nVID: Integer): TVectorLineInfo;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
Result := nil;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.VID = nVID then
begin
Result := AVLInfo;
Break;
end;
end;
end;
function TVectorMap.GetVectorStr: string;
const
C_XML = '<LineInfo VID ="%d" VName ="%s" VType="%s" VColor="%d" VValue="%f" VAngle="%f" VDrawPoint="%s">%s</LineInfo>';
C_XML_ARC = '<ArcInfo VID ="%d" VName ="%s" StartVectorName="%s" EndVectorName="%s" StartVectorID="%d" EndVectorID="%d"> </ArcInfo>';
var
i: Integer;
begin
Result := '<?xml version="1.0" encoding="gb2312"?>' + #13#10;
Result := Result + '<VectorMap>' + #13#10;
Result := Result + '<VectorLine>' + #13#10;
for i := 0 to FVectorList.Count - 1 do
begin
with VectorInfo[i] do
begin
Result := Result + Format(C_XML, [VID, VName, VTypeStr, VColor, VValue, VAngle,BoolToStr(IsDrawPoint), VName ]) + #13#10;
end;
end;
Result := Result + '</VectorLine>' + #13#10;
Result := Result + '<VectorArc>' + #13#10;
for i := 0 to FArcList.Count - 1 do
begin
with ArcInfo[i] do
begin
if Assigned(StartVector) and Assigned(EndVector) then
begin
Result := Result + Format(C_XML_ARC, [VID, VName, StartVector.VName, EndVector.VName, StartVector.VID, EndVector.VID]) + #13#10;
end;
end;
end;
Result := Result + '</VectorArc>' + #13#10;
Result := Result + '</VectorMap>' + #13#10;
end;
procedure TVectorMap.MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
SetNoSelect;
SetArcNoSelect;
if Assigned(FOnSelectVector) then
FOnSelectVector(nil);
if Assigned(FOnSelectArc) then
FOnSelectArc(nil);
end;
procedure TVectorMap.VectorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure SetVectorMain;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsSelected then
begin
AVLInfo.IsMainSelect := True;
Break;
end;
end;
end;
var
nCount : Integer;
begin
nCount := GetSelectVectorCount;
if ssCtrl in Shift then
begin
if nCount = 0 then
begin
TVectorLineInfo(Sender).IsSelected := true;
TVectorLineInfo(Sender).IsMainSelect := true;
end
else
begin
TVectorLineInfo(Sender).IsSelected := not TVectorLineInfo(Sender).IsSelected;
if not TVectorLineInfo(Sender).IsSelected then
begin
TVectorLineInfo(Sender).IsMainSelect := False;
SetVectorMain;
end;
end;
TVectorLineInfo(Sender).Draw;
end
else
begin
if TVectorLineInfo(Sender).IsSelected then
begin
SetNoMainSelect;
TVectorLineInfo(Sender).IsMainSelect := true;
end
else
begin
SetNoSelect;
TVectorLineInfo(Sender).IsSelected := true;
TVectorLineInfo(Sender).IsMainSelect := true;
end;
TVectorLineInfo(Sender).Draw;
end;
if Assigned(FOnSelectVector) then
FOnSelectVector(Sender);
end;
procedure TVectorMap.SetArcNoSelect;
var
i: Integer;
begin
for i := 0 to FArcList.Count - 1 do
begin
if ArcInfo[i].IsSelected then
begin
ArcInfo[i].IsSelected := False;
ArcInfo[i].Draw;
end;
end;
end;
procedure TVectorMap.SetCanvas(const Value: TControl);
begin
if FCanvas <> Value then
begin
FCanvas := Value;
end;
end;
procedure TVectorMap.SetIsCanSelect(const Value: Boolean);
var
i: Integer;
begin
FIsCanSelect := Value;
for i := 0 to FVectorList.Count - 1 do
VectorInfo[i].IsCanSelect := Value;
end;
procedure TVectorMap.SetNoMainSelect;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
AVLInfo.IsMainSelect := False;
AVLInfo.Draw;
end;
end;
procedure TVectorMap.SetNoSelect;
var
i: Integer;
AVLInfo : TVectorLineInfo;
begin
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
AVLInfo.IsSelected := False;
AVLInfo.IsMainSelect := False;
AVLInfo.Draw;
end;
end;
procedure TVectorMap.SetVectorStr(const Value: string);
function GetStrValue(sValue : string; Anode:IXMLNode) : string;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := '';
end;
function GetIntValue(sValue : string; Anode:IXMLNode) : Integer;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := 0;
end;
function GetFloatValue(sValue : string; Anode:IXMLNode) : Double;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := 0;
end;
function GetBoolValue(sValue : string; Anode:IXMLNode) : Boolean;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := True;
end;
var
node, nodeInfo: IXMLNode;
i: Integer;
j: Integer;
AVLInfo : TVectorLineInfo;
AArcInfo : TVectorArc;
begin
ClearList(FVectorList);
ClearList(FArcList);
XMLDocument1.XML.Text := Value;
XMLDocument1.Active := True;
for i := 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do
begin
node := XMLDocument1.DocumentElement.ChildNodes[i];
if node.NodeName = 'VectorLine' then
begin
for j := 0 to node.ChildNodes.Count - 1 do
begin
nodeInfo := node.ChildNodes[j];
AVLInfo := AddVector;
AVLInfo.VID := GetIntValue('VID', nodeInfo);
AVLInfo.VName := GetStrValue('VName', nodeInfo);
AVLInfo.VTypeStr := GetStrValue('VType', nodeInfo);
AVLInfo.VColor := GetIntValue('VColor', nodeInfo);
AVLInfo.VValue := GetFloatValue('VValue', nodeInfo);
AVLInfo.VAngle := GetFloatValue('VAngle', nodeInfo);
AVLInfo.IsDrawPoint := GetBoolValue('VDrawPoint', nodeInfo);
end;
end;
end;
for i := 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do
begin
node := XMLDocument1.DocumentElement.ChildNodes[i];
if node.NodeName = 'VectorArc' then
begin
for j := 0 to node.ChildNodes.Count - 1 do
begin
nodeInfo := node.ChildNodes[j];
AArcInfo := AddArc;
AArcInfo.VID := GetIntValue('VID', nodeInfo);
AArcInfo.VName := GetStrValue('VName', nodeInfo);
AArcInfo.StartVector := GetVectorInfoByID(GetIntValue('StartVectorID', nodeInfo));
AArcInfo.EndVector := GetVectorInfoByID(GetIntValue('EndVectorID', nodeInfo));
end;
end;
end;
Draw;
end;
procedure TVectorMap.VectorDblClick(Sender: TObject);
begin
end;
end.
|
unit MainFrm;
{$WARN UNIT_PLATFORM OFF}
interface
uses
Classes,
ComCtrls,
Controls,
Dialogs,
Forms,
Mask,
StdCtrls,
XMLDOM,
XMLIntf,
DataBindingHintsXML,
XMLDataBindingGenerator
{
cxButtonEdit,
cxContainer,
cxControls,
cxEdit,
cxLookAndFeels,
cxMaskEdit,
cxTextEdit,
cxGraphics, cxLookAndFeelPainters, cxClasses}
;
type
TMainForm = class(TForm)
btnClose: TButton;
btnGenerate: TButton;
btnHints: TButton;
dlgOutputFile: TSaveDialog;
dlgSchema: TOpenDialog;
gbOutput: TGroupBox;
lblFile: TLabel;
lblFolder: TLabel;
lblFolderPostfix: TLabel;
lblFolderPrefix: TLabel;
lblSchema: TLabel;
plOutput: TPageControl;
rbFile: TRadioButton;
rbFolder: TRadioButton;
spFile: TTabSheet;
spFolder: TTabSheet;
cbHasChecksEmpty: TCheckBox;
cbGenerateGetOptionalOrDefault: TCheckBox;
edtFolderPrefix: TEdit;
edtFolderPostfix: TEdit;
deFolder: TEdit;
deFolderPropertiesButton: TButton;
feSchema: TEdit;
SchmeFileBrowseButton: TButton;
feFile: TEdit;
ButtonOutputFileBrowseButton: TButton;
procedure btnCloseClick(Sender: TObject);
procedure btnGenerateClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OutputTypeClick(Sender: TObject);
procedure feFilePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
procedure deFolderPropertiesButtonClick(Sender: TObject);
procedure feSchemaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
procedure feSchemaPropertiesChange(Sender: TObject);
procedure btnHintsClick(Sender: TObject);
procedure SchmeFileBrowseButtonClick(Sender: TObject);
procedure ButtonOutputFileBrowseButtonClick(Sender: TObject);
private
function CheckValidSchemaFile: Boolean;
function CheckReadOnly(const AFileName: String): Boolean;
procedure GetFileName(Sender: TObject; const SchemaName: String; var Path, FileName: String);
function GetSettingsFileName(const AFileName: String): String;
procedure LoadSettings(const AFileName: String);
procedure SaveSettings(const AFileName: String);
end;
implementation
uses
FileCtrl,
SysUtils,
Windows,
Generics.Collections,
MSXMLDOM,
MSXML2_TLB,
X2UtNamedFormat,
X2UtTempFile,
DataBindingSettingsXML,
DelphiXMLDataBindingGenerator;
type
TProtectedXMLDataBindingItem = class(TXMLDataBindingItem);
TProtectedXMLDataBindingProperty = class(TXMLDataBindingProperty);
THintsDelphiXMLDataBindingGenerator = class(TDelphiXMLDataBindingGenerator)
private
FHints: IXMLDataBindingHints;
protected
procedure GenerateDataBinding; override;
procedure ProcessHints;
procedure ProcessEnumerations;
procedure ProcessDocumentElements;
procedure ProcessInterfaces;
procedure ProcessProperties;
function FindSchema(const ASchemaName: String; out ASchema: TXMLDataBindingSchema): Boolean;
function FindNode(const ASchemaName, AXPath: String; out AItem: TXMLDataBindingItem): Boolean;
public
property Hints: IXMLDataBindingHints read FHints write FHints;
end;
{$R *.dfm}
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
var
schemaFile: String;
begin
plOutput.ActivePageIndex := 0;
if ParamCount > 0 then
begin
schemaFile := ParamStr(1);
if FileExists(schemaFile) then
begin
feFile.Text := ChangeFileExt(schemaFile, '.pas');
deFolder.Text := ExtractFilePath(schemaFile);
{ Set schema last, the Change event will attempt to load the
settings file and overwrite the file / folder. }
feSchema.Text := schemaFile;
end;
end;
end;
procedure TMainForm.OutputTypeClick(Sender: TObject);
begin
if Sender = rbFile then
plOutput.ActivePage := spFile
else if Sender = rbFolder then
plOutput.ActivePage := spFolder;
end;
procedure TMainForm.btnGenerateClick(Sender: TObject);
var
hintsFile: String;
hints: IXMLDataBindingHints;
generator: THintsDelphiXMLDataBindingGenerator;
begin
if not CheckValidSchemaFile then
Exit;
hintsFile := ChangeFileExt(feSchema.Text, '.hints.xml');
if FileExists(hintsFile) then
hints := LoadDataBindingHints(hintsFile);
try
generator := THintsDelphiXMLDataBindingGenerator.Create;
try
generator.Hints := hints;
if rbFile.Checked then
begin
if not CheckReadOnly(feFile.Text) then
Exit;
generator.OutputType := otSingle;
generator.OutputPath := feFile.Text;
end else if rbFolder.Checked then
begin
generator.OutputType := otMultiple;
generator.OutputPath := deFolder.Text;
end;
generator.HasChecksEmpty := cbHasChecksEmpty.Checked;
generator.HasGenerateGetOptionalOrDefault := cbGenerateGetOptionalOrDefault.Checked;
generator.OnGetFileName := GetFileName;
generator.Execute(feSchema.Text);
SaveSettings(feSchema.Text);
ShowMessage('The data binding has been generated.');
finally
FreeAndNil(generator);
end;
finally
hints := nil;
end;
end;
procedure TMainForm.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.GetFileName(Sender: TObject; const SchemaName: String; var Path, FileName: String);
begin
FileName := ChangeFileExt(edtFolderPrefix.Text + FileName,
edtFolderPostfix.Text + ExtractFileExt(FileName));
CheckValidFileName(FileName);
end;
procedure TMainForm.feFilePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
if dlgOutputFile.Execute then
feFile.Text := dlgOutputFile.FileName;
end;
procedure TMainForm.deFolderPropertiesButtonClick(Sender: TObject);
var
directory: String;
begin
if SelectDirectory('Select output folder', '', directory) then
deFolder.Text := directory;
end;
procedure TMainForm.feSchemaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
if dlgSchema.Execute then
feSchema.Text := dlgSchema.FileName;
end;
procedure TMainForm.feSchemaPropertiesChange(Sender: TObject);
begin
if FileExists(feSchema.Text) then
LoadSettings(feSchema.Text);
end;
function TMainForm.GetSettingsFileName(const AFileName: String): String;
begin
Result := ChangeFileExt(AFileName, '.settings.xml');
end;
procedure TMainForm.LoadSettings(const AFileName: String);
var
fileName: String;
settings: IXMLDataBindingSettings;
outputSingle: IXMLOutputSingle;
outputMultiple: IXMLOutputMultiple;
begin
fileName := GetSettingsFileName(AFileName);
if FileExists(fileName) then
begin
settings := LoadDataBindingSettings(fileName);
if settings.HasOutput then
begin
case settings.Output.OutputType of
DataBindingOutputType_Single:
begin
outputSingle := settings.Output.OutputSingle;
rbFile.Checked := True;
feFile.Text := outputSingle.FileName;
end;
DataBindingOutputType_Multiple:
begin
outputMultiple := settings.Output.OutputMultiple;
rbFolder.Checked := True;
deFolder.Text := outputMultiple.Path;
edtFolderPrefix.Text := outputMultiple.Prefix;
edtFolderPostfix.Text := outputMultiple.Postfix;
end;
end;
cbHasChecksEmpty.Checked := settings.Output.HasHasChecksEmpty and settings.Output.HasChecksEmpty;
cbGenerateGetOptionalOrDefault.Checked := settings.Output.HasGenerateGetOptionalOrDefault and settings.Output.GenerateGetOptionalOrDefault;
end;
end;
end;
procedure TMainForm.SaveSettings(const AFileName: String);
var
fileName: String;
settings: IXMLDataBindingSettings;
outputSingle: IXMLOutputSingle;
outputMultiple: IXMLOutputMultiple;
begin
fileName := GetSettingsFileName(AFileName);
if FileExists(fileName) then
settings := LoadDataBindingSettings(fileName)
else
settings := NewDataBindingSettings;
settings.Output.ChildNodes.Clear;
if rbFile.Checked then
begin
settings.Output.OutputType := DataBindingOutputType_Single;
outputSingle := settings.Output.OutputSingle;
outputSingle.FileName := feFile.Text;
end else
begin
settings.Output.OutputType := DataBindingOutputType_Multiple;
outputMultiple := settings.Output.OutputMultiple;
outputMultiple.Path := deFolder.Text;
outputMultiple.Prefix := edtFolderPrefix.Text;
outputMultiple.Postfix := edtFolderPostfix.Text;
end;
settings.Output.HasChecksEmpty := cbHasChecksEmpty.Checked;
settings.Output.GenerateGetOptionalOrDefault := cbGenerateGetOptionalOrDefault.Checked;
settings.OwnerDocument.SaveToFile(fileName);
end;
procedure TMainForm.SchmeFileBrowseButtonClick(Sender: TObject);
begin
if dlgSchema.Execute then
begin
feSchema.Text := dlgSchema.FileName;
end;
end;
function TMainForm.CheckValidSchemaFile: Boolean;
begin
Result := FileExists(feSchema.Text);
if not Result then
begin
MessageBox(Self.Handle, 'Please specify a valid schema file.',
'Schema file does not exist', MB_OK or MB_ICONERROR);
ActiveControl := feFile;
Exit;
end;
end;
function TMainForm.CheckReadOnly(const AFileName: String): Boolean;
begin
Result := True;
if FileExists(AFileName) and FileIsReadOnly(AFileName) then
begin
if MessageBox(Self.Handle, 'The output file is read-only. Do you want to ' +
'remove the read-only attribute?',
'Read-only', MB_YESNO or MB_ICONQUESTION) = ID_YES then
begin
Result := FileSetReadOnly(AFileName, False);
end else
Result := False;
end;
end;
procedure TMainForm.btnHintsClick(Sender: TObject);
var
hintsFile: String;
hints: IXMLDataBindingHints;
begin
if CheckValidSchemaFile then
begin
hintsFile := ChangeFileExt(feSchema.Text, '.hints.xml');
if FileExists(hintsFile) then
begin
if MessageBox(Self.Handle, 'Do you want to overwrite the existing hints file?',
'Overwrite', MB_YESNO or MB_ICONQUESTION) <> ID_YES then
Exit;
end;
hints := NewDataBindingHints;
hints.OwnerDocument.SaveToFile(hintsFile);
ShowMessage('The hints file has been generated.');
end;
end;
procedure TMainForm.ButtonOutputFileBrowseButtonClick(Sender: TObject);
begin
if dlgOutputFile.Execute then
begin
feFile.Text := dlgOutputFile.FileName;
end;
end;
{ THintsDelphiXMLDataBindingGenerator }
procedure THintsDelphiXMLDataBindingGenerator.GenerateDataBinding;
begin
if Assigned(Hints) then
ProcessHints;
inherited GenerateDataBinding;
end;
procedure THintsDelphiXMLDataBindingGenerator.ProcessHints;
begin
if Hints.HasEnumerations then
ProcessEnumerations;
if Hints.HasDocumentElements then
ProcessDocumentElements;
if Hints.HasInterfaces then
ProcessInterfaces;
if Hints.HasProperties then
ProcessProperties;
end;
procedure THintsDelphiXMLDataBindingGenerator.ProcessEnumerations;
procedure ProcessEnumeration(ABindingEnumeration: TXMLDataBindingEnumeration; AHintEnumeration: IXMLEnumeration);
var
hintMemberIndex: Integer;
memberName: String;
memberIndex: Integer;
begin
for hintMemberIndex := 0 to Pred(AHintEnumeration.Count) do
begin
memberName := AHintEnumeration.Member[hintMemberIndex].Name;
for memberIndex := 0 to Pred(ABindingEnumeration.MemberCount) do
begin
if ABindingEnumeration.Members[memberIndex].Name = memberName then
begin
ABindingEnumeration.Members[memberIndex].TranslatedName := AHintEnumeration[hintMemberIndex].Text;
Break;
end;
end;
end;
end;
function GetNewMembers(ABindingEnumeration: TXMLDataBindingEnumeration; AHintEnumeration: IXMLEnumeration): TList<TXMLDataBindingEnumerationMember>;
var
hintMemberIndex: Integer;
member: TXMLDataBindingEnumerationMember;
begin
Result := TList<TXMLDataBindingEnumerationMember>.Create;
for hintMemberIndex := 0 to Pred(AHintEnumeration.Count) do
begin
member := TXMLDataBindingEnumerationMember.Create(Self, ABindingEnumeration, AHintEnumeration[hintMemberIndex].Name);
member.TranslatedName := AHintEnumeration[hintMemberIndex].Text;
Result.Add(member);
end;
end;
var
itemIndex: Integer;
enumeration: IXMLEnumeration;
schemaItem: TXMLDataBindingItem;
enumerationItem: TXMLDataBindingEnumeration;
propertyItem: TXMLDataBindingSimpleProperty;
newMembers: TList<TXMLDataBindingEnumerationMember>;
newPropertyItem: TXMLDataBindingItemProperty;
targetSchema: TXMLDataBindingSchema;
begin
for itemIndex := 0 to Pred(Hints.Enumerations.Count) do
begin
enumeration := Hints.Enumerations[itemIndex];
if FindNode(enumeration.Schema, enumeration.XPath, schemaItem) then
begin
case schemaItem.ItemType of
itEnumeration:
begin
enumerationItem := TXMLDataBindingEnumeration(schemaItem);
if enumeration.HasReplaceMembers and enumeration.ReplaceMembers then
begin
newMembers := GetNewMembers(enumerationItem, enumeration);
try
enumerationItem.ReplaceMembers(newMembers);
finally
FreeAndNil(newMembers);
end;
end else
ProcessEnumeration(TXMLDataBindingEnumeration(schemaItem), enumeration);
end;
itProperty:
if TXMLDataBindingProperty(schemaItem).PropertyType = ptSimple then
begin
propertyItem := TXMLDataBindingSimpleProperty(schemaItem);
if propertyItem.DataType.Name = 'string' then
begin
enumerationItem := TXMLDataBindingEnumeration.Create(Self, schemaItem.SchemaItem, nil, schemaItem.Name);
if FindSchema(enumeration.Schema, targetSchema) then
targetSchema.AddItem(enumerationItem);
newPropertyItem := TXMLDataBindingItemProperty.Create(Self, propertyItem.SchemaItem, propertyItem.Name, enumerationItem);
newMembers := GetNewMembers(enumerationItem, enumeration);
try
enumerationItem.ReplaceMembers(newMembers);
ReplaceItem(schemaItem, newPropertyItem, False);
finally
FreeAndNil(newMembers);
end;
end;
end;
end;
end;
end;
end;
procedure THintsDelphiXMLDataBindingGenerator.ProcessDocumentElements;
var
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
itemIndex: Integer;
documentElement: IXMLDocumentElement;
schemaItem: TXMLDataBindingItem;
begin
for schemaIndex := 0 to Pred(SchemaCount) do
begin
schema := Schemas[schemaIndex];
for itemIndex := 0 to Pred(schema.ItemCount) do
schema.Items[itemIndex].DocumentElement := False;
end;
for itemIndex := 0 to Pred(Hints.DocumentElements.Count) do
begin
documentElement := Hints.DocumentElements[itemIndex];
if FindNode(documentElement.Schema, documentElement.XPath, schemaItem) then
begin
if schemaItem.ItemType = itInterface then
schemaItem.DocumentElement := True;
end;
end;
end;
procedure THintsDelphiXMLDataBindingGenerator.ProcessInterfaces;
var
itemIndex: Integer;
interfaceName: IXMLInterfaceName;
schemaItem: TXMLDataBindingItem;
propertyItem: TXMLDataBindingProperty;
begin
for itemIndex := 0 to Pred(Hints.Interfaces.Count) do
begin
interfaceName := Hints.Interfaces[itemIndex];
if FindNode(interfaceName.Schema, interfaceName.XPath, schemaItem) then
begin
case schemaItem.ItemType of
itInterface,
itEnumeration:
schemaItem.TranslatedName := interfaceName.Text;
itProperty:
begin
propertyItem := TXMLDataBindingProperty(schemaItem);
if propertyItem.PropertyType = ptItem then
TXMLDataBindingItemProperty(propertyItem).Item.TranslatedName := interfaceName.Text;
end;
end;
end;
end;
end;
procedure THintsDelphiXMLDataBindingGenerator.ProcessProperties;
var
itemIndex: Integer;
propertyName: IXMLPropertyName;
schemaItem: TXMLDataBindingItem;
begin
for itemIndex := 0 to Pred(Hints.Properties.Count) do
begin
propertyName := Hints.Properties[itemIndex];
if FindNode(propertyName.Schema, propertyName.XPath, schemaItem) then
begin
if schemaItem.ItemType = itProperty then
schemaItem.TranslatedName := propertyName.Text;
end;
end;
end;
function THintsDelphiXMLDataBindingGenerator.FindSchema(const ASchemaName: String; out ASchema: TXMLDataBindingSchema): Boolean;
var
schemaIndex: Integer;
begin
Result := False;
if SchemaCount > 0 then
begin
if Length(ASchemaName) = 0 then
begin
ASchema := Schemas[0];
Result := True;
end else
begin
for schemaIndex := 0 to Pred(SchemaCount) do
if SameText(Schemas[schemaIndex].SchemaName, ASchemaName) then
begin
ASchema := Schemas[schemaIndex];
Result := True;
Break;
end;
end;
end;
end;
function THintsDelphiXMLDataBindingGenerator.FindNode(const ASchemaName, AXPath: String; out AItem: TXMLDataBindingItem): Boolean;
function SameNode(ANode1, ANode2: IDOMNode): Boolean;
var
attributeIndex: Integer;
attribute1: IDOMNode;
attribute2: IDOMNode;
hasParent1: Boolean;
hasParent2: Boolean;
begin
{ Compare name and number of attributes }
Result := (ANode1.nodeName = ANode2.nodeName) and
(ANode1.attributes.length = ANode2.attributes.length);
if Result then
begin
{ Compare attribute content }
for attributeIndex := 0 to Pred(ANode1.attributes.length) do
begin
attribute1 := ANode1.attributes[attributeIndex];
attribute2 := ANode2.attributes[attributeIndex];
Result := (attribute1.nodeName = attribute2.nodeName) and
(attribute1.nodeValue = attribute2.nodeValue);
if not Result then
Break;
end;
if Result then
begin
{ Compare parent nodes }
hasParent1 := Assigned(ANode1.parentNode) and (ANode1.parentNode.nodeType <> NODE_DOCUMENT);
hasParent2 := Assigned(ANode2.parentNode) and (ANode2.parentNode.nodeType <> NODE_DOCUMENT);
if hasParent1 = hasParent2 then
begin
if hasParent1 then
Result := SameNode(ANode1.parentNode, ANode2.parentNode);
end else
Result := False;
end;
end;
end;
var
schema: TXMLDataBindingSchema;
schemaItem: IDOMNode;
item: TProtectedXMLDataBindingItem;
itemIndex: Integer;
domDocument: IXMLDOMDocument2;
interfaceItem: TXMLDataBindingInterface;
propertyIndex: Integer;
propertyItem: TProtectedXMLDataBindingProperty;
begin
Result := False;
if (Length(AXPath) > 0) and FindSchema(ASchemaName, schema) then
begin
domDocument := ((schema.SchemaDef.OwnerDocument.DOMDocument as IXMLDOMNodeRef).GetXMLDOMNode as IXMLDOMDocument2);
domDocument.setProperty('SelectionLanguage', 'XPath');
domDocument.setProperty('SelectionNamespaces', 'xmlns:xs="http://www.w3.org/2001/XMLSchema"');
schemaItem := (schema.SchemaDef.DOMNode as IDOMNodeSelect).selectNode(AXPath);
if Assigned(schemaItem) then
begin
for itemIndex := 0 to Pred(schema.ItemCount) do
begin
item := TProtectedXMLDataBindingItem(schema.Items[itemIndex]);
if Assigned(item.SchemaItem) and SameNode(item.SchemaItem.DOMNode, schemaItem) then
begin
AItem := schema.Items[itemIndex];
Result := True;
end else if item.ItemType = itInterface then
begin
interfaceItem := TXMLDataBindingInterface(item);
for propertyIndex := 0 to Pred(interfaceItem.PropertyCount) do
begin
propertyItem := TProtectedXMLDataBindingProperty(interfaceItem.Properties[propertyIndex]);
if Assigned(propertyItem.SchemaItem) and SameNode(propertyItem.SchemaItem.DOMNode, schemaItem) then
begin
AItem := propertyItem;
Result := True;
Break;
end;
end;
end;
if Result then
Break;
end;
end;
end;
end;
end.
|
unit SLABHIDtoUART;
interface
uses windows, classes;
type
HID_UART_STATUS = integer;
/////////////////////////////////////////////////////////////////////////////
// Return Code Definitions
/////////////////////////////////////////////////////////////////////////////
const
// Return Codes
HID_UART_SUCCESS = $00;
HID_UART_DEVICE_NOT_FOUND = $01;
HID_UART_INVALID_HANDLE = $02;
HID_UART_INVALID_DEVICE_OBJECT = $03;
HID_UART_INVALID_PARAMETER = $04;
HID_UART_INVALID_REQUEST_LENGTH = $05;
HID_UART_READ_ERROR = $10;
HID_UART_WRITE_ERROR = $11;
HID_UART_READ_TIMED_OUT = $12;
HID_UART_WRITE_TIMED_OUT = $13;
HID_UART_DEVICE_IO_FAILED = $14;
HID_UART_DEVICE_ACCESS_ERROR = $15;
HID_UART_DEVICE_NOT_SUPPORTED = $16;
HID_UART_INVALID_CONFIG_VERSION = $17;
HID_UART_UNKNOWN_ERROR = $FF;
// Product String Types
HID_UART_GET_VID_STR = $01;
HID_UART_GET_PID_STR = $02;
HID_UART_GET_PATH_STR = $03;
HID_UART_GET_SERIAL_STR = $04;
HID_UART_GET_MANUFACTURER_STR = $05;
HID_UART_GET_PRODUCT_STR = $06;
// String Lengths
HID_UART_DEVICE_STRLEN = 260;
type
HID_UART_DEVICE_STR = array [0 .. HID_UART_DEVICE_STRLEN - 1] of ansichar;
const
/////////////////////////////////////////////////////////////////////////////
// UART Definitions
/////////////////////////////////////////////////////////////////////////////
// Error Status
HID_UART_PARITY_ERROR = $01;
HID_UART_OVERRUN_ERROR = $02;
// Line Break Status
HID_UART_LINE_BREAK_INACTIVE = $00;
HID_UART_LINE_BREAK_ACTIVE = $01;
// Data Bits
HID_UART_FIVE_DATA_BITS = $00;
HID_UART_SIX_DATA_BITS = $01;
HID_UART_SEVEN_DATA_BITS = $02;
HID_UART_EIGHT_DATA_BITS = $03;
// Parity
HID_UART_NO_PARITY = $00;
HID_UART_ODD_PARITY = $01;
HID_UART_EVEN_PARITY = $02;
HID_UART_MARK_PARITY = $03;
HID_UART_SPACE_PARITY = $04;
// Stop Bits
// Short = 1 stop bit
// Long = 1.5 stop bits (5 data bits)
// = 2 stop bits (6-8 data bits)
HID_UART_SHORT_STOP_BIT = $00;
HID_UART_LONG_STOP_BIT = $01;
// Flow Control
HID_UART_NO_FLOW_CONTROL = $00;
HID_UART_RTS_CTS_FLOW_CONTROL = $01;
// Read/Write Limits
HID_UART_MIN_READ_SIZE = 1;
HID_UART_MAX_READ_SIZE = 32768;
HID_UART_MIN_WRITE_SIZE = 1;
HID_UART_MAX_WRITE_SIZE = 4096;
/////////////////////////////////////////////////////////////////////////////
// Part Number Definitions
/////////////////////////////////////////////////////////////////////////////
// Part Numbers
HID_UART_PART_CP2110 = $0A;
HID_UART_PART_CP2114 = $0E;
/////////////////////////////////////////////////////////////////////////////
// User Customization Definitions
/////////////////////////////////////////////////////////////////////////////
// User-Customizable Field Lock Bitmasks
HID_UART_LOCK_PRODUCT_STR_1 = $0001;
HID_UART_LOCK_PRODUCT_STR_2 = $0002;
HID_UART_LOCK_SERIAL_STR = $0004;
HID_UART_LOCK_PIN_CONFIG = $0008;
HID_UART_LOCK_VID = $0100;
HID_UART_LOCK_PID = $0200;
HID_UART_LOCK_POWER = $0400;
HID_UART_LOCK_POWER_MODE = $0800;
HID_UART_LOCK_RELEASE_VERSION = $1000;
HID_UART_LOCK_FLUSH_BUFFERS = $2000;
HID_UART_LOCK_MFG_STR_1 = $4000;
HID_UART_LOCK_MFG_STR_2 = $8000;
// Field Lock Bit Values
HID_UART_LOCK_UNLOCKED = 1;
HID_UART_LOCK_LOCKED = 0;
// Power Max Value (500 mA)
HID_UART_BUS_POWER_MAX = $FA;
// Power Modes
HID_UART_BUS_POWER = $00;
HID_UART_SELF_POWER_VREG_DIS = $01;
HID_UART_SELF_POWER_VREG_EN = $02;
// Flush Buffers Bitmasks
HID_UART_FLUSH_TX_OPEN = $01;
HID_UART_FLUSH_TX_CLOSE = $02;
HID_UART_FLUSH_RX_OPEN = $04;
HID_UART_FLUSH_RX_CLOSE = $08;
// USB Config Bitmasks
HID_UART_SET_VID = $01;
HID_UART_SET_PID = $02;
HID_UART_SET_POWER = $04;
HID_UART_SET_POWER_MODE = $08;
HID_UART_SET_RELEASE_VERSION = $10;
HID_UART_SET_FLUSH_BUFFERS = $20;
// USB Config Bit Values
HID_UART_SET_IGNORE = 0;
HID_UART_SET_PROGRAM = 1;
// String Lengths
HID_UART_MFG_STRLEN = 62;
HID_UART_PRODUCT_STRLEN = 62;
HID_UART_SERIAL_STRLEN = 30;
type
HID_UART_MFG_STR = array [0 .. HID_UART_MFG_STRLEN - 1] of ansichar; // HID_UART_MFG_STR
HID_UART_PRODUCT_STR = array [0 .. HID_UART_PRODUCT_STRLEN - 1] of ansichar; // HID_UART_PRODUCT_STR
HID_UART_SERIAL_STR = array [0 .. HID_UART_SERIAL_STRLEN - 1] of ansichar; // HID_UART_PRODUCT_STR
const
/////////////////////////////////////////////////////////////////////////////
// Pin Definitions
/////////////////////////////////////////////////////////////////////////////
// Pin Config Modes
HID_UART_GPIO_MODE_INPUT = $00;
HID_UART_GPIO_MODE_OUTPUT_OD = $01;
HID_UART_GPIO_MODE_OUTPUT_PP = $02;
HID_UART_GPIO_MODE_FUNCTION1 = $03;
HID_UART_GPIO_MODE_FUNCTION2 = $04;
// Suspend Value Bit Values
HID_UART_VALUE_SUSPEND_LO = 0;
HID_UART_VALUE_SUSPEND_HI = 1;
// Suspend Mode Bit Values
HID_UART_MODE_SUSPEND_OD = 0;
HID_UART_MODE_SUSPEND_PP = 1;
// RS485 Active Levels
HID_UART_MODE_RS485_ACTIVE_LO = $00;
HID_UART_MODE_RS485_ACTIVE_HI = $01;
type
HID_UART_DEVICE = pointer;
pHID_UART_DEVICE = ^HID_UART_DEVICE;
function HidUart_GetNumDevices(var numDevices:DWORD; vid:WORD; pid:WORD):HID_UART_STATUS; stdcall;
function HidUart_GetString(deviceNum:DWORD; vid:WORD; pid:WORD; deviceString:PAnsiChar; options:DWORD):HID_UART_STATUS; stdcall;
function HidUart_GetOpenedString(device:HID_UART_DEVICE; deviceString:PAnsiChar; options:DWORD):HID_UART_STATUS; stdcall;
function HidUart_GetIndexedString(deviceNum:DWORD; vid:WORD; pid:WORD; stringIndex:DWORD; deviceString:PAnsiChar):HID_UART_STATUS; stdcall;
function HidUart_GetOpenedIndexedString(device:HID_UART_DEVICE; stringIndex:DWORD; deviceString:PAnsiChar):HID_UART_STATUS; stdcall;
function HidUart_GetAttributes(deviceNum:DWORD; vid:WORD; pid:WORD ; deviceVid:PWORD; devicePid:PWORD; deviceReleaseNumber:PWORD):HID_UART_STATUS; stdcall;
function HidUart_GetOpenedAttributes(device:HID_UART_DEVICE; deviceVid:PWORD; devicePid:PWORD; deviceReleaseNumber:PWORD):HID_UART_STATUS; stdcall;
function HidUart_Open(device:pHID_UART_DEVICE; deviceNum:DWORD; vid:WORD; pid:WORD):HID_UART_STATUS; stdcall;
function HidUart_Close(device:HID_UART_DEVICE):HID_UART_STATUS; stdcall;
function HidUart_IsOpened(device:HID_UART_DEVICE; opened:PBOOL):HID_UART_STATUS; stdcall;
function HidUart_SetUartEnable(device:HID_UART_DEVICE; enable:BOOL):HID_UART_STATUS; stdcall;
function HidUart_GetUartEnable(device:HID_UART_DEVICE; enable:PBOOL):HID_UART_STATUS; stdcall;
function HidUart_Read(device:HID_UART_DEVICE; buffer:PByte; numBytesToRead:DWORD; numBytesRead:pDWORD):HID_UART_STATUS; stdcall;
function HidUart_Write(device:HID_UART_DEVICE; buffer:PByte; numBytesToWrite:DWORD; numBytesWritten:PDWORD):HID_UART_STATUS; stdcall;
function HidUart_FlushBuffers(device:HID_UART_DEVICE; flushTransmit:BOOL; flushReceive:BOOL):HID_UART_STATUS; stdcall;
function HidUart_CancelIo(device:HID_UART_DEVICE):HID_UART_STATUS; stdcall;
function HidUart_SetTimeouts(device:HID_UART_DEVICE; readTimeout:DWORD; writeTimeout:DWORD):HID_UART_STATUS; stdcall;
function HidUart_GetTimeouts(device:HID_UART_DEVICE; readTimeout:PDWORD; writeTimeout:PDWORD):HID_UART_STATUS; stdcall;
function HidUart_GetUartStatus(device:HID_UART_DEVICE; transmitFifoSize:PWORD; receiveFifoSize:PWORD; errorStatus:PByte; lineBreakStatus:PByte):HID_UART_STATUS; stdcall;
function HidUart_SetUartConfig(device:HID_UART_DEVICE; baudRate:DWORD; dataBits:BYTE; parity:BYTE; stopBits:BYTE; flowControl:BYTE):HID_UART_STATUS; stdcall;
function HidUart_GetUartConfig(device:HID_UART_DEVICE; baudRate:PDWORD; dataBits:PByte; parity:PByte; stopBits:PByte; flowControl:PByte):HID_UART_STATUS; stdcall;
function HidUart_StartBreak(device:HID_UART_DEVICE; duration:BYTE):HID_UART_STATUS; stdcall;
function HidUart_StopBreak(device:HID_UART_DEVICE):HID_UART_STATUS; stdcall;
function HidUart_Reset(device:HID_UART_DEVICE):HID_UART_STATUS; stdcall;
function HidUart_ReadLatch(device:HID_UART_DEVICE; latchValue:PWORD):HID_UART_STATUS; stdcall;
function HidUart_WriteLatch(device:HID_UART_DEVICE; latchValue:WORD; latchMask:WORD):HID_UART_STATUS; stdcall;
function HidUart_GetPartNumber(device:HID_UART_DEVICE; partNumber:PByte; version:PByte):HID_UART_STATUS; stdcall;
function HidUart_GetLibraryVersion(major:PByte; minor:PByte; release:PBOOL):HID_UART_STATUS; stdcall;
function HidUart_GetHidLibraryVersion( major:PByte; minor:PByte; release:PBOOL):HID_UART_STATUS; stdcall;
function HidUart_GetHidGuid(guid:pointer):HID_UART_STATUS; stdcall;
function HidUart_SetLock(device:HID_UART_DEVICE; lock:WORD):HID_UART_STATUS; stdcall;
function HidUart_GetLock(device:HID_UART_DEVICE; lock:PWORD):HID_UART_STATUS; stdcall;
function HidUart_SetUsbConfig(device:HID_UART_DEVICE; vid:WORD; pid:WORD; power:BYTE; powerMode:BYTE; releaseVersion:WORD; flushBuffers:BYTE; mask:BYTE):HID_UART_STATUS; stdcall;
function HidUart_GetUsbConfig(device:HID_UART_DEVICE; vid:PWORD; pid:PWORD; power:PByte; powerMode:PByte; releaseVersion:PWORD; flushBuffers:PByte):HID_UART_STATUS; stdcall;
function HidUart_SetManufacturingString(device:HID_UART_DEVICE; manufacturingString:PAnsiChar; strlen:BYTE):HID_UART_STATUS; stdcall;
function HidUart_GetManufacturingString(device:HID_UART_DEVICE; manufacturingString:PAnsiChar; strlen:pBYTE):HID_UART_STATUS; stdcall;
function HidUart_SetProductString(device:HID_UART_DEVICE; productString:PAnsiChar; strlen:BYTE ):HID_UART_STATUS; stdcall;
function HidUart_GetProductString(device:HID_UART_DEVICE; productString:PAnsiChar; strlen:pBYTE):HID_UART_STATUS; stdcall;
function HidUart_SetSerialString(device:HID_UART_DEVICE; serialString:PAnsiChar; strlen:BYTE):HID_UART_STATUS; stdcall;
function HidUart_GetSerialString(device:HID_UART_DEVICE; serialString:PAnsiChar; strlen:pBYTE):HID_UART_STATUS; stdcall;
function hid_status_format(status : integer):string;
type
thidlog_func = procedure(str:string) of object;
function HidUart_ALL_serials(log_func:thidlog_func):tstringlist;
function HidUart_open_serial(serial:string; baudRate:DWORD; parity:Byte; log_func:thidlog_func):HID_UART_DEVICE;
function is_cp2114(name:string):boolean;
const
HidUart_NAME_PERFIX = 'CP2114::';
implementation
uses sysutils;
const
D2XXDLL = 'SLABHIDtoUART.dll';
function HidUart_GetNumDevices ;external D2XXDLL name 'HidUart_GetNumDevices';
function HidUart_GetString ;external D2XXDLL name 'HidUart_GetString';
function HidUart_GetOpenedString ;external D2XXDLL name 'HidUart_GetOpenedString';
function HidUart_GetIndexedString ;external D2XXDLL name 'HidUart_GetIndexedString';
function HidUart_GetOpenedIndexedString ;external D2XXDLL name 'HidUart_GetOpenedIndexedString';
function HidUart_GetAttributes ;external D2XXDLL name 'HidUart_GetAttributes';
function HidUart_GetOpenedAttributes ;external D2XXDLL name 'HidUart_GetOpenedAttributes';
function HidUart_Open ;external D2XXDLL name 'HidUart_Open';
function HidUart_Close ;external D2XXDLL name 'HidUart_Close';
function HidUart_IsOpened ;external D2XXDLL name 'HidUart_IsOpened';
function HidUart_SetUartEnable ;external D2XXDLL name 'HidUart_SetUartEnable';
function HidUart_GetUartEnable ;external D2XXDLL name 'HidUart_GetUartEnable';
function HidUart_Read ;external D2XXDLL name 'HidUart_Read';
function HidUart_Write ;external D2XXDLL name 'HidUart_Write';
function HidUart_FlushBuffers ;external D2XXDLL name 'HidUart_FlushBuffers';
function HidUart_CancelIo ;external D2XXDLL name 'HidUart_CancelIo';
function HidUart_SetTimeouts ;external D2XXDLL name 'HidUart_SetTimeouts';
function HidUart_GetTimeouts ;external D2XXDLL name 'HidUart_GetTimeouts';
function HidUart_GetUartStatus ;external D2XXDLL name 'HidUart_GetUartStatus';
function HidUart_SetUartConfig ;external D2XXDLL name 'HidUart_SetUartConfig';
function HidUart_GetUartConfig ;external D2XXDLL name 'HidUart_GetUartConfig';
function HidUart_StartBreak ;external D2XXDLL name 'HidUart_StartBreak';
function HidUart_StopBreak ;external D2XXDLL name 'HidUart_StopBreak';
function HidUart_Reset ;external D2XXDLL name 'HidUart_Reset';
function HidUart_ReadLatch ;external D2XXDLL name 'HidUart_ReadLatch';
function HidUart_WriteLatch ;external D2XXDLL name 'HidUart_WriteLatch';
function HidUart_GetPartNumber ;external D2XXDLL name 'HidUart_GetPartNumber';
function HidUart_GetLibraryVersion ;external D2XXDLL name 'HidUart_GetLibraryVersion';
function HidUart_GetHidLibraryVersion ;external D2XXDLL name 'HidUart_GetHidLibraryVersion';
function HidUart_GetHidGuid ;external D2XXDLL name 'HidUart_GetHidGuid';
function HidUart_SetLock ;external D2XXDLL name 'HidUart_SetLock';
function HidUart_GetLock ;external D2XXDLL name 'HidUart_GetLock';
function HidUart_SetUsbConfig ;external D2XXDLL name 'HidUart_SetUsbConfig';
function HidUart_GetUsbConfig ;external D2XXDLL name 'HidUart_GetUsbConfig';
function HidUart_SetManufacturingString ;external D2XXDLL name 'HidUart_SetManufacturingString';
function HidUart_GetManufacturingString ;external D2XXDLL name 'HidUart_GetManufacturingString';
function HidUart_SetProductString ;external D2XXDLL name 'HidUart_SetProductString';
function HidUart_GetProductString ;external D2XXDLL name 'HidUart_GetProductString';
function HidUart_SetSerialString ;external D2XXDLL name 'HidUart_SetSerialString';
function HidUart_GetSerialString ;external D2XXDLL name 'HidUart_GetSerialString';
function hid_status_format(status : integer):string;
begin
result := '????';
if status = HID_UART_SUCCESS then result := 'HID_UART_SUCCESS ';
if status = HID_UART_DEVICE_NOT_FOUND then result := 'HID_UART_DEVICE_NOT_FOUND ';
if status = HID_UART_INVALID_HANDLE then result := 'HID_UART_INVALID_HANDLE ';
if status = HID_UART_INVALID_DEVICE_OBJECT then result := 'HID_UART_INVALID_DEVICE_OBJECT ';
if status = HID_UART_INVALID_PARAMETER then result := 'HID_UART_INVALID_PARAMETER ';
if status = HID_UART_INVALID_REQUEST_LENGTH then result := 'HID_UART_INVALID_REQUEST_LENGTH';
if status = HID_UART_READ_ERROR then result := 'HID_UART_READ_ERROR ';
if status = HID_UART_WRITE_ERROR then result := 'HID_UART_WRITE_ERROR ';
if status = HID_UART_READ_TIMED_OUT then result := 'HID_UART_READ_TIMED_OUT ';
if status = HID_UART_WRITE_TIMED_OUT then result := 'HID_UART_WRITE_TIMED_OUT ';
if status = HID_UART_DEVICE_IO_FAILED then result := 'HID_UART_DEVICE_IO_FAILED ';
if status = HID_UART_DEVICE_ACCESS_ERROR then result := 'HID_UART_DEVICE_ACCESS_ERROR ';
if status = HID_UART_DEVICE_NOT_SUPPORTED then result := 'HID_UART_DEVICE_NOT_SUPPORTED ';
if status = HID_UART_INVALID_CONFIG_VERSION then result := 'HID_UART_INVALID_CONFIG_VERSION';
if status = HID_UART_UNKNOWN_ERROR then result := 'HID_UART_UNKNOWN_ERROR ';
end;
function HidUart_ALL_serials(log_func:thidlog_func):tstringlist;
procedure log(str:string); begin if @log_func<>nil then log_func(str); end;
var
res : HID_UART_STATUS;
numDevices : DWORD;
i : integer;
buf : array [0 .. 4095] of ansichar;
serial : string;
begin
result := TStringList.create;
res := HidUart_GetNumDevices(numDevices, $10C4, $EAB0);
log('HidUart_GetNumDevices(numDevices, $10C4, $EAB0); // ' + hid_status_format(res));
log(#9'numDevices = ' + inttostr(numDevices));
for i := 0 to integer(numDevices) - 1 do
begin
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_PRODUCT_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_PRODUCT_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_SERIAL_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_SERIAL_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
serial := buf;
serial := HidUart_NAME_PERFIX + serial;
if res = HID_UART_SUCCESS then
result.Add(serial);
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_PATH_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_PATH_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_MANUFACTURER_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_MANUFACTURER_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
log(' ');
end;
end;
function HidUart_open_serial(serial:string; baudRate:DWORD; parity:Byte; log_func:thidlog_func):HID_UART_DEVICE;
procedure log(str:string); begin if @log_func<>nil then log_func(str); end;
var
res : HID_UART_STATUS;
numDevices : DWORD;
open_pos : integer;
i : integer;
buf : array [0 .. 4095] of ansichar;
device : HID_UART_DEVICE;
b : BOOL;
str : string;
const
dataBits:Byte = HID_UART_EIGHT_DATA_BITS;
stopBits:Byte = HID_UART_LONG_STOP_BIT;
flowControl:Byte = HID_UART_NO_FLOW_CONTROL;
begin
result := nil;
res := HidUart_GetNumDevices(numDevices, $10C4, $EAB0);
log('HidUart_GetNumDevices(numDevices, $10C4, $EAB0); // ' + hid_status_format(res));
log(#9'numDevices = ' + inttostr(numDevices));
open_pos := -1;
for i := 0 to integer(numDevices) - 1 do
begin
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_PRODUCT_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_PRODUCT_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_SERIAL_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_SERIAL_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
str := buf;
str := HidUart_NAME_PERFIX + str;
if res = HID_UART_SUCCESS then
if str = serial then
begin
open_pos := i;
break;
end;
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_PATH_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_PATH_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
ZeroMemory(@buf[0], length(buf));
res := HidUart_GetString(i, $10C4, $EAB0, buf, HID_UART_GET_MANUFACTURER_STR);
log('HidUart_GetString(' + inttostr(i) + ', $10C4, $EAB0, buf, HID_UART_GET_MANUFACTURER_STR); // ' + hid_status_format(res));
log(#9'buf = ' + buf);
log(' ');
end;
if open_pos < 0 then
exit;
device := nil;
res := HidUart_Open(@device, open_pos, $10C4, $EAB0);
log('HidUart_Open(@device, ' + inttostr(open_pos) + ', $10C4, $EAB0); // ' + hid_status_format(res));
log(#9'device = ' + inttohex(cardinal(device), 8));
log(' ');
if res <> HID_UART_SUCCESS then
exit;
res := HidUart_GetUartEnable(device, @b);
log('HidUart_GetUartEnable(device, @b); // ' + hid_status_format(res));
log(#9'b = ' + BoolToStr(b, true));
if b <> true then
begin
res := HidUart_SetUartEnable(device, true);
log('HidUart_SetUartEnable(device, true); // ' + hid_status_format(res));
end;
log(' ');
res := HidUart_SetUartConfig(device, baudRate, databits, parity, stopbits, flowControl);
log('HidUart_SetUartConfig(device, @boundrate, @databits, @parity, @stopbits, @flowconrol); // ' + hid_status_format(res));
log(#9'baudRate = ' + inttostr(baudRate));
log(#9'dataBits = ' + inttostr(dataBits));
log(#9'parity = ' + inttostr(parity));
log(#9'stopBits = ' + inttostr(stopBits));
log(#9'flowControl = ' + inttostr(flowControl));
log(' ');
res := HidUart_SetTimeouts(Device, 0, 500);
log('HidUart_SetTimeouts(Device, 10, 500); // ' + hid_status_format(res));
log(' ');
result := device;
end;
function is_cp2114(name:string):boolean;
begin
result:=pos(HidUart_NAME_PERFIX, name)=1;
end;
end.
|
{Record access...also nested records}
program HelloWorld;
type
rec1 = record
a : integer;
b : integer
end;
rec2 = record
a: integer;
b: integer;
r : rec1
end;
var
i : integer;
r1 : rec1;
r2 : rec2;
begin
i := r1.b;
i := r2.r.a
end.
|
unit JAPalette;
{$mode objfpc}{$H+}
{$i JA.inc}
{This is for managing the Amiga's Colour Registers. Each register is an
entry of a Palette. OCS Amiga's are limited to 32 Colour Registers.}
interface
uses
sysutils, math,
{Amiga} Exec, Intuition, AGraphics, Utility, picasso96api,
{JAE} JATypes, JAMath, JALog;
type
TJAPaletteMask = record
Index : UInt8;
Mask : UInt8;
end;
PJAPaletteMask = ^TJAPaletteMask;
TJAPaletteLight = record
Colour : TJColour3UInt8;
Index : UInt8;
Mask : UInt8;
end;
PJAPaletteLight = ^TJAPaletteLight;
TJAPalette = record
ViewPort : pViewPort; {Viewport of this Palette}
ColourMap : pColorMap; {ColourMap of this Palette}
SaveColorMap: Boolean;
OldColours: array of record
r: LongWord;
G: LongWord;
B: LongWord;
end;
Colours : array of TJColour3UInt8; {1:1 Hardware/Software Palette Array}
//ColourCount : SInt16; {how many entries does the palette have}
PenBlack : SInt16;
PenRed : SInt16;
PenGreen : SInt16;
PenBlue : SInt16;
PenWhite : SInt16;
PenGrey : SInt16;
PenYellow : SInt16;
{$IFDEF JA_ENABLE_SHADOW}
Bands : PJAPaletteMask; {Colour Bands - light levels, color mixing etc}
BandCount : SInt16; {how many Bands is the palette divided into}
BandColourCount : SInt16; {how many colours in each band}
Lights : PJAPaletteLight; {Band Indices for Lights}
LightCount : SInt16; {Number of Lights in this Palette}
{$ENDIF}
end;
PJAPalette = ^TJAPalette;
var
Palette : PJAPalette;
function JAPaletteCreate(AViewPort : pViewPort; AColourMap : pColorMap; AColourCount, ABandCount, ALightCount : SInt16; ASaveColorMap: Boolean) : PJAPalette;
function JAPaletteDestroy(APalette : PJAPalette) : boolean;
procedure JAPaletteSetColour(APalette : PJAPalette; AColourIndex : SInt16; AColour : TJColour3UInt8);
procedure JAPaletteBandModulate(APalette : PJAPalette; ASourceBand, ADestinationBand : SInt16; AModulation : TJColour3UInt8);
procedure JAPaletteLightSetColour(APalette : PJAPalette; ALightIndex : SInt16; AColour : TJColour3UInt8);
{Setup the a colour within all colour bands for band lighting mode}
procedure JAPaletteBandSetColour(AIndex : SInt16; AColour : TJColour3UInt8);
procedure JAPaletteBandLightCascade(APalette : PJAPalette; ARootBandIndex : SInt16; ACascadeCount : SInt16; ACascadeFactor : Float32);
{setup the palette for mixing the colour of multiple lights}
procedure JAPaletteSetupLights(ALight0, ALight1, ALight2 : TJColour; ABandIndexStart : SInt16);
implementation
function ColourMix(A,B : TJColour3UInt8) : TJColour3UInt8;
begin
{Additive}
Result.R := JClamp((A.R + B.R),0,255);
Result.G := JClamp((A.G + B.G),0,255);
Result.B := JClamp((A.B + B.B),0,255);
{Average}
{
Result.R := (A.R + B.R) div 2;
Result.G := (A.G + B.G) div 2;
Result.B := (A.B + B.B) div 2;
}
end;
function JAPaletteCreate(AViewPort: pViewPort; AColourMap: pColorMap; AColourCount, ABandCount, ALightCount : SInt16; ASaveColorMap: Boolean): PJAPalette;
var
I,K : SInt16;
ColourRegister : SInt16;
ARed : TJColour3UInt8;
AGreen : TJColour3UInt8;
ABlue : TJColour3UInt8;
AWhite : TJColour3UInt8;
AGrey : TJColour3UInt8;
AYellow : TJColour3UInt8;
AModulate : TJColour3UInt8;
L0,L1,L2 : UInt8;
begin
Log('JAPaletteCreate','Creating Palette');
Result := PJAPalette(JAMemGet(SizeOf(TJAPalette)));
with Result^ do
begin
Viewport := AViewPort;
ColourMap := AColourMap;
//ColourCount := AColourCount;
SaveColorMap := ASaveColorMap;
if ASaveColorMap then
begin
// save the old colormap if not on Screen
SetLength(OldColours, PColorMap(ViewPort^.ColorMap)^.Count);
GetRGB32(Viewport^.ColorMap, 0, PColorMap(ViewPort^.ColorMap)^.Count, @oldColours[0]);
end;
{Get Memory for Arrays}
SetLength(Colours, AColourCount);
//Colours := JAMemGet(SizeOf(TJColour3UInt8) * ColourCount);
{$IFDEF JA_ENABLE_SHADOW}
BandCount := ABandCount;
LightCount := ALightCount;
BandColourCount := 8;
Bands := JAMemGet(SizeOf(TJAPaletteMask) * BandCount);
Lights := JAMemGet(SizeOf(TJAPaletteLight) * LightCount);
{Setup Light Level Bands}
for I := 0 to BandCount-1 do
begin
{we skip 16 as that block is reserved for the first hardware sprite,
which we're using for the mouse cursor}
//if I < 2 then
Result^.Bands[I].Index := I * BandColourCount;// else
// Result^.Bands[I].Index := 8 + I * BandColourCount;
Result^.Bands[I].Mask := Result^.Bands[I].Index;
end;
{Setup Light Colour Masks}
for I := 0 to LightCount-1 do
begin
Result^.Lights[I].Index := (I+1) * (BandCount * BandColourCount);
Result^.Lights[I].Mask := Result^.Lights[I].Index;
end;
{Setup Light Colours}
{Red/Blue}
//Lights[0].Colour := JColour3UInt8(160,60,60);
//Lights[1].Colour := JColour3UInt8(60,60,160);
{Grey}
Lights[0].Colour := JColour3UInt8(128,128,128);
Lights[1].Colour := JColour3UInt8(128,128,128);
{$ENDIF}
{Assign the Base Colour Registers}
PenBlack := 0;
PenRed := 1;
PenGreen := 2;
PenBlue := 3;
PenWhite := 4;
PenGrey := 5;
PenYellow := 6;
AModulate := JColour3UInt8(200,200,200);
ARed := JColour3UInt8(255,0,0) * AModulate;
AGreen := JColour3UInt8(0,255,0) * AModulate;
ABlue := JColour3UInt8(0,0,255) * AModulate;
AWhite := JColour3UInt8(255,255,255) * AModulate;
AGrey := JColour3UInt8(175,175,175) * AModulate;
AYellow := JColour3UInt8(255,255,0) * AModulate;
{Setup Full-Bright Colours}
JAPaletteSetColour(Result, PenBlack, JColour3UInt8(0,0,0)); {0=Screen Border Colour Also}
JAPaletteSetColour(Result, PenRed, ARed);
JAPaletteSetColour(Result, PenGreen, AGreen);
JAPaletteSetColour(Result, PenBlue, ABlue);
JAPaletteSetColour(Result, PenWhite, AWhite);
JAPaletteSetColour(Result, PenGrey, AGrey);
JAPaletteSetColour(Result, PenYellow, AYellow);
{$IFDEF JA_ENABLE_SHADOW}
{Cascade Light Level Bands}
L0 := 220;
L1 := 175;
L2 := 55;
JAPaletteBandModulate(Result, 0, 1, JColour3UInt8(L0,L0,L0));
JAPaletteBandModulate(Result, 0, 2, JColour3UInt8(L1,L1,L1));
JAPaletteBandModulate(Result, 0, 3, JColour3UInt8(L2,L2,L2));
L0 := 220;
L1 := 175;
L2 := 55;
JAPaletteBandModulate(Result, 0, 4, Lights[0].Colour);
JAPaletteBandModulate(Result, 0, 5, Lights[0].Colour * JColour3UInt8(L0,L0,L0));
JAPaletteBandModulate(Result, 0, 6, Lights[0].Colour * JColour3UInt8(L1,L1,L1));
JAPaletteBandModulate(Result, 0, 7, Lights[0].Colour * JColour3UInt8(L2,L2,L2));
L0 := 220;
L1 := 175;
L2 := 55;
JAPaletteBandModulate(Result, 0, 8, Lights[1].Colour);
JAPaletteBandModulate(Result, 0, 9, Lights[1].Colour * JColour3UInt8(L0,L0,L0));
JAPaletteBandModulate(Result, 0, 10, Lights[1].Colour * JColour3UInt8(L1,L1,L1));
JAPaletteBandModulate(Result, 0, 11, Lights[1].Colour * JColour3UInt8(L2,L2,L2));
L0 := 220;
L1 := 175;
L2 := 55;
JAPaletteBandModulate(Result, 0, 12, ColourMix(Lights[0].Colour, Lights[1].Colour));
{JAPaletteBandModulate(Result, 0, 13, ColourMix(Lights[0].Colour, Lights[1].Colour) * JColour3UInt8(L0,L0,L0));
JAPaletteBandModulate(Result, 0, 14, ColourMix(Lights[0].Colour, Lights[1].Colour) * JColour3UInt8(L1,L1,L1));
JAPaletteBandModulate(Result, 0, 15, ColourMix(Lights[0].Colour, Lights[1].Colour) * JColour3UInt8(L2,L2,L2));}
JAPaletteBandModulate(Result, 0, 13, ColourMix(Lights[0].Colour * JColour3UInt8(L0,L0,L0), Lights[1].Colour * JColour3UInt8(L0,L0,L0)));
JAPaletteBandModulate(Result, 0, 14, ColourMix(Lights[0].Colour * JColour3UInt8(L1,L1,L1), Lights[1].Colour * JColour3UInt8(L1,L1,L1)));
JAPaletteBandModulate(Result, 0, 15, ColourMix(Lights[0].Colour * JColour3UInt8(L2,L2,L2), Lights[1].Colour * JColour3UInt8(L2,L2,L2)));
{TEST : Set First Band to be the darkest - for shadow blending}
L2 := 55;
JAPaletteSetColour(Result, PenBlack, JColour3UInt8(0,0,0)); {0=Screen Border Colour Also}
JAPaletteSetColour(Result, PenRed, ARed * JColour3UInt8(L2,L2,L2));
JAPaletteSetColour(Result, PenGreen, AGreen * JColour3UInt8(L2,L2,L2));
JAPaletteSetColour(Result, PenBlue, ABlue * JColour3UInt8(L2,L2,L2));
JAPaletteSetColour(Result, PenWhite, AWhite * JColour3UInt8(L2,L2,L2));
JAPaletteSetColour(Result, PenGrey, AGrey * JColour3UInt8(L2,L2,L2));
//PenRed := ObtainBestPenA(AColourMap, QBR.U32, 0, 0, nil);
//PenGreen := ObtainPen(AColourMap, -1, 0, 0, 0, PEN_NO_SETCOLOR);
//PenBlue := ObtainPen(AColourMap, -1, 0, 0, 0, PEN_EXCLUSIVE);
//WriteLn('PenRed=' + IntToStr(PenRed));
//WriteLn('PenGreen=' + IntToStr(PenGreen));
//WriteLn('PenBlue=' + IntToStr(PenBlue));
{SetRGB4CM(AColourMap, PenBlack, 0,0,0);
SetRGB4CM(AColourMap, PenRed, 15,00,0);
SetRGB4CM(AColourMap, 8 + PenRed, 15 div 2 ,00,0);
SetRGB4CM(AColourMap, 8 + PenWhite, 15 div 2, 15 div 2,15 div 2);}
{$ENDIF}
end;
end;
function JAPaletteDestroy(APalette : PJAPalette) : boolean;
var
i:Integer;
begin
if (APalette=nil) then exit(false);
Log('JAPaletteDestroy','Destroying Palette');
with APalette^ do
begin
// restore old colormap
if SaveColorMap then
begin
for i := 0 to High(OldColours) do
SetRGB32(Viewport, i, OldColours[i].R, OldColours[i].G, OldColours[i].B);
SetLength(OldColours, 0);
end;
//JAMemFree(Colours, SizeOf(TJColour3UInt8) * ColourCount);
SetLength(Colours, 0);
{$IFDEF JA_ENABLE_SHADOW}
JAMemFree(Lights,SizeOf(TJAPaletteLight) * LightCount);
JAMemFree(Bands,SizeOf(TJAPaletteMask) * BandCount);
{$ENDIF}
end;
JAMemFree(APalette,SizeOf(TJAPalette));
Result := true;
end;
procedure JAPaletteSetColour(APalette: PJAPalette; AColourIndex: SInt16; AColour: TJColour3UInt8);
begin
with APalette^ do
begin
if AColourIndex < High(Colours) then
begin
Colours[AColourIndex] := AColour;
SetRGB4(ViewPort, AColourIndex, AColour.R shr 4, AColour.G shr 4, AColour.B shr 4);
end;
end;
end;
procedure JAPaletteBandModulate(APalette: PJAPalette; ASourceBand, ADestinationBand: SInt16; AModulation: TJColour3UInt8);
var
I : SInt16;
IndexSource,IndexDest : SInt16;
begin
{$IFDEF JA_ENABLE_SHADOW}
with APalette^ do
begin
for I := 0 to BandColourCount-1 do
begin
IndexSource := Bands[ASourceBand].Index+I;
IndexDest := Bands[ADestinationBand].Index+I;
JAPaletteSetColour(APalette, IndexDest, Colours[IndexSource] * AModulation);
//Colours[IndexDest] := Colours[IndexSource] * AModulation;
//SetRGB4(ViewPort, IndexDest,
// Colours[IndexDest].R shr 4,
// Colours[IndexDest].G shr 4,
// Colours[IndexDest].B shr 4);
end;
end;
{$ENDIF}
end;
procedure JAPaletteLightSetColour(APalette: PJAPalette; ALightIndex: SInt16; AColour : TJColour3UInt8);
begin
{$IFDEF JA_ENABLE_SHADOW}
with APalette^ do
begin
Lights[ALightIndex].Colour := AColour;
end;
{$ENDIF}
end;
procedure JAPaletteBandSetColour(AIndex: SInt16; AColour: TJColour3UInt8);
begin
{CursorSpriteIndex := 0; {The cursor is Sprite 0}
CursorColourRegister := 16 + ((CursorSpriteIndex and $06) shl 1);
//SetRGB4(Window^.ViewPort,CursorColourRegister + 0,0,0,0); {Cursor Pal 0 Transparent - Can't change}
SetRGB4(Window^.ViewPort, CursorColourRegister + 1,15,0,0); {Cursor Pal 1}
}
end;
procedure JAPaletteBandLightCascade(APalette: PJAPalette; ARootBandIndex: SInt16; ACascadeCount: SInt16; ACascadeFactor: Float32);
var
I,J : SInt16;
LightFactor : Float32;
begin
{$IFDEF JA_ENABLE_SHADOW}
LightFactor := ACascadeFactor;
for I := ARootBandIndex+1 to (ARootBandIndex+ACascadeCount) do
begin
for J := 0 to APalette^.BandColourCount-1 do
begin
//APalette^.Bands[I+J].Colour := APalette^.Bands[ARootBandIndex+J].Colour;// * LightFactor;
end;
LightFactor *= ACascadeFactor;
end;
{$ENDIF}
end;
procedure JAPaletteSetupLights(ALight0, ALight1, ALight2: TJColour; ABandIndexStart: SInt16);
begin
end;
end.
|
unit uDataRecord;
interface
uses SysUtils, Classes, Variants, DB;
type
TDataItem = class(TObject)
public
Modified: Variant;
Data: Variant;
end;
TDataRecord = class
private
FList: TStrings;
procedure ClearList;
function FindFieldData(const FieldName: string): TDataItem;
function GetFieldData(const FieldName: string): TDataItem;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromDataSet(DataSet: TDataSet);
procedure SaveToDataSet(const KeyFields: string; DataSet: TDataSet; FieldsMapping: string = '');
procedure CloneFrom(DataRecord: TDataRecord);
function GetFieldValue(const FieldName: string): Variant;
procedure SetFieldValue(const FieldName: string; Value: Variant);
function FieldValueAsString(const FieldName: string): string;
function FieldValueAsBoolean(const FieldName: string): Boolean;
function FieldValueAsCurrency(const FieldName: string): Currency;
function FieldValueAsDateTime(const FieldName: string): TDateTime;
function FieldValueAsFloat(const FieldName: string): Double;
function FieldValueAsInteger(const FieldName: string): Integer;
function GetFieldCount: Integer;
function GetFieldName(const Index: Integer): string;
property FieldValues[const FieldName: string]: Variant read GetFieldValue write SetFieldValue;
end;
implementation
{ TDataRecord }
procedure TDataRecord.ClearList;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
FList.Objects[I].Free;
FList.Clear;
end;
constructor TDataRecord.Create;
begin
FList := TStringList.Create;
end;
destructor TDataRecord.Destroy;
begin
ClearList;
FList.Free;
inherited;
end;
function TDataRecord.FieldValueAsBoolean(const FieldName: string): Boolean;
var
tmpValue: Variant;
begin
tmpValue := Self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := False
else
Result := tmpValue;
end;
function TDataRecord.FieldValueAsCurrency(const FieldName: string): Currency;
var
tmpValue: Variant;
begin
tmpValue := Self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else
Result := tmpValue;
end;
function TDataRecord.FieldValueAsDateTime(const FieldName: string): TDateTime;
var
tmpValue: Variant;
begin
tmpValue := Self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else
Result := tmpValue;
end;
function TDataRecord.FieldValueAsFloat(const FieldName: string): Double;
var
tmpValue: Variant;
begin
tmpValue := Self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0.0
else
Result := tmpValue;
end;
function TDataRecord.FieldValueAsInteger(const FieldName: string): Integer;
var
tmpValue: Variant;
begin
tmpValue := Self.GetFieldValue(FieldName);
if VarIsNull(tmpValue) then
Result := 0
else
Result := tmpValue;
end;
function TDataRecord.FieldValueAsString(const FieldName: string): string;
begin
Result := VarToStr(GetFieldValue(FieldName));
end;
function TDataRecord.GetFieldCount: Integer;
begin
Result := FList.Count;
end;
function TDataRecord.GetFieldName(const Index: Integer): string;
begin
Result := FList[Index];
end;
function TDataRecord.GetFieldValue(const FieldName: string): Variant;
var
lItem: TDataItem;
begin
lItem := Self.GetFieldData(FieldName);
Result := lItem.Data;
end;
procedure TDataRecord.LoadFromDataSet(DataSet: TDataSet);
var
lItem: TDataItem;
I: Integer;
begin
Self.ClearList;
if DataSet = nil then Exit;
for I := 0 to DataSet.FieldCount - 1 do
begin
lItem := TDataItem.Create;
lItem.Modified := False;
lItem.Data := DataSet.Fields[I].Value;
FList.AddObject(DataSet.Fields[I].FieldName, lItem);
end;
end;
procedure TDataRecord.SaveToDataSet(const KeyFields: string; DataSet: TDataSet;
FieldsMapping: string);
var
I, Idx: Integer;
lItem: TDataItem;
FieldValues: Variant;
FieldList, FieldMappingList: TStrings;
s: string;
begin
FieldList := TStringList.Create;
FieldMappingList := TStringList.Create;
try
FieldList.Delimiter := ';';
FieldList.DelimitedText := KeyFields;
FieldMappingList.Delimiter := ';';
FieldMappingList.DelimitedText := FieldsMapping;
FieldValues := VarArrayCreate([0, FieldList.Count - 1], varVariant);
for I := 0 to FieldList.Count - 1 do
begin
s := FieldMappingList.Values[FieldList[I]];
if s = '' then
s := FieldList[I];
Idx := FList.IndexOf(s);
if Idx <> -1 then
begin
lItem := TDataItem(FList.Objects[Idx]);
FieldValues[I] := lItem.Data;
end
else
FieldValues[I] := NULL;
end;
if DataSet.Locate(KeyFields, FieldValues, []) then
DataSet.Edit
else
DataSet.Append;
for I := 0 to DataSet.FieldCount - 1 do
begin
s := FieldMappingList.Values[DataSet.Fields[I].FieldName];
if s = '' then
s := DataSet.Fields[I].FieldName;
Idx := FList.IndexOf(s);
if Idx <> -1 then
begin
lItem := TDataItem(FList.Objects[Idx]);
if lItem.Modified then
DataSet.Fields[I].Value := lItem.Data;
end;
end;
DataSet.Post;
finally
FieldList.Free;
FieldMappingList.Free;
end;
end;
procedure TDataRecord.SetFieldValue(const FieldName: string; Value: Variant);
var
lItem: TDataItem;
begin
lItem := Self.FindFieldData(FieldName);
if lItem <> nil then
begin
lItem.Modified := True;
lItem.Data := Value;
end
else
begin
lItem := TDataItem.Create;
lItem.Modified := True;
lItem.Data := Value;
FList.AddObject(FieldName, lItem);
end;
end;
function TDataRecord.GetFieldData(const FieldName: string): TDataItem;
begin
Result := FindFieldData(FieldName);
if Result = nil then
Raise Exception.CreateFmt('×Ö¶Î[%s]²»´æÔÚ£¡', [FieldName]);
end;
function TDataRecord.FindFieldData(const FieldName: string): TDataItem;
var
Idx: Integer;
begin
Result := nil;
Idx := FList.IndexOf(FieldName);
if Idx <> -1 then
Result := TDataItem(FList.Objects[Idx]);
end;
procedure TDataRecord.CloneFrom(DataRecord: TDataRecord);
var
I: Integer;
FieldName: string;
begin
if DataRecord = nil then
Exit;
Self.ClearList;
for I := 0 to DataRecord.GetFieldCount - 1 do
begin
FieldName := DataRecord.GetFieldName(I);
Self.FieldValues[FieldName] := DataRecord.FieldValues[FieldName];
end;
end;
end.
|
unit uSupplyServices;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, ZDataset, ZSequence, ZSqlUpdate, Forms, Controls,
Graphics, Dialogs, StdCtrls, ActnList, ExtCtrls, Buttons, DbCtrls, DBGrids,
uBaseDbForm, db, ZAbstractDataset;
type
{ TfrmSupplyServices }
TfrmSupplyServices = class(TbaseDbForm)
actCharFilter: TAction;
actClearFilter: TAction;
actFindServices: TActionList;
btnCharFilter: TSpeedButton;
btnShowAll: TSpeedButton;
cmbCharFilter: TComboBox;
cmbFieldArg: TComboBox;
dbgServices: TDBGrid;
dblMeasure: TDBLookupComboBox;
dblTax: TDBLookupComboBox;
dsGroups: TDataSource;
dbCode: TDBEdit;
dblGroup: TDBLookupComboBox;
dbName: TDBEdit;
dsMeasure: TDataSource;
dsServices: TDataSource;
dsTaxes: TDataSource;
edtLocate: TEdit;
gbEditServices: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
panelParams: TPanel;
zqServices: TZQuery;
zqServicesGROUP_CODE: TStringField;
zqServicesGROUP_NAME: TStringField;
zqServicesMEASURE_CODE: TStringField;
zqServicesMEASURE_NAME: TStringField;
zqServicesSS_CODE: TStringField;
zqServicesSS_GROUP: TLongintField;
zqServicesSS_ID: TLongintField;
zqServicesSS_MEASURE: TLongintField;
zqServicesSS_NAME: TStringField;
zqServicesSS_TAX: TLongintField;
zqServicesTAX_CODE: TStringField;
zqServicesTAX_VALUE: TFloatField;
zroGroups: TZReadOnlyQuery;
zroGroupsSSG_ID: TLongintField;
zroGroupsSSG_NAME: TStringField;
zroMeasure: TZReadOnlyQuery;
zroMeasureM_ID: TLongintField;
zroMeasureM_NAME: TStringField;
zroTaxes: TZReadOnlyQuery;
zroTaxesTX_CODE: TStringField;
zroTaxesTX_ID: TLongintField;
zseqSupplyServices: TZSequence;
zupdServices: TZUpdateSQL;
procedure actCharFilterExecute(Sender: TObject);
procedure actClearFilterExecute(Sender: TObject);
procedure cmbFieldArgChange(Sender: TObject);
procedure dbgServicesMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure dbgServicesTitleClick(Column: TColumn);
procedure edtLocateEnter(Sender: TObject);
procedure edtLocateExit(Sender: TObject);
procedure edtLocateKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState
);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure zqServicesAfterDelete(DataSet: TDataSet);
procedure zqServicesAfterOpen(DataSet: TDataSet);
procedure zqServicesAfterPost(DataSet: TDataSet);
procedure zqServicesAfterScroll(DataSet: TDataSet);
private
{ private declarations }
charArg : String; {name-start with this char}
fieldArg : String; {locate text from field}
procedure saveBeforeClose;
public
{ public declarations }
procedure onActFirst; override;
procedure onActPrior; override;
procedure onActNext; override;
procedure onActLast; override;
procedure onActInsert; override;
procedure onActDelete; override;
procedure onActEdit; override;
procedure onActSave; override;
procedure onActCancel; override;
{open dataSet using charArg}
procedure openRODataSets;
procedure applyCharFilter;
end;
var
frmSupplyServices: TfrmSupplyServices;
const
{msg}
EMPTY_SET : String = 'Prazan skup podataka.';
{fields of tbl suupply_service}
FS_ID : String = 'SS_ID';
FS_CODE : String = 'SS_CODE';
FS_NAME : String = 'SS_NAME';
FS_GROUP : String = 'SS_GROUP';
FS_MEASURE : String = 'SS_MEASURE';
FS_TAX : String = 'SS_TAX';
{fields of view supply_services_v --FSV - field-service_view}
FSV_GROUP_CODE : String = 'GROUP_CODE';
FSV_GROUP_NAME : String = 'GROUP_NAME';
FSV_MEASURE_CODE : String = 'MEASURE_CODE';
FSV_MEASURE_NAME : String = 'MEASURE_NAME';
FSV_TAX_CODE : String = 'TAX_CODE';
FSV_TAX_VALUE : String = 'TAX_VALUE';
{params}
PARAM_NAME : String = 'SS_NAME'; {:SS_NAME}
implementation
uses
uDModule, uConfirm;
{$R *.lfm}
{ TfrmSupplyServices }
procedure TfrmSupplyServices.FormCreate(Sender: TObject);
begin
{default args for query}
charArg:= 'A%';
fieldArg:= PARAM_NAME; {locate using field_name}
end;
procedure TfrmSupplyServices.actCharFilterExecute(Sender: TObject);
begin
{set filter}
charArg:= cmbCharFilter.Text + '%';
{apply filter}
applyCharFilter;
end;
procedure TfrmSupplyServices.actClearFilterExecute(Sender: TObject);
begin
{set char-argument}
charArg:= '%'; {show all}
applyCharFilter;
{set cmbCharFilter index}
cmbCharFilter.Text:= 'Usluge na slovo ...'; {message like text}
end;
procedure TfrmSupplyServices.cmbFieldArgChange(Sender: TObject);
begin
case cmbFieldArg.ItemIndex of
1: fieldArg:= FS_NAME;
2: fieldArg:= FS_CODE;
else
fieldArg:= FS_NAME;
end;
{set focus}
edtLocate.SetFocus;
end;
procedure TfrmSupplyServices.dbgServicesMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
{set cursor again}
dbgServices.Cursor:= crHandPoint;
end;
procedure TfrmSupplyServices.dbgServicesTitleClick(Column: TColumn);
var
recCount, recNo : String;
recMsg : String = '0 od 0'; {find again recNo}
begin
{sort}
doSortDbGrid(TZAbstractDataset(zqServices), Column);
{refresh after sort}
dbgServices.Refresh;
{ find recNo}
recCount:= IntToStr(TZAbstractDataset(zqServices).RecordCount);
recNo:= IntToStr(TZAbstractDataset(zqServices).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmSupplyServices.edtLocateEnter(Sender: TObject);
begin
{clear text and set font-color}
edtLocate.Text:= '';
edtLocate.Font.Color:= clBlack;
end;
procedure TfrmSupplyServices.edtLocateExit(Sender: TObject);
begin
{set text and font-color}
edtLocate.Text:= 'Pronadji ...';
edtLocate.Font.Color:= clGray;
end;
procedure TfrmSupplyServices.edtLocateKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{try to locate}
if(not TZAbstractDataset(zqServices).Locate(fieldArg, edtLocate.Text, [loCaseInsensitive, loPartialKey])) then
begin
Beep;
edtLocate.SelectAll;
end;
end;
procedure TfrmSupplyServices.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
{check for unsaved changes}
saveBeforeClose;
inherited;
end;
procedure TfrmSupplyServices.zqServicesAfterDelete(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{upply updates}
TZAbstractDataset(DataSet).ApplyUpdates;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmSupplyServices.zqServicesAfterOpen(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{set btns cheking recCount}
doAfterOpenDataSet(TZAbstractDataset(DataSet));
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmSupplyServices.zqServicesAfterPost(DataSet: TDataSet);
var
currId : Longint;
firstChar : String = '';
currText : String;
{calc records(recNo and countRec)}
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{upply updates}
TZAbstractDataset(DataSet).ApplyUpdates;
{rtefresh current row}
TZAbstractDataset(DataSet).RefreshCurrentRow(True);
{find currText}
currText:= TZAbstractDataset(DataSet).FieldByName(FS_NAME).AsString;
{first char to firstChar-var}
firstChar:= LeftStr(currText, 1);
firstChar:= firstChar + '%';
{compare current charFilter}
if(charArg <> firstChar) then
begin
{save position}
currId:= TZAbstractDataset(DataSet).FieldByName(FS_ID).AsInteger;
charArg:= firstChar;
applyCharFilter;
{locate}
TZAbstractDataset(DataSet).Locate(FS_ID, currId, []);
end;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then {*** never ***}
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmSupplyServices.zqServicesAfterScroll(DataSet: TDataSet);
var
recCount, recNo : String;
recMsg : String = '0 od 0';
begin
{set btns cheking recCount}
if(TZAbstractDataset(DataSet).State in [dsEdit, dsInsert]) then
Exit;
{show recNo and countRec}
if(TZAbstractDataset(DataSet).IsEmpty) then
begin
edtRecNo.Text:= recMsg;
Exit;
end;
{find vars}
recCount:= IntToStr(TZAbstractDataset(DataSet).RecordCount);
recNo:= IntToStr(TZAbstractDataset(DataSet).RecNo);
{create recMsg}
recMsg:= recNo + ' od ' + recCount;
edtRecNo.Text:= recMsg;
end;
procedure TfrmSupplyServices.saveBeforeClose;
var
newDlg : TdlgConfirm;
confirmMsg : String = 'Postoje izmene koje nisu sačuvane!';
saveAll : Boolean = False;
begin
{set confirm msg}
confirmMsg:= confirmMsg + #13#10;
confirmMsg:= confirmMsg + 'Želite da sačuvamo izmene?';
if(TZAbstractDataset(zqServices).State in [dsEdit, dsInsert]) then
begin
{ask user to confirm}
newDlg:= TdlgConfirm.Create(nil);
newDlg.memoMsg.Lines.Text:= confirmMsg;
if(newDlg.ShowModal = mrOK) then
saveAll:= True;
{free dialog}
newDlg.Free;
end;
{check all}
if saveAll then
doSaveRec(TZAbstractDataset(zqServices)); {in this case just one dataSet}
end;
procedure TfrmSupplyServices.onActFirst;
begin
{jump to first rec}
doFirstRec(TZAbstractDataset(zqServices));
end;
procedure TfrmSupplyServices.onActPrior;
begin
{jump to prior rec}
doPriorRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActNext;
begin
{jump to next rec}
doNextRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActLast;
begin
{jump to last rec}
doLastRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActInsert;
begin
{set focus and insert new rec}
dbCode.SetFocus;
doInsertRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActDelete;
begin
{delete rec}
doDeleteRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActEdit;
begin
{set focus and edit rec}
dbCode.SetFocus;
doEditRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActSave;
begin
{save rec}
doSaveRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.onActCancel;
begin
{cancel rec}
doCancelRec(TZAbstractDataset(zqSErvices));
end;
procedure TfrmSupplyServices.openRODataSets;
begin
//product groups
zroGroups.DisableControls;
zroGroups.Open;
zroGroups.EnableControls;
//measure
zroMeasure.DisableControls;
zroMeasure.Open;
zroMeasure.EnableControls;
//taxes
zroTaxes.DisableControls;
zroTaxes.Open;
zroTaxes.EnableControls;
end;
procedure TfrmSupplyServices.applyCharFilter;
begin
TZAbstractDataset(zqSErvices).DisableControls;
TZAbstractDataset(zqSErvices).Close;
try
TZAbstractDataset(zqSErvices).ParamByName(PARAM_NAME).AsString:= charArg;
TZAbstractDataset(zqSErvices).Open;
TZAbstractDataset(zqSErvices).EnableControls;
{show arg in cmbChar}
//cmbCharFilter.ItemIndex:= cmbCharFilter.Items.IndexOf(LeftStr(charArg, 1)); {without '%'}
except
on e : Exception do
begin
dModule.zdbh.Rollback;
TZAbstractDataset(zqSErvices).EnableControls;
ShowMessage(e.Message);
end;
end;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 5 O(LgN) Trivial Method
}
program
WriteANumberWithLetters;
const
MaxN = 9999;
var
N : Integer;
const
Yek : array [1 .. 9] of string[15] = ('yek','do','se','chahaar','panj',
'shesh','haft','hasht','noh');
Dah : array [1 .. 9] of string[15] = ('dah','bist','si','chehel','panjah',
'shast','haftad','hashtad','navad');
Sad : array [1 .. 9] of string[15] = ('sad','devist','sisad','chahaarsad',
'paansad','sheshsad','haftsad','hashtsad','nohsad');
Bist : array [11 .. 19] of string[15] = ('yaazdah','davaazdah','sizdah',
'chahaardah','paanzdah','shanzdah','hefdah','hijdah','noozdah');
begin
Readln(N);
if N = 0 then
Write('sefr');
if N div 1000 > 1 then
begin
Write(Yek[N div 1000], ' hezaar ');
N := N mod 1000;
if N > 0 then
Write('o ');
end
else
N := N mod 1000;
if N div 100 > 0 then
begin
Write(Sad[N div 100], ' ');
N := N mod 100;
if N > 0 then
Write('o ');
end;
if (N >= 20) or (N = 10) then
begin
Write(Dah[N div 10], ' ');
N := N mod 10;
if N > 0 then
Write('o ');
end
else
if N >= 10 then
begin
Write(Bist[N]);
N := 0;
end;
if N > 0 then
Write(Yek[N]);
Writeln;
end. |
{* ***************************************************************************************
\Program Upload code for microcontroller - Version 1.0
\brief Upload code with input parameters to microcontroller ESP8266 WEMOS D1
\author Anh Tu Nguyen
\date 06.01.2020
\note (C) Copyright imess GmbH
Contents and presentations are protected world-wide.
Any kind of using, copying etc. is prohibited without prior permission.
All rights - incl. industrial property rights - are reserved.
*************************************************************************************** *}
unit upload;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Registry, Mask, ShellApi, StrUtils, FileCtrl, ExtCtrls, WinInet;
type
TuploadForm = class(TForm)
btnCreateFile: TButton;
edtWifiPassword: TEdit;
lbWifiPassword: TLabel;
lbIPAddress: TLabel;
lbGateway: TLabel;
lbSubnet: TLabel;
lbCOMPort: TLabel;
lbWifiSSID: TLabel;
edtWifiSSID: TEdit;
cbComPort: TComboBox;
meditIPAddress: TMaskEdit;
meditGateWay: TMaskEdit;
meditSubnet: TMaskEdit;
lbPort: TLabel;
meditPort: TMaskEdit;
Panel3: TPanel;
Image2: TImage;
lbExplain: TLabel;
btnScanPort: TButton;
procedure SearchComPort;
procedure FormCreate(Sender: TObject);
procedure ButtonUploadClick(Sender: TObject);
procedure CreateSourceCode(WifiSSID, WifiPassword, IPAddress, Port, Gateway, Subnet: string);
procedure CreateBatchFile(comPort: string);
function CheckUploadCodeSuccessful: Integer;
function CheckInputAddressEmpty(InputParameter: string): Integer;
function ValidateIP(IP4: string): Integer;
function ShellExecute_AndWait(FileName: string; Params: string): bool;
procedure btnScanPortClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
uploadForm: TuploadForm;
implementation
{$R *.dfm}
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.SearchComPort;
// This procedure searchs available serial port in current computer
var
reg: TRegistry;
st: Tstrings;
i: Integer;
begin
reg:=TRegistry.Create;
try
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKey('hardware\devicemap\serialcomm', False);
st := TstringList.Create;
try
reg.GetValueNames(st);
for i := 0 to st.Count - 1 do
cbComPort.Items.Add(reg.Readstring(st.strings[i]));
finally
st.Free;
end;
reg.CloseKey;
finally
reg.Free;
end;
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.FormCreate(Sender: TObject);
// This procedure create upload form
begin
SearchComPort;
meditIPAddress.EditMask := '!099.099.099.099;1; ';
meditGateWay.EditMask := '!099.099.099.099;1; ';
meditSubnet.EditMask := '!099.099.099.099;1; ';
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.ButtonUploadClick(Sender: TObject);
// This procedure runs when button Upload is clicked
var
wifiSSID: string;
wifiPassword: string;
ipAddress: string;
gateWay: string;
subnet: string;
port: string;
comPort: string;
flags: Windows.DWORD;
begin
//Get input info
wifiSSID := edtWifiSSID.Text;
wifiPassword := edtWifiPassword.Text;
ipAddress := meditIPAddress.Text;
port := meditPort.Text;
gateWay := meditGateWay.Text;
subnet := meditSubnet.Text;
comPort := cbComPort.Text;
flags := 0;
if(WinInet.InternetGetConnectedState(@flags, 0)) then //If has internet connection
begin
//Check if string input empty
if (wifiSSID = '') or (wifiPassword = '') or (ipAddress = '') or (gateWay = '') or (subnet = '') or (port = '') or (comPort = '') then
begin
Application.MessageBox('Input parameters empty!', 'Error', MB_ICONERROR);
end
else
begin
if(CheckInputAddressEmpty(ipAddress) <> 0) then
begin
if (CheckInputAddressEmpty(gateWay) <> 0)then
begin
if (CheckInputAddressEmpty(subnet) <> 0) then
begin
CreateSourceCode(wifiSSID, wifiPassword, ipAddress, port, gateWay, subnet) ;
CreateBatchFile(comPort);
if ShellExecute_AndWait(PChar(GetCurrentDir+'\batchFile.cmd'), '') then
begin
if CheckUploadCodeSuccessful = 0 then
begin
ShowMessage('Upload code successful');
end
else if CheckUploadCodeSuccessful = 1 then
begin
ShowMessage('COM Port is busy!');
end
else
begin
ShowMessage('Error while uploading!');
end;
end
else
begin
ShowMessage('Error while running batch file!');
end;
end
else
Application.MessageBox('Not correct Subnet!', 'Error', MB_ICONERROR);
end
else
Application.MessageBox('Not correct Gateway!', 'Error', MB_ICONERROR);
end
else
Application.MessageBox('Not correct IP Address!', 'Error', MB_ICONERROR);
end;
end
else
begin
ShowMessage('No internet connection!');
end;
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.CreateSourceCode(wifiSSID, wifiPassword, ipAddress, port,
gateWay, subnet: string);
// This procedure creates source code for microcontroller
// Input: "wifiSSID" : wifi name
// "wifiPassword" : wifi password
// "ipAddress" : static IP Address of microcontroller
// "port" : serial port
// "gateWay" : router IP
// "subnet" : network subnet
var
sampleFile: TextFile;
sourceCode: TextFile;
line: string;
begin
//Save input info to source code for microcontroller
AssignFile(sampleFile, 'sampleCode');
Reset(sampleFile);
AssignFile(sourceCode, GetCurrentDir+'\cli\sourceCode\sourceCode.ino');
ReWrite(sourceCode);
//Replace , to . and remove space
ipAddress := StringReplace(ipAddress, '.', ',', [rfReplaceAll]);
ipAddress := StringReplace(ipAddress, ' ', '', [rfReplaceAll]);
gateWay := StringReplace(gateWay, '.', ',', [rfReplaceAll]);
gateWay := StringReplace(gateWay, ' ', '', [rfReplaceAll]);
subnet := StringReplace(subnet, '.', ',', [rfReplaceAll]);
subnet := StringReplace(subnet, ' ', '', [rfReplaceAll]);
port := StringReplace(port, ' ', '', [rfReplaceAll]);
while not Eof(sampleFile) do
begin
ReadLn(sampleFile, line);
if AnsiContainsStr(line,'testWLAN') then
begin
line := StringReplace(line, 'testWLAN', wifiSSID, [rfReplaceAll]);
end
else if AnsiContainsStr(line,'testPassword') then
begin
line := StringReplace(line, 'testPassword', wifiPassword, [rfReplaceAll]);
end
else if AnsiContainsStr(line,'ip(192,168,11,98)') then
begin
line := StringReplace(line, '192,168,11,98', ipAddress, [rfReplaceAll]);
end
else if AnsiContainsStr(line,'gateway(192,168,11,241)') then
begin
line := StringReplace(line, '192,168,11,241', gateWay, [rfReplaceAll]);
end
else if AnsiContainsStr(line, 'server(80)') then
begin
line := StringReplace(line, '80', port, [rfReplaceAll]);
end
else if AnsiContainsStr(line,'subnet(255,255,255,0)') then
begin
line := StringReplace(line, '255,255,255,0', subnet, [rfReplaceAll]);
end;
WriteLn(sourceCode, line);
end;
CloseFile(sampleFile);
CloseFile(sourceCode);
//ShowMessage('CREATE FILE DONE!');
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
function TuploadForm.CheckInputAddressEmpty(inputParameter: string): Integer;
// This function checks input IP Address, Gateway, Subnet, if it is empty
// Input: "inputParameter": string of input parameter
// Result: 0, correct Address, 1, incorrect Address
begin
//Replace space
inputParameter := StringReplace(inputParameter, ' ', '', [rfReplaceAll]);
if(Length(inputParameter) > 3) then
begin
result := ValidateIP(inputParameter);
end
else result := 1; //Not correct
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
function TuploadForm.ValidateIP(iP4: string): Integer;
// This function checks IP Address, Gateway, Subnet, if it is correct
// Input: "ip4": string of IP Address, Gateway or Subnet
// Result: 0, correct Address, 1, incorrect Address
var
octet : String;
dots, I : Integer;
begin
//ip4 := IP4+'.'; //add a dot. We use a dot to trigger the Octet check, so need the last one
dots := 0;
octet := '0';
for I := 1 To Length(iP4) do
begin
if iP4[I] in ['0'..'9','.'] then
begin
if iP4[I] = '.' then //found a dot so inc dots and check octet value
begin
Inc(dots);
If (length(octet) =1) Or (StrToInt(octet) > 255) Then
dots := 5; //Either there's no number or it's higher than 255 so push dots out of range
octet := '0'; // Reset to check the next octet
end // End of IP4[I] is a dot
else // Else IP4[I] is not a dot so
octet := octet + iP4[I]; // Add the next character to the octet
end // End of IP4[I] is not a dot
else // Else IP4[I] Is not in CheckSet so
dots := 5; // Push dots out of range
end;
if dots = 4 then
result := 0 // The only way that Dots will equal 4 is if we passed all the tests
else
result := 1
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.CreateBatchFile(comPort: string);
// This procedure creates batch file to upload code
// Input: "comPort": Selected Serial Port
var
sampleBatchFile: TextFile;
batchFile: TextFile;
line: string;
begin
AssignFile(sampleBatchFile, 'sampleBatch');
Reset(sampleBatchFile);
AssignFile(batchFile, GetCurrentDir+'\batchFile.cmd');
ReWrite(batchFile);
while not Eof(sampleBatchFile) do
begin
ReadLn(sampleBatchFile, line);
if AnsiContainsText(line, 'C:\Users\Admin\Desktop\Upload code program') then
begin
line := StringReplace(line, 'C:\Users\Admin\Desktop\Upload code program', GetCurrentDir, [rfReplaceAll]);
end
else if AnsiContainsText(line, 'COMPort') then
begin
line := StringReplace(line, 'COMPort', comPort, [rfReplaceAll]);
end;
WriteLn(batchFile, line);
end;
CloseFile(sampleBatchFile);
CloseFile(batchFile);
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
function TuploadForm.CheckUploadCodeSuccessful: Integer;
// This function checks output.txt file in folder \cli, if code for microcontroller is installed correctly
// Result: 0, installed correctly, 1, installed incorrectly COM port is busy , 2 installed incorrectly
var
outputFile: TextFile;
line: string;
checkUploadCorrect: Integer;
begin
try
AssignFile(outputFile, GetCurrentDir+'\cli\output.txt');
Reset(outputFile);
checkUploadCorrect := 0;
while not Eof(outputFile) do
begin
ReadLn(outputFile, line);
if AnsiContainsStr(line,'Connecting....') then
begin
checkUploadCorrect := checkUploadCorrect + 1;
end
else if AnsiContainsStr(line,'100 %') then
begin
checkUploadCorrect := checkUploadCorrect + 1;
end
else if AnsiContainsStr(line,'Hash of data verified.') then
begin
checkUploadCorrect := checkUploadCorrect + 1;
end
else if AnsiContainsStr(line,'........_____....._____....._____') then
begin
checkUploadCorrect := checkUploadCorrect + 1; // found error
end;
end;
if checkUploadCorrect = 3 then
begin
result := 0; //correct
end
else if checkUploadCorrect = 0 then
begin
result := 1; //incorrect COM port is busy
end
else if checkUploadCorrect = 1 then
begin
result := 2; //incorrect
end;
CloseFile(outputFile);
except
result := 1; //incorrect
end;
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
procedure TuploadForm.btnScanPortClick(Sender: TObject);
// This procedure re-scan to search new COM Port
begin
cbComPort.Clear;
SearchComPort;
end;
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
function TuploadForm.ShellExecute_AndWait(FileName: string; Params: string): bool;
var
exInfo: TShellExecuteInfo;
Ph: DWORD;
begin
FillChar(exInfo, SizeOf(exInfo), 0);
with exInfo do
begin
cbSize := SizeOf(exInfo);
fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
Wnd := GetActiveWindow();
exInfo.lpVerb := 'open';
exInfo.lpParameters := PChar(Params);
lpFile := PChar(FileName);
nShow := SW_HIDE;
end;
if ShellExecuteEx(@exInfo) then
Ph := exInfo.hProcess
else
begin
ShowMessage(SysErrorMessage(GetLastError));
Result := true;
exit;
end;
while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
Application.ProcessMessages;
CloseHandle(Ph);
Result := true;
end;
end.
|
unit vr_SysUtils;
{$mode delphi}{$H+}
interface
uses
SysUtils, types;
procedure LockVar; inline;
procedure UnLockVar; inline;
function LockedVarCompare(const ATarget: Pointer; const AComparend: Pointer): Integer;
function LockedVarIsNil(const ATarget: Pointer): Boolean;
//? call TObject.Create
//procedure LockedObjectCreate(var AObject; const AClass: TClass; const AFree: Boolean = False);
//procedure LockedObjectCreateIfNil(var AObject; const AClass: TClass);
procedure LockedObjectFreeAndNil(var AObject);
procedure LockedVarSetNil(var v);
function LockedIntefaceGet(const AIntf: IUnknown): IUnknown;
procedure LockedIntefaceSet(var AIntf; const AValue: IUnknown);
function LockedStringGet(const S: string): string; overload;
function LockedStringGet(const S: UnicodeString): UnicodeString;overload;
procedure LockedStringSet(var S: string; const AValue: string);overload;
procedure LockedStringSet(var S: UnicodeString; const AValue: UnicodeString);overload;
function LockedStringEmpty(const S: string): Boolean;overload;
function LockedStringEmpty(const S: UnicodeString): Boolean;overload;
function LockedVarGet(const v): PtrInt;
procedure LockedVarSet(var v; const AValue: PtrInt);
function LockedBoolGet(const v: Boolean): Boolean;
procedure LockedBoolSet(var v: Boolean; const AValue: Boolean);
function LockedByteArrayGet(const arr: TByteDynArray): TByteDynArray;
procedure LockedByteArraySet(var arr: TByteDynArray; const AValue: TByteDynArray);
procedure RaiseToDoException(AMsg: string = '');
implementation
var
_VarOperationLock: TRTLCriticalSection;
procedure LockVar;
begin
EnterCriticalSection(_VarOperationLock);
end;
procedure UnLockVar;
begin
LeaveCriticalSection(_VarOperationLock);
end;
function LockedVarCompare(const ATarget: Pointer; const AComparend: Pointer
): Integer;
begin
LockVar;
try
if ATarget = AComparend then
Result := 0
else if ATarget < AComparend then
Result := -1
else
Result := 1;
finally
UnLockVar;
end;
end;
function LockedVarIsNil(const ATarget: Pointer): Boolean;
begin
LockVar;
try
Result := ATarget = nil;
finally
UnLockVar;
end;
end;
procedure LockedObjectCreate(var AObject; const AClass: TClass;
const AFree: Boolean);
var
tmp: TObject;
begin
LockVar;
try
tmp := TObject(AObject);
TObject(AObject) := AClass.Create;
finally
UnLockVar;
end;
if AFree then
tmp.Free
end;
procedure LockedObjectCreateIfNil(var AObject; const AClass: TClass);
begin
LockVar;
try
if TObject(AObject) = nil then
TObject(AObject) := AClass.Create;
finally
UnLockVar;
end;
end;
procedure LockedObjectFreeAndNil(var AObject);
var
tmp: TObject;
begin
LockVar;
try
tmp := TObject(AObject);
Pointer(AObject) := nil;
finally
UnLockVar;
end;
tmp.Free;
end;
procedure LockedVarSetNil(var v);
begin
LockVar;
try
Pointer(v) := nil;
finally
UnLockVar;
end;
end;
function LockedIntefaceGet(const AIntf: IUnknown): IUnknown;
begin
LockVar;
try
Result := AIntf;
finally
UnLockVar;
end;
end;
procedure LockedIntefaceSet(var AIntf; const AValue: IUnknown);
begin
LockVar;
try
IUnknown(AIntf) := AValue;
finally
UnLockVar;
end;
end;
function LockedStringGet(const S: string): string;
begin
LockVar;
try
Result := S;
UniqueString(Result);
finally
UnLockVar;
end;
end;
function LockedStringGet(const S: UnicodeString): UnicodeString;
begin
LockVar;
try
Result := S;
UniqueString(Result);
finally
UnLockVar;
end;
end;
procedure LockedStringSet(var S: string; const AValue: string);
begin
LockVar;
try
S := AValue;
UniqueString(S);
finally
UnLockVar;
end;
end;
procedure LockedStringSet(var S: UnicodeString; const AValue: UnicodeString);
begin
LockVar;
try
S := AValue;
UniqueString(S);
finally
UnLockVar;
end;
end;
function LockedStringEmpty(const S: string): Boolean;
begin
LockVar;
try
Result := S = '';
finally
UnLockVar;
end;
end;
function LockedStringEmpty(const S: UnicodeString): Boolean;
begin
LockVar;
try
Result := S = '';
finally
UnLockVar;
end;
end;
function LockedVarGet(const v): PtrInt;
begin
LockVar;
try
Result := PtrInt(v);
finally
UnLockVar;
end;
end;
procedure LockedVarSet(var v; const AValue: PtrInt);
begin
LockVar;
try
PtrInt(v) := AValue;
finally
UnLockVar;
end;
end;
function LockedBoolGet(const v: Boolean): Boolean;
begin
LockVar;
try
Result := v;
finally
UnLockVar;
end;
end;
procedure LockedBoolSet(var v: Boolean; const AValue: Boolean);
begin
LockVar;
try
v := AValue;
finally
UnLockVar;
end;
end;
function LockedByteArrayGet(const arr: TByteDynArray): TByteDynArray;
begin
LockVar;
try
Result := Copy(arr, 0, MaxInt);
finally
UnLockVar;
end;
end;
procedure LockedByteArraySet(var arr: TByteDynArray; const AValue: TByteDynArray);
begin
LockVar;
try
arr := Copy(AValue, 0, MaxInt);
finally
UnLockVar;
end;
end;
procedure RaiseToDoException(AMsg: string);
begin
if AMsg = '' then
AMsg := 'Not implemented';
raise Exception.Create('TODO: ' + AMsg);
end;
initialization
InitCriticalSection(_VarOperationLock);
finalization
DoneCriticalsection(_VarOperationLock);
end.
|
unit uAudioThumb;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
implementation
uses
Graphics, Types, DCClassesUtf8, uThumbnails, uMasks, uGraphics;
var
MaskList: TMaskList = nil;
type
TFrameHeader = packed record
ID: array [1..4] of AnsiChar;
Size: Integer;
Flags: UInt16;
end;
TTagHeader = packed record
ID: array [1..3] of AnsiChar;
Version: Byte;
Revision: Byte;
Flags: Byte;
Size: array [1..4] of Byte;
end;
function GetThumbnail(const aFileName: String; aSize: TSize): Graphics.TBitmap;
var
AInc: Byte;
FSize: Int64;
AData: UInt16;
Index: Integer;
AChar: AnsiChar;
ALength: Integer;
ATag: TTagHeader;
AFile: TFileStreamEx;
AFrame: TFrameHeader;
ABitmap: TRasterImage;
AStream: TMemoryStream;
AMimeType: array[Byte] of AnsiChar;
begin
Result:= nil;
if MaskList.Matches(aFileName) then
begin
try
AFile:= TFileStreamEx.Create(aFileName, fmOpenRead or fmShareDenyNone);
try
AFile.ReadBuffer(ATag, SizeOf(TTagHeader));
if (ATag.ID = 'ID3') and (ATag.Version >= 3) then
begin
FSize := (ATag.Size[1] shl 21) or (ATag.Size[2] shl 14) +
(ATag.Size[3] shl 7 ) or (ATag.Size[4]) + 10;
if ATag.Flags and $10 = $10 then Inc(FSize, 10);
while (AFile.Position < FSize) do
begin
AFile.ReadBuffer(AFrame, SizeOf(TFrameHeader));
if not (AFrame.ID[1] in ['A'..'Z']) then Break;
ALength:= BEtoN(AFrame.Size);
if (AFrame.ID = 'APIC') then
begin
AStream:= TMemoryStream.Create;
try
AStream.SetSize(ALength);
AFile.ReadBuffer(AStream.Memory^, ALength);
// Text encoding
case AStream.ReadByte of
$01, $02: AInc:= 2;
else AInc:= 1;
end;
// MIME type
Index:= 0;
repeat
AChar:= Chr(AStream.ReadByte);
AMimeType[Index]:= AChar;
Inc(Index);
until not ((AChar > #0) and (Index < High(Byte)));
// Picture type
AStream.ReadByte;
// Description
repeat
AStream.ReadBuffer(AData, AInc);
until (AData = 0);
// Picture data
if (StrPos(AMimeType, 'image/') = nil) then
begin
AMimeType := 'image/' + AMimeType;
end;
if AMimeType = 'image/png' then
begin
ABitmap:= TPortableNetworkGraphic.Create;
end
else if AMimeType = 'image/jpeg' then
begin
ABitmap:= TJPEGImage.Create;
end;
if Assigned(ABitmap) then
try
ABitmap.LoadFromStream(AStream, ALength - AStream.Position);
Result:= TBitmap.Create;
BitmapAssign(Result, ABitmap);
finally
ABitmap.Free;
end;
finally
AStream.Free;
end;
Break;
end;
AFile.Seek(ALength, soCurrent);
end;
end;
finally
AFile.Free;
end;
except
// Ignore
end;
end;
end;
procedure Initialize;
begin
MaskList:= TMaskList.Create('*.mp3');
// Register thumbnail provider
TThumbnailManager.RegisterProvider(@GetThumbnail);
end;
initialization
Initialize;
finalization
MaskList.Free;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSceneViewerToolbar<p>
Added GLScene's toolbar to Delphi IDE.<p>
<b>History : </b><font size=-1><ul>
<li>21/11/10 - Yar - Creation
</ul></font>
}
unit GLSceneToolbar;
interface
implementation
uses
Classes,
SysUtils,
Graphics,
ImgList,
Controls,
ComCtrls,
ExtCtrls,
ActnList,
ToolsAPI,
GLScene,
GLSGenerics;
const
cGLSceneViewerToolbar = 'GLSceneViewerToolbar';
type
TGLSToolButtonReceiver = class
protected
FActionList: GList<TBasicAction>;
procedure OnClick(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
var
vReciver: TGLSToolButtonReceiver;
function MsgServices: IOTAMessageServices;
begin
Result := (BorlandIDEServices as IOTAMessageServices);
Assert(Result <> nil, 'IOTAMessageServices not available');
end;
procedure AddGLSceneToolbar;
var
Services: INTAServices;
T: Integer;
GLToolbar: TToolBar;
procedure AddButton(const AHint, AResName: string);
var
Bmp: TBitmap;
Act: TAction;
begin
Act := TAction.Create(nil);
Act.ActionList := Services.ActionList;
vReciver.FActionList.Add(Act);
Bmp := TBitmap.Create;
Bmp.LoadFromResourceName(HInstance, AResName);
Act.ImageIndex := Services.AddMasked(Bmp, Bmp.TransparentColor, 'GLScene.' + AResName);
Bmp.Destroy;
Act.Hint := AHint;
Act.Tag := T;
Act.OnExecute := vReciver.OnClick;
with Services.AddToolButton(cGLSceneViewerToolbar, 'GLSButton' + IntToStr(T), Act) do
Action := Act;
Act.Enabled := True;
Inc(T);
end;
begin
if not Supports(BorlandIDEServices, INTAServices, Services) then
exit;
GLToolbar := Services.ToolBar[cGLSceneViewerToolbar];
vReciver := TGLSToolButtonReceiver.Create;
T := 0;
if not Assigned(GLToolbar) then
begin
GLToolbar := Services.NewToolbar(cGLSceneViewerToolbar, 'GLScene Viewer Control');
if Assigned(GLToolbar) then
with GLToolbar do
begin
AddButton('GLSceneViewer default control mode', 'GLSceneViewerControlToolbarDefault');
AddButton('GLSceneViewer navigation mode', 'GLSceneViewerControlToolbarNavigation');
AddButton('GLSceneViewer gizmo mode', 'GLSceneViewerControlToolbarGizmo');
AddButton('Reset view to GLSceneViewer camera', 'GLSceneViewerControlToolbarCameraReset');
Visible := True;
end;
MsgServices.AddTitleMessage('GLScene Toolbar created');
end
else
begin
for T := 0 to GLToolbar.ButtonCount - 1 do
begin
GLToolbar.Buttons[T].Action.OnExecute := vReciver.OnClick;
vReciver.FActionList.Add(GLToolbar.Buttons[T].Action);
end;
MsgServices.AddTitleMessage('GLScene Toolbar activated');
end;
Services.ToolbarModified(GLToolbar);
end;
constructor TGLSToolButtonReceiver.Create;
begin
FActionList := GList<TBasicAction>.Create;
vGLSceneViewerMode := svmDefault;
end;
destructor TGLSToolButtonReceiver.Destroy;
var
I: Integer;
begin
for I := 0 to FActionList.Count - 1 do
FActionList[I].OnExecute := nil;
FActionList.Destroy;
vGLSceneViewerMode := svmDisabled;
end;
procedure TGLSToolButtonReceiver.OnClick(Sender: TObject);
const
cMode: array [TGLSceneViewerMode] of string = ('', 'default', 'navigation', 'gizmo');
var
T: Integer;
begin
inherited;
T := TComponent(Sender).Tag;
if T < 3 then
begin
vGLSceneViewerMode := TGLSceneViewerMode(T+1);
MsgServices.AddTitleMessage(Format('GLSceneViewer %s mode', [cMode[vGLSceneViewerMode]]));
end
else
vResetDesignView := True;
end;
initialization
AddGLSceneToolbar;
finalization
vReciver.Free;
end.
|
object frmMain: TfrmMain
Left = 0
Top = 0
BorderStyle = bsNone
Caption = 'frmMain'
ClientHeight = 262
ClientWidth = 358
Color = 66051
Constraints.MinHeight = 120
Constraints.MinWidth = 320
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
KeyPreview = True
OldCreateOrder = False
ShowHint = True
OnCloseQuery = FormCloseQuery
OnCreate = FormCreate
OnDestroy = FormDestroy
OnKeyDown = FormKeyDown
OnMouseDown = pnlDragWindow
OnMouseMove = pnlVideoMouseMove
OnMouseWheel = FormMouseWheel
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object pnlControl: TPanel
Left = 0
Top = 0
Width = 358
Height = 35
Align = alTop
TabOrder = 0
OnMouseDown = pnlDragWindow
OnMouseLeave = pnlControlMouseLeave
object btnStop: TSpeedButton
Left = 68
Top = 2
Width = 30
Height = 30
Hint = 'Stop'
Glyph.Data = {
8E000000424D8E000000000000003E0000002800000014000000140000000100
010000000000500000000000000000000000020000000000000000000000FFFF
FF00FFFFF000FFFFF000FFFFF000FFFFF000F000F000F000F000F000F000F000
F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000
F000FFFFF000FFFFF000FFFFF000FFFFF000}
OnClick = btnStopClick
end
object btnPlay: TSpeedButton
Left = 4
Top = 2
Width = 31
Height = 30
Hint = 'Play'
AllowAllUp = True
GroupIndex = 1
Glyph.Data = {
8E000000424D8E000000000000003E0000002800000014000000140000000100
010000000000500000000000000000000000020000000000000000000000FFFF
FF00FFFFF000FFFFF000FFFFF000FFFFF000FBFFF000F8FFF000F87FF000F81F
F000F807F000F803F000F803F000F807F000F81FF000F87FF000F8FFF000FBFF
F000FFFFF000FFFFF000FFFFF000FFFFF000}
OnClick = btnPlayClick
end
object btnPauseStill: TSpeedButton
Left = 36
Top = 2
Width = 31
Height = 30
Hint = 'Pause/Still'
AllowAllUp = True
GroupIndex = 2
Glyph.Data = {
8E000000424D8E000000000000003E0000002800000014000000140000000100
010000000000500000000000000000000000020000000000000000000000FFFF
FF00FFFFF000FFFFF000FFFFF000FFFFF000F37FF000F31FF000F30FF000F303
F000F300F000F3007000F3007000F300F000F303F000F30FF000F31FF000F37F
F000FFFFF000FFFFF000FFFFF000FFFFF000}
OnClick = btnPauseStillClick
end
object lblV: TLabel
Left = 103
Top = 2
Width = 18
Height = 13
Caption = 'V: ?'
end
object lblA: TLabel
Left = 103
Top = 17
Width = 19
Height = 13
Caption = 'A: ?'
end
object pnlControlRight: TPanel
Left = 212
Top = 1
Width = 145
Height = 33
Align = alRight
BevelOuter = bvNone
TabOrder = 0
object btnClose: TSpeedButton
Left = 112
Top = 2
Width = 30
Height = 30
Hint = 'Exit'
Glyph.Data = {
66010000424D6601000000000000760000002800000014000000140000000100
040000000000F000000000000000000000001000000000000000000000000000
8000008000000080800080000000800080008080000080808000C0C0C0000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00FFFFFFFFFFFF
FFFFFFFF0000FFFFFFFFFFFFFFFFFFFF0000FF000FFFFFFFFF0000FF0000FF00
00FFFFFFF00000FF0000FF00000FFFFF000000FF0000FF000000FFF000000FFF
0000FFF000000F000000FFFF0000FFFF00000000000FFFFF0000FFFFF0000000
00FFFFFF0000FFFFFF0000000FFFFFFF0000FFFFFF0000000FFFFFFF0000FFFF
F000000000FFFFFF0000FFFF00000000000FFFFF0000FFF000000F000000FFFF
0000FF000000FFF000000FFF0000FF00000FFFFF000000FF0000FF0000FFFFFF
F00000FF0000FF000FFFFFFFFF0000FF0000FFFFFFFFFFFFFFFFFFFF0000FFFF
FFFFFFFFFFFFFFFF0000}
OnClick = btnCloseClick
end
object btnSettings: TSpeedButton
Left = 14
Top = 2
Width = 30
Height = 30
Hint = 'Configuration'
Glyph.Data = {
C6050000424DC605000000000000360400002800000014000000140000000100
08000000000090010000C40E0000C40E00000001000000010000000000000202
0200030303000A0A0A000C0C0C000D0D0D000E0E0E000F0F0F00101010001717
1700191919001E1E1E004C4C4C00515151005454540057575700585858006060
60006969690070707000747474007F7F7F0080808000ACACAC00B2B2B200B3B3
B300B8B8B800BDBDBD00C2C2C200E1E1E100E7E7E700F3F3F300F4F4F400F5F5
F500F7F7F700F8F8F800F9F9F900FCFCFC00FFFFFF0000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000262626262326
26160000000016262623262626262626261D111C25150000000015251C111D26
262626261E0C000B19140000000014190B000C1E2626261D0C02000008050000
000005080000020C1D262311000000000000000000000000000000001123261C
0B00000000000000000000000000000B1C262220170700000000000000000000
00000717202211111003000000000A12120A0000000003101111000000000000
00091B24241B0900000000000000000000000000000F212626210F0000000000
0000000000000000000E202626200E0000000000000000000000000000081A1F
1F1A08000000000000001515130400000000060D0D0600000000041315162625
180700000000000000000000000007182526261C0B0000000000000000000000
0000000B1C262311000000000000000000000000000000001123261D0C010000
08050000000005080000020C1D2626261E0C000B19140000000014190B000C1E
26262626261D111C25150000000015251C111D26262626262626232626150000
00001526262326262626}
OnClick = btnSettingsClick
end
object btnFullscreen: TSpeedButton
Left = 79
Top = 2
Width = 30
Height = 30
Hint = 'Fullscreen'
AllowAllUp = True
GroupIndex = 2
Glyph.Data = {
8E000000424D8E000000000000003E0000002800000014000000140000000100
010000000000500000000000000000000000020000000000000000000000FFFF
FF00FF9FF000FF0FF000FE07F000FF9FF000FF9FF000FFFFF000F801F000D801
B00098019000080100000801000098019000D801B000F801F000FFFFF000FF9F
F000FF9FF000FE07F000FF0FF000FF9FF000}
OnClick = btnFullscreenClick
end
object btnMinimize: TSpeedButton
Left = 46
Top = 2
Width = 30
Height = 30
Hint = 'Minimize'
Glyph.Data = {
8E000000424D8E000000000000003E0000002800000014000000140000000100
010000000000500000000000000000000000020000000000000000000000FFFF
FF00FFFFF000C0003000C0003000FFFFF000FFFFF000FFFFF000FFFFF000FFFF
F000FFFFF000FFFFF000FFFFF000FFFFF000FFFFF000FFFFF000FFFFF000FFFF
F000FFFFF000FFFFF000FFFFF000FFFFF000}
OnClick = btnMinimizeClick
end
end
end
object pnlMain: TPanel
Left = 0
Top = 35
Width = 358
Height = 227
Align = alClient
BevelOuter = bvNone
Color = 66051
TabOrder = 1
OnMouseDown = pnlDragWindow
OnMouseMove = pnlVideoMouseMove
end
object tmrShowControl: TTimer
Enabled = False
Interval = 500
OnTimer = tmrShowControlTimer
Left = 8
Top = 40
end
object tmrCursorHide: TTimer
Enabled = False
Interval = 3000
OnTimer = tmrCursorHideTimer
Left = 8
Top = 72
end
object tmrRefreshControl: TTimer
Interval = 100
OnTimer = tmrRefreshControlTimer
Left = 8
Top = 112
end
object tmrGetFilePos: TTimer
OnTimer = tmrGetFilePosTimer
Left = 8
Top = 152
end
object tmrAntirepeat: TTimer
Enabled = False
Interval = 100
OnTimer = tmrAntirepeatTimer
Left = 8
Top = 192
end
object tmrSavePlaylists: TTimer
Interval = 120000
OnTimer = tmrSavePlaylistsTimer
Left = 56
Top = 40
end
end
|
Program PasswordTest;
Const
saved='1234';
Var
bool:boolean;
Function checkpassword():boolean;
Var
password:string;
tries:integer;
check:boolean;
Begin
tries:=0;
check:= false;
Repeat
Write ('Enter your password : ');
Readln (password);
tries:= (tries + 1);
If (password = saved) then
Begin
Write ('Success! ');
check := true;
End;
If (check = false) then
Begin
Writeln ('You have entered a wrong password, please try again');
Writeln ('The times you entered a password are : ', tries);
End;
If ( (tries=3) and (check = false) ) then
Writeln ('ACCESS DENIED!!!')
Until ( (password = saved) or ( (tries>=3) and (check = false) ) );
checkpassword:=check;
End;
Begin
bool:=checkpassword();
If (bool=true) then
writeln('You are now authorized!');
End.
|
unit u_DMWeight;
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.Stan.ExprFuncs,
FireDAC.Phys.SQLiteDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.Comp.UI, FireDAC.Phys.SQLite, u_WeightComm,
Variants;
const
CONST_FIELDNAME_ID = 'ID';
CONST_FIELDNAME_MANIFESTNO = 'MainfestNo';
CONST_FIELDNAME_PLATELIC = 'PlateLic';
CONST_FIELDNAME_DRIVERNAME = 'DriverName';
CONST_FIELDNAME_DRIVERIDC = 'DriverIDC';
CONST_FIELDNAME_WEIGHTBRIDGENO = 'WeighBridgeNo';
CONST_FIELDNAME_WEIGHTGROSS = 'WeightGross';
CONST_FIELDNAME_WEIGHTGROSSTIME = 'WeightGrossTime';
CONST_FIELDNAME_WEIGHTGROSSVALID = 'WeightGrossValid';
CONST_FIELDNAME_WEIGHTARE = 'WeightTare';
CONST_FIELDNAME_WEIGHTTARETIME = 'WeightTareTime';
CONST_FIELDNAME_WEIGHTTAREVALID = 'WeightTareValid';
CONST_FIELDNAME_COMMITED = 'Commited';
CONST_FIELDNAME_NOTE = 'Note';
type
TdmWeight = class(TDataModule)
FDConnection1: TFDConnection;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDQuery1: TFDQuery;
DataSource1: TDataSource;
FDCommand1: TFDCommand;
FDTable1: TFDTable;
FDConnection2: TFDConnection;
FDTable1ID: TIntegerField;
FDTable1MainfestNo: TWideStringField;
FDTable1PlateLic: TWideStringField;
FDTable1DriverName: TWideStringField;
FDTable1DriverIDC: TWideStringField;
FDTable1WeighBridgeNo: TWideStringField;
FDTable1WeightGross: TFloatField;
FDTable1WeightGrossTime: TDateTimeField;
FDTable1WeightGrossValid: TBooleanField;
FDTable1WeightTare: TFloatField;
FDTable1WeightTareTime: TDateTimeField;
FDTable1WeightTareValid: TBooleanField;
FDTable1Note: TWideStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
function CheckNullDef(const Value: Variant; ValueIfNull: Variant): Variant;
Procedure CheckOpenDB;
Procedure CheckOpenDB2;
Procedure UpdateFieldDisplay();
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
Function DB_InsertAuthInfo(const Value: TWeightAuth): Integer;
Function DB_MainfestExist(const MainfestNo: String): Boolean;
Function DB_2Record(var Value: TWeightInfo): Boolean; Overload;
// Function DB_2Record(const MainfestNo: String; var Value: TWeightInfo): Boolean; Overload;
function DB_Mainfest2Record(const MainfestNo: String;
var Value: TWeightInfo): Boolean;
// Function DB_Mainfest2Record(const MainfestNum: String; var Value: TWeightInfo): Boolean;
Function DB_SaveGross(const MainfestNo: String; Weight: Single; SampleTime: TDateTime): Boolean;
Function DB_SaveTare(const MainfestNo: String; Weight: Single; SampleTime: TDateTime): Boolean;
Function DB_IsWeightBridgeEmpty(const MainfestNo: String): Boolean;
Procedure DB_UpdateBridgeNo(const MainfestNo: String; const BridgeNo: String);
Procedure DB_SetMainfestCommited(const MainfestNo: String);
end;
var
dmWeight: TdmWeight;
implementation
uses
System.Generics.Collections ,CnCommon;
const
CONST_DBFILENAME = 'SQLTest.sdb';
CONST_TABLENAME = 'WeightInfo';
{$R *.dfm}
function TdmWeight.CheckNullDef(const Value: Variant;
ValueIfNull: Variant): Variant;
begin
if VarIsNull(Value) then
Result:= ValueIfNull
else
Result:= Value;
end;
procedure TdmWeight.CheckOpenDB;
const
dbPath = '.\' + CONST_DBFILENAME;
//var
// dbPath: String;
//begin
// dbPath:= AppPath + '\WeightInfo.sdb';
var
Tables: TStringList;
begin
with FDConnection1 do begin
Params.Add('DriverID=SQLite');
Params.Add('Database=' + dbPath);
Connected := True;
end;
Tables:= TStringList.Create;
try
FDConnection1.GetTableNames('', '', '', Tables);
if Tables.IndexOf(CONST_TABLENAME) < 0 then
begin
FDConnection1.ExecSQL('CREATE TABLE ' + CONST_TABLENAME + ' (' +
CONST_FIELDNAME_ID +' integer PRIMARY KEY,' +
CONST_FIELDNAME_MANIFESTNO + ' string(500), ' +
CONST_FIELDNAME_PLATELIC + ' string(50), ' +
CONST_FIELDNAME_DRIVERNAME + ' string(10), ' +
CONST_FIELDNAME_DRIVERIDC + ' string(20), ' +
CONST_FIELDNAME_WEIGHTBRIDGENO +' string(10), ' +
CONST_FIELDNAME_WEIGHTGROSS + ' float, ' +
CONST_FIELDNAME_WEIGHTGROSSTIME +' DATETIME, ' +
CONST_FIELDNAME_WEIGHTGROSSVALID + ' bit default 0, ' +
CONST_FIELDNAME_WEIGHTARE + ' float, ' +
CONST_FIELDNAME_WEIGHTTARETIME + ' DATETIME, ' +
CONST_FIELDNAME_WEIGHTTAREVALID +' bit default 0, ' +
CONST_FIELDNAME_COMMITED + ' bit default 0, ' +
CONST_FIELDNAME_NOTE + ' string(100)' +
')');
end;
finally
Tables.Free;
end;
{查看表}
FDQuery1.Open('SELECT * FROM WeightInfo where ' + CONST_FIELDNAME_COMMITED + ' = 0');
UpdateFieldDisplay();
end;
procedure TdmWeight.CheckOpenDB2;
const
dbPath = '.\SQLiteTest.sdb';
begin
if FileExists(dbPath) then
DeleteFile(dbPath);
with FDConnection1 do begin
Params.Add('DriverID=SQLite');
Params.Add('Database=' + dbPath);
Connected := True;
end;
with FDCommand1.CommandText do begin
Add('CREATE TABLE MyTable(');
Add('ID integer PRIMARY KEY,'); //Integer 类型, 同时设为主键
Add('Name string(10),'); //能容下 10 个字符的 String 类型
Add('Age byte,'); //Byte 类型
Add('Note text,'); //Memo 类型
Add('Picture blob'); //Blob(二进制)类型
Add(')');
end;
FDCommand1.Active := True;
{查看表}
//FDQuery1.Open('SELECT * FROM MyTable');
//UpdateFieldDisplay();
end;
constructor TdmWeight.Create(AOwner: TComponent);
begin
inherited;
CheckOpenDB();
// CheckOpenDB2();
end;
procedure TdmWeight.DataModuleCreate(Sender: TObject);
begin
// CREATE TABLE testtable (
// [ID] INTEGER PRIMARY KEY,
// [OtherID] INTEGER NULL,
// [Name] VARCHAR (255),
// [Number] FLOAT,
// [notes] BLOB,
// [picture] BLOB COLLATE NOCASE)
//---------------------
end;
function TdmWeight.DB_2Record(var Value: TWeightInfo): Boolean;
begin
Result:= False;
if FDQuery1.Active and (FDQuery1.RecNo > 0) then
begin
//// Value.Auth.MainfestNo:= FDQuery1.FieldByName(CONST_FIELDNAME_MAINFESTNO).Value;
//// Value.Auth.PlateNum:= FDQuery1.FieldByName(CONST_FIELDNAME_PLATELIC).Value;
//// Value.Auth.DriverName:= FDQuery1.FieldByName(CONST_FIELDNAME_DRIVERNAME).Value;
//// Value.Auth.DriverIDC:= FDQuery1.FieldByName(CONST_FIELDNAME_DRIVERIDC).Value;
//
// Value.Auth.MainfestNo:= FDQuery1[CONST_FIELDNAME_MAINFESTNO];
// Value.Auth.PlateNum:= FDQuery1[CONST_FIELDNAME_PLATELIC];
// Value.Auth.DriverName:= FDQuery1[CONST_FIELDNAME_DRIVERNAME];
// Value.Auth.DriverIDC:= FDQuery1[CONST_FIELDNAME_DRIVERIDC];
//
//
// Value.Mesure.WeightBridge:= CheckNullDef(FDQuery1[CONST_FIELDNAME_WEIGHTBRIDGENO], '');
//
//
// Value.Mesure.Gross.Valid:= FDQuery1[CONST_FIELDNAME_WEIGHTGROSSVALID];
// if Value.Mesure.Gross.Valid then
// begin
// Value.Mesure.Gross.Wegiht_KG:= FDQuery1[CONST_FIELDNAME_WEIGHTGROSS];
// Value.Mesure.Gross.WegihtTime:= FDQuery1[CONST_FIELDNAME_WEIGHTGROSSTIME];
// end;
//
// Value.Mesure.Tare.Valid:= FDQuery1[CONST_FIELDNAME_WEIGHTTAREVALID];
// if Value.Mesure.Tare.Valid then
// begin
// Value.Mesure.Tare.Wegiht_KG:= FDQuery1[CONST_FIELDNAME_WEIGHTARE];
// Value.Mesure.Tare.WegihtTime:= FDQuery1[CONST_FIELDNAME_WEIGHTTARETIME];
// end;
//
// value.Mesure.Note:= CheckNullDef(FDQuery1[CONST_FIELDNAME_NOTE], '');;
// Result:= True;
Result:= DB_Mainfest2Record(FDQuery1[CONST_FIELDNAME_MANIFESTNO], Value);
end;
end;
//function TdmWeight.DB_2Record(const MainfestNo: String;
// var Value: TWeightInfo): Boolean;
////var
//// bs: TBookmark;
//begin
// Result:= False;
// FDQuery1.DisableControls;
// try
//// bs:= FDQuery1.Bookmark;
//
// if FDQuery1.Locate(CONST_FIELDNAME_MAINFESTNO, MainfestNo) then
// begin
// Result:= DB_2Record(Value);
// end;
//// FDQuery1.GotoBookmark(bs);
// finally
// FDQuery1.EnableControls;
// end;
//end;
function TdmWeight.DB_InsertAuthInfo(const Value: TWeightAuth): Integer;
begin
Result:= -1;
FDQuery1.DisableControls();
try
if not DB_MainfestExist(Value.MainfestNo) then
begin
FDQuery1.Append();
FDQuery1.FieldByName(CONST_FIELDNAME_MANIFESTNO).Value:= Value.MainfestNo;
FDQuery1.FieldByName(CONST_FIELDNAME_PLATELIC).Value:= Value.PlateNum;
FDQuery1.FieldByName(CONST_FIELDNAME_DRIVERNAME).Value:= Value.DriverName;
FDQuery1.FieldByName(CONST_FIELDNAME_DRIVERIDC).Value:= Value.DriverIDC;
FDQuery1.Post;
Result:= 0;
end
else
Begin
raise Exception.Create('认证的联单编号已经认证过:' + Value.MainfestNo);
End;
finally
FDQuery1.EnableControls();
end;
end;
function TdmWeight.DB_IsWeightBridgeEmpty(const MainfestNo: String): Boolean;
var
AInfo: TWeightInfo;
begin
Result:= DB_Mainfest2Record(MainfestNo, AInfo);
if Result then
begin
Result:= Trim(AInfo.Mesure.WeightBridge) = '';
end;
end;
function TdmWeight.DB_Mainfest2Record(const MainfestNo: String;
var Value: TWeightInfo): Boolean;
var
V: Variant;
begin
Result:= False;
if FDQuery1.Active and (FDQuery1.RecNo > 0) then
begin
V:= FDQuery1.Lookup(CONST_FIELDNAME_MANIFESTNO, MainfestNo,
CONST_FIELDNAME_MANIFESTNO + '; ' +
CONST_FIELDNAME_PLATELIC + '; ' +
CONST_FIELDNAME_DRIVERNAME + '; ' +
CONST_FIELDNAME_DRIVERIDC + '; ' +
CONST_FIELDNAME_WEIGHTBRIDGENO + '; ' +
CONST_FIELDNAME_WEIGHTGROSSVALID + '; ' +
CONST_FIELDNAME_WEIGHTGROSS + '; ' +
CONST_FIELDNAME_WEIGHTGROSSTIME + '; ' +
CONST_FIELDNAME_WEIGHTTAREVALID + '; ' +
CONST_FIELDNAME_WEIGHTARE + '; ' +
CONST_FIELDNAME_WEIGHTTARETIME + '; ' +
CONST_FIELDNAME_NOTE + '; ' +
CONST_FIELDNAME_COMMITED
);
if Not VarIsNull(V) then
begin
Value.Auth.MainfestNo:= V[0];
Value.Auth.PlateNum:= V[1];
Value.Auth.DriverName:= V[2];
Value.Auth.DriverIDC:= V[3];
Value.Mesure.WeightBridge:= CheckNullDef(V[4], '');
Value.Mesure.Gross.Valid:= CheckNullDef(V[5], False);
if Value.Mesure.Gross.Valid then
begin
Value.Mesure.Gross.Wegiht:= V[6];
Value.Mesure.Gross.WegihtTime:= V[7];
end;
Value.Mesure.Tare.Valid:= CheckNullDef(V[8], False);
if Value.Mesure.Tare.Valid then
begin
Value.Mesure.Tare.Wegiht:= V[9];
Value.Mesure.Tare.WegihtTime:= V[10];
end;
Value.Mesure.Note:= CheckNullDef(V[11], '');;
Value.Commited:= CheckNullDef(V[11], False);;
Result:= True;
end;
end;
end;
function TdmWeight.DB_MainfestExist(const MainfestNo: String): Boolean;
begin
Result:= Not VarIsNull(FDQuery1.Lookup(CONST_FIELDNAME_MANIFESTNO, MainfestNo, CONST_FIELDNAME_ID));
end;
function TdmWeight.DB_SaveGross(const MainfestNo: String; Weight: Single;
SampleTime: TDateTime): Boolean;
var
SQL: String;
begin
SQL:= Format(
'UPDATE %s SET %s = :a , ' +
' %s = :b , ' +
' %s = 1 ' +
' WHERE %s = :c',
[CONST_TABLENAME,
CONST_FIELDNAME_WEIGHTGROSS,
CONST_FIELDNAME_WEIGHTGROSSTIME,
CONST_FIELDNAME_WEIGHTGROSSVALID,
CONST_FIELDNAME_MANIFESTNO]
);
FDConnection1.ExecSQL(SQL, [Weight, SampleTime, MainfestNo]);
FDQuery1.Refresh;
end;
function TdmWeight.DB_SaveTare(const MainfestNo: String; Weight: Single;
SampleTime: TDateTime): Boolean;
var
SQL: String;
begin
SQL:= Format(
'UPDATE %s SET %s = :a , ' +
' %s = :b , ' +
' %s = 1 ' +
' WHERE %s = :c',
[CONST_TABLENAME,
CONST_FIELDNAME_WEIGHTARE,
CONST_FIELDNAME_WEIGHTTARETIME,
CONST_FIELDNAME_WEIGHTTAREVALID,
CONST_FIELDNAME_MANIFESTNO]
);
FDConnection1.ExecSQL(SQL, [Weight, SampleTime, MainfestNo]);
FDQuery1.Refresh;
end;
procedure TdmWeight.DB_SetMainfestCommited(const MainfestNo: String);
var
SQL: String;
begin
SQL:= Format(
'UPDATE %s SET %s = 1' +
' WHERE %s = :a',
[CONST_TABLENAME,
CONST_FIELDNAME_COMMITED,
CONST_FIELDNAME_MANIFESTNO]
);
FDConnection1.ExecSQL(SQL, [MainfestNo]);
FDQuery1.Refresh;
end;
procedure TdmWeight.DB_UpdateBridgeNo(const MainfestNo, BridgeNo: String);
var
SQL: String;
begin
SQL:= Format(
'UPDATE %s SET %s = :a' +
' WHERE %s = :b',
[CONST_TABLENAME,
CONST_FIELDNAME_WEIGHTBRIDGENO,
CONST_FIELDNAME_MANIFESTNO]
);
FDConnection1.ExecSQL(SQL, [BridgeNo, MainfestNo]);
FDQuery1.Refresh;
end;
procedure TdmWeight.UpdateFieldDisplay();
type
TFieldDispInfo = Record
FieldName: String;
DisplayLabel: String;
DisplayWidth: Integer;
end;
var
AList: TArray<TFieldDispInfo>;
Procedure ListAdd(AName: string; ADisplayText: String; DisplayWidth: Integer);
var
AItem: TFieldDispInfo;
begin
AItem.FieldName:= AName;
AItem.DisplayLabel:= ADisplayText;
AItem.DisplayWidth:= DisplayWidth;
Insert(AItem, AList, 0);
end;
var
i: Integer;
AFieldName: String;
AField: TField;
begin
ListAdd('ID' ,'ID' , 5);
ListAdd('MainfestNo' ,'联单编码' , 15);
ListAdd('PlateLic' ,'车牌号' , 30);
ListAdd('DriverName' ,'驾驶员姓名' , 10);
ListAdd('DriverIDC' ,'驾驶员身份证号' , 20);
ListAdd('WeighBridgeNo' ,'地磅编号' , 5);
ListAdd('WeightGross' ,'毛重' , 10);
ListAdd('WeightGrossTime' ,'毛重时间' , 20);
ListAdd('WeightTareValid' ,'皮重有效' , 2 );
ListAdd('WeightTare' ,'皮重' , 10);
ListAdd('WeightTareTime' ,'皮重时间' , 20);
ListAdd('WeightGrossvalid','毛重有效' , 2);
ListAdd('Note' ,'备注' , 50);
ListAdd(CONST_FIELDNAME_COMMITED, '已提交', 2);
for i := 0 to Length(AList) - 1 do
begin
AField:= FDQuery1.FindField(AList[i].FieldName);
if AField <> nil then
begin
AField.DisplayLabel:= AList[i].DisplayLabel;
AField.DisplayWidth:= AList[i].DisplayWidth;
end;
end;
// TDateTimeField(FDQuery1.FieldByName(CONST_FIELDNAME_WEIGHTGROSSTIME)).DisplayFormat:= 'YYYY-MM-DD HH:NN:SS';
// TDateTimeField(FDQuery1.FieldByName(CONST_FIELDNAME_WEIGHTTARETIME)).DisplayFormat:= 'YYYY-MM-DD HH:NN:SS';
TFloatField(FDQuery1.FieldByName(CONST_FIELDNAME_WEIGHTGROSS)).DisplayFormat:= '0.00';
TFloatField(FDQuery1.FieldByName(CONST_FIELDNAME_WEIGHTARE)).DisplayFormat:= '0.00';
end;
end.
|
unit HGM.GraphQL.Fields;
interface
uses
System.Generics.Collections, HGM.GraphQL.Types;
type
TGraphFields = class;
TGraphField = class
private
FArgs: TGraphArgList;
FName: string;
FSubFields: TGraphFields;
procedure SetName(const Value: string);
public
function ToString: string; reintroduce;
constructor Create(const AName: string);
destructor Destroy; override;
function AddSub(const Item: TGraphField): TGraphField; overload;
function AddSub(const Item: string): TGraphField; overload;
function AddArg(const Item: TGraphArg): TGraphField;
property Args: TGraphArgList read FArgs;
property SubFields: TGraphFields read FSubFields;
property Name: string read FName write SetName;
end;
TGraphFields = class(TObjectList<TGraphField>)
public
constructor Create; reintroduce; overload;
constructor Create(const Items: TArray<string>); overload;
function AddField(const Item: TGraphField): TGraphFields;
function ToString: string; reintroduce;
end;
implementation
uses
System.SysUtils;
{ TGraphField }
function TGraphField.AddArg(const Item: TGraphArg): TGraphField;
begin
Args.Add(Item);
Result := Self;
end;
function TGraphField.AddSub(const Item: TGraphField): TGraphField;
begin
SubFields.Add(Item);
Result := Self;
end;
function TGraphField.AddSub(const Item: string): TGraphField;
begin
SubFields.Add(TGraphField.Create(Item));
Result := Self;
end;
constructor TGraphField.Create(const AName: string);
begin
FArgs := TGraphArgList.Create;
FSubFields := TGraphFields.Create;
FName := AName;
end;
destructor TGraphField.Destroy;
begin
FArgs.Free;
FSubFields.Free;
inherited;
end;
procedure TGraphField.SetName(const Value: string);
begin
FName := Value;
end;
function TGraphField.ToString: string;
begin
Result := FName;
if FArgs.Count > 0 then
Result := Result + FArgs.ToString;
if FSubFields.Count > 0 then
Result := Result + FSubFields.ToString;
end;
{ TGraphFields }
constructor TGraphFields.Create;
begin
inherited Create;
end;
function TGraphFields.AddField(const Item: TGraphField): TGraphFields;
begin
Add(Item);
Result := Self;
end;
constructor TGraphFields.Create(const Items: TArray<string>);
var
Item: string;
begin
Create;
for Item in Items do
Add(TGraphField.Create(Item));
end;
function TGraphFields.ToString: string;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Result := Result + Items[i].ToString + ', ';
Result := '{' + Result.TrimRight([',', ' ']) + '}';
end;
end.
|
unit Model.Register.Base;
interface
uses
System.SysUtils, System.Classes, Model.Base, Model.Connection,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Methods.Anonymous;
type
TdtmdlRegister = class(TdtmdlBase)
fdqryList: TFDQuery;
dsList: TDataSource;
fdqryRegister: TFDQuery;
dsRegister: TDataSource;
procedure fdqryRegisterNewRecord(DataSet: TDataSet);
private
function GetIsListActive: Boolean;
protected
procedure SaveDetail; virtual;
procedure OpenDetail; virtual;
procedure CloseDetail; virtual;
procedure CancelDetail; virtual;
procedure CachedUpdates; virtual;
public
property IsListActive: Boolean read GetIsListActive;
procedure NewRegister; virtual;
procedure EditRegister; virtual;
procedure SaveRegister; virtual;
procedure CancelRegister; virtual;
procedure IndexFilter(AField: string);
procedure FilterList(AField, AValue: string);
procedure FillInField(AProc: TProc<string, string>);
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdtmdlRegister.CachedUpdates;
begin
if fdqryRegister.CachedUpdates then
begin
fdqryRegister.ApplyUpdates(0);
fdqryRegister.CommitUpdates;
end;
end;
procedure TdtmdlRegister.CancelDetail;
begin
end;
procedure TdtmdlRegister.CancelRegister;
begin
CancelDetail;
if fdqryList.State in dsEditModes then
fdqryList.Cancel;
CloseDetail;
fdqryRegister.Close;
end;
procedure TdtmdlRegister.CloseDetail;
begin
end;
procedure TdtmdlRegister.EditRegister;
begin
fdqryRegister.Close;
fdqryRegister.Params[0].AsString := fdqryList.FieldByName('id').AsString;
fdqryRegister.Open();
OpenDetail;
end;
procedure TdtmdlRegister.fdqryRegisterNewRecord(DataSet: TDataSet);
var
LFieldId: TField;
begin
inherited;
LFieldId := DataSet.FindField('id');
if LFieldId = nil then
raise Exception.Create('id not found');
LFieldId.AsString := TGUID.NewGuid.ToString;
end;
procedure TdtmdlRegister.FillInField(AProc: TProc<string, string>);
var
LField: TField;
begin
for LField in fdqryList.Fields do
begin
if (LField.Visible) and (LField.DataType in [ftMemo, ftString, ftFmtMemo,
ftFixedChar, ftWideString, ftFixedWideChar, ftWideMemo]) then
AProc(LField.FieldName, LField.DisplayLabel);
end;
end;
procedure TdtmdlRegister.FilterList(AField, AValue: string);
const
FILTER = 'where %s like %s';
var
LField: TField;
begin
LField := fdqryList.FindField(AField);
if LField = nil then
raise Exception.Create('Filter field not found');
fdqryList.Close;
fdqryList.MacroByName('where').AsRaw :=
Format(FILTER, [AField, QuotedStr('%' + AValue + '%')]);
fdqryList.Open();
end;
function TdtmdlRegister.GetIsListActive: Boolean;
begin
Result := fdqryList.Active;
end;
procedure TdtmdlRegister.IndexFilter(AField: string);
begin
fdqryList.IndexFieldNames := AField;
end;
procedure TdtmdlRegister.NewRegister;
begin
fdqryRegister.Close;
fdqryRegister.Params[0].AsString := '-1';
fdqryRegister.Open();
OpenDetail;
end;
procedure TdtmdlRegister.OpenDetail;
begin
end;
procedure TdtmdlRegister.SaveRegister;
begin
if fdqryRegister.State in dsEditModes then
fdqryRegister.Post;
CachedUpdates;
SaveDetail;
CloseDetail;
fdqryRegister.Close;
fdqryList.Close;
fdqryList.MacroByName('where').AsRaw := EmptyStr;
fdqryList.Open();
end;
procedure TdtmdlRegister.SaveDetail;
begin
end;
end.
|
unit Loading;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects,
ColorClass, FMX.Ani, FMX.MultiResBitmap;
type
TLoadingIconType = (Arc, Path, Image);
TLoading = class(TControl)
private
{ Private declarations }
procedure Animation1();
procedure Animation2();
procedure OnExitButton1(Sender: TObject);
protected
{ Protected declarations }
FBackground: TRectangle;
FArcIcon: TArc;
FPathIcon: TPath;
FImageIcon: TImage;
FAnimation: TFloatAnimation;
{ Block focus on background }
FButton1: TButton;
procedure Paint; override;
procedure Resize; override;
procedure Painting; override;
function GetFTag: NativeInt;
procedure SetFTag(const Value: NativeInt);
function GetFCornerRound: Single;
procedure SetFCornerRound(const Value: Single);
function GetFIconImageWrapMode: TImageWrapMode;
procedure SetFIconImageWrapMode(const Value: TImageWrapMode);
function GetFCursor: TCursor;
procedure SetFCursor(const Value: TCursor);
procedure SetMultiResBitmap(const Value: TFixedMultiResBitmap);
function GetFMultiResBitmap: TFixedMultiResBitmap;
function GetFBackgroundColor: TAlphaColor;
procedure SetFBackgroundColor(const Value: TAlphaColor);
function GetFIconType: TLoadingIconType;
procedure SetFIconType(const Value: TLoadingIconType);
function GetFIconArcColor: TAlphaColor;
function GetFIconPathColor: TAlphaColor;
function GetFIconPathData: TPathData;
procedure SetFIconArcColor(const Value: TAlphaColor);
procedure SetFIconPathColor(const Value: TAlphaColor);
procedure SetFIconPathData(const Value: TPathData);
function GetFIconSize: Single;
procedure SetFIconSize(const Value: Single);
function GetFAnimationDuration: Single;
procedure SetFAnimationDuration(const Value: Single);
function GetFAnimationAnimationType: TAnimationType;
function GetFAnimationAutoReverse: Boolean;
function GetFAnimationInterpolation: TInterpolationType;
function GetFAnimationPropertyName: String;
function GetFAnimationStartValue: Single;
function GetFAnimationStopValue: Single;
procedure SetFAnimationAnimationType(const Value: TAnimationType);
procedure SetFAnimationAutoReverse(const Value: Boolean);
procedure SetFAnimationInterpolation(const Value: TInterpolationType);
procedure SetFAnimationPropertyName(const Value: String);
procedure SetFAnimationStartValue(const Value: Single);
procedure SetFAnimationStopValue(const Value: Single);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open(Duration: Single = 0.2); virtual;
procedure Close(Duration: Single = 0.2); virtual;
published
{ Published declarations }
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
{ Additional properties }
property Cursor: TCursor read GetFCursor write SetFCursor;
property BackgroundColor: TAlphaColor read GetFBackgroundColor write SetFBackgroundColor;
property IconType: TLoadingIconType read GetFIconType write SetFIconType;
property IconArcColor: TAlphaColor read GetFIconArcColor write SetFIconArcColor;
property IconPathData: TPathData read GetFIconPathData write SetFIconPathData;
property IconPathColor: TAlphaColor read GetFIconPathColor write SetFIconPathColor;
property IconImage: TFixedMultiResBitmap read GetFMultiResBitmap write SetMultiResBitmap;
property IconImageWrapMode: TImageWrapMode read GetFIconImageWrapMode write SetFIconImageWrapMode;
property IconSize: Single read GetFIconSize write SetFIconSize;
property AnimationDuration: Single read GetFAnimationDuration write SetFAnimationDuration;
property AnimationAutoReverse: Boolean read GetFAnimationAutoReverse write SetFAnimationAutoReverse;
property AnimationAnimationType: TAnimationType read GetFAnimationAnimationType write SetFAnimationAnimationType;
property AnimationInterpolation: TInterpolationType read GetFAnimationInterpolation
write SetFAnimationInterpolation;
property AnimationPropertyName: String read GetFAnimationPropertyName write SetFAnimationPropertyName;
property AnimationStartValue: Single read GetFAnimationStartValue write SetFAnimationStartValue;
property AnimationStopValue: Single read GetFAnimationStopValue write SetFAnimationStopValue;
property CornerRound: Single read GetFCornerRound write SetFCornerRound;
property Tag: NativeInt read GetFTag write SetFTag;
// property HitTest: Boolean read GetFHitTest write SetFHitTest default True;
// property Color: TAlphaColor read GetFBackgroudColor write SetFBackgroudColor;
// property Elevation: Boolean read GetFElevation write SetFElevation;
// property ElevationDistance: Single read GetFElevationDistance write SetFElevationDistance;
// property ElevationDirection: Single read GetFElevationDirection write SetFElevationDirection;
// property ElevationOpacity: Single read GetFElevationOpacity write SetFElevationOpacity;
// property ElevationSoftness: Single read GetFElevationSoftness write SetFElevationSoftness;
// property ElevationColor: TAlphaColor read GetFElevationColor write SetFElevationColor;
// property CornerRound: Single read GetFCornerRound write SetFCornerRound;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
// property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick;
// property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick;
// property OnKeyDown: TKeyEvent read GetFOnKeyDown write SetFOnKeyDown;
// property OnKeyUp: TKeyEvent read GetFOnKeyUp write SetFOnKeyUp;
// property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown;
// property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp;
// property OnMouseWheel: TMouseWheelEvent read GetFOnMouseWheel write SetFOnMouseWheel;
// property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove;
// property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter;
// property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TLoading]);
end;
{ TLoading }
{ Block focus on background }
procedure TLoading.OnExitButton1(Sender: TObject);
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
FButton1.SetFocus;
end);
end).Start;
end;
procedure TLoading.Open(Duration: Single = 0.2);
begin
Self.Visible := True;
Self.Opacity := 0;
FAnimation.Start;
Self.AnimateFloat('Opacity', 1, Duration, TAnimationType.InOut, TInterpolationType.Circular);
{ Block focus on background }
FButton1.OnExit := OnExitButton1;
FButton1.SetFocus;
end;
procedure TLoading.Animation1;
begin
FAnimation.AnimationType := TAnimationType.InOut;
FAnimation.AutoReverse := False;
FAnimation.Duration := 1;
FAnimation.Interpolation := TInterpolationType.Sinusoidal;
FAnimation.Loop := True;
FAnimation.PropertyName := 'RotationAngle';
FAnimation.StartValue := 0;
FAnimation.StopValue := 360;
end;
procedure TLoading.Animation2;
begin
FAnimation.AnimationType := TAnimationType.InOut;
FAnimation.AutoReverse := False;
FAnimation.Duration := 1.5;
FAnimation.Interpolation := TInterpolationType.Elastic;
FAnimation.Loop := True;
FAnimation.PropertyName := 'RotationAngle';
FAnimation.StartValue := 0;
FAnimation.StopValue := 360;
end;
procedure TLoading.Close(Duration: Single = 0.2);
begin
{ Block focus on background }
FButton1.OnExit := nil;
Self.AnimateFloatWait('Opacity', 0, Duration, TAnimationType.InOut, TInterpolationType.Circular);
Self.Visible := False;
Self.Opacity := 1;
FAnimation.Stop;
end;
constructor TLoading.Create(AOwner: TComponent);
begin
inherited;
Self.Align := TAlignLayout.Client;
FButton1 := TButton.Create(Self);
Self.AddObject(FButton1);
FButton1.SetSubComponent(True);
FButton1.Stored := False;
FButton1.Opacity := 0;
FBackground := TRectangle.Create(Self);
Self.AddObject(FBackground);
FBackground.SetSubComponent(True);
FBackground.Stored := False;
FBackground.Align := TAlignLayout.Contents;
FBackground.Stroke.Kind := TBrushKind.None;
FBackground.Fill.Color := TAlphaColor($FFFFFFFF);
FBackground.HitTest := True;
FBackground.Cursor := crHourGlass;
FArcIcon := TArc.Create(Self);
FBackground.AddObject(FArcIcon);
FArcIcon.SetSubComponent(True);
FArcIcon.Stored := False;
FArcIcon.Align := TAlignLayout.Center;
FArcIcon.Stroke.Color := TAlphaColor(SOLID_PRIMARY_COLOR);
FArcIcon.Stroke.Thickness := 4;
FArcIcon.EndAngle := 120;
FArcIcon.Width := 50;
FArcIcon.Height := 50;
FArcIcon.HitTest := False;
FPathIcon := TPath.Create(Self);
FBackground.AddObject(FPathIcon);
FPathIcon.SetSubComponent(True);
FPathIcon.Stored := False;
FPathIcon.Align := TAlignLayout.Center;
FPathIcon.WrapMode := TPathWrapMode.Fit;
FPathIcon.Fill.Color := TAlphaColor(SOLID_PRIMARY_COLOR);
FPathIcon.Stroke.Kind := TBrushKind.None;
FPathIcon.Width := 25;
FPathIcon.Height := 25;
FPathIcon.HitTest := False;
FPathIcon.Data.Data :=
'M6,2H18V8H18V8L14,12L18,16V16H18V22H6V16H6V16L10,12L6,8V8H6V2M16,16.5L12,12.5L8,16.5V20H16V16.5M12,11.5L16,7.5V4H8V7.5L12,11.5M10,6H14V6.75L12,8.75L10,6.75V6Z';
FImageIcon := TImage.Create(Self);
FBackground.AddObject(FImageIcon);
FImageIcon.SetSubComponent(True);
FImageIcon.Stored := False;
FImageIcon.Align := TAlignLayout.Center;
FImageIcon.WrapMode := TImageWrapMode.Original;
FImageIcon.Width := 64;
FImageIcon.Height := 64;
FImageIcon.HitTest := False;
FAnimation := TFloatAnimation.Create(Self);
FAnimation.Parent := FArcIcon;
FAnimation.AnimationType := TAnimationType.InOut;
FAnimation.Duration := 1;
FAnimation.Interpolation := TInterpolationType.Sinusoidal;
FAnimation.Loop := True;
FAnimation.PropertyName := 'RotationAngle';
FAnimation.StartValue := 0;
FAnimation.StopValue := 360;
SetFIconType(TLoadingIconType.Arc);
end;
destructor TLoading.Destroy;
begin
if Assigned(FImageIcon) then
FImageIcon.Free;
if Assigned(FPathIcon) then
FPathIcon.Free;
if Assigned(FArcIcon) then
FArcIcon.Free;
if Assigned(FBackground) then
FBackground.Free;
inherited;
end;
function TLoading.GetFAnimationAnimationType: TAnimationType;
begin
Result := FAnimation.AnimationType;
end;
function TLoading.GetFAnimationAutoReverse: Boolean;
begin
Result := FAnimation.AutoReverse;
end;
function TLoading.GetFAnimationDuration: Single;
begin
Result := FAnimation.Duration;
end;
function TLoading.GetFAnimationInterpolation: TInterpolationType;
begin
Result := FAnimation.Interpolation;
end;
function TLoading.GetFAnimationPropertyName: String;
begin
Result := FAnimation.PropertyName;
end;
function TLoading.GetFAnimationStartValue: Single;
begin
Result := FAnimation.StartValue;
end;
function TLoading.GetFAnimationStopValue: Single;
begin
Result := FAnimation.StopValue;
end;
function TLoading.GetFBackgroundColor: TAlphaColor;
begin
Result := FBackground.Fill.Color;
end;
function TLoading.GetFCornerRound: Single;
begin
Result := FBackground.XRadius;
end;
function TLoading.GetFCursor: TCursor;
begin
Result := FBackground.Cursor;
end;
function TLoading.GetFIconArcColor: TAlphaColor;
begin
Result := FArcIcon.Stroke.Color
end;
function TLoading.GetFIconImageWrapMode: TImageWrapMode;
begin
Result := FImageIcon.WrapMode;
end;
function TLoading.GetFIconPathColor: TAlphaColor;
begin
Result := FPathIcon.Fill.Color;
end;
function TLoading.GetFIconPathData: TPathData;
begin
Result := FPathIcon.Data;
end;
function TLoading.GetFIconSize: Single;
begin
Result := FArcIcon.Width;
if FPathIcon.Visible then
Result := FPathIcon.Width
else if FImageIcon.Visible then
Result := FImageIcon.Width;
end;
function TLoading.GetFIconType: TLoadingIconType;
begin
Result := TLoadingIconType.Arc;
if FPathIcon.Visible then
Result := TLoadingIconType.Path
else if FImageIcon.Visible then
Result := TLoadingIconType.Image;
end;
function TLoading.GetFMultiResBitmap: TFixedMultiResBitmap;
begin
Result := FImageIcon.MultiResBitmap;
end;
function TLoading.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
procedure TLoading.Paint;
begin
inherited;
end;
procedure TLoading.Painting;
begin
inherited;
end;
procedure TLoading.Resize;
begin
inherited;
end;
procedure TLoading.SetFAnimationAnimationType(const Value: TAnimationType);
begin
FAnimation.AnimationType := Value;
end;
procedure TLoading.SetFAnimationAutoReverse(const Value: Boolean);
begin
FAnimation.AutoReverse := Value;
end;
procedure TLoading.SetFAnimationDuration(const Value: Single);
begin
FAnimation.Duration := Value;
end;
procedure TLoading.SetFAnimationInterpolation(const Value: TInterpolationType);
begin
FAnimation.Interpolation := Value;
end;
procedure TLoading.SetFAnimationPropertyName(const Value: String);
begin
FAnimation.PropertyName := Value;
end;
procedure TLoading.SetFAnimationStartValue(const Value: Single);
begin
FAnimation.StartValue := Value;
end;
procedure TLoading.SetFAnimationStopValue(const Value: Single);
begin
FAnimation.StopValue := Value;
end;
procedure TLoading.SetFBackgroundColor(const Value: TAlphaColor);
begin
FBackground.Fill.Color := Value;
end;
procedure TLoading.SetFCornerRound(const Value: Single);
begin
FBackground.XRadius := Value;
FBackground.YRadius := Value;
end;
procedure TLoading.SetFCursor(const Value: TCursor);
begin
FBackground.Cursor := Value;
end;
procedure TLoading.SetFIconArcColor(const Value: TAlphaColor);
begin
FArcIcon.Stroke.Color := Value;
end;
procedure TLoading.SetFIconImageWrapMode(const Value: TImageWrapMode);
begin
FImageIcon.WrapMode := Value;
end;
procedure TLoading.SetFIconPathColor(const Value: TAlphaColor);
begin
FPathIcon.Fill.Color := Value;
end;
procedure TLoading.SetFIconPathData(const Value: TPathData);
begin
FPathIcon.Data := Value;
end;
procedure TLoading.SetFIconSize(const Value: Single);
begin
if GetFIconType = TLoadingIconType.Arc then
begin
FArcIcon.Width := Value;
FArcIcon.Height := Value;
end
else if GetFIconType = TLoadingIconType.Path then
begin
FPathIcon.Width := Value;
FPathIcon.Height := Value;
end
else
begin
FImageIcon.Width := Value;
FImageIcon.Height := Value;
end;
end;
procedure TLoading.SetFIconType(const Value: TLoadingIconType);
begin
FArcIcon.Visible := False;
FPathIcon.Visible := False;
FImageIcon.Visible := False;
if Value = TLoadingIconType.Arc then
begin
FArcIcon.Visible := True;
FAnimation.Parent := FArcIcon;
Animation1();
end
else if Value = TLoadingIconType.Path then
begin
FPathIcon.Visible := True;
FAnimation.Parent := FPathIcon;
Animation2();
end
else
begin
FImageIcon.Visible := True;
FAnimation.Parent := FImageIcon;
Animation2();
end;
end;
procedure TLoading.SetFTag(const Value: NativeInt);
begin
FBackground.Tag := Value;
TControl(Self).Tag := Value;
end;
procedure TLoading.SetMultiResBitmap(const Value: TFixedMultiResBitmap);
begin
FImageIcon.MultiResBitmap := Value;
end;
end.
|
unit AsciiCheck;
interface
uses
SysUtils, Character;
type
TStringHelper = class
public
function IsAscii(const PathToValidate: String): Boolean;
end;
var
StringHelper: TStringHelper;
implementation
{$R-}
function TStringHelper.IsAscii(const PathToValidate: String): Boolean;
var
CurrentCharacter: Char;
begin
result := true;
for CurrentCharacter in PathToValidate do
if Ord(CurrentCharacter) > Byte.MaxValue then
exit(false);
end;
initialization
StringHelper := TStringHelper.Create;
finalization
StringHelper.Free;
end.
|
(* VectorClass: MM, 2020-06-05 *)
(* ------ *)
(* Simple Class to store Vectors in an IntArray *)
(* ========================================================================= *)
UNIT VectorClass;
INTERFACE
TYPE
IntArray = ARRAY [0..0] OF INTEGER;
Vector = ^VectorObj;
VectorObj = OBJECT
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
FUNCTION IsFull: BOOLEAN;
PROCEDURE Add(value: INTEGER); VIRTUAL;
PROCEDURE InsertElementAt(pos, value: INTEGER); VIRTUAL;
PROCEDURE WriteVector;
PROCEDURE GetElementAt(pos: INTEGER; VAR ok: BOOLEAN; VAR value: INTEGER);
FUNCTION GetSize: INTEGER;
FUNCTION GetCapacity: INTEGER;
PROCEDURE Clear;
PROTECTED
data: ^IntArray;
capacity: INTEGER;
size: INTEGER;
PROCEDURE DoubleSize;
END; (* VectorObj *)
IMPLEMENTATION
CONSTRUCTOR VectorObj.Init;
BEGIN (* VectorObj.Init *)
capacity := 10;
size := 0;
GetMem(data, capacity * SizeOf(INTEGER));
END; (* VectorObj.Init *)
DESTRUCTOR VectorObj.Done;
BEGIN (* VectorObj.Done *)
FreeMem(data, capacity * SizeOf(INTEGER));
END; (* VectorObj.Done *)
FUNCTION VectorObj.IsFull: BOOLEAN;
BEGIN (* VectorObj.IsFull *)
IsFull := size >= capacity;
END; (* VectorObj.IsFull *)
PROCEDURE VectorObj.DoubleSize;
VAR newdata: ^IntArray;
i: INTEGER;
BEGIN (* VectorObj.DoubleSize *)
GetMem(newdata, capacity * 2 * SizeOf(INTEGER));
FOR i := 0 TO capacity - 1 DO BEGIN
{$R-}newdata^[i] := data^[i];{$R+}
END; (* FOR *)
FreeMem(data, capacity * SizeOf(INTEGER));
data := newdata;
capacity := capacity * 2;
END; (* VectorObj.DoubleSize *)
PROCEDURE VectorObj.Add(value: INTEGER);
BEGIN (* VectorObj.Add *)
IF (IsFull) THEN BEGIN
DoubleSize;
END; (* IF *)
{$R-}data^[size] := value; {$R+}
Inc(size);
END; (* VectorObj.Add *)
PROCEDURE VectorObj.InsertElementAt(pos, value: INTEGER);
VAR i: INTEGER;
BEGIN (* VectorObj.InsertElementAt *)
IF (IsFull) THEN
DoubleSize;
IF (pos <= 0) THEN
pos := 0;
IF (pos > size) THEN BEGIN
Add(value);
END ELSE BEGIN
FOR i := size DOWNTO pos DO BEGIN
{$R-}data^[i] := data^[i-1];{$R+}
END; (* FOR *)
{$R-}data^[pos] := value;{$R+}
Inc(size);
END; (* IF *)
END; (* VectorObj.InsertElementAt *)
PROCEDURE VectorObj.WriteVector;
VAR i: INTEGER;
BEGIN (* VectorObj.WriteVector *)
WriteLn('Vector ------------------------------');
WriteLn('capacity: ', capacity);
WriteLn('size: ', size);
FOR i := 0 TO size - 1 DO BEGIN
{$R-}WriteLn('data[', i, '] = ', data^[i]);{$R+}
END; (* FOR *)
WriteLn('--------------------------------------');
END; (* VectorObj.WriteVector *)
PROCEDURE VectorObj.GetElementAt(pos: INTEGER; VAR ok: BOOLEAN; VAR value: INTEGER);
BEGIN (* VectorObj.GetElementAt *)
ok := (0 <= pos) AND (pos < size);
IF (ok) THEN
{$R-}value := data^[pos];{$R+}
END; (* VectorObj.GetElementAt *)
FUNCTION VectorObj.GetSize: INTEGER;
BEGIN (* VectorObj.GetSize *)
GetSize := SELF.size;
END; (* VectorObj.GetSize *)
FUNCTION VectorObj.GetCapacity: INTEGER;
BEGIN (* VectorObj.GetCapacity *)
GetCapacity := SELF.capacity;
END; (* VectorObj.GetCapacity *)
PROCEDURE VectorObj.Clear;
VAR i: INTEGER;
BEGIN (* VectorObj.Clear *)
FOR i := 0 TO size - 1 DO BEGIN
{$R-}data^[i] := 0;{$R+}
END; (* FOR *)
size := 0;
END; (* VectorObj.Clear *)
END. (* Vector *) |
(*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit KeyGenTaskImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskOptionsIntf,
TaskIntf,
SysUtils;
type
(*!--------------------------------------
* Task that generate random key
*---------------------------------------------
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TKeyGenTask = class(TInterfacedObject, ITask)
private
function readRandomBytes(const numberOfBytes : integer) : TBytes;
function encodeB64(aob: TBytes): string;
public
function run(
const opt : ITaskOptions;
const longOpt : shortstring
) : ITask;
end;
implementation
uses
Classes,
Base64,
BaseUnix;
function TKeyGenTask.readRandomBytes(const numberOfBytes : integer) : TBytes;
var fs : TFileStream;
bytes : TBytes;
begin
fs := TFileStream.create('/dev/urandom', fmOpenRead);
try
setLength(bytes, numberOfBytes);
fs.readBuffer(bytes[0], numberOfBytes);
result := bytes;
finally
fs.free();
end;
end;
(*!------------------------------------------------
* encode array of bytes to Base64 string
*-------------------------------------------------
* @param aob array of bytes
* @return Base64 encoded string
*-------------------------------------------------
* @author: howardpc
* @credit: https://forum.lazarus.freepascal.org/index.php?topic=23646.0
*-------------------------------------------------*)
function TKeyGenTask.encodeB64(aob: TBytes): string;
var
i: integer;
tmp: string;
begin
setLength(tmp, length(aob));
for i := low(aob) to high(aob) do
begin
tmp[i+1] := char(aob[i]);
end;
result := encodeStringBase64(tmp);
end;
function TKeyGenTask.run(
const opt : ITaskOptions;
const longOpt : shortstring
) : ITask;
var numberOfBytes : integer;
begin
numberOfBytes := strToInt(opt.getOptionValueDef(longOpt, '64'));
write(encodeB64(readRandomBytes(numberOfBytes)));
result := self;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBByteBuffer;
interface
uses System.SysUtils;
type
TDBByteBuffer = class
strict private
FBuffer: TArray<Byte>;
FOffset: Integer;
FUsed: Integer;
procedure CheckSpace(SpaceNeeded: Integer);
public
constructor Create; overload;
constructor Create(Buffer: TArray<Byte>); overload;
constructor Create(Capacity: Integer); overload;
destructor Destroy; override;
function GetBytes: TArray<Byte>;
procedure SetString(Value: string);
procedure SetBytes(Value: TArray<Byte>);
procedure Append(Value: string); overload;
procedure Append(Value: TArray<Byte>); overload;
procedure Append(Value: PChar; Count: Integer); overload;
end;
implementation
{ TDBByteBuffer }
constructor TDBByteBuffer.Create(Buffer: TArray<Byte>);
begin
inherited Create;
FBuffer := Buffer;
end;
procedure TDBByteBuffer.CheckSpace(SpaceNeeded: Integer);
begin
if Length(FBuffer) < FUsed + SpaceNeeded then
begin
raise ERangeError.Create('CheckSpace');
end;
end;
procedure TDBByteBuffer.Append(Value: string);
begin
CheckSpace(Value.Length);
Move(PByte(Value)^, PByte(FBuffer)^, Value.Length * SizeOf(Char));
end;
procedure TDBByteBuffer.Append(Value: TArray<Byte>);
begin
CheckSpace(Length(Value));
Move(PChar(Value)^, PChar(FBuffer)^, Length(Value));
end;
procedure TDBByteBuffer.Append(Value: PChar; Count: Integer);
begin
CheckSpace(Count);
Move(Value^, PChar(FBuffer)^, Count);
end;
constructor TDBByteBuffer.Create(Capacity: Integer);
begin
inherited Create;
SetLength(FBuffer, Capacity);
end;
constructor TDBByteBuffer.Create;
begin
inherited Create;
end;
destructor TDBByteBuffer.Destroy;
begin
FBuffer := nil;
inherited;
end;
function TDBByteBuffer.GetBytes: TArray<Byte>;
begin
Result := FBuffer;
end;
procedure TDBByteBuffer.SetBytes(Value: TArray<Byte>);
begin
SetLength(FBuffer, Length(Value));
FOffset := 0;
Append(Value);
end;
procedure TDBByteBuffer.SetString(Value: string);
begin
SetLength(FBuffer, Value.Length * SizeOf(Char));
FOffset := 0;
Append(Value);
end;
end.
|
program PARSTRAD;
(* Parse afs:TRADE holdings report into lotus Readable file *)
{$M 20000, 0, 655360}
uses DOS, Calendar;
const
extension = '.prn' (* output file extenstion *);
VAR
Fields : ARRAY[0..50] OF INTEGER;
(* =================================================== *)
FUNCTION StripCommas(SuspectStr: STRING) : String;
VAR
len, i : INTEGER;
CleanedStr : String;
NewChr : String;
BEGIN
len := length(SuspectStr);
CleanedStr := '';
i := 1;
REPEAT
NewChr := copy(SuspectStr,i,1);
IF NewChr <> ',' THEN
CleanedStr := CleanedStr + NewChr;
INC(i)
UNTIL i > len;
StripCommas := CleanedStr;
END (* StripCommas *);
(* =================================================== *)
FUNCTION Trim(SuspectStr: STRING) : String;
VAR
len, i,j : INTEGER;
NewChr : String;
BEGIN
len := length(SuspectStr);
i := 1; j := len;
REPEAT
NewChr := copy(SuspectStr,i,1);
IF NewChr = ' ' THEN
INC(i)
UNTIL (NewChr <> ' ') OR (i > len);
REPEAT
NewChr := copy(SuspectStr,j,1);
IF NewChr = ' ' THEN
DEC(j)
UNTIL (NewChr <> ' ') OR (j = 0);
Trim := copy(SuspectStr,i,j);
END (* StripCommas *);
(* =================================================== *)
PROCEDURE ParseFile;
CONST
RecSize = 1;
VAR
infile, outfile1 : TEXT;
Name, Name1, TextLine : String;
FUNCTION TestLine(line : STRING) : BOOLEAN;
(*
Test of text qualifies as the first line of a holdings
description.
*)
VAR
amt : LONGINT;
ErrCode : INTEGER;
temp : string;
BEGIN
temp := StripCommas(copy(line,1,7));
Val(StripCommas(Copy(line,1,7)),amt,ErrCode);
TestLine := (ErrCode = 0); (* TRUE if first 7 chars is a number *)
END (* TestLine *);
(* =================================================== *)
PROCEDURE Parse(VAR infile : text; VAR line : String);
TYPE
TokenType = (NumTok, StrTok, DatTok);
VAR
TokenIndex, i : INTEGER;
line2 : String;
TokenArray : ARRAY[0..50] OF STRING;
(* =================================================== *)
PROCEDURE Token(TokType : TokenType; Start,Stop : INTEGER);
VAR
Tok : STRING;
a,b,temp : LONGINT;
BEGIN
Tok := copy(line,Start,Stop-Start+1);
INC(TokenIndex);
CASE TokType OF
NumTok : Tok := StripCommas(Tok) + ',';
StrTok : Tok := '"' + Trim(Tok) + '"' + ',';
DatTok : BEGIN
a := ParseDateStr(Tok);
b := today;
IF ParseDateStr(Tok) < Today THEN
Tok := '"",'
ELSE BEGIN
temp := ParseDateStr(Tok);
temp := date(12,31,1899);
str(ParseDateStr(Tok) - date(12,30,1899),Tok);
Tok := Tok + ',';
END;
END;
END (* CASE *);
TokenArray[TokenIndex] := Tok;
END (* MakeToken *);
(* =================================================== *)
BEGIN
TokenIndex := 0;
(* start building Token Array *);
Token(NumTok,1,7); { par }
Token(StrTok,10,38); { description }
Token(NumTok,40,46); { coupon }
Token(DatTok,49,56); { mat date }
Token(StrTok,59,62); { moody }
Token(StrTok,64,67); { s&p }
Token(DatTok,70,77); { next call}
Token(DatTok,80,87); { par call}
Token(DatTok,90,97); { put feat}
Token(NumTok,102,108); { avg cost}
Token(NumTok,110,116); { cost yield}
Token(NumTok,119,124); { curr yield}
Token(NumTok,127,132); { %TTL }
(* get next line *)
Readln(infile,line);
Token(StrTok,12,20); { cusip }
Token(DatTok,23,30); { dtd date }
Token(StrTok,31,36); { state }
Token(StrTok,37,38); { sector1 }
Token(StrTok,40,41); { sector2 }
Token(NumTok,71,77); { next call px}
Token(NumTok,81,87); { par call px}
Token(NumTok,91,97); { put feat px}
Token(NumTok,102,108); { mkt px }
Token(NumTok,110,116); { mkt yield}
Token(NumTok,119,124); { duration }
Token(StrTok,125,132); { yld basis }
(* build string with desired fields *)
line2 := '';
i := 0;
IF Fields[0] = 0 THEN (* use all fields *)
FOR i := 0 TO TokenIndex DO
line2 := line2 + TokenArray[i]
ELSE
WHILE Fields[i] > 0 DO
BEGIN
line2 := line2 + TokenArray[Fields[i]];
INC(i)
END;
(* terminate by stripping final comma *)
delete(line2,length(line2),1);
line := line2;
END (* Parse *);
(* =================================================== *)
PROCEDURE ParseName(VAR FromName, To1 : String);
VAR
err, i,
ErrCount : INTEGER;
path : PathStr;
dir : DirStr;
name : NameStr;
ext : ExtStr;
BEGIN
IF (ParamCount < 1) or (ParamStr(1) = '?') THEN
BEGIN
WriteLn('usage: PARSTRAD FileName [FieldNum [FieldNum...]]');
WriteLn('Where FileName is a text file containing an afs:TRADE');
WriteLn('portfolio holdings report and FieldNums are optional');
WriteLn('ordinal positions of report fields you wish to include.');
WriteLn('If no field nubmers are indicated all will be included.');
HALT;
END;
path := ParamStr(1);
FSplit(path,dir,name,ext);
FromName := path;
To1 := name + extension;
(* Get Field Numbers To include *)
ErrCount := 0;
i := 0;
Fields[i] := 0;
IF ParamCount > 1 THEN
BEGIN
FOR i := 2 TO ParamCount DO
BEGIN
val(ParamStr(i),Fields[i-2-errcount],err);
IF err > 0 THEN
INC(ErrCount)
END;
(* 0 indicates end of field list *)
Fields[i-1-errcount] := 0;
END;
END (* ParseName *);
(* =================================================== *)
BEGIN
ParseName(Name, Name1);
Assign(infile, Name);
Reset(infile);
Assign(outfile1, Name1);
Rewrite(outfile1);
WriteLn('Parsing file ' ,Name);
REPEAT
ReadLn(infile,TextLine);
IF TestLine(TextLine) THEN
BEGIN
Parse(infile, TextLine);
WriteLn(outfile1,TextLine);
END;
UNTIL EOF(infile);
Close(infile);
Close(outfile1);
WriteLn('Wrote ',Name1);
END (* ParseFile *);
(* =================================================== *)
BEGIN
ParseFile;
END (*ParsTRAD*). |
unit NtUtils.Lsa;
interface
uses
Winapi.WinNt, Winapi.ntlsa, NtUtils.Exceptions, NtUtils.Security.Sid,
DelphiUtils.AutoObject;
type
TLsaHandle = Winapi.ntlsa.TLsaHandle;
ILsaHandle = DelphiUtils.AutoObject.IHandle;
TLsaAutoHandle = class(TCustomAutoHandle, ILsaHandle)
// Close LSA auto-handle
destructor Destroy; override;
end;
TLsaAutoMemory = class(TCustomAutoMemory, IMemory)
// Free LSA memory
destructor Destroy; override;
end;
TPrivilegeDefinition = record
Name: String;
LocalValue: TLuid;
end;
TLogonRightRec = record
Value: Cardinal;
IsAllowedType: Boolean;
Name, Description: String;
end;
{ --------------------------------- Policy ---------------------------------- }
// Open LSA for desired access
function LsaxOpenPolicy(out hxPolicy: ILsaHandle;
DesiredAccess: TAccessMask; SystemName: String = ''): TNtxStatus;
// Make sure the policy handle is provided
function LsaxpEnsureConnected(var hxPolicy: ILsaHandle;
DesiredAccess: TAccessMask): TNtxStatus;
// Query policy information
function LsaxQueryPolicy(hPolicy: TLsaHandle; InfoClass:
TPolicyInformationClass; out xMemory: IMemory): TNtxStatus;
// Set policy information
function LsaxSetPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass;
Data: Pointer): TNtxStatus;
{ --------------------------------- Accounts -------------------------------- }
// Open an account from LSA database
function LsaxOpenAccount(out hxAccount: ILsaHandle; AccountSid: PSid;
DesiredAccess: TAccessMask; hxPolicy: ILsaHandle = nil): TNtxStatus;
// Add an account to LSA database
function LsaxCreateAccount(out hxAccount: ILsaHandle; AccountSid: PSid;
DesiredAccess: TAccessMask; hxPolicy: ILsaHandle = nil): TNtxStatus;
// Delete account from LSA database
function LsaxDeleteAccount(hAccount: TLsaHandle): TNtxStatus;
// Enumerate account in the LSA database
function LsaxEnumerateAccounts(hPolicy: TLsaHandle; out Accounts: TArray<ISid>):
TNtxStatus;
// Enumerate privileges assigned to an account
function LsaxEnumeratePrivilegesAccount(hAccount: TLsaHandle;
out Privileges: TArray<TPrivilege>): TNtxStatus;
function LsaxEnumeratePrivilegesAccountBySid(AccountSid: PSid;
out Privileges: TArray<TPrivilege>): TNtxStatus;
// Assign privileges to an account
function LsaxAddPrivilegesAccount(hAccount: TLsaHandle;
Privileges: TArray<TPrivilege>): TNtxStatus;
// Revoke privileges to an account
function LsaxRemovePrivilegesAccount(hAccount: TLsaHandle; RemoveAll: Boolean;
Privileges: TArray<TPrivilege>): TNtxStatus;
// Assign & revoke privileges to account in one operation
function LsaxManagePrivilegesAccount(AccountSid: PSid; RemoveAll: Boolean;
Add, Remove: TArray<TPrivilege>): TNtxStatus;
// Query logon rights of an account
function LsaxQueryRightsAccount(hAccount: TLsaHandle;
out SystemAccess: Cardinal): TNtxStatus;
function LsaxQueryRightsAccountBySid(AccountSid: PSid;
out SystemAccess: Cardinal): TNtxStatus;
// Set logon rights of an account
function LsaxSetRightsAccount(hAccount: TLsaHandle; SystemAccess: Cardinal):
TNtxStatus;
function LsaxSetRightsAccountBySid(AccountSid: PSid; SystemAccess: Cardinal):
TNtxStatus;
{ -------------------------------- Privileges ------------------------------- }
// Enumerate all privileges on the system
function LsaxEnumeratePrivileges(hPolicy: TLsaHandle;
out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus;
function LsaxEnumeratePrivilegesLocal(
out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus;
// Convert a numerical privilege value to internal name
function LsaxQueryNamePrivilege(hPolicy: TLsaHandle; Luid: TLuid;
out Name: String): TNtxStatus;
// Convert an privilege's internal name to a description
function LsaxQueryDescriptionPrivilege(hPolicy: TLsaHandle; const Name: String;
out DisplayName: String): TNtxStatus;
// Lookup multiple privilege names and descriptions at once
function LsaxLookupMultiplePrivileges(Luids: TArray<TLuid>;
out Names, Descriptions: TArray<String>): TNtxStatus;
// Get the minimal integrity level required to use a specific privilege
function LsaxQueryIntegrityPrivilege(Luid: TLuid): Cardinal;
{ ------------------------------- Logon Rights ------------------------------ }
// Enumerate known logon rights
function LsaxEnumerateLogonRights: TArray<TLogonRightRec>;
implementation
uses
Ntapi.ntdef, Ntapi.ntstatus, Winapi.NtSecApi, Ntapi.ntseapi, System.SysUtils,
NtUtils.Tokens.Misc, NtUtils.Access.Expected;
{ Common & Policy }
destructor TLsaAutoHandle.Destroy;
begin
if FAutoRelease then
LsaClose(FHandle);
inherited;
end;
destructor TLsaAutoMemory.Destroy;
begin
if FAutoRelease then
LsaFreeMemory(FAddress);
inherited;
end;
function LsaxOpenPolicy(out hxPolicy: ILsaHandle;
DesiredAccess: TAccessMask; SystemName: String = ''): TNtxStatus;
var
ObjAttr: TObjectAttributes;
SystemNameStr: TLsaUnicodeString;
pSystemNameStr: PLsaUnicodeString;
hPolicy: TLsaHandle;
begin
InitializeObjectAttributes(ObjAttr);
if SystemName <> '' then
begin
SystemNameStr.FromString(SystemName);
pSystemNameStr := @SystemNameStr;
end
else
pSystemNameStr := nil;
Result.Location := 'LsaOpenPolicy';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @PolicyAccessType;
Result.Status := LsaOpenPolicy(pSystemNameStr, ObjAttr, DesiredAccess,
hPolicy);
if Result.IsSuccess then
hxPolicy := TLsaAutoHandle.Capture(hPolicy);
end;
function LsaxpEnsureConnected(var hxPolicy: ILsaHandle;
DesiredAccess: TAccessMask): TNtxStatus;
begin
if not Assigned(hxPolicy) then
Result := LsaxOpenPolicy(hxPolicy, DesiredAccess)
else
Result.Status := STATUS_SUCCESS
end;
function LsaxQueryPolicy(hPolicy: TLsaHandle; InfoClass:
TPolicyInformationClass; out xMemory: IMemory): TNtxStatus;
var
Buffer: Pointer;
begin
Result.Location := 'LsaQueryInformationPolicy';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TPolicyInformationClass);
RtlxComputePolicyQueryAccess(Result.LastCall, InfoClass);
Result.Status := LsaQueryInformationPolicy(hPolicy, InfoClass, Buffer);
if Result.IsSuccess then
xMemory := TLsaAutoMemory.Capture(Buffer, 0);
end;
function LsaxSetPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass;
Data: Pointer): TNtxStatus;
begin
Result.Location := 'LsaSetInformationPolicy';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TPolicyInformationClass);
RtlxComputePolicySetAccess(Result.LastCall, InfoClass);
Result.Status := LsaSetInformationPolicy(hPolicy, InfoClass, Data);
end;
{ Accounts }
function LsaxOpenAccount(out hxAccount: ILsaHandle; AccountSid: PSid;
DesiredAccess: TAccessMask; hxPolicy: ILsaHandle = nil): TNtxStatus;
var
hAccount: TLsaHandle;
begin
Result := LsaxpEnsureConnected(hxPolicy, POLICY_VIEW_LOCAL_INFORMATION);
if not Result.IsSuccess then
Exit;
Result.Location := 'LsaOpenAccount';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @AccountAccessType;
Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType);
Result.Status := LsaOpenAccount(hxPolicy.Handle, AccountSid, DesiredAccess,
hAccount);
if Result.IsSuccess then
hxAccount := TLsaAutoHandle.Capture(hAccount);
end;
function LsaxCreateAccount(out hxAccount: ILsaHandle; AccountSid: PSid;
DesiredAccess: TAccessMask; hxPolicy: ILsaHandle = nil): TNtxStatus;
var
hAccount: TLsaHandle;
begin
Result := LsaxpEnsureConnected(hxPolicy, POLICY_CREATE_ACCOUNT);
if not Result.IsSuccess then
Exit;
Result.Location := 'LsaCreateAccount';
Result.LastCall.Expects(POLICY_CREATE_ACCOUNT, @PolicyAccessType);
Result.Status := LsaCreateAccount(hxPolicy.Handle, AccountSid, DesiredAccess,
hAccount);
if Result.IsSuccess then
hxAccount := TLsaAutoHandle.Capture(hAccount);
end;
function LsaxDeleteAccount(hAccount: TLsaHandle): TNtxStatus;
begin
Result.Location := 'LsaDelete';
Result.LastCall.Expects(_DELETE, @AccountAccessType);
Result.Status := LsaDelete(hAccount);
end;
function LsaxEnumerateAccounts(hPolicy: TLsaHandle; out Accounts: TArray<ISid>):
TNtxStatus;
var
EnumContext: TLsaEnumerationHandle;
Buffer: PSidArray;
Count, i: Integer;
begin
EnumContext := 0;
Result.Location := 'LsaEnumerateAccounts';
Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType);
Result.Status := LsaEnumerateAccounts(hPolicy, EnumContext, Buffer,
MAX_PREFERRED_LENGTH, Count);
if not Result.IsSuccess then
Exit;
SetLength(Accounts, Count);
for i := 0 to High(Accounts) do
Accounts[i] := TSid.CreateCopy(Buffer{$R-}[i]{$R+});
LsaFreeMemory(Buffer);
end;
function LsaxEnumeratePrivilegesAccount(hAccount: TLsaHandle;
out Privileges: TArray<TPrivilege>): TNtxStatus;
var
PrivilegeSet: PPrivilegeSet;
i: Integer;
begin
Result.Location := 'LsaEnumeratePrivilegesOfAccount';
Result.LastCall.Expects(ACCOUNT_VIEW, @AccountAccessType);
Result.Status := LsaEnumeratePrivilegesOfAccount(hAccount, PrivilegeSet);
if not Result.IsSuccess then
Exit;
SetLength(Privileges, PrivilegeSet.PrivilegeCount);
for i := 0 to High(Privileges) do
Privileges[i] := PrivilegeSet.Privilege{$R-}[i]{$R+};
LsaFreeMemory(PrivilegeSet);
end;
function LsaxEnumeratePrivilegesAccountBySid(AccountSid: PSid;
out Privileges: TArray<TPrivilege>): TNtxStatus;
var
hxAccount: ILsaHandle;
begin
Result := LsaxOpenAccount(hxAccount, AccountSid, ACCOUNT_VIEW);
if Result.IsSuccess then
Result := LsaxEnumeratePrivilegesAccount(hxAccount.Handle, Privileges);
end;
function LsaxAddPrivilegesAccount(hAccount: TLsaHandle;
Privileges: TArray<TPrivilege>): TNtxStatus;
var
PrivSet: PPrivilegeSet;
begin
PrivSet := NtxpAllocPrivilegeSet(Privileges);
Result.Location := 'LsaAddPrivilegesToAccount';
Result.LastCall.Expects(ACCOUNT_ADJUST_PRIVILEGES, @AccountAccessType);
Result.Status := LsaAddPrivilegesToAccount(hAccount, PrivSet);
FreeMem(PrivSet);
end;
function LsaxRemovePrivilegesAccount(hAccount: TLsaHandle; RemoveAll: Boolean;
Privileges: TArray<TPrivilege>): TNtxStatus;
var
PrivSet: PPrivilegeSet;
begin
PrivSet := NtxpAllocPrivilegeSet(Privileges);
Result.Location := 'LsaRemovePrivilegesFromAccount';
Result.LastCall.Expects(ACCOUNT_ADJUST_PRIVILEGES, @AccountAccessType);
Result.Status := LsaRemovePrivilegesFromAccount(hAccount, RemoveAll, PrivSet);
FreeMem(PrivSet);
end;
function LsaxManagePrivilegesAccount(AccountSid: PSid; RemoveAll: Boolean;
Add, Remove: TArray<TPrivilege>): TNtxStatus;
var
hxAccount: ILsaHandle;
begin
if (Length(Add) = 0) and (Length(Remove) = 0) and not RemoveAll then
begin
Result.Status := STATUS_SUCCESS;
Exit;
end;
// Try to open the account
Result := LsaxOpenAccount(hxAccount, AccountSid, ACCOUNT_ADJUST_PRIVILEGES);
// If there is no such account
if Result.Matches(STATUS_OBJECT_NAME_NOT_FOUND, 'LsaOpenAccount') then
begin
if Length(Add) = 0 then
begin
// No account - no privileges - nothing to remove
Result.Status := STATUS_SUCCESS;
Exit;
end;
// We need to add the account to LSA database in order to assign privileges
Result := LsaxCreateAccount(hxAccount, AccountSid,
ACCOUNT_ADJUST_PRIVILEGES);
end;
// Add privileges
if Result.IsSuccess and (Length(Add) > 0) then
Result := LsaxAddPrivilegesAccount(hxAccount.Handle, Add);
// Remove privileges
if Result.IsSuccess and (RemoveAll or (Length(Remove) > 0)) then
Result := LsaxRemovePrivilegesAccount(hxAccount.Handle, RemoveAll, Remove);
end;
function LsaxQueryRightsAccount(hAccount: TLsaHandle;
out SystemAccess: Cardinal): TNtxStatus;
begin
Result.Location := 'LsaGetSystemAccessAccount';
Result.LastCall.Expects(ACCOUNT_VIEW, @AccountAccessType);
Result.Status := LsaGetSystemAccessAccount(hAccount, SystemAccess);
end;
function LsaxQueryRightsAccountBySid(AccountSid: PSid;
out SystemAccess: Cardinal): TNtxStatus;
var
hxAccount: ILsaHandle;
begin
Result := LsaxOpenAccount(hxAccount, AccountSid, ACCOUNT_VIEW);
if Result.IsSuccess then
Result := LsaxQueryRightsAccount(hxAccount.Handle, SystemAccess);
end;
function LsaxSetRightsAccount(hAccount: TLsaHandle; SystemAccess: Cardinal)
: TNtxStatus;
begin
Result.Location := 'LsaSetSystemAccessAccount';
Result.LastCall.Expects(ACCOUNT_ADJUST_SYSTEM_ACCESS, @AccountAccessType);
Result.Status := LsaSetSystemAccessAccount(hAccount, SystemAccess);
end;
function LsaxSetRightsAccountBySid(AccountSid: PSid; SystemAccess: Cardinal):
TNtxStatus;
var
hxAccount: ILsaHandle;
begin
Result := LsaxOpenAccount(hxAccount, AccountSid,
ACCOUNT_ADJUST_SYSTEM_ACCESS);
// Add the account to the LSA database if necessary
if Result.Matches(STATUS_OBJECT_NAME_NOT_FOUND, 'LsaOpenAccount') then
Result := LsaxCreateAccount(hxAccount, AccountSid,
ACCOUNT_ADJUST_SYSTEM_ACCESS);
if Result.IsSuccess then
Result := LsaxSetRightsAccount(hxAccount.Handle, SystemAccess);
end;
{ Privileges }
function LsaxEnumeratePrivileges(hPolicy: TLsaHandle;
out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus;
var
EnumContext: TLsaEnumerationHandle;
Count, i: Integer;
Buffer: PPolicyPrivilegeDefinitionArray;
begin
EnumContext := 0;
Result.Location := 'LsaEnumeratePrivileges';
Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType);
Result.Status := LsaEnumeratePrivileges(hPolicy, EnumContext, Buffer,
MAX_PREFERRED_LENGTH, Count);
if not Result.IsSuccess then
Exit;
SetLength(Privileges, Count);
for i := 0 to High(Privileges) do
begin
Privileges[i].Name := Buffer{$R-}[i]{$R+}.Name.ToString;
Privileges[i].LocalValue := Buffer{$R-}[i]{$R+}.LocalValue;
end;
LsaFreeMemory(Buffer);
end;
function LsaxEnumeratePrivilegesLocal(
out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus;
var
hxPolicy: ILsaHandle;
begin
Result := LsaxOpenPolicy(hxPolicy, POLICY_VIEW_LOCAL_INFORMATION);
if Result.IsSuccess then
Result := LsaxEnumeratePrivileges(hxPolicy.Handle, Privileges);
end;
function LsaxQueryNamePrivilege(hPolicy: TLsaHandle; Luid: TLuid;
out Name: String): TNtxStatus;
var
Buffer: PLsaUnicodeString;
begin
Result.Location := 'LsaLookupPrivilegeName';
Result.LastCall.Expects(POLICY_LOOKUP_NAMES, @PolicyAccessType);
Result.Status := LsaLookupPrivilegeName(hPolicy, Luid, Buffer);
if Result.IsSuccess then
begin
Name := Buffer.ToString;
LsaFreeMemory(Buffer);
end;
end;
function LsaxQueryDescriptionPrivilege(hPolicy: TLsaHandle; const Name: String;
out DisplayName: String): TNtxStatus;
var
NameStr: TLsaUnicodeString;
BufferDisplayName: PLsaUnicodeString;
LangId: SmallInt;
begin
NameStr.FromString(Name);
Result.Location := 'LsaLookupPrivilegeDisplayName';
Result.LastCall.Expects(POLICY_LOOKUP_NAMES, @PolicyAccessType);
Result.Status := LsaLookupPrivilegeDisplayName(hPolicy, NameStr,
BufferDisplayName, LangId);
if Result.IsSuccess then
begin
DisplayName := BufferDisplayName.ToString;
LsaFreeMemory(BufferDisplayName);
end;
end;
function LsaxLookupMultiplePrivileges(Luids: TArray<TLuid>;
out Names, Descriptions: TArray<String>): TNtxStatus;
var
hxPolicy: ILsaHandle;
i: Integer;
begin
Result := LsaxOpenPolicy(hxPolicy, POLICY_LOOKUP_NAMES);
if not Result.IsSuccess then
Exit;
SetLength(Names, Length(Luids));
SetLength(Descriptions, Length(Luids));
for i := 0 to High(Luids) do
if not LsaxQueryNamePrivilege(hxPolicy.Handle, Luids[i], Names[i]).IsSuccess
or not LsaxQueryDescriptionPrivilege(hxPolicy.Handle, Names[i],
Descriptions[i]).IsSuccess then
begin
Result.Location := 'LsaxQueryNamesPrivileges';
Result.Status := STATUS_SOME_NOT_MAPPED;
end;
end;
function LsaxQueryIntegrityPrivilege(Luid: TLuid): Cardinal;
begin
// Some privileges require a specific integrity level to be enabled.
// The ones that require more than Medium also trigger UAC to split logon
// sessions. The following data is gathered by experimenting and should be
// maintained in sync with Windows behavior when new privileges are
// introduced.
case TSeWellKnownPrivilege(Luid) of
// Ten of them require High
SE_CREATE_TOKEN_PRIVILEGE,
SE_TCB_PRIVILEGE,
SE_TAKE_OWNERSHIP_PRIVILEGE,
SE_LOAD_DRIVER_PRIVILEGE,
SE_BACKUP_PRIVILEGE,
SE_RESTORE_PRIVILEGE,
SE_DEBUG_PRIVILEGE,
SE_IMPERSONATE_PRIVILEGE,
SE_RELABEL_PRIVILEGE,
SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE:
Result := SECURITY_MANDATORY_HIGH_RID;
// Three of them does not require anything
SE_CHANGE_NOTIFY_PRIVILEGE,
SE_UNDOCK_PRIVILEGE,
SE_INCREASE_WORKING_SET_PRIVILEGE:
Result := SECURITY_MANDATORY_UNTRUSTED_RID;
else
// All other require Medium
Result := SECURITY_MANDATORY_MEDIUM_RID;
end;
end;
{ Logon rights }
function LsaxEnumerateLogonRights: TArray<TLogonRightRec>;
begin
// If someone knows a system function to enumerate logon rights on the system
// you are welcome to use it here.
SetLength(Result, 10);
Result[0].Value := SECURITY_ACCESS_INTERACTIVE_LOGON;
Result[0].IsAllowedType := True;
Result[0].Name := SE_INTERACTIVE_LOGON_NAME;
Result[0].Description := 'Allow interactive logon';
Result[1].Value := SECURITY_ACCESS_NETWORK_LOGON;
Result[1].IsAllowedType := True;
Result[1].Name := SE_NETWORK_LOGON_NAME;
Result[1].Description := 'Allow network logon';
Result[2].Value := SECURITY_ACCESS_BATCH_LOGON;
Result[2].IsAllowedType := True;
Result[2].Name := SE_BATCH_LOGON_NAME;
Result[2].Description := 'Allow batch job logon';
Result[3].Value := SECURITY_ACCESS_SERVICE_LOGON;
Result[3].IsAllowedType := True;
Result[3].Name := SE_SERVICE_LOGON_NAME;
Result[3].Description := 'Allow service logon';
Result[4].Value := SECURITY_ACCESS_REMOTE_INTERACTIVE_LOGON;
Result[4].IsAllowedType := True;
Result[4].Name := SE_REMOTE_INTERACTIVE_LOGON_NAME;
Result[4].Description := 'Allow Remote Desktop Services logon';
Result[5].Value := SECURITY_ACCESS_DENY_INTERACTIVE_LOGON;
Result[5].IsAllowedType := False;
Result[5].Name := SE_DENY_INTERACTIVE_LOGON_NAME;
Result[5].Description := 'Deny interactive logon';
Result[6].Value := SECURITY_ACCESS_DENY_NETWORK_LOGON;
Result[6].IsAllowedType := False;
Result[6].Name := SE_DENY_NETWORK_LOGON_NAME;
Result[6].Description := 'Deny network logon';
Result[7].Value := SECURITY_ACCESS_DENY_BATCH_LOGON;
Result[7].IsAllowedType := False;
Result[7].Name := SE_DENY_BATCH_LOGON_NAME;
Result[7].Description := 'Deny batch job logon';
Result[8].Value := SECURITY_ACCESS_DENY_SERVICE_LOGON;
Result[8].IsAllowedType := False;
Result[8].Name := SE_DENY_SERVICE_LOGON_NAME;
Result[8].Description := 'Deny service logon';
Result[9].Value := SECURITY_ACCESS_DENY_REMOTE_INTERACTIVE_LOGON;
Result[9].IsAllowedType := False;
Result[9].Name := SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME;
Result[9].Description := 'Deny Remote Desktop Services logon';
end;
end.
|
// ##################################
// # TPLVisor - Michel Kunkler 2013 #
// ##################################
(*
In dieser Unit wird zunächst eine Mutterklasse TBefehl definiert, die als Grundlage für
die Kindsklassen, die jeweiligen Befehle bildet.
Die Attribute der Klasse TBefehl werden im folgenden kurz beschrieben:
Start : Startposition des Befehls (für späteres markieren);
Ende : Endposition;
Ziel : nächster Zustand sofern gegeben;
Zustand : eigener Zustand;
Schreibe : Zu schreibender Wert beim write Befehl;
Bedingung : Bedingung beim case Befehl;
Befehl : Name des Befehls;
Fehler : Zeiger auf einen Fehlerstring;
Parameter : Parameter (nach Leerzeichen gesplitteter Befehl);
Jeder Befehl hat grundsätzlich zwei Methoden:
function Parsen : boolean; Override;
Parst den jeweiligen Befehl und gibt true oder false zurück.
Bei false wird auf den Wert des Fehlerzeigers geschreiben.
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
Interpretiert den Befehl, d.h.: führt sich selbst auf einer übergebenen
Turingmaschine aus.
Die Interpretieren Methoden von insb. TCase und TWrite sind exemplarisch
wie ein endlicher Automat aufgebaut. Ergo: Es gibt einen Zustand und eine Eingabe
nach denen der Code parst.
Dieses Prinzip ist im Sinne der Aufgabenstellung performant aber m.E. nach sehr
unübersichtlich.
Für weitere Informationen siehe:
http://www.codeproject.com/Articles/5412/Writing-own-regular-expression-parser
*)
unit TPLBefehle;
interface
uses
Classes,
SysUtils,
Dialogs, // ShowMessage
TPLErrors,
TPLTuringmaschine;
type
TBefehlRecord = record
Name : string;
Befehl : pointer;
end;
TBefehl = class
private
public
Start : integer;
Ende : integer;
Ziel : integer;
Zustand : integer;
Schreibe : char;
Bedingung : char;
Befehl : string;
Fehler : pstring;
Parameter : TStringList;
Constructor Create; Virtual;
function Parsen : boolean; Virtual;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Virtual;
function InAlphabet(Parameter : string) : boolean;
function GetNr(Nr : string) : integer;
end;
CBefehl = class of TBefehl;
TRight = class(TBefehl)
Constructor Create; Override;
function Parsen : boolean; Override;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
end;
TLeft = class(TBefehl)
Constructor Create; Override;
function Parsen : boolean; Override;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
end;
TCase = class(TBefehl)
Constructor Create; Override;
function Parsen : boolean; Override;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
end;
TWrite = class(TBefehl)
Constructor Create; Override;
function Parsen : boolean; Override;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
end;
THalt = class(TBefehl)
Constructor Create; Override;
function Parsen : boolean; Override;
function Interpretieren(Turingmaschine : TTuringmaschine) : boolean; Override;
end;
const
BefehlsListe : array[0..4] of TBefehlRecord =
(
(Name : 'right'; Befehl : TRight),
(Name : 'left'; Befehl : TLeft),
(Name : 'write'; Befehl : TWrite),
(Name : 'case'; Befehl : TCase),
(Name : 'halt'; Befehl : THalt)
);
implementation
{ TBefehl }
Constructor TBefehl.Create;
begin
end;
function TBefehl.Parsen : boolean;
begin
Result := False;
end;
function TBefehl.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Result := False;
end;
function TBefehl.GetNr(Nr : string) : integer;
begin
try
Result := strtoint(Nr);
except
Result := -1;
end;
end;
function TBefehl.InAlphabet(Parameter : string) : boolean;
begin
Result := False;
if Length(Parameter) = 1 then
Result := True;
end;
{ TRight }
Constructor TRight.Create;
begin
self.Befehl := 'right';
end;
function TRight.Parsen : boolean;
begin
Result := True;
if self.Parameter.Count > 0 then
begin
self.Fehler^ := Format(ParserError.KeinParameter, [self.Parameter[0]]);
Result := False;
end;
end;
function TRight.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Turingmaschine.BefehlRechts;
Result := True;
end;
{ TLeft }
Constructor TLeft.Create;
begin
self.Befehl := 'left';
end;
function TLeft.Parsen : boolean;
begin
Result := True;
if self.Parameter.Count > 0 then
begin
self.Fehler^ := Format(ParserError.KeinParameter, [self.Parameter[0]]);
Result := False;
end;
end;
function TLeft.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Turingmaschine.BefehlLinks;
Result := True;
end;
{ TWrite }
Constructor TWrite.Create;
begin
self.Befehl := 'write';
end;
function TWrite.Parsen : boolean;
type
TStatus = (SNull, Se);
var
Status : TStatus;
begin
Status := SNull;
Result := False;
while self.Parameter.Count > 0 do
begin
case Status of
SNull :
begin
if self.InAlphabet(self.Parameter[0]) = False then
begin
self.Fehler^ := Format(ParserError.NichtImAlphabet, [self.Parameter[0]]);
break;
end;
Status := Se;
self.Schreibe := self.Parameter[0][1];
self.Parameter.Delete(0);
end;
Se :
begin
Result := True;
if self.Parameter.Count > 0 then
begin
Result := False;
self.Fehler^ := Format(ParserError.KeinParameter, [self.Parameter[0]]);
end;
break;
end;
end;
end;
end;
function TWrite.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Turingmaschine.BefehlSchreibe(self.Schreibe);
Result := True;
end;
{ TCase }
Constructor TCase.Create;
begin
self.Befehl := 'case';
end;
function TCase.Parsen : boolean;
type
TStatus = (SNull, Se, SJump, Sn);
var
Status : TStatus;
begin
Status := SNull;
Result := False;
while self.Parameter.Count > 0 do
begin
case Status of
SNull :
begin
if self.InAlphabet(self.Parameter[0]) = False then
begin
self.Fehler^ := Format(ParserError.NichtImAlphabet, [self.Parameter[0]]);
break;
end;
self.Bedingung := Parameter[0][1];
Status := Se;
self.Parameter.Delete(0);
end;
Se :
begin
if LowerCase(self.Parameter[0]) <> 'jump' then
begin
self.Fehler^ := Format(ParserError.JumpErwartet, [self.Parameter[0]]);
break;
end;
Status := SJump;
self.Parameter.Delete(0);
end;
SJump :
begin
if self.GetNr(self.Parameter[0]) = -1 then
begin
self.Fehler^ := Format(ParserError.UngZiel, [self.Parameter[0]]);
break;
end;
Status := Sn;
self.Ziel := self.GetNr(self.Parameter[0]);
self.Parameter.Delete(0);
end;
Sn :
begin
Result := True;
if self.Parameter.Count > 0 then
begin
Result := False;
self.Fehler^ := Format(ParserError.KeinParameter, [self.Parameter[0]]);
end;
break;
end;
end;
end;
end;
function TCase.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Result := Turingmaschine.BefehlSpringeWenn(self.Bedingung, self.Ziel);
end;
{ THalt }
Constructor THalt.Create;
begin
self.Befehl := 'halt';
end;
function THalt.Parsen : boolean;
begin
Result := True;
if self.Parameter.Count > 0 then
begin
Result := False;
self.Fehler^ := Format(ParserError.KeinParameter, [self.Parameter[0]]);
end;
end;
function THalt.Interpretieren(Turingmaschine : TTuringmaschine) : boolean;
begin
Result := False;
end;
end.
|
{
IsOffline: in the case where a Hayes style modem (one
that uses the AT command syntax), test to see if it's
connected or not. If we had the DCD (Carrier Detect)
signal available, we'd use that. But since we don't,
we send an empty AT command and see if there's a
modem there in the offline state, in which case it'll
echo AT<nl><nl>OK<nl>.
}
FUNCTION IsOffline : BOOLEAN;
CONST
expected : String[80] = 'AT'^M^J^M^J'OK'^M^J;
CR = ^M;
VAR
timeOut : INTEGER;
ch : CHAR;
idx : INTEGER;
BEGIN
timeOut := 0;
idx := 1;
WHILE ModemInReady DO
Read(Aux, ch);
Write(Aux,'AT',CR);
REPEAT
WHILE ModemInReady AND (idx<=Length(expected)) DO BEGIN
timeOut := 0;
Read(Aux, ch);
IF ch = expected[idx] THEN BEGIN
idx := Succ(idx);
END;
END;
Delay(1);
timeOut := Succ(timeOut);
UNTIL (idx>Length(expected)) OR (timeOut > 2000);
WHILE ModemInReady DO BEGIN
Read(Aux, ch);
idx := Succ(idx);
END;
IsOffline := idx = Length(expected)+1;
END;
|
unit SplashScreenU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, dxGDIPlusClasses;
type
TSplashForm = class(TForm)
Image1: TImage;
Label1: TLabel;
Label2: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
Procedure ShowSplashscreen;
Procedure HideSplashScreen;
Procedure ShowSplashScreenMessage( const S: String );
implementation
uses PBThreadedSplashscreenU;
{$R *.dfm}
var
ThreadedSplashForm: TPBThreadedSplashscreen;
{: Create a hidden instance of the TSplashForm class and use it as a
template for the real splash form. The template is only a convenience
to be able to design the splash from in the IDE, it may serve as
an about box as well, however. }
Procedure ShowSplashscreen;
Var
SplashForm: TSplashForm;
bmp: TBitmap;
Begin
If Assigned( ThreadedSplashForm ) Then Exit;
Splashform := TSplashform.Create( Application );
try
ThreadedSplashForm:= TPBThreadedSplashscreen.Create( nil );
Try
ThreadedSplashform.Left := Splashform.Left;
ThreadedSplashform.Top := Splashform.Top;
ThreadedSplashform.Center:=
Splashform.Position in [ poScreenCenter, poMainFormCenter,
poDesktopCenter ];
bmp:= Splashform.GetFormImage;
try
ThreadedSplashform.Image := bmp;
finally
bmp.Free;
end;
ThreadedSplashForm.UseStatusbar := True;
// ThreadedSplashForm.TopMost := true;
ThreadedSplashForm.Show;
Except
FreeAndNil(ThreadedSplashForm);
raise;
End; { Except }
finally
Splashform.Free;
end;
End;
Procedure HideSplashScreen;
Begin
FreeAndNil(ThreadedSplashForm);
End;
Procedure ShowSplashScreenMessage( const S: String );
Begin
If Assigned( ThreadedSplashForm ) Then
ThreadedSplashForm.ShowStatusMessage( S );
End;
end.
|
unit Report_GoodsMI_Package;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorReport, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters,
dxSkinscxPCPainter, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls,
dxCore, cxDateUtils, dxSkinsdxBarPainter, dsdAddOn, ChoicePeriod,
dxBarExtItems, dxBar, cxClasses, dsdDB, Datasnap.DBClient, dsdAction,
Vcl.ActnList, cxPropertiesStore, cxLabel, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC,
dsdGuides, cxButtonEdit, cxCurrencyEdit, Vcl.Menus, cxCheckBox;
type
TReport_GoodsMI_PackageForm = class(TAncestorReportForm)
GoodsCode: TcxGridDBColumn;
GoodsName: TcxGridDBColumn;
FormParams: TdsdFormParams;
Amount_Send_in: TcxGridDBColumn;
Amount_Production: TcxGridDBColumn;
MeasureName: TcxGridDBColumn;
cxLabel3: TcxLabel;
GuidesUnit: TdsdGuides;
edUnit: TcxButtonEdit;
Weight_diff: TcxGridDBColumn;
Amount_Send_out: TcxGridDBColumn;
actPrint: TdsdPrintAction;
actPrintByGoods: TdsdPrintAction;
bbPrint: TdxBarButton;
bbPrintByGoods: TdxBarButton;
CountPackage: TcxGridDBColumn;
WeightPackage: TcxGridDBColumn;
Weight_Send_out: TcxGridDBColumn;
Weight_Send_in: TcxGridDBColumn;
GoodsGroupName: TcxGridDBColumn;
GoodsKindName: TcxGridDBColumn;
Weight_Production: TcxGridDBColumn;
GoodsCode_basis: TcxGridDBColumn;
GoodsName_basis: TcxGridDBColumn;
ReceiptCode_code: TcxGridDBColumn;
ReceiptCode: TcxGridDBColumn;
ReceiptName: TcxGridDBColumn;
WeightPackage_one: TcxGridDBColumn;
CountPackage_calc: TcxGridDBColumn;
WeightPackage_calc: TcxGridDBColumn;
ExecuteDialog: TExecuteDialog;
bbExecuteDialog: TdxBarButton;
WeightTotal: TcxGridDBColumn;
cbisDate: TcxCheckBox;
actRefreshData: TdsdDataSetRefresh;
actReport_Goods: TdsdOpenForm;
bbReport_Goods: TdxBarButton;
cbisPersonalGroup: TcxCheckBox;
actRefreshDataPersonalGroup: TdsdDataSetRefresh;
PersonalGroupName: TcxGridDBColumn;
InvNumber: TcxGridDBColumn;
MovementDescName: TcxGridDBColumn;
cbMovement: TcxCheckBox;
actRefreshMov: TdsdDataSetRefresh;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TReport_GoodsMI_PackageForm);
end.
|
unit uDownloads.Model.Entidades.LogDowload;
interface
uses
uDownloads.Model.Interfaces, Data.DB, System.SysUtils;
type
TModelEntidadesLogDowload = class(TInterfacedObject, IEntidadeLogDowload)
private
FoQuery: IQuery;
function RetornarDataLog: String;
function ConsultarIDLog: Integer;
public
class function New: IEntidadeLogDowload;
constructor Create;
destructor Destroy; override;
function Listar(ADataSource: TDataSource): IEntidadeLogDowload;
function Inserir(AcUrl: String): Integer;
function AtualizarHoraFinal(AnIdLog: Integer): IEntidadeLogDowload;
end;
implementation
uses
uDownloads.Controller.Factory.Query;
class function TModelEntidadesLogDowload.New: IEntidadeLogDowload;
begin
Result := Create;
end;
constructor TModelEntidadesLogDowload.Create;
begin
FoQuery := TControllerFactoryQuery.New.GetQuery(nil);
end;
function TModelEntidadesLogDowload.Listar(ADataSource: TDataSource): IEntidadeLogDowload;
begin
Result := Self;
FoQuery.SQL('SELECT * FROM LOGDOWNLOAD');
ADataSource.DataSet := FoQuery.DataSet;
end;
function TModelEntidadesLogDowload.Inserir(AcUrl: String): Integer;
begin
FoQuery.Execute(Format('INSERT INTO LOGDOWNLOAD (URL, DATAINICIO) VALUES (%s, %s)',
[QuotedStr(AcUrl), RetornarDataLog]));
Result := ConsultarIDLog;
end;
function TModelEntidadesLogDowload.AtualizarHoraFinal(AnIdLog: Integer): IEntidadeLogDowload;
begin
Result := Self;
FoQuery.Execute(Format('UPDATE LOGDOWNLOAD SET DATAFIM = %s WHERE CODIGO = %d',
[RetornarDataLog, AnIdLog]));
end;
function TModelEntidadesLogDowload.RetornarDataLog: String;
begin
Result := QuotedStr(FormatDateTime('YYYY-MM-DD', Now));
end;
function TModelEntidadesLogDowload.ConsultarIDLog: Integer;
begin
Result := FoQuery.SQL(
'SELECT MAX(CODIGO) AS CODIGO FROM LOGDOWNLOAD'
).DataSet.FieldByName('CODIGO').AsInteger;
end;
destructor TModelEntidadesLogDowload.Destroy;
begin
inherited;
end;
end.
|
unit FIToolkit.Exceptions;
interface
uses
FIToolkit.Commons.Exceptions;
type
EApplicationException = class abstract (ECustomException);
EApplicationExecutionFailed = class (EApplicationException);
ECLIOptionsProcessingFailed = class (EApplicationException);
EErroneousConfigSpecified = class (EApplicationException);
ENoValidConfigSpecified = class (EApplicationException);
EUnableToGenerateConfig = class (EApplicationException);
EUnknownInputFileType = class (EApplicationException);
implementation
uses
FIToolkit.Consts;
initialization
RegisterExceptionMessage(EApplicationExecutionFailed, RSApplicationExecutionFailed);
RegisterExceptionMessage(ECLIOptionsProcessingFailed, RSCLIOptionsProcessingFailed);
RegisterExceptionMessage(EErroneousConfigSpecified, RSErroneousConfigSpecified);
RegisterExceptionMessage(ENoValidConfigSpecified, RSNoValidConfigSpecified);
RegisterExceptionMessage(EUnableToGenerateConfig, RSUnableToGenerateConfig);
RegisterExceptionMessage(EUnknownInputFileType, RSUnknownInputFileType);
end.
|
unit regconst;
interface
resourcestring
SAbout = 'Borland Turbo Register Server -- COM Server Registration utility.' +
#13#10'Version 1.1. Copyright (c) 1997,99 Inprise Corporation'#13#10;
SUsage = 'Syntax: TREGSVR [options] filename'#13#10 +
' -u = Unregister server or type library'#13#10 +
' -q = Quiet (silent) operation'#13#10 +
' -t = Register type library (default for .TLB files)'#13#10;
SFileNotFound = 'File "%s" not found';
SCantFindProc = '%s procedure not found in "%s"';
SRegFail = 'Call to %s failed in "%s"';
SLoadFail = 'Failed to load "%s"';
SRegSuccessful = 'Call to %s was successful!';
SRegStr = 'registered';
SUnregStr = 'unregistered';
STlbName = 'Type library name: %s';
STlbGuid = 'Type library GUID: %s';
STlbRegSuccessful = 'Type library successfully %s!';
SCantUnregTlb = 'The version of OLEAUT32.DLL on this machine does not ' +
'support type library unregistration.';
SNeedFileExt = 'You must specify a file extension for "%s"';
SExeRegSuccessful = '%s successfully called.';
SExeRegUnsuccessful = '%s failed.';
implementation
end.
|
(* CIStringSetUnit: MM, 2020-05-30 *)
(* ------ *)
(* A simple class for CaseInsensitiveStringSet Operations using *)
(* a single linked list *)
(* ========================================================================= *)
UNIT CIStringSetUnit;
INTERFACE
USES StringSetListUnit;
TYPE
CIStringSet = ^CIStringSetObj;
CIStringSetObj = OBJECT(StringSetObj)
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
FUNCTION Contains(x: STRING): BOOLEAN;
PROCEDURE Add(x: STRING);
END; (* StringSetObj *)
IMPLEMENTATION
CONSTRUCTOR CIStringSetObj.Init;
BEGIN
INHERITED Init;
END; (* CIStringSetObj.Init *)
DESTRUCTOR CIStringSetObj.Done;
BEGIN
INHERITED Done;
END; (* CIStringSetObj.Done *)
FUNCTION CIStringSetObj.Contains(x: STRING): BOOLEAN;
VAR curr: Node;
BEGIN (* CIStringSetObj.Contains *)
curr := elements;
IF(curr <> NIL) THEN BEGIN
WHILE (curr^.next <> NIL) AND (UpCase(curr^.value) <> UpCase(x)) DO BEGIN
curr := curr^.next;
END; (* WHILE *)
Contains := UpCase(curr^.value) = UpCase(x);
END ELSE BEGIN
Contains := FALSE;
END; (* IF *)
END; (* CIStringSetObj.Contains *)
PROCEDURE CIStringSetObj.Add(x: STRING);
BEGIN (* StringSetObj.Add *)
IF (NOT Contains(x)) THEN BEGIN
INHERITED AddFromSubClass(x);
END; (* IF *)
END; (* StringSetObj.Add *)
END. (* CIStringSetUnit *) |
unit Classe_Usuario;
interface
uses Classes, Dialogs, SysUtils,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TUsuario = class
private
FCodigo,
FNome,
FSenha : String;
FAtivo : Boolean;
procedure setCodigo(Const Value:String);
procedure setNome(Const Value:String);
procedure setSenha(Const Value:String);
procedure setAtivo(Const Value:Boolean);
function getCodigo:String;
function getNome:String;
function getSenha:String;
function getAtivo:Boolean;
published
property Codigo: String read getCodigo
write setCodigo;
property Senha: String read getSenha
write setSenha;
property Nome: String read getNome
write setNome;
function Existe(Const Value:String):Boolean;
procedure Insert;
Procedure Update;
end;
implementation
{ TUsuario }
uses Dados, Funcoes;
function TUsuario.getAtivo: Boolean;
begin
result := FAtivo;
end;
function TUsuario.getCodigo: String;
begin
result := FCodigo;
end;
function TUsuario.getNome: String;
begin
result := FNome;
end;
function TUsuario.getSenha: String;
begin
result := FSenha;
end;
procedure TUsuario.Insert;
var qLocal: TFDQuery;
begin
FAtivo := True; // Sim
//
qLocal := TFDQuery.Create(nil);
qLocal.ConnectionName := 'X';
qLocal.Close;
qLocal.SQL.Clear;
qLocal.SQL.Add('INSERT INTO USUARIO_USU ');
qLocal.SQL.Add(' ( ');
qLocal.SQL.Add(' USU_CODIGO, ');
qLocal.SQL.Add(' USU_NOME, ');
qLocal.SQL.Add(' USU_SENHA, ');
qLocal.SQL.Add(' USU_ATIVO, ');
qLocal.SQL.Add(' USU_ATUALIZADO_NA_NUVEM, ');
qLocal.SQL.Add(' USU_ATUALIZADO_NA_NUVEMW ');
qLocal.SQL.Add(' ) ');
qLocal.SQL.Add(' VALUES ');
qLocal.SQL.Add(' ( ');
qLocal.SQL.Add(' :USU_CODIGO, ');
qLocal.SQL.Add(' :USU_NOME, ');
qLocal.SQL.Add(' :USU_SENHA, ');
qLocal.SQL.Add(' :USU_ATIVO, ');
qLocal.SQL.Add(' :USU_ATUALIZADO_NA_NUVEM, ');
qLocal.SQL.Add(' :USU_ATUALIZADO_NA_NUVEMW ');
qLocal.SQL.Add(' ) ');
qLocal.ParamByName('USU_CODIGO').AsString := FCodigo;
qLocal.ParamByName('USU_NOME' ).AsString := FNome;
qLocal.ParamByName('USU_SENHA' ).AsString := FSenha;
qLocal.ParamByName('USU_ATIVO' ).AsInteger:= 1;
qLocal.ParamByName('USU_ATUALIZADO_NA_NUVEM' ).AsInteger:= 0;
qLocal.ParamByName('USU_ATUALIZADO_NA_NUVEMW').AsInteger:= 0;
qLocal.ExecSql;
//
qLocal.Free;
Log('Cad Usu '+FCodigo);
end;
procedure TUsuario.setAtivo(const Value: Boolean);
begin
FAtivo := Value;
end;
procedure TUsuario.setCodigo(const Value: String);
begin
FCodigo := Value;
end;
procedure TUsuario.setNome(const Value: String);
begin
FNome := Value;
end;
procedure TUsuario.setSenha(const Value: String);
begin
FSenha := Value;
end;
procedure TUsuario.Update;
var qLocal: TFDQuery;
begin
qLocal := TFDQuery.Create(nil);
qLocal.ConnectionName := 'X';
qLocal.Close;
qLocal.SQL.Clear;
qLocal.SQL.Add('UPDATE USUARIO_USU ');
qLocal.SQL.Add(' SET USU_NOME = :USU_NOME, ');
qLocal.SQL.Add(' USU_SENHA = :USU_SENHA, ');
qLocal.SQL.Add(' USU_ATIVO = :USU_ATIVO, ');
qLocal.SQL.Add(' USU_ATUALIZADO_NA_NUVEM = :USU_ATUALIZADO_NA_NUVEM,');
qLocal.SQL.Add(' USU_ATUALIZADO_NA_NUVEMW = :USU_ATUALIZADO_NA_NUVEMW');
qLocal.SQL.Add(' WHERE USU_CODIGO = :USU_CODIGO ');
qLocal.ParamByName('USU_CODIGO').AsString := FCodigo;
qLocal.ParamByName('USU_NOME' ).AsString := FNome;
qLocal.ParamByName('USU_SENHA' ).AsString := Criptografar(FSenha);
if FAtivo then
qLocal.ParamByName('USU_ATIVO').AsInteger:= 1
else
qLocal.ParamByName('USU_ATIVO').AsInteger:= 0;
qLocal.ParamByName('USU_ATUALIZADO_NA_NUVEM' ).AsInteger:= 0;
qLocal.ParamByName('USU_ATUALIZADO_NA_NUVEMW').AsInteger:= 0;
qLocal.ExecSql;
//
qLocal.Free;
Log('Alt Usu '+FCodigo);
end;
function TUsuario.Existe(Const Value:String):Boolean;
begin
if Value = 'MASTER' then
begin
FCodigo := Value;
FNome := Value;
FSenha := '@123@';
FAtivo := True;
Result := True;
exit;
end;
DM.qUSUARIO.close;
DM.qUSUARIO.sql.clear;
DM.qUSUARIO.sql.add('SELECT * FROM USUARIO_USU ');
DM.qUSUARIO.sql.add(' WHERE USU_CODIGO = :USU_CODIGO');
DM.qUSUARIO.ParamByName('USU_CODIGO').AsString := Value;
DM.qUSUARIO.Open;
if DM.qUSUARIO.Eof then
begin
Result := False;
exit;
end;
Result := True;
FCodigo:= DM.qUSUARIO.FieldByName('USU_CODIGO').AsString;
FNome := DM.qUSUARIO.FieldByName('USU_NOME' ).AsString;
FSenha := Descriptografar(DM.qUSUARIO.FieldByName('USU_SENHA').AsString);
FAtivo := (DM.qUSUARIO.FieldByName('USU_ATIVO').AsInteger = 1);
DM.qUSUARIO.close;
end;
end.
|
unit sosemanu;
{Sosemanuk stream cipher routines}
interface
{$i STD.INC}
{$define CHECK_KEY_BITS} {undef to allow key sizes from 0 to 256 bits}
{otherwise 128 to 256 bits are used.}
{.$define DebugAlign} {Debug output for BASM16 alignment}
(*************************************************************************
DESCRIPTION : Sosemanuk stream cipher routines
REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : 2 KB static Alpha tables
DISPLAY MODE : ---
REMARKS : Some BASM16 hints: High speed 16 bit code needs careful
tuning (note that BP7 real mode code is faster than FPC
32 bit with -O3 optimization)! The most important measure
is to dword align the local variables in MakeStreamBlock.
This must be done before MakeStreamBlock is called (with
code that tests and conditionally adjust the stack pointer).
Good but less important (about 1 cycle per byte) is the
dword access and alignment of the mul/divAlpha-Tables, via
$define Alpha32 and the DummyAlignBasm word.
REFERENCES : [1] Phase 3 version for ECRYPT Stream Cipher Project
http://www.ecrypt.eu.org/stream/sosemanukp3.html
http://www.ecrypt.eu.org/stream/p3ciphers/sosemanuk/sosemanuk_p3source.zip
http://www.ecrypt.eu.org/stream/p3ciphers/sosemanuk/sosemanuk_p3.pdf
[2] http://www.cl.cam.ac.uk/~rja14/serpent.html
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.01 10.04.09 W.Ehrhardt Initial version: Key setup from fast java implementation
0.02 10.04.09 we IV setup from fast java implementation
0.03 10.04.09 we Stream generator from fast java implementation
0.04 11.04.09 we BIT16: Recycling of Serpent Key/IV setup
0.05 11.04.09 we Replace RotateLeft by shl/shr
0.06 11.04.09 we Common context definition
0.07 11.04.09 we Working 32 bit selftest
0.08 11.04.09 we MakeStreamBlock with nblk parameter
0.09 11.04.09 we mulAlpha/divAlpha tables
0.10 11.04.09 we sose_keystream_blocks, sose_keystream_bytes
0.11 11.04.09 we sose_encrypt_bytes
0.12 11.04.09 we extendend selftest
0.13 11.04.09 we Changed sose_encrypt_bytes to avoid D3/D3 Internal error: URW882
0.14 11.04.09 we Working 16 bit part (with 32 bit MakeStreamBlock)
0.15 12.04.09 we SM16INC/MakeStreamBlock: r2 := RotL(tt * $54655307,7)
0.16 12.04.09 we SM16INC/MakeStreamBlock: mul/divAlpha index via byte
0.17 12.04.09 we SM16INC/MakeStreamBlock: BASM for RotL(tt * $54655307,7)
0.18 12.04.09 we SM16INC/MakeStreamBlock: SHL8/SHR8 inline
0.19 12.04.09 we Cond. define CHECK_KEY_BITS
0.20 13.04.09 we Improved sose_encrypt_bytes/sose_keystream_bytes
0.21 13.04.09 we Special FPC code in sose_encrypt_bytes
0.22 14.04.09 we SM16INC/MakeStreamBlock: separate code for BASM16
0.23 14.04.09 we SM16INC/MakeStreamBlock: more BASM code
0.24 14.04.09 we SM16INC/MakeStreamBlock: conditional define Alpha32
0.25 14.04.09 we BASM16: Add code to dword align local variables of MakeStreamBlock
0.26 15.04.09 we Second pass in selftest with length <> blocksize
0.27 15.04.09 we Separate BIT16 inc files, sose_ivsetup with BASM16
0.28 24.04.09 we BASM16 keysetup
0.29 24.04.09 we Faster lkey setup in sose_keysetup; BASM16: dword align K0
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
(*************************************************************************
Encryption/decryption of arbitrary length messages.
For efficiency reasons, the API provides two types of encrypt/decrypt
functions. The sose_encrypt_bytes function encrypts byte strings of
arbitrary length, while the sose_encrypt_blocks function only accepts
lengths which are multiples of sose_blocklength.
The user is allowed to make multiple calls to sose_encrypt_blocks to
incrementally encrypt a long message, but he is NOT allowed to make
additional encryption calls once he has called sose_encrypt_bytes
(unless he starts a new message of course). For example, this sequence
of calls is acceptable:
sose_keysetup();
sose_ivsetup();
sose_encrypt_blocks();
sose_encrypt_blocks();
sose_encrypt_bytes();
sose_ivsetup();
sose_encrypt_blocks();
sose_encrypt_blocks();
sose_ivsetup();
sose_encrypt_bytes();
The following sequence is not:
sose_keysetup();
sose_ivsetup();
sose_encrypt_blocks();
sose_encrypt_bytes();
sose_encrypt_blocks();
**************************************************************************)
uses
BTypes;
const
sose_blocklength = 80; {Block length in bytes}
type
TSMBlock = packed array[0..79] of byte;
TSMBlockW = packed array[0..19] of longint;
TPSMBlock = ^TSMBlock;
TPSMBlockW = ^TSMBlockW;
{Structure containing the context of Sosemanuk}
sose_ctx = packed record
lfsr : array[0..9] of longint; {Internal state LFSR}
fsmr : array[1..2] of longint; {Finite state machine}
RndKey : array[0..99] of longint; {Round keys from key setup}
end;
function sose_keysetup(var ctx: sose_ctx; key: pointer; keybits: word): integer;
{-Key setup, keybits div 8 (max. 32) bytes of key^ are used, if CHECK_KEY_BITS}
{ is defined (default), keybits must be at least 128. It is the user's }
{ responsibility to supply a pointer to at least keybits accessible bits.}
procedure sose_ivsetup(var ctx: sose_ctx; IV: pointer);
{-IV setup, 128 bits of IV^ are used. It is the user's responsibility to }
{ supply least 128 accessible IV bits. After having called sose_keysetup,}
{ the user is allowed to call sose_ivsetup different times in order to }
{ encrypt/decrypt different messages with the same key but different IV's}
procedure sose_encrypt_bytes(var ctx: sose_ctx; ptp, ctp: pointer; msglen: longint);
{-Bytewise encryption, msglen: message length in bytes}
procedure sose_encrypt_blocks(var ctx: sose_ctx; ptp, ctp: pointer; blocks: word);
{-Blockwise encrypt plainttext to ciphertext, blocks: length in 80 byte blocks}
procedure sose_encrypt_packet(var ctx: sose_ctx; IV, ptp, ctp: pointer; msglen: longint);
{-All-in-one encryption of (short) packets, msglen: message length in bytes}
{ It is the user's responsibility to supply least 128 accessible IV bits.}
procedure sose_decrypt_bytes(var ctx: sose_ctx; ctp, ptp: pointer; msglen: longint);
{-Bytewise decryption, msglen: message length in bytes}
procedure sose_decrypt_blocks(var ctx: sose_ctx; ctp, ptp: pointer; blocks: word);
{-Blockwise decryption, blocks: length in 80 byte blocks}
procedure sose_decrypt_packet(var ctx: sose_ctx; IV, ctp, ptp: pointer; msglen: longint);
{-All-in-one encryption of (short) packets, msglen: message length in bytes}
{ It is the user's responsibility to supply least 128 accessible IV bits.}
procedure sose_keystream_bytes(var ctx: sose_ctx; keystream: pointer; kslen: longint);
{-Generate keystream, kslen: keystream length in bytes}
procedure sose_keystream_blocks(var ctx: sose_ctx; keystream: pointer; blocks: word);
{-Generate keystream, blocks: keystream length in 80 byte blocks}
function sose_selftest: boolean;
{-Simple self-test of Sosemanuk}
implementation
type
TWA4 = packed array[0..3] of longint;
PWA4 = ^TWA4;
{.$undef BASM16}
(*
The sig const is used for the translation of conditional Java/C expressions
like ((r1 & 0x01) != 0 ? s8 : 0)) into (sig[r1 and 1] and s8).
BASM does not need this const, because the translation is done as follows
mov ax,[r1]
shr ax,1
sbb eax,eax
and eax,[s8]
*)
{$ifndef BASM16}
const
sig: array[0..1] of longint = (0, -1);
{$endif}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9+ errors!}
{$endif}
const
{$ifdef BASM16}
{$define Alpha32} {define Alpha32 to use dword access in MakeStreamBlock}
DummyAlignBasm: word = 0; {Use this const to dowrd align the mul/divAlpha-Tables}
{$endif}
mulAlpha: array[0..255] of longint = (
$00000000, $e19fcf13, $6b973726, $8a08f835, $d6876e4c, $3718a15f, $bd10596a, $5c8f9679,
$05a7dc98, $e438138b, $6e30ebbe, $8faf24ad, $d320b2d4, $32bf7dc7, $b8b785f2, $59284ae1,
$0ae71199, $eb78de8a, $617026bf, $80efe9ac, $dc607fd5, $3dffb0c6, $b7f748f3, $566887e0,
$0f40cd01, $eedf0212, $64d7fa27, $85483534, $d9c7a34d, $38586c5e, $b250946b, $53cf5b78,
$1467229b, $f5f8ed88, $7ff015bd, $9e6fdaae, $c2e04cd7, $237f83c4, $a9777bf1, $48e8b4e2,
$11c0fe03, $f05f3110, $7a57c925, $9bc80636, $c747904f, $26d85f5c, $acd0a769, $4d4f687a,
$1e803302, $ff1ffc11, $75170424, $9488cb37, $c8075d4e, $2998925d, $a3906a68, $420fa57b,
$1b27ef9a, $fab82089, $70b0d8bc, $912f17af, $cda081d6, $2c3f4ec5, $a637b6f0, $47a879e3,
$28ce449f, $c9518b8c, $435973b9, $a2c6bcaa, $fe492ad3, $1fd6e5c0, $95de1df5, $7441d2e6,
$2d699807, $ccf65714, $46feaf21, $a7616032, $fbeef64b, $1a713958, $9079c16d, $71e60e7e,
$22295506, $c3b69a15, $49be6220, $a821ad33, $f4ae3b4a, $1531f459, $9f390c6c, $7ea6c37f,
$278e899e, $c611468d, $4c19beb8, $ad8671ab, $f109e7d2, $109628c1, $9a9ed0f4, $7b011fe7,
$3ca96604, $dd36a917, $573e5122, $b6a19e31, $ea2e0848, $0bb1c75b, $81b93f6e, $6026f07d,
$390eba9c, $d891758f, $52998dba, $b30642a9, $ef89d4d0, $0e161bc3, $841ee3f6, $65812ce5,
$364e779d, $d7d1b88e, $5dd940bb, $bc468fa8, $e0c919d1, $0156d6c2, $8b5e2ef7, $6ac1e1e4,
$33e9ab05, $d2766416, $587e9c23, $b9e15330, $e56ec549, $04f10a5a, $8ef9f26f, $6f663d7c,
$50358897, $b1aa4784, $3ba2bfb1, $da3d70a2, $86b2e6db, $672d29c8, $ed25d1fd, $0cba1eee,
$5592540f, $b40d9b1c, $3e056329, $df9aac3a, $83153a43, $628af550, $e8820d65, $091dc276,
$5ad2990e, $bb4d561d, $3145ae28, $d0da613b, $8c55f742, $6dca3851, $e7c2c064, $065d0f77,
$5f754596, $beea8a85, $34e272b0, $d57dbda3, $89f22bda, $686de4c9, $e2651cfc, $03fad3ef,
$4452aa0c, $a5cd651f, $2fc59d2a, $ce5a5239, $92d5c440, $734a0b53, $f942f366, $18dd3c75,
$41f57694, $a06ab987, $2a6241b2, $cbfd8ea1, $977218d8, $76edd7cb, $fce52ffe, $1d7ae0ed,
$4eb5bb95, $af2a7486, $25228cb3, $c4bd43a0, $9832d5d9, $79ad1aca, $f3a5e2ff, $123a2dec,
$4b12670d, $aa8da81e, $2085502b, $c11a9f38, $9d950941, $7c0ac652, $f6023e67, $179df174,
$78fbcc08, $9964031b, $136cfb2e, $f2f3343d, $ae7ca244, $4fe36d57, $c5eb9562, $24745a71,
$7d5c1090, $9cc3df83, $16cb27b6, $f754e8a5, $abdb7edc, $4a44b1cf, $c04c49fa, $21d386e9,
$721cdd91, $93831282, $198beab7, $f81425a4, $a49bb3dd, $45047cce, $cf0c84fb, $2e934be8,
$77bb0109, $9624ce1a, $1c2c362f, $fdb3f93c, $a13c6f45, $40a3a056, $caab5863, $2b349770,
$6c9cee93, $8d032180, $070bd9b5, $e69416a6, $ba1b80df, $5b844fcc, $d18cb7f9, $301378ea,
$693b320b, $88a4fd18, $02ac052d, $e333ca3e, $bfbc5c47, $5e239354, $d42b6b61, $35b4a472,
$667bff0a, $87e43019, $0decc82c, $ec73073f, $b0fc9146, $51635e55, $db6ba660, $3af46973,
$63dc2392, $8243ec81, $084b14b4, $e9d4dba7, $b55b4dde, $54c482cd, $decc7af8, $3f53b5eb);
divAlpha: array[0..255] of longint = (
$00000000, $180f40cd, $301e8033, $2811c0fe, $603ca966, $7833e9ab, $50222955, $482d6998,
$c078fbcc, $d877bb01, $f0667bff, $e8693b32, $a04452aa, $b84b1267, $905ad299, $88559254,
$29f05f31, $31ff1ffc, $19eedf02, $01e19fcf, $49ccf657, $51c3b69a, $79d27664, $61dd36a9,
$e988a4fd, $f187e430, $d99624ce, $c1996403, $89b40d9b, $91bb4d56, $b9aa8da8, $a1a5cd65,
$5249be62, $4a46feaf, $62573e51, $7a587e9c, $32751704, $2a7a57c9, $026b9737, $1a64d7fa,
$923145ae, $8a3e0563, $a22fc59d, $ba208550, $f20decc8, $ea02ac05, $c2136cfb, $da1c2c36,
$7bb9e153, $63b6a19e, $4ba76160, $53a821ad, $1b854835, $038a08f8, $2b9bc806, $339488cb,
$bbc11a9f, $a3ce5a52, $8bdf9aac, $93d0da61, $dbfdb3f9, $c3f2f334, $ebe333ca, $f3ec7307,
$a492d5c4, $bc9d9509, $948c55f7, $8c83153a, $c4ae7ca2, $dca13c6f, $f4b0fc91, $ecbfbc5c,
$64ea2e08, $7ce56ec5, $54f4ae3b, $4cfbeef6, $04d6876e, $1cd9c7a3, $34c8075d, $2cc74790,
$8d628af5, $956dca38, $bd7c0ac6, $a5734a0b, $ed5e2393, $f551635e, $dd40a3a0, $c54fe36d,
$4d1a7139, $551531f4, $7d04f10a, $650bb1c7, $2d26d85f, $35299892, $1d38586c, $053718a1,
$f6db6ba6, $eed42b6b, $c6c5eb95, $decaab58, $96e7c2c0, $8ee8820d, $a6f942f3, $bef6023e,
$36a3906a, $2eacd0a7, $06bd1059, $1eb25094, $569f390c, $4e9079c1, $6681b93f, $7e8ef9f2,
$df2b3497, $c724745a, $ef35b4a4, $f73af469, $bf179df1, $a718dd3c, $8f091dc2, $97065d0f,
$1f53cf5b, $075c8f96, $2f4d4f68, $37420fa5, $7f6f663d, $676026f0, $4f71e60e, $577ea6c3,
$e18d0321, $f98243ec, $d1938312, $c99cc3df, $81b1aa47, $99beea8a, $b1af2a74, $a9a06ab9,
$21f5f8ed, $39fab820, $11eb78de, $09e43813, $41c9518b, $59c61146, $71d7d1b8, $69d89175,
$c87d5c10, $d0721cdd, $f863dc23, $e06c9cee, $a841f576, $b04eb5bb, $985f7545, $80503588,
$0805a7dc, $100ae711, $381b27ef, $20146722, $68390eba, $70364e77, $58278e89, $4028ce44,
$b3c4bd43, $abcbfd8e, $83da3d70, $9bd57dbd, $d3f81425, $cbf754e8, $e3e69416, $fbe9d4db,
$73bc468f, $6bb30642, $43a2c6bc, $5bad8671, $1380efe9, $0b8faf24, $239e6fda, $3b912f17,
$9a34e272, $823ba2bf, $aa2a6241, $b225228c, $fa084b14, $e2070bd9, $ca16cb27, $d2198bea,
$5a4c19be, $42435973, $6a52998d, $725dd940, $3a70b0d8, $227ff015, $0a6e30eb, $12617026,
$451fd6e5, $5d109628, $750156d6, $6d0e161b, $25237f83, $3d2c3f4e, $153dffb0, $0d32bf7d,
$85672d29, $9d686de4, $b579ad1a, $ad76edd7, $e55b844f, $fd54c482, $d545047c, $cd4a44b1,
$6cef89d4, $74e0c919, $5cf109e7, $44fe492a, $0cd320b2, $14dc607f, $3ccda081, $24c2e04c,
$ac977218, $b49832d5, $9c89f22b, $8486b2e6, $ccabdb7e, $d4a49bb3, $fcb55b4d, $e4ba1b80,
$17566887, $0f59284a, $2748e8b4, $3f47a879, $776ac1e1, $6f65812c, $477441d2, $5f7b011f,
$d72e934b, $cf21d386, $e7301378, $ff3f53b5, $b7123a2d, $af1d7ae0, $870cba1e, $9f03fad3,
$3ea637b6, $26a9777b, $0eb8b785, $16b7f748, $5e9a9ed0, $4695de1d, $6e841ee3, $768b5e2e,
$fedecc7a, $e6d18cb7, $cec04c49, $d6cf0c84, $9ee2651c, $86ed25d1, $aefce52f, $b6f3a5e2);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
{$ifdef BIT16}
{$F-}
{$ifdef BASM16}
{$i sm16inca.pas}
{$else}
{$i sm16incp.pas}
{$endif}
{$else}
{$i sm32inc.pas}
{$endif}
{---------------------------------------------------------------------------}
procedure sose_encrypt_bytes(var ctx: sose_ctx; ptp, ctp: pointer; msglen: longint);
{-Bytewise encryption, msglen: message length in bytes}
var
i: integer;
tmp: TSMBlock;
im: integer;
begin
{$ifdef BASM16}
{dword align local variables in MakeStreamBlock}
if sptr and 3 = 0 then asm push ax; end;
{$endif}
while msglen>0 do begin
MakeStreamBlock(ctx, TPSMBlockW(@tmp), 1);
if msglen<=sose_blocklength then im := integer(msglen)
else im := sose_blocklength;
{$ifdef BASM16}
{Note that the 32 bit access may be unaligned and the latency }
{will be increased, but AFAIK even then the code will be faster}
{than a pure 8 bit access version. In the unlikely event that }
{the unaligned 32 bit access is too slow, remove the lines of }
{code from 'shr cx,2' ... 'jz @@4'.}
asm
push ds
lds si,[ptp]
les di,[ctp]
lea bx,[tmp]
mov cx,[im]
shr cx,2
jz @@2
@@1: db $66; mov ax,ss:[bx]
db $66; xor ax,[si]
db $66; mov es:[di],ax
add si,4
add di,4
add bx,4
dec cx
jnz @@1
@@2: mov cx,[im]
and cx,3
jz @@4
@@3: mov al,ss:[bx]
xor al,[si]
mov es:[di],al
inc si
inc di
inc bx
dec cx
jnz @@3
@@4: mov word ptr [ptp],si
mov word ptr [ctp],di
pop ds
end;
{$else}
{$ifdef FPC}
for i:=0 to pred(im) do begin
pByte(ctp)^ := byte(ptp^) xor tmp[i];
inc(Ptr2Inc(ptp));
inc(Ptr2Inc(ctp));
end;
{$else}
for i:=0 to pred(im) do TPSMBlock(ctp)^[i] := TPSMBlock(ptp)^[i] xor tmp[i];
inc(Ptr2Inc(ptp),im);
inc(Ptr2Inc(ctp),im);
{$endif}
{$endif}
dec(msglen,sose_blocklength);
end;
end;
{---------------------------------------------------------------------------}
procedure sose_keystream_bytes(var ctx: sose_ctx; keystream: pointer; kslen: longint);
{-Generate keystream, kslen: keystream length in bytes}
var
tmp: TSMBlock;
i: word;
begin
{$ifdef BASM16}
{dword align local variables in MakeStreamBlock}
if sptr and 3 = 0 then asm push ax; end;
{$endif}
i := 800*sose_blocklength;
while kslen>=i do begin
MakeStreamBlock(ctx, keystream, 800);
inc(Ptr2Inc(keystream), i);
dec(kslen,i);
end;
i := kslen div sose_blocklength;
if i>0 then begin
MakeStreamBlock(ctx, keystream, i);
inc(Ptr2Inc(keystream),i*sose_blocklength);
dec(kslen,i*sose_blocklength);
end;
if kslen>0 then begin
{here 0 < kslen < sose_blocklength}
MakeStreamBlock(ctx, TPSMBlockW(@tmp), 1);
move(tmp,keystream^,integer(kslen));
end;
end;
{---------------------------------------------------------------------------}
procedure sose_decrypt_bytes(var ctx: sose_ctx; ctp, ptp: pointer; msglen: longint);
{-Bytewise decryption, msglen: message length in bytes}
begin
sose_encrypt_bytes(ctx, ctp, ptp, msglen);
end;
{---------------------------------------------------------------------------}
procedure sose_encrypt_blocks(var ctx: sose_ctx; ptp, ctp: pointer; blocks: word);
{-Blockwise encryption, blocks: length in 80 byte blocks}
begin
sose_encrypt_bytes(ctx, ptp, ctp, longint(Blocks)*sose_blocklength);
end;
{---------------------------------------------------------------------------}
procedure sose_decrypt_blocks(var ctx: sose_ctx; ctp, ptp: pointer; blocks: word);
{-Blockwise decryption, blocks: length in 80 byte blocks}
begin
sose_encrypt_bytes(ctx, ctp, ptp, longint(Blocks)*sose_blocklength);
end;
{---------------------------------------------------------------------------}
procedure sose_encrypt_packet(var ctx: sose_ctx; IV, ptp, ctp: pointer; msglen: longint);
{-All-in-one encryption of (short) packets, msglen: message length in bytes}
{ It is the user's responsibility to supply least 128 accessible IV bits.}
begin
sose_ivsetup(ctx, iv);
sose_encrypt_bytes(ctx, ptp, ctp, msglen);
end;
{---------------------------------------------------------------------------}
procedure sose_decrypt_packet(var ctx: sose_ctx; IV, ctp, ptp: pointer; msglen: longint);
{-All-in-one encryption of (short) packets, msglen: message length in bytes}
{ It is the user's responsibility to supply least 128 accessible IV bits.}
begin
sose_ivsetup(ctx, iv);
sose_encrypt_bytes(ctx, ctp, ptp, msglen);
end;
{---------------------------------------------------------------------------}
procedure sose_keystream_blocks(var ctx: sose_ctx; keystream: pointer; blocks: word);
{-Generate keystream, blocks: keystream length in 80 byte blocks}
begin
{$ifdef BASM16}
{dword align local variables in MakeStreamBlock}
if sptr and 3 = 0 then asm push ax; end;
{$endif}
makeStreamBlock(ctx, keystream, Blocks);
end;
{---------------------------------------------------------------------------}
function sose_selftest: boolean;
{-Simple self-test of Sosemanuk, detailed test vector 2 of eSTREAM submission}
const
key: array[0.. 15] of byte = ($00,$11,$22,$33,$44,$55,$66,$77,$88,$99,$AA,$BB,$CC,$DD,$EE,$FF);
IV: array[0.. 15] of byte = ($88,$99,$AA,$BB,$CC,$DD,$EE,$FF,$00,$11,$22,$33,$44,$55,$66,$77);
ks: array[0..159] of byte = ($FA,$61,$DB,$EB,$71,$17,$81,$31,$A7,$7C,$71,$4B,$D2,$EA,$BF,$4E,
$13,$94,$20,$7A,$25,$69,$8A,$A1,$30,$8F,$2F,$06,$3A,$0F,$76,$06,
$04,$CF,$67,$56,$9B,$A5,$9A,$3D,$FA,$D7,$F0,$01,$45,$C7,$8D,$29,
$C5,$FF,$E5,$F9,$64,$95,$04,$86,$42,$44,$51,$95,$2C,$84,$03,$9D,
$23,$4D,$9C,$37,$EE,$CB,$BC,$A1,$EB,$FB,$0D,$D1,$6E,$A1,$19,$4A,
$6A,$FC,$1A,$46,$0E,$33,$E3,$3F,$E8,$D5,$5C,$48,$97,$70,$79,$C6,
$87,$81,$0D,$74,$FE,$DD,$EE,$1B,$39,$86,$21,$8F,$B1,$E1,$C1,$76,
$5E,$4D,$F6,$4D,$7F,$69,$11,$C1,$9A,$27,$0C,$59,$C7,$4B,$24,$46,
$17,$17,$F8,$6C,$E3,$B1,$18,$08,$FA,$CD,$4F,$2E,$71,$41,$68,$DA,
$44,$CF,$63,$60,$D5,$4D,$DA,$22,$41,$BC,$B7,$94,$01,$A4,$ED,$CC);
var
ctx: sose_ctx;
tmp: array[0..159] of byte;
i,j,len: integer;
begin
sose_selftest := false;
for j:=0 to 1 do begin
len := sizeof(tmp);
if j=1 then dec(len,27);
{if j=1 then check the routines with msglen not a multiple of}
{the blocksize, and that remaining bytes of tmp are untouched.}
if sose_keysetup(ctx, @key, sizeof(key)*8) <> 0 then exit;
fillchar(tmp, sizeof(tmp), 0);
sose_ivsetup(ctx, @IV);
sose_keystream_bytes(ctx, @tmp, len);
for i:=0 to pred(len) do begin
if tmp[i]<>ks[i] then exit;
end;
for i:=len to pred(sizeof(tmp)) do begin
if tmp[i]<>0 then exit;
end;
fillchar(tmp, sizeof(tmp), 0);
sose_ivsetup(ctx, @IV);
sose_encrypt_bytes(ctx, @tmp, @tmp, len);
for i:=0 to pred(len) do begin
if tmp[i]<>ks[i] then exit;
end;
for i:=len to pred(sizeof(tmp)) do begin
if tmp[i]<>0 then exit;
end;
fillchar(tmp, sizeof(tmp), 0);
sose_encrypt_packet(ctx, @IV, @tmp, @tmp, len);
for i:=0 to pred(len) do begin
if tmp[i]<>ks[i] then exit;
end;
for i:=len to pred(sizeof(tmp)) do begin
if tmp[i]<>0 then exit;
end;
end;
sose_selftest := true;
end;
{$ifdef BASM16}
{$ifdef DebugAlign}
begin
writeln('ofs(MulAlpha) and 3 = ', ofs(MulAlpha) and 3);
{$endif}
{$endif}
end.
|
unit asmstring;
interface
uses Classes;
// TAsmStr allows you to assemble a shellcode string piece by piece. Supports
// use of labels and jumps (also forward declarations).
type
TAsmStr = class(TObject)
private
RelBList : TStringList;
RelCList : TStringList;
OffsList : TStringList;
LabelList : TStringList;
Base : Cardinal;
function FindLabel(s : AnsiString; var c : Cardinal) : Boolean;
public
Data : AnsiString;
constructor Create;
destructor Destroy; override;
procedure Init(c : Cardinal);
procedure AddBin(s : AnsiString);
procedure AddHex(s : AnsiString);
procedure AddCVal(c : Cardinal);
procedure AddWVal(w : Word);
procedure AddOffs(s : AnsiString);
procedure AddLabel(s : AnsiString);
procedure AddRelA(c : Cardinal);
procedure AddRelB(s : AnsiString);
procedure AddRelC(s : AnsiString);
function Finalize : Boolean;
end;
implementation
////////////////////////////////////////////////////////////////////////////////
constructor TAsmStr.Create;
begin
inherited Create;
RelBList:=TStringList.Create;
RelCList:=TStringList.Create;
OffsList:=TStringList.Create;
LabelList:=TStringList.Create;
LabelList.Sorted:=True;
end;
////////////////////////////////////////////////////////////////////////////////
destructor TAsmStr.Destroy;
begin
RelBList.Free;
RelCList.Free;
OffsList.Free;
LabelList.Free;
inherited Destroy;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.Init(c : Cardinal);
// resets all lists and variables, also sets base offset
begin
RelBList.Clear;
RelCList.Clear;
OffsList.Clear;
LabelList.Clear;
Base:=c;
Data:='';
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddBin(s : AnsiString);
// adds simple binary code
begin
Data:=Data+s;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddHex(s : AnsiString);
// adds simple code in hex format
var
i : Integer;
b : Byte;
begin
b:=0;
for i:=1 to Length(s) do
begin
b:=b shl 4;
case s[i] of
'0'..'9': b:=b + Byte(s[i]) - 48;
'A'..'F': b:=b + Byte(s[i]) - 55;
'a'..'f': b:=b + Byte(s[i]) - 87;
end;
if i and 1 = 1 then Continue;
Data:=Data+AnsiChar(b);
b:=0;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddCVal(c : Cardinal);
// adds an absolute cardinal
var
s : AnsiString;
begin
s:=#0#0#0#0;
Move(c,s[1],4); // fill buffer
Data:=Data+s; // add buffer
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddWVal(w : Word);
// adds an absolute word
var
s : AnsiString;
begin
s:=#0#0;
Move(w,s[1],2); // fill buffer
Data:=Data+s; // add buffer
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddOffs(s : AnsiString);
// adds an absolute cardinal that points to a label
begin
OffsList.AddObject(s,TObject(Length(Data)));
Data:=Data+#0#0#0#0;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddLabel(s : AnsiString);
// registers a label at the current offset
begin
LabelList.AddObject(s,TObject(Length(Data)));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddRelA(c : Cardinal);
// adds a relative cardinal that points to an external address
var
d : Cardinal;
begin
Data:=Data+#0#0#0#0; // add buffer first
d:=Length(Data);
c:=c-(Base+d); // calculate delta value between target and next position
Move(c,Data[d-3],4); // write delta to buffer
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddRelB(s : AnsiString);
// adds a relative byte that points to a label
begin
RelBList.AddObject(s,TObject(Length(Data)));
Data:=Data+#0;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TAsmStr.AddRelC(s : AnsiString);
// adds a relative cardinal that points to a label
begin
RelCList.AddObject(s,TObject(Length(Data)));
Data:=Data+#0#0#0#0;
end;
////////////////////////////////////////////////////////////////////////////////
function TAsmStr.FindLabel(s : AnsiString; var c : Cardinal) : Boolean;
// returns label offset
var
i : Integer;
begin
Result:=False;
if not LabelList.Find(s,i) then Exit;
c:=Cardinal(LabelList.Objects[i]);
Result:=True;
end;
////////////////////////////////////////////////////////////////////////////////
function TAsmStr.Finalize : Boolean;
// fills in Offs, RelB and RelC based on registered labels
var
c : Cardinal;
src : Cardinal;
trg : Cardinal;
begin
Result:=False; // fail in case of dangling jump without matching label
while OffsList.Count>0 do
begin
if not FindLabel(OffsList[0],c) then Exit;
trg:=Cardinal(OffsList.Objects[0]);
src:=Base+c; // calculate offset
Move(src,Data[1+trg],4); // fill in offset
OffsList.Delete(0);
end;
while RelBList.Count>0 do
begin
if not FindLabel(RelBList[0],c) then Exit;
trg:=Cardinal(RelBList.Objects[0]);
src:=c-(trg+1); // calculate delta
Move(src,Data[1+trg],1); // fill in delta
RelBList.Delete(0);
end;
while RelCList.Count>0 do
begin
if not FindLabel(RelCList[0],c) then Exit;
trg:=Cardinal(RelCList.Objects[0]);
src:=c-(trg+4); // calculate delta
Move(src,Data[1+trg],4); // fill in delta
RelCList.Delete(0);
end;
Result:=True;
end;
////////////////////////////////////////////////////////////////////////////////
end.
|
unit FIToolkit.Commons.Types;
interface
uses
System.SysUtils, System.Rtti;
type
TObjectPropertyFilter = reference to function (Instance : TObject; Prop : TRttiProperty) : Boolean;
TAssignable<T> = record
private
type
TOnChange = reference to procedure (WasAssigned : Boolean; const CurrentValue, OldValue : T);
TOnChanging = reference to procedure (WasAssigned : Boolean; const CurrentValue, NewValue : T;
var AllowChange : Boolean);
TOnUnassign = reference to procedure (WasAssigned : Boolean; const OldValue : T);
strict private
FAssigned : String;
FValue : T;
FOnChange : TOnChange;
FOnChanging : TOnChanging;
FOnUnassign : TOnUnassign;
private
function GetValue : T;
procedure SetValue(const AValue : T);
public
class operator Implicit(const AValue : T) : TAssignable<T>;
class operator Implicit(const AValue : TAssignable<T>) : T;
constructor Create(const AValue : T);
function Assigned : Boolean;
procedure Unassign;
property Value : T read GetValue write SetValue;
property OnChange : TOnChange read FOnChange write FOnChange;
property OnChanging : TOnChanging read FOnChanging write FOnChanging;
property OnUnassign : TOnUnassign read FOnUnassign write FOnUnassign;
end;
TAssignableFileName = TAssignable<TFileName>;
TAssignableString = TAssignable<String>;
implementation
{ TAssignable<T> }
function TAssignable<T>.Assigned : Boolean;
begin
Result := not FAssigned.IsEmpty;
end;
constructor TAssignable<T>.Create(const AValue : T);
begin
SetValue(AValue);
end;
function TAssignable<T>.GetValue : T;
begin
if Assigned then
Result := FValue
else
Result := Default(T);
end;
class operator TAssignable<T>.Implicit(const AValue : T) : TAssignable<T>;
begin
Result := TAssignable<T>.Create(AValue);
end;
class operator TAssignable<T>.Implicit(const AValue : TAssignable<T>) : T;
begin
Result := AValue.Value;
end;
procedure TAssignable<T>.SetValue(const AValue : T);
var
bAllowChange, bWasAssigned : Boolean;
OldValue : T;
begin
bAllowChange := True;
bWasAssigned := Assigned;
OldValue := GetValue;
if System.Assigned(FOnChanging) then
FOnChanging(bWasAssigned, OldValue, AValue, bAllowChange);
if bAllowChange then
begin
FValue := AValue;
FAssigned := True.ToString;
if System.Assigned(FOnChange) then
FOnChange(bWasAssigned, FValue, OldValue);
end;
end;
procedure TAssignable<T>.Unassign;
var
bWasAssigned : Boolean;
OldValue : T;
begin
bWasAssigned := Assigned;
OldValue := GetValue;
FValue := Default(T);
FAssigned := String.Empty;
if System.Assigned(FOnUnassign) then
FOnUnassign(bWasAssigned, OldValue);
end;
end.
|
unit ff7background;
interface
Uses Windows, SysUtils, Classes, Graphics, FF7Types;
function RebuildBackground(Original:TMemoryStream;NewForeground,NewBackground:TBitmap):TMemoryStream;
Type
TFullTile = array[0..15,0..15] of Word;
TTile = array[0..15,0..15] of Byte;
PTile = ^TTile;
TPalettePage = array[Byte] of Word;
PPalettePage = ^TPalettePage;
TPalette = class
private
Data: Pointer;
FSize: Integer;
function GetColour(Idx:Integer):Word;
function GetPage(Idx:Integer):TPalettePage;
public
Constructor CreateFromLevel(Lvl:TStream);
Constructor Create;
Destructor Destroy; Override;
property Colour[Index:Integer]: Word read GetColour;
property Page[Index:Integer]: TPalettePage read GetPage;
property NumColours: Integer read FSize;
end;
TBuildPalette = class(TPalette)
private
public
function GetTilePageIndex(Tile:TFullTile): Integer;
function GetSection: TMemoryStream;
end;
TTileCollection = class
private
Data: Pointer;
FSize: Integer;
function GetTile(Idx:Integer):TTile;
function GetTileEx(X,Y,Page:Integer):TTile;
public
Constructor CreateFromLevel(Lvl:TStream);
Destructor Destroy; Override;
property Tile[Index:Integer]: TTile read GetTile;
property PageTile[I1,I2,I3:Integer]: TTile read GetTileEx;
property NumTiles: Integer read FSize;
end;
TBackground = class
private
Back,Fore: PFF7BgSprite;
NumBack,NumFore: Integer;
Palette: TPalette;
Texture: PByte;
public
Constructor Create;
Destructor Destroy; Override;
function GetSection: TMemoryStream;
function GetPaletteSection: TMemoryStream;
procedure WriteBackground(NewBack:TBitmap);
procedure WriteForeground(NewFore:TBitmap);
end;
implementation
function BuildFieldFile(Src: Array of TStream): TMemoryStream;
begin
end;
Constructor TPalette.CreateFromLevel(Lvl:TStream);
var
Offset,Offset2: Integer;
begin
Inherited Create;
Lvl.Position := 2 + (3+1)*4;
Lvl.ReadBuffer(Offset,4); Inc(Offset,4);
Lvl.ReadBuffer(Offset2,4);
Lvl.Position := Offset + $C;
GetMem(Data,Offset2-Offset);
Lvl.ReadBuffer(Data^,Offset2-Offset);
FSize := (Offset2-Offset) div 2;
end;
Constructor TPalette.Create;
begin
Inherited Create;
FSize := 0; Data := nil;
end;
Destructor TPalette.Destroy;
begin
FreeMem(Data);
Inherited Destroy;
end;
function TPalette.GetColour(Idx:Integer):Word;
var
PW: PWord;
begin
If (Idx<0) or (Idx>=FSize) then Raise EListError.Create('Attempt to access invalid palette entry in FF7Background.TPalette.GetColour!');
PW := Data;
Inc(PW,Idx);
Result := PW^;
end;
function TPalette.GetPage(Idx:Integer):TPalettePage;
var
PPage: PPalettePage;
begin
If (Idx<0) or (Idx>=(FSize div 256)) then Raise EListError.Create('Attempt to access invalid palette page in FF7Background.TPalette.GetPage!');
PPage := Data;
Inc(PPage,Idx);
Result := PPage^;
end;
function TileMatchesPalette(Tile:TFullTile;Palette:TPalettePage):Boolean;
var
I,J,K: Integer;
begin
Result := False;
For I := 0 to 15 do
For J := 0 to 15 do begin
K := 0;
While (K<=$FF) and (Palette[K] <> Tile[I,J]) do Inc(K);
If Palette[K] <> Tile[I,J] then Exit;
end;
Result := True;
end;
function TBuildPalette.GetTilePageIndex(Tile:TFullTile): Integer;
var
I: Integer;
PW: PWord;
begin
For I := 0 to (FSize div $100)-1 do
If TileMatchesPalette(Tile,Page[I]) then begin
Result := I;
Exit;
end;
ReallocMem(Data,(FSize*2)+($200));
PW := Data;
Inc(PW,FSize);
For I := 0 to $FF do begin
PW^ := Tile[ I div 16, I mod 16];
Inc(PW);
end;
Inc(FSize,$100);
Result := (FSize div $100)-1;
end;
function TBuildPalette.GetSection: TMemoryStream;
var
I: Integer;
begin
Result := TMemoryStream.Create; Result.Size := (FSize*2)+$C;
I := Result.Size-4;
Result.Position := 0;
Result.WriteBuffer(I,4);
Result.WriteBuffer(I,4);
I := DEF_PALETTE_CODE;
Result.WriteBuffer(I,4);
Result.WriteBuffer(Data^,FSize*2);
end;
Constructor TTileCollection.CreateFromLevel(Lvl:TStream);
begin
Inherited Create;
end;
Destructor TTileCollection.Destroy;
begin
Inherited Destroy;
end;
function TTileCollection.GetTile(Idx:Integer):TTile;
begin
end;
function TTileCollection.GetTileEx(X,Y,Page:Integer):TTile;
begin
end;
Constructor TBackground.Create;
begin
end;
Destructor TBackground.Destroy;
begin
end;
function TBackground.GetSection: TMemoryStream;
begin
end;
function TBackground.GetPaletteSection: TMemoryStream;
begin
end;
procedure TBackground.WriteBackground(NewBack:TBitmap);
begin
end;
procedure TBackground.WriteForeground(NewFore:TBitmap);
begin
end;
function GetTileFromBitmap(Src:TBitmap;SrcX,SrcY:Integer):TFullTile;
var
Tmp: TBitmap;
PW: PWord;
Output,I,J: Integer;
begin
Tmp := TBitmap.Create;
With Tmp do begin
Height := Src.Height;
Width := Src.Width;
PixelFormat := pf15Bit;
Canvas.Draw(0,0,Src);
end;
Output := 0;
For I := SrcY to (SrcY+15) do begin
PW := Tmp.ScanLine[I]; Inc(PW,SrcX);
For J := 0 to 15 do begin
Result[Output,J] := PW^;
Inc(PW);
end;
Inc(Output);
end;
Tmp.Free;
end;
function TilesAreSame(Tile1,Tile2:TTile;Pal1,Pal2:TPalettePage):Boolean;
var
I,J: Integer;
begin
Result := False; I := 0;
For I := 0 to 15 do
For J := 0 to 15 do
If Pal1[Tile1[I,J]]<>Pal2[Tile2[I,J]] then Exit;
Result := True;
end;
function GetPalColour(Pal:TPalettePage;Colour:Word): Byte;
var
I: Integer;
begin
For I := 0 to $FF do
If Pal[I]=Colour then begin
Result := I; Exit;
end;
end;
function PalettizeFullTile(Original:TFullTile;Palette:TPalettePage): TTile;
var
I,J: Integer;
begin
For I := 0 to $F do
For J := 0 to $F do
Result[I,J] := GetPalColour(Palette,Original[I,J]);
end;
function SpritesAreSame(Spr1,Spr2:TFF7BgSprite;Palette:TPalette;Tiles:TTileCollection):Boolean;
var
Page1,Page2: TPalettePage;
begin
Page1 := Palette.Page[Spr1.Pal];
Page2 := Palette.Page[Spr2.Pal];
Result := TilesAreSame(Tiles.PageTile[Spr1.SrcX,Spr1.SrcY,Spr1.Page],Tiles.PageTile[Spr2.SrcX,Spr2.SrcY,Spr2.Page],Page1,Page2);
end;
function RebuildBackground(Original:TMemoryStream;NewForeground,NewBackground:TBitmap):TMemoryStream;
begin
Result := nil;
end;
end.
|
unit Test.Devices.Vacon.ReqCreator;
interface
uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst;
type
TVaconNXLReqCreatorTest = class(TDeviceReqCreatorTestBase)
protected
function GetDevType(): int; override;
procedure DoCheckRequests(); override;
end;
implementation
{ TVaconNXLReqCreatorTest }
procedure TVaconNXLReqCreatorTest.DoCheckRequests;
begin
CheckReqHexString(0, '1, 3, 8, 38, 0, 1, 7, A7');
CheckReqHexString(1, '1, 3, 8, 39, 0, 1, 56, 67');
CheckReqHexString(2, '1, 3, 8, 3E, 0, 1, E7, A6');
CheckReqHexString(3, '1, 3, 8, 3B, 0, 1, F7, A7');
CheckReqHexString(4, '1, 3, 7, D2, 0, 1, 25, 47');
CheckReqHexString(5, '1, 3, 7, D3, 0, 1, 74, 87');
end;
function TVaconNXLReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_VACON_NXL;
end;
initialization
RegisterTest('GMIOPSrv/Devices/Vacon', TVaconNXLReqCreatorTest.Suite);
end.
|
unit uwebsockClock;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SynCommons, SynCrtSock, SynBidirSock;
type
TWebsocketClockincoming = procedure(const msg:RawByteString) of object;
{ TWebSocketProtocolClock }
TWebSocketProtocolClock = class(TWebSocketProtocolChat)
private
fIncoming: TWebsocketClockincoming;
public
procedure InComingMsg(Sender: THttpServerResp; const Frame: TWebSocketFrame);
property Incoming:TWebsocketClockincoming read fIncoming write fIncoming;
end;
{ TWebsocketClockServer }
TWebsocketClockServer=class
private
fServer:TWebSocketServer;
fProtocol:TWebSocketProtocolClock;
protected
public
constructor Create(const Port, Name: string);
destructor Destroy; override;
procedure BroadcastMsg(const msg: RawByteString);
property Protocol:TWebSocketProtocolClock read fProtocol;
end;
implementation
{ TWebSocketProtocolClock }
procedure TWebSocketProtocolClock.InComingMsg(Sender: THttpServerResp;
const Frame: TWebSocketFrame);
var
sout:RawByteString;
begin
case Frame.opcode of
focText, focBinary :
if Assigned(fIncoming) then begin
fIncoming(Frame.payload);
end;
end;
end;
{ TWebsocketClockServer }
constructor TWebsocketClockServer.Create(const Port,Name: string);
begin
fServer:=TWebSocketServer.Create(Port,nil,nil,Name);
fProtocol:=TWebSocketProtocolClock.Create('chatclock','');
fProtocol.OnIncomingFrame:=@fProtocol.InComingMsg;
fServer.WebSocketProtocols.Add(fProtocol);
end;
destructor TWebsocketClockServer.Destroy;
begin
fServer.Free;
inherited Destroy;
end;
procedure TWebsocketClockServer.BroadcastMsg(const msg:RawByteString);
var
outmsg:TWebSocketFrame;
begin
outmsg.opcode:=focText;
outmsg.payload:=msg;
fServer.WebSocketBroadcast(outmsg);
end;
end.
|
unit Test.Devices.Vzlet;
interface
uses Windows, TestFrameWork, Devices.Vzlet;
type
TVzletTest = class(TTestCase)
private
protected
published
procedure CRC();
end;
implementation
{ VzletTest }
procedure TVzletTest.CRC;
var buf: array [0..10] of byte;
begin
buf[0] := $01;
buf[1] := $04;
buf[2] := $C1;
buf[3] := $AA;
buf[4] := $00;
buf[5] := $02;
buf[6] := $6C;
buf[7] := $17;
Check(Vzlet_CheckCRC(buf, 8), 'Vzlet good CRC');
buf[0] := $02;
Check(not Vzlet_CheckCRC(buf, 8), 'Vzlet bad CRC');
end;
initialization
RegisterTest('GMIOPSrv/Devices/Vzlet', TVzletTest.Suite);
end.
|
unit IdDICTServer;
interface
uses
Classes,
IdGlobal,
IdTCPServer;
const
KnownCommands: array[1..10] of string =
(
'AUTH',
'CLIENT',
'DEFINE',
'HELP',
'MATCH',
'OPTION',
'QUIT',
'SASLAUTH',
'SHOW',
'STATUS'
);
type
TIdDICTGetEvent = procedure(Thread: TIdPeerThread) of object;
TIdDICTOtherEvent = procedure(Thread: TIdPeerThread; Command, Parm: string) of
object;
TIdDICTDefineEvent = procedure(Thread: TIdPeerThread; Database, WordToFind:
string) of object;
TIdDICTMatchEvent = procedure(Thread: TIdPeerThread; Database, Strategy,
WordToFind: string) of object;
TIdDICTShowEvent = procedure(Thread: TIdPeerThread; Command: string) of
object;
TIdDICTAuthEvent = procedure(Thread: TIdPeerThread; Username, authstring:
string) of object;
TIdDICTServer = class(TIdTCPServer)
protected
fOnCommandHELP: TIdDICTGetEvent;
fOnCommandDEFINE: TIdDICTDefineEvent;
fOnCommandMATCH: TIdDICTMatchEvent;
fOnCommandQUIT: TIdDICTGetEvent;
fOnCommandSHOW: TIdDICTShowEvent;
fOnCommandAUTH, fOnCommandSASLAuth: TIdDICTAuthEvent;
fOnCommandOption: TIdDICTOtherEvent;
fOnCommandSTAT: TIdDICTGetEvent;
fOnCommandCLIENT: TIdDICTShowEvent;
fOnCommandOther: TIdDICTOtherEvent;
function DoExecute(Thread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
property DefaultPort default IdPORT_DICT;
property OnCommandHelp: TIdDICTGetEvent read fOnCommandHelp write
fOnCommandHelp;
property OnCommandDefine: TIdDICTDefineEvent read fOnCommandDefine write
fOnCommandDefine;
property OnCommandMatch: TIdDICTMatchEvent read fOnCommandMatch write
fOnCommandMatch;
property OnCommandQuit: TIdDICTGetEvent read fOnCommandQuit write
fOnCommandQuit;
property OnCommandShow: TIdDICTShowEvent read fOnCommandShow write
fOnCommandShow;
property OnCommandAuth: TIdDICTAuthEvent read fOnCommandAuth write
fOnCommandAuth;
property OnCommandSASLAuth: TIdDICTAuthEvent read fOnCommandSASLAuth write
fOnCommandSASLAuth;
property OnCommandOption: TIdDICTOtherEvent read fOnCommandOption write
fOnCommandOption;
property OnCommandStatus: TIdDICTGetEvent read fOnCommandStat write
fOnCommandStat;
property OnCommandClient: TIdDICTShowEvent read fOnCommandClient write
fOnCommandClient;
property OnCommandOther: TIdDICTOtherEvent read fOnCommandOther write
fOnCommandOther;
end;
implementation
uses
IdResourceStrings,
SysUtils;
constructor TIdDICTServer.Create(AOwner: TComponent);
begin
inherited;
DefaultPort := IdPORT_DICT;
end;
function TIdDICTServer.DoExecute(Thread: TIdPeerThread): boolean;
var
s, sCmd, sCmd2: string;
procedure NotHandled;
begin
Thread.Connection.Writeln('500 ' + RSCMDNotRecognized);
end;
begin
result := true;
s := Thread.Connection.ReadLn;
sCmd := UpperCase(Fetch(s));
case Succ(PosInStrArray(Uppercase(sCmd), KnownCommands)) of
1: {auth}
if assigned(OnCommandAuth) then
begin
sCmd2 := UpperCase(Fetch(s));
OnCommandAuth(Thread, sCmd2, S);
end
else
NotHandled;
2: {client}
if assigned(OnCommandClient) then
OnCommandClient(Thread, S)
else
NotHandled;
3: {define}
if assigned(OnCommandHelp) then
begin
sCmd2 := UpperCase(Fetch(s));
OnCommandHelp(Thread);
end
else
NotHandled;
4: {help}
if assigned(OnCommandHelp) then
OnCommandHelp(Thread)
else
NotHandled;
5: {match}
if assigned(OnCommandMatch) then
begin
sCmd := UpperCase(Fetch(s));
sCmd2 := UpperCase(Fetch(s));
OnCommandMatch(Thread, sCmd, sCmd2, S);
end
else
NotHandled;
6: {option}
if assigned(OnCommandOption) then
OnCommandOption(Thread, s, '')
else
NotHandled;
7: {quit}
if assigned(OnCommandQuit) then
OnCommandQuit(Thread)
else
NotHandled;
8: {saslauth}
if assigned(OnCommandSASLAuth) then
begin
sCmd2 := UpperCase(Fetch(s));
OnCommandSASLAuth(Thread, sCmd2, s);
end
else
NotHandled;
9: {show}
if assigned(OnCommandShow) then
OnCommandShow(Thread, s)
else
NotHandled;
10: {status}
if assigned(OnCommandStatus) then
OnCommandStatus(Thread)
else
NotHandled;
else
begin
if assigned(OnCommandOther) then
OnCommandOther(Thread, sCmd, S);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ExpertsUIInternalWizard;
interface
uses
Windows, ToolsApi, Controls, Forms, SysUtils, Classes, Dialogs, ComObj,
WizardAPI,
Generics.Collections, ExpertsUIIniOptions,
Graphics;
type
IPageMrWizard = interface
['{96A05927-BD09-4C2E-93F6-98D535CAEA34}']
function GetImage: TBitmap;
function LoadImage: TBitmap;
procedure UpdateButtons;
procedure UpdateSteps;
end;
TCustomPageMrWizard = class(TInterfacedObject, IMrWizard, IPageMrWizard)
strict private
{ Wizard Info }
FWizard: IWizard;
FHelpContext: Integer;
FCaption: string;
FBitmap: TBitmap;
{ Ini info }
FUIOptions: TWizardIniOptions;
procedure InitOptions(const AOptionsFileName: string);
private
procedure AddFirstPage(out AID: TGuid; out AName: string);
{ IMrWizard }
procedure Start;
function FirstPage: IWizardPage;
procedure Cancel;
function GetWizard: IWizard;
procedure SetWizard(const Value: IWizard);
function GetPersonality: string;
{ IPageMrWizard }
function GetImage: TBitmap;
function HandleFirstPage(const CurrentPage: IWizardPage): IWizardPage;
procedure UpdateButtons; virtual;
procedure UpdateSteps;
protected
{ Wizard Utility functions }
function CanFinish: Boolean; virtual;
function GetFirstPage: IWizardpage; virtual;
procedure DoOnShowing; virtual;
procedure Finish; virtual;
function Caption: string;
function GetHelpContext: Integer;
procedure AddSelectablePages(const ParentID: TGUID; const ParentName: string); virtual;
function GetFirstPageGuidAndName(out AID: TGUID; out AName: string): Boolean; virtual;
function HasSelectablePages: Boolean; virtual;
function FirstSelectablePage: IWizardpage; virtual;
property Wizard: IWizard read GetWizard;
function LoadImage: TBitmap; virtual;
public
constructor Create(const ACaption: string;
AHelpContext: Integer; const AImage: string; const AOptionsFile: string);
destructor Destroy; override;
end;
TCustomMrWizardPageClass = class(TPersistent)
protected
procedure AssignTo(Dest: TPersistent); override;
public
Name: string;
Guid: TGUID;
end;
TPageListMrWizard = class(TCustomPageMrWizard, IWizardEvents)
private
function GetNextPageDictionary: TDictionary<string, TCustomMrWizardPageClass>;
procedure UpdatePageCount(AList: TList<TCustomMrWizardPageClass>); overload;
function GetSelectedPageList: TList<TCustomMrWizardPageClass>;
function ClonePage(APage: TCustomMrWizardPageClass): TCustomMrWizardPageClass;
function GetPageCount(AList: TList<TCustomMrWizardPageClass>): Integer;
function GetPageIndex(AList: TList<TCustomMrWizardPageClass>): Integer;
procedure UpdateButtonsInternal(AList: TList<TCustomMrWizardPageClass>);
protected
procedure UpdatePageCount; overload;
{ IWizardEvents }
procedure OnEnterPage(LastPage, CurrentPage: IWizardPage; PageTransition: TPageTransition); virtual;
procedure OnLeavePage(WizardPage: IWizardPage; PageTransition: TPageTransition); virtual;
procedure OnLeavingPage(WizardPage: IWizardPage; PageTransition: TPageTransition; var Allow: Boolean); virtual;
function IsPageSelected(APage: TCustomMrWizardPageClass): Boolean; virtual;
function CreateWizardPage(APage: TCustomMrWizardPageClass): IWizardPage; virtual;
procedure GetSelectablePages(AList: TList<TCustomMrWizardPageClass>); virtual;
function HandleNextPage(const CurrentPage: IWizardPage): IWizardPage;
procedure AddSelectablePages(const ParentID: TGUID; const ParentName: string); override; final;
function HasSelectablePages: Boolean; override; final;
function FirstSelectablePage: IWizardpage; override; final;
public
constructor Create(const ACaption: string;
AHelpContext: Integer; const AImageName: string; const AOptionsFileName: string);
procedure UpdateButtons; override;
end;
TCustomMrWizardPage = class(TWizardPage, IWizardPage, IWizardPageEvents, IWizardPageStatus)
private
FID: TGuid;
{ IWizardPage }
function Close: Boolean;
procedure Clear;
protected
procedure UpdateInfo; virtual;
{ IWizardPage }
function Page: TFrame; virtual;
{ IWizardPageStatus }
function IsComplete: Boolean; virtual;
{ IWizardPageEvents }
procedure OnLeavingPage(PageTransition: TPageTransition; var Allow: Boolean); virtual;
procedure OnEnterPage(PageTransition: TPageTransition); virtual;
procedure OnLeavePage(PageTransition: TPageTransition); virtual;
public
function PageID: TGUID; override;
constructor Create(AID: TGuid; const AName, ATitle, ADescription: string);
function GetImage: TBitmap; override;
end;
const
// Wizard control margins
cRadioLeftMargin = 10;
cLabelLeftMargin = 10;
implementation
{ TPageListMrWizard }
constructor TPageListMrWizard.Create(const ACaption: string;
AHelpContext: Integer; const AImageName: string; const AOptionsFileName: string);
begin
inherited;
end;
function TPageListMrWizard.IsPageSelected(APage: TCustomMrWizardPageClass): Boolean;
begin
Result := True;
end;
procedure TPageListMrWizard.OnEnterPage(LastPage, CurrentPage: IWizardPage;
PageTransition: TPageTransition);
begin
UpdatePageCount;
end;
procedure TPageListMrWizard.OnLeavePage(WizardPage: IWizardPage;
PageTransition: TPageTransition);
begin
end;
procedure TPageListMrWizard.OnLeavingPage(WizardPage: IWizardPage;
PageTransition: TPageTransition; var Allow: Boolean);
begin
end;
function TPageListMrWizard.CreateWizardPage(APage: TCustomMrWizardPageClass): IWizardPage;
begin
Result := nil;
end;
function TPageListMrWizard.GetNextPageDictionary: TDictionary<string, TCustomMrWizardPageClass>;
var
LList: TList<TCustomMrWizardPageClass>;
LPage: TCustomMrWizardPageClass;
LPrevPage: string;
begin
LPrevPage := GetFirstPage.Name;
LList := GetSelectedPageList;
try
Result := TObjectDictionary<string, TCustomMrWizardPageClass>.Create([doOwnsValues]);
for LPage in LList do
begin
Result.Add(LPrevPage, ClonePage(LPage));
LPrevPage := LPage.Name;
end;
finally
LList.Free;
end;
end;
function TPageListMrWizard.ClonePage(APage: TCustomMrWizardPageClass): TCustomMrWizardPageClass;
begin
Result := TCustomMrWizardPageClass(APage.ClassType.Create);
Result.Assign(APage);
end;
procedure TPageListMrWizard.GetSelectablePages(AList: TList<TCustomMrWizardPageClass>);
begin
Assert(False);
end;
function TPageListMrWizard.GetSelectedPageList: TList<TCustomMrWizardPageClass>;
var
LList: TList<TCustomMrWizardPageClass>;
LPage: TCustomMrWizardPageClass;
begin
LList := TObjectList<TCustomMrWizardPageClass>.Create;
GetSelectablePages(LList);
try
Result := TObjectList<TCustomMrWizardPageClass>.Create;
for LPage in LList do
if IsPageSelected(LPage) then
Result.Add(ClonePage(LPage));
finally
LList.Free;
end;
end;
// Handler to get next page
function TPageListMrWizard.HandleNextPage(
const CurrentPage: IWizardPage): IWizardPage;
var
LNextPage: TCustomMrWizardPageClass;
LDictionary: TDictionary<string, TCustomMrWizardPageClass>;
LLastPage: Boolean;
begin
LLastPage := True;
Result := nil;
LDictionary := GetNextPageDictionary;
try
if LDictionary.TryGetValue(CurrentPage.Name, LNextPage) then
begin
Result := CreateWizardPage(LNextPage);
LLastPage := not LDictionary.ContainsKey(LNextPage.Name);
end;
finally
LDictionary.Free;
end;
// Causes problems when validation of a page fails
// Wizard.Finish := LLastPage;
// Wizard.Next := not LLastPage;
end;
procedure TPageListMrWizard.UpdatePageCount;
var
LList: TList<TCustomMrWizardPageClass>;
begin
LList := GetSelectedPageList;
try
UpdatePageCount(LList);
finally
LList.Free;
end;
end;
procedure TPageListMrWizard.UpdateButtons;
var
LList: TList<TCustomMrWizardPageClass>;
begin
LList := GetSelectedPageList;
try
UpdateButtonsInternal(LList);
finally
LList.Free;
end;
end;
function TPageListMrWizard.GetPageCount(AList: TList<TCustomMrWizardPageClass>): Integer;
begin
Result := AList.Count+1;
end;
function TPageListMrWizard.GetPageIndex(AList: TList<TCustomMrWizardPageClass>): Integer;
var
LName: string;
I: Integer;
begin
if Wizard.CurrentPage <> nil then
begin
if Wizard.CurrentPage = GetFirstPage then
Exit(1)
else
begin
LName := Wizard.CurrentPage.Name;
for I := 0 to AList.Count - 1 do
if AList[I].Name = LName then
begin
Exit(I + 2);
end;
end;
end;
Assert(False);
Result := 0;
end;
procedure TPageListMrWizard.UpdatePageCount(AList: TList<TCustomMrWizardPageClass>);
var
LPageCount: Integer;
LPageIndex: Integer;
begin
if Wizard.CurrentPage <> nil then
begin
LPageCount := GetPageCount(AList);
LPageIndex := GetPageIndex(AList);
Assert(LPageIndex <> 0);
Wizard.PageCount := LPageCount;
Wizard.PageIndex := LPageIndex;
UpdateButtonsInternal(AList);
end;
end;
procedure TPageListMrWizard.UpdateButtonsInternal(AList: TList<TCustomMrWizardPageClass>);
var
LPageCount: Integer;
LPageIndex: Integer;
begin
if Wizard.CurrentPage <> nil then
begin
LPageCount := GetPageCount(AList);
LPageIndex := GetPageIndex(AList);
Wizard.Next := LPageIndex < LPageCount;
Wizard.Finish := (LPageIndex = LPageCount) or CanFinish;
Wizard.Back := LPageIndex > 1;
end;
end;
// override
procedure TPageListMrWizard.AddSelectablePages(const ParentID: TGUID; const ParentName: string);
var
LParentID: TGUID;
LParentName: string;
procedure AddPage(const ChildID: TGUID; const ChildName: string;
Callback: TWizardFunctionCallback; AllowBack: Boolean);
begin
Wizard.AddPage(LParentID, LParentName, ChildId,
ChildName, Callback, AllowBack);
LParentID := ChildId;
LParentName := ChildName;
end;
var
LList: TList<TCustomMrWizardPageClass>;
LPage: TCustomMrWizardPageClass;
begin
LParentID := ParentID;
LParentName := ParentName;
LList := TObjectList<TCustomMrWizardPageClass>.Create;
GetSelectablePages(LList);
try
for LPage in LList do
AddPage(LPage.Guid, LPage.Name, HandleNextPage, True);
UpdatePageCount(LList);
finally
LList.Free;
end;
end;
// override;
function TPageListMrWizard.HasSelectablePages: Boolean;
var
LList: TList<TCustomMrWizardPageClass>;
begin
LList := GetSelectedPageList;
try
Result := LList.Count > 0;
finally
LList.Free;
end;
end;
// override
function TPageListMrWizard.FirstSelectablePage: IWizardpage;
var
LList: TList<TCustomMrWizardPageClass>;
begin
LList := GetSelectedPageList;
try
Assert(LList.Count > 0);
Result := CreateWizardPage(LList[0]);
// Wizard.Next := LList.Count > 1;
// Wizard.Finish := (LList.Count = 1) or CanFinish;
finally
LList.Free;
end;
end;
{ TCustomMrWizardPageClass }
procedure TCustomMrWizardPageClass.AssignTo(Dest: TPersistent);
begin
if Dest is TCustomMrWizardPageClass then
begin
TCustomMrWizardPageClass(Dest).Name := Name;
TCustomMrWizardPageClass(Dest).Guid := Guid;
end
else
inherited;
end;
{ TCustomMrWizardPage }
procedure TCustomMrWizardPage.Clear;
begin
end;
function TCustomMrWizardPage.Close: Boolean;
begin
Result := True;
end;
constructor TCustomMrWizardPage.Create(AID: TGuid; const AName, ATitle, ADescription: string);
begin
inherited Create;
FID := AID;
Title := ATitle;
Description := ADescription;
Name := AName;
end;
// override
function TCustomMrWizardPage.GetImage: TBitmap;
var
Intf: IPageMrWizard;
begin
if Supports(Wizard.MrWizard, IPageMrWizard, Intf) then
Result := Intf.GetImage
else
Result := nil;
end;
function TCustomMrWizardPage.IsComplete: Boolean;
begin
Result := False;
end;
procedure TCustomMrWizardPage.OnEnterPage(PageTransition: TPageTransition);
begin
UpdateInfo;
end;
procedure TCustomMrWizardPage.OnLeavePage(PageTransition: TPageTransition);
begin
end;
procedure TCustomMrWizardPage.OnLeavingPage(PageTransition: TPageTransition;
var Allow: Boolean);
begin
end;
function TCustomMrWizardPage.Page: TFrame;
begin
Assert(False);
Result := nil;
end;
procedure TCustomMrWizardPage.UpdateInfo;
begin
end;
// override
function TCustomMrWizardPage.PageID: TGUID;
begin
Result := FID;
end;
const
{ Wizard State }
ivFormTop = 'FormTop';
ivFormLeft = 'FormLeft';
ivFormWidth = 'FormWidth';
ivFormHeight = 'FormHeight';
procedure TCustomPageMrWizard.InitOptions(const AOptionsFileName: string);
begin
TWizardIniOptions.InitOptions(AOptionsFileName, FUIOptions);
end;
function TCustomPageMrWizard.LoadImage: TBitmap;
begin
Result := nil;
end;
//function TCustomPageMrWizard.LoadImage: TBitmap;
//begin
// if FImageName <> '' then
// Result := LoadImage(FImageName)
// else
// Result := nil;
//end;
//function TCustomPageMrWizard.LoadImage(Instance: THandle; const ResourceName: string): TBitmap;
//begin
// Result := TBitmap.Create;
// try
// Result.LoadFromResourceName(Instance, ResourceName);
// except
// FreeAndNil(Result);
// end;
//end;
constructor TCustomPageMrWizard.Create(const ACaption: string;
AHelpContext: Integer; const AImage: string; const AOptionsFile: string);
begin
inherited Create;
FCaption := ACaption;
FHelpContext := AHelpContext;
FWizard := nil;
// FImageName := AImage;
InitOptions(AOptionsFile);
end;
destructor TCustomPageMrWizard.Destroy;
begin
FWizard := nil;
FUIOPtions.Free;
FBitmap.Free;
inherited;
end;
procedure TCustomPageMrWizard.DoOnShowing;
begin
//
end;
function TCustomPageMrWizard.CanFinish: Boolean;
begin
Result := False;
end;
procedure TCustomPageMrWizard.AddFirstPage(out AID: TGUID; out AName: string);
begin
if GetFirstPageGuidAndName(AID, AName) then
begin
Wizard.AddPage(AID,
AName, HandleFirstPage);
end;
end;
// Called to initialize wizard when first page is shown
function TCustomPageMrWizard.HandleFirstPage(const CurrentPage: IWizardPage): IWizardPage;
begin
// Wizard.Back := False;
// Wizard.Next := HasSelectablePages;
// Wizard.Finish := (not HasSelectablePages) or CanFinish;
// Wizard.Cancel := True;
if HasSelectablePages then
Result := FirstSelectablePage;
end;
procedure TCustomPageMrWizard.Cancel;
begin
if FUIOptions <> nil then
begin
FUIOptions[ivFormLeft] := Wizard.WizardForm.Left;
FUIOptions[ivFormTop] := Wizard.WizardForm.Top;
FUIOptions[ivFormWidth] := Wizard.WizardForm.Width;
FUIOptions[ivFormHeight] := Wizard.WizardForm.Height;
end;
end;
procedure TCustomPageMrWizard.Start;
var
LID: TGUID;
LName: string;
begin
if Wizard <> nil then
begin
if FUIOptions <> nil then
begin
Wizard.WizardForm.Left := FUIOptions.GetOption(ivFormLeft, Wizard.WizardForm.Left);
Wizard.WizardForm.Top := FUIOptions.GetOption(ivFormTop, Wizard.WizardForm.Top);
Wizard.WizardForm.Width := FUIOptions.GetOption(ivFormWidth, Wizard.WizardForm.Width);
Wizard.WizardForm.Height := FUIOptions.GetOption(ivFormHeight, Wizard.WizardForm.Height);
end;
DoOnShowing;
AddFirstPage(LID, LName);
// Add all pages, even if they are not currently selectable
//if HasSelectablePages then
AddSelectablePages(LID,
LName);
end;
end;
procedure TCustomPageMrWizard.UpdateButtons;
begin
end;
procedure TCustomPageMrWizard.UpdateSteps;
begin
if Wizard <> nil then
Wizard.UpdateSteps;
end;
function TCustomPageMrWizard.HasSelectablePages: Boolean;
begin
Result := False;
end;
procedure TCustomPageMrWizard.AddSelectablePages(const ParentID: TGUID; const ParentName: string);
begin
Assert(False);
end;
procedure TCustomPageMrWizard.Finish;
begin
if FUIOptions <> nil then
begin
FUIOptions[ivFormLeft] := Wizard.WizardForm.Left;
FUIOptions[ivFormTop] := Wizard.WizardForm.Top;
FUIOptions[ivFormWidth] := Wizard.WizardForm.Width;
FUIOptions[ivFormHeight] := Wizard.WizardForm.Height;
end;
end;
function TCustomPageMrWizard.FirstSelectablePage: IWizardpage;
begin
Assert(False);
end;
function TCustomPageMrWizard.FirstPage: IWizardpage;
begin
Result := GetFirstPage as IWizardPage;
// Wizard.Back := False;
// Wizard.Next := True;
// Wizard.Finish := CanFinish;
// Wizard.Cancel := True;
end;
function TCustomPageMrWizard.GetFirstPage: IWizardpage;
begin
Assert(False); // Ancestor must override
end;
function TCustomPageMrWizard.GetFirstPageGuidAndName(out AID: TGUID;
out AName: string): Boolean;
begin
AID := TGuid.Empty;
AName := '';
Result := False;
end;
function TCustomPageMrWizard.GetHelpContext: Integer;
begin
Result := FHelpContext;
end;
function TCustomPageMrWizard.GetImage: TBitmap;
begin
if FBitmap = nil then
FBitmap := LoadImage;
Result := FBitmap;
end;
function TCustomPageMrWizard.Caption: string;
begin
Result := FCaption;
end;
function TCustomPageMrWizard.GetPersonality: string;
begin
// Just return current personality
Result := PersonalityServices.CurrentPersonality;
end;
function TCustomPageMrWizard.GetWizard: IWizard;
begin
Result := FWizard;
end;
procedure TCustomPageMrWizard.SetWizard(const Value: IWizard);
begin
FWizard := Value;
end;
end.
|
unit MainFormU;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Data.DB,
Vcl.ExtCtrls,
Vcl.FileCtrl,
Vcl.ComCtrls,
Vcl.Grids,
Vcl.DBGrids,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
Vcl.OleCtrls,
SHDocVw,
System.Generics.Collections;
type
TDataItem = class
private
fProp2: string;
fProp3: string;
fProp1: string;
fPropInt: Integer;
public
constructor Create(const Value1, Value2, Value3: string; const IntValue: Integer);
property Prop1: string read fProp1 write fProp1;
property Prop2: string read fProp2 write fProp2;
property Prop3: string read fProp3 write fProp3;
property PropInt: Integer read fPropInt write fPropInt;
end;
TMainForm = class(TForm)
ds1: TFDMemTable;
ds1name: TStringField;
FileListBox1: TFileListBox;
Panel1: TPanel;
Button1: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
chkOpenGeneratedFile: TCheckBox;
ds2: TFDMemTable;
ds1id: TIntegerField;
ds2id: TIntegerField;
ds2contact: TStringField;
ds2contact_type: TStringField;
ds2id_person: TIntegerField;
DataSource1: TDataSource;
DataSource2: TDataSource;
TabSheet3: TTabSheet;
DBGrid1: TDBGrid;
DBGrid2: TDBGrid;
Splitter1: TSplitter;
Splitter2: TSplitter;
ds1country: TStringField;
MemoTemplate: TMemo;
MemoOutput: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FileListBox1DblClick(Sender: TObject);
private
function GetItems: TObjectList<TObject>;
procedure GenerateReport(const aTemplateString: string);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
System.IOUtils,
Winapi.Shellapi,
RandomTextUtilsU,
TemplateProU,
Winapi.ActiveX;
procedure TMainForm.Button1Click(Sender: TObject);
begin
GenerateReport(MemoTemplate.Lines.Text);
end;
procedure TMainForm.FileListBox1DblClick(Sender: TObject);
begin
PageControl1.ActivePageIndex := 1;
if tfile.Exists(FileListBox1.FileName) then
MemoTemplate.Lines.LoadFromFile(FileListBox1.FileName, TEncoding.UTF8);
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
I: Integer;
J: Integer;
lName: string;
lLastName: string;
begin
ds1.Open;
ds2.Open;
for I := 1 to 100 do
begin
lName := GetRndFirstName;
lLastName := getrndlastname;
ds1.AppendRecord([I, lName + ' ' + lLastName, GetRndCountry]);
for J := 1 to Random(15) + 2 do
begin
ds2.AppendRecord([I * 100 + J, I, Format('%s.%s@%s.com', [lName.Substring(0, 1).ToLower,
lLastName.ToLower, GetRndCountry.ToLower]), 'email']);
end;
end;
ds1.First;
ds2.First;
// Button2Click(self);
end;
// http://www.cryer.co.uk/brian/delphi/twebbrowser/put_HTML.htm
procedure LoadHtmlIntoBrowser(browser: TWebBrowser; const html: string);
var
lSWriter: TStreamWriter;
begin
// -------------------
// Load a blank page.
// -------------------
browser.Navigate('about:blank');
while browser.ReadyState <> READYSTATE_COMPLETE do
begin
Sleep(5);
Application.ProcessMessages;
end;
// ---------------
// Load the html.
// ---------------
lSWriter := TStreamWriter.Create(TMemoryStream.Create);
try
lSWriter.OwnStream;
lSWriter.Write(html);
lSWriter.BaseStream.Position := 0;
(browser.Document as IPersistStreamInit).Load(
TStreamAdapter.Create(lSWriter.BaseStream));
finally
lSWriter.Free;
end;
end;
procedure TMainForm.GenerateReport(const aTemplateString: string);
var
lTPEngine: TTemplateProEngine;
lTemplate: string;
lOutputFileName: string;
lOutput: string;
lOutputStream: TStringStream;
lItems: TObjectList<TObject>;
begin
// MemoTemplate.Lines.LoadFromFile(aReport);
ds1.First;
lTemplate := aTemplateString;
lTPEngine := TTemplateProEngine.Create(TEncoding.UTF8);
try
lTPEngine.SetVar('first_name', 'Daniele');
lTPEngine.SetVar('last_name', 'Teti');
lTPEngine.SetVar('today', DateToStr(date));
lOutputStream := TStringStream.Create('', TEncoding.UTF8);
try
lItems := GetItems;
try
lTPEngine.Execute(
aTemplateString,
['items'], [lItems],
['people', 'contacts'], [ds1, ds2],
lOutputStream);
finally
lItems.Free;
end;
TDirectory.CreateDirectory(ExtractFilePath(Application.ExeName) + 'output');
lOutputFileName := ExtractFilePath(Application.ExeName) + 'output\' +
'last_output.html';
lOutput := lOutputStream.DataString;
// LoadHtmlIntoBrowser(wb, lOutput);
tfile.WriteAllText(lOutputFileName, lOutput);
MemoOutput.Lines.LoadFromFile(lOutputFileName);
finally
lOutputStream.Free;
end;
finally
lTPEngine.Free;
end;
if chkOpenGeneratedFile.Checked then
ShellExecute(0, pchar('open'), pchar(lOutputFileName), nil, nil, SW_NORMAL);
PageControl1.ActivePageIndex := 0;
end;
function TMainForm.GetItems: TObjectList<TObject>;
begin
Result := TObjectList<TObject>.Create(True);
Result.Add(TDataItem.Create('value1.1', 'value2.1', 'value3.1', 1));
Result.Add(TDataItem.Create('value1.2', 'value2.2', 'value3.2', 2));
Result.Add(TDataItem.Create('value1.3', 'value2.3', 'value3.3', 3));
end;
{ TDataItem }
constructor TDataItem.Create(const Value1, Value2, Value3: string; const IntValue: Integer);
begin
inherited Create;
fProp1 := Value1;
fProp2 := Value2;
fProp3 := Value3;
fPropInt := IntValue;
end;
end.
|
unit GRAPHOBJ;
{$mode tp}
interface
uses Graph;
type
tGraphObj = object
private
x, y: integer;
color: word;
public
constructor Init(newX, newY: integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
procedure Move(newX, newY: integer);
end;
tArc = object(tGraphObj)
private
rad, startAngle, endAngle : integer;
public
constructor Init(newX, newY, newRad, newStart, newEnd: integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
end;
tLine = object(tGraphObj)
private
dX12, dY12: integer;
public
constructor Init(newX, newY, newX2, newY2: integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
end;
tAngle = object(tLine)
private
dX13, dY13: integer;
public
constructor Init(newX, newY, newX2, newY2, newX3, newY3: integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
end;
tFillQuadrilateral = object(tAngle)
private
coords : array[0..6] of PointType;
dX14, dY14: integer;
public
constructor Init(newX, newY, newX2, newY2, newX3, newY3, newX4, newY4 : integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
end;
tFillHexagon = object(tFillQuadrilateral)
private
dX15, dY15, dX16, dY16: integer;
public
constructor Init(newX, newY, newX2, newY2, newX3, newY3, newX4, newY4, newX5, newY5, newX6, newY6 : integer; newColor: word);
procedure Hide; virtual;
procedure Draw; virtual;
end;
implementation
constructor tGraphObj.Init;
begin
x := newX;
y := newY;
color := newColor;
end;
procedure tGraphObj.Hide;
begin
end;
procedure tGraphObj.Draw;
begin
end;
procedure tGraphObj.Move;
begin
Hide;
x := newX;
y := newY;
Draw;
end;
constructor tArc.Init;
begin
tGraphObj.Init(newX, newY, newColor);
rad := newRad;
startAngle := newStart;
endAngle := newEnd;
end;
procedure tArc.Hide;
begin
SetColor(GetBkColor);
Ellipse(x, y, startAngle, endAngle, rad, rad);
end;
procedure tArc.Draw;
begin
SetColor(color);
Ellipse(x, y, startAngle, endAngle, rad, rad);
end;
constructor tLine.Init;
begin
tGraphObj.Init(newX, newY, newColor);
dX12 := newX2 - newX;
dY12 := newY2 - newY;
end;
procedure tLine.Hide;
begin
SetColor(GetBkColor);
Line(x, y, x + dX12, y + dY12);
end;
procedure tLine.Draw;
begin
SetColor(color);
Line(x, y, x + dX12, y + dY12);
end;
constructor tAngle.Init;
begin
tLine.Init(newX, newY, newX2, newY2, newColor);
dX13 := newX3 - newX;
dY13 := newY3 - newY;
end;
procedure tAngle.Hide;
begin
SetColor(GetBkColor);
Line(x, y, x + dX12, y + dY12);
Line(x, y, x + dX13, y + dY13);
end;
procedure tAngle.Draw;
begin
SetColor(color);
Line(x, y, x + dX12, y + dY12);
Line(x, y, x + dX13, y + dY13);
end;
constructor tFillQuadrilateral.Init;
begin
tAngle.Init(newX, newY, newX2, newY2, newX3, newY3, newColor);
coords[0].x := newX;
coords[0].y := newY;
coords[1].x := newX2;
coords[1].y := newY2;
coords[2].x := newX3;
coords[2].y := newY3;
coords[3].x := newX4;
coords[3].y := newY4;
coords[4].x := newX;
coords[4].y := newY;
coords[5].x := 0;
coords[5].y := 0;
coords[6].x := 0;
coords[6].y := 0;
dX14 := newX4 - newX;
dY14 := newY4 - newY;
end;
procedure tFillQuadrilateral.Hide;
begin
coords[0].x := x;
coords[0].y := y;
coords[1].x := x + dX12;
coords[1].y := y + dY12;
coords[2].x := x + dX13;
coords[2].y := y + dY13;
coords[3].x := x + dX14;
coords[3].y := y + dY14;
coords[4].x := x;
coords[4].y := y;
SetColor(GetBkColor);
SetFillStyle(SolidFill, GetBkColor);
FillPoly(5, coords);
end;
procedure tFillQuadrilateral.Draw;
begin
coords[0].x := x;
coords[0].y := y;
coords[1].x := x + dX12;
coords[1].y := y + dY12;
coords[2].x := x + dX13;
coords[2].y := y + dY13;
coords[3].x := x + dX14;
coords[3].y := y + dY14;
coords[4].x := x;
coords[4].y := y;
SetColor(color);
SetFillStyle(SolidFill, color);
FillPoly(5, coords);
end;
constructor tFillHexagon.Init;
begin
tFillQuadrilateral.Init(newX, newY, newX2, newY2, newX3, newY3, newX4, newY4, newColor);
coords[4].x := newX5;
coords[4].y := newY5;
coords[5].x := newX6;
coords[5].y := newY6;
coords[6].x := newX;
coords[6].y := newY;
dX15 := newX5 - newX;
dY15 := newY5 - newY;
dX16 := newX6 - newX;
dY16 := newY6 - newY;
end;
procedure tFillHexagon.Hide;
begin
coords[0].x := x;
coords[0].y := y;
coords[1].x := x + dX12;
coords[1].y := y + dY12;
coords[2].x := x + dX13;
coords[2].y := y + dY13;
coords[3].x := x + dX14;
coords[3].y := y + dY14;
coords[4].x := x + dX15;
coords[4].y := y + dY15;
coords[5].x := x + dX16;
coords[5].y := y + dY16;
coords[6].x := x;
coords[6].y := y;
SetColor(GetBkColor);
SetFillStyle(SolidFill, GetBkColor);
FillPoly(7, coords);
end;
procedure tFillHexagon.Draw;
begin
coords[0].x := x;
coords[0].y := y;
coords[1].x := x + dX12;
coords[1].y := y + dY12;
coords[2].x := x + dX13;
coords[2].y := y + dY13;
coords[3].x := x + dX14;
coords[3].y := y + dY14;
coords[4].x := x + dX15;
coords[4].y := y + dY15;
coords[5].x := x + dX16;
coords[5].y := y + dY16;
coords[6].x := x;
coords[6].y := y;
SetColor(color);
SetFillStyle(SolidFill, color);
FillPoly(7, coords);
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/coins.h
// Bitcoin file: src/coins.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TSaltedOutputHasher;
interface
class SaltedOutpointHasher
{
private:
/** Salt */
const uint64_t k0, k1;
public:
SaltedOutpointHasher();
/**
* This *must* return size_t. With Boost 1.46 on 32-bit systems the
* unordered_map will behave unpredictably if the custom hasher returns a
* uint64_t, resulting in failures when syncing the chain (#4634).
*
* Having the hash noexcept allows libstdc++'s unordered_map to recalculate
* the hash during rehash, so it does not have to cache the value. This
* reduces node's memory by sizeof(size_t). The required recalculation has
* a slight performance penalty (around 1.6%), but this is compensated by
* memory savings of about 9% which allow for a larger dbcache setting.
*
* @see https://gcc.gnu.org/onlinedocs/gcc-9.2.0/libstdc++/manual/manual/unordered_associative.html
*/
size_t operator()(const COutPoint& id) const noexcept {
return SipHashUint256Extra(k0, k1, id.hash, id.n);
}
};
implementation
SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
//
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyClasssysUser;
interface
uses
Classes, DB, DBClient, Variants;
type
TEasysysUser = class
private
{ Private declarations }
FUserGUID: string;
FUserName: string;
FPassWord: string;
FEmployeeGUID: string;
FIsEnable: Boolean;
FEndDate: TDateTime;
FRoleGUID: string;
FCreateTime: TDateTime;
FCreaterGUID: string;
public
{ Public declarations }
property UserGUID: string read FUserGUID write FUserGUID;
property UserName: string read FUserName write FUserName;
property PassWord: string read FPassWord write FPassWord;
property EmployeeGUID: string read FEmployeeGUID write FEmployeeGUID;
property IsEnable: Boolean read FIsEnable write FIsEnable;
property EndDate: TDateTime read FEndDate write FEndDate;
property RoleGUID: string read FRoleGUID write FRoleGUID;
property CreateTime: TDateTime read FCreateTime write FCreateTime;
property CreaterGUID: string read FCreaterGUID write FCreaterGUID;
class procedure GeneratesysUser(var Data: OleVariant; AResult: TList);
class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
class procedure InitSingleSysUser(AClientDataSet: TClientDataSet; AObj: TEasysysUser);
end;
implementation
{TEasysysUser}
class procedure TEasysysUser.GeneratesysUser(var Data: OleVariant; AResult: TList);
var
I: Integer;
AEasysysUser: TEasysysUser;
AClientDataSet: TClientDataSet;
begin
//创建数据源,并获取数据
AClientDataSet := TClientDataSet.Create(nil);
AClientDataSet.Data := Data;
AClientDataSet.First;
try
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
//此句为实例化指定的对象
AEasysysUser := TEasysysUser.Create;
with AEasysysUser do
begin
//1 UserGUID
UserGUID := AClientDataSet.FieldByName('UserGUID').AsString;
//2 UserName
UserName := AClientDataSet.FieldByName('UserName').AsString;
//3 PassWord
PassWord := AClientDataSet.FieldByName('PassWord').AsString;
//4 EmployeeGUID
EmployeeGUID := AClientDataSet.FieldByName('EmployeeGUID').AsString;
//5 IsEnable
IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean;
//6 EndDate
EndDate := AClientDataSet.FieldByName('EndDate').AsDateTime;
//7 RoleGUID
RoleGUID := AClientDataSet.FieldByName('RoleGUID').AsString;
//8 CreateTime
CreateTime := AClientDataSet.FieldByName('CreateTime').AsDateTime;
//9 CreaterGUID
CreaterGUID := AClientDataSet.FieldByName('CreaterGUID').AsString;
end;
//在此添加将对象存放到指定容器的代码
AResult.Add(AEasysysUser);
//如果要关联树也在此添加相应代码
AClientDataSet.Next;
end;
finally
AClientDataSet.Free;
end;
end;
class procedure TEasysysUser.AppendClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
begin
with ACds do
begin
Append;
//1 UserGUID
FieldByName('UserGUID').AsString := AObj.UserGUID;
//2 UserName
FieldByName('UserName').AsString := AObj.UserName;
//3 PassWord
FieldByName('PassWord').AsString := AObj.PassWord;
//4 EmployeeGUID
FieldByName('EmployeeGUID').AsString := AObj.EmployeeGUID;
//5 IsEnable
FieldByName('IsEnable').AsBoolean := AObj.IsEnable;
//6 EndDate
FieldByName('EndDate').AsDateTime := AObj.EndDate;
//7 RoleGUID
FieldByName('RoleGUID').AsString := AObj.RoleGUID;
//8 CreateTime
FieldByName('CreateTime').AsDateTime := AObj.CreateTime;
//9 CreaterGUID
FieldByName('CreaterGUID').AsString := AObj.CreaterGUID;
post;
end;
AObjList.Add(AObj);
end;
class procedure TEasysysUser.EditClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
begin
if ACds.Locate('UserGUID', VarArrayOf([AObj.UserGUID]), [loCaseInsensitive]) then
begin
with ACds do
begin
Edit;
//1 UserGUID
FieldByName('UserGUID').AsString := AObj.UserGUID;
//2 UserName
FieldByName('UserName').AsString := AObj.UserName;
//3 PassWord
FieldByName('PassWord').AsString := AObj.PassWord;
//4 EmployeeGUID
FieldByName('EmployeeGUID').AsString := AObj.EmployeeGUID;
//5 IsEnable
FieldByName('IsEnable').AsBoolean := AObj.IsEnable;
//6 EndDate
FieldByName('EndDate').AsDateTime := AObj.EndDate;
//7 RoleGUID
FieldByName('RoleGUID').AsString := AObj.RoleGUID;
//8 CreateTime
FieldByName('CreateTime').AsDateTime := AObj.CreateTime;
//9 CreaterGUID
FieldByName('CreaterGUID').AsString := AObj.CreaterGUID;
post;
end;
end;
end;
class procedure TEasysysUser.DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasysysUser; var AObjList: TList);
var
I,
DelIndex: Integer;
begin
DelIndex := -1;
if ACds.Locate('UserGUID', VarArrayOf([AObj.UserGUID]), [loCaseInsensitive]) then
ACds.Delete;
for I := 0 to AObjList.Count - 1 do
begin
if TEasysysUser(AObjList[I]).UserGUID = TEasysysUser(AObj).UserGUID then
begin
DelIndex := I;
Break;
end;
end;
if DelIndex <> -1 then
begin
TEasysysUser(AObjList[DelIndex]).Free;
AObjList.Delete(DelIndex);
end;
end;
class procedure TEasysysUser.InitSingleSysUser(AClientDataSet: TClientDataSet;
AObj: TEasysysUser);
begin
with AObj do
begin
//1 UserGUID
UserGUID := AClientDataSet.FieldByName('UserGUID').AsString;
//2 UserName
UserName := AClientDataSet.FieldByName('UserName').AsString;
//3 PassWord
PassWord := AClientDataSet.FieldByName('PassWord').AsString;
//4 EmployeeGUID
EmployeeGUID := AClientDataSet.FieldByName('EmployeeGUID').AsString;
//5 IsEnable
IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean;
//6 EndDate
EndDate := AClientDataSet.FieldByName('EndDate').AsDateTime;
//7 RoleGUID
RoleGUID := AClientDataSet.FieldByName('RoleGUID').AsString;
//8 CreateTime
CreateTime := AClientDataSet.FieldByName('CreateTime').AsDateTime;
//9 CreaterGUID
CreaterGUID := AClientDataSet.FieldByName('CreaterGUID').AsString;
end;
end;
end.
|
unit ncaFrmEditValidade;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, Menus, cxLabel, cxTextEdit, cxMaskEdit, cxSpinEdit,
StdCtrls, cxButtons, cxGroupBox, ComCtrls, dxCore, cxDateUtils,
cxDropDownEdit, cxCalendar, cxCheckBox, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, DateUtils,
dxGDIPlusClasses, ExtCtrls;
const
modo_val_semvalidade = 0;
modo_val_tempo = 1;
modo_val_data = 2;
utempo_dias = 0;
utempo_meses = 1;
utempo_anos = 2;
type
TncValidadeOrcamento = class
public
Modo : Byte; //0 = sem validade, 0 = tempo, 1 = data
Tempo : Integer;
UTempo : Byte; //0 = dias, 1 = meses, 2 = anos
Data : TDateTime;
DataInicial : TDateTime;
constructor Create;
function ValidoAte: TDateTime;
function AsString: String;
end;
TFrmEditValidade = class(TForm)
LMDSimplePanel4: TLMDSimplePanel;
LMDSimplePanel2: TLMDSimplePanel;
lbValidoAte: TcxLabel;
edAte: TcxDateEdit;
LMDSimplePanel1: TLMDSimplePanel;
lbValidoPor: TcxLabel;
edTempo: TcxSpinEdit;
lbAnos: TcxLabel;
lbMeses: TcxLabel;
lbDias: TcxLabel;
cbSemValidade: TcxCheckBox;
LMDSimplePanel3: TLMDSimplePanel;
btnOk: TcxButton;
btnCancelar: TcxButton;
cbPadrao: TcxCheckBox;
procedure FormCreate(Sender: TObject);
procedure lbMesesClick(Sender: TObject);
procedure lbAnosClick(Sender: TObject);
procedure lbDiasClick(Sender: TObject);
procedure edTempoPropertiesEditValueChanged(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edAtePropertiesEditValueChanged(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbSemValidadeClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FLastChangeAte: Boolean;
FDados : TncValidadeOrcamento;
FUTempo : Byte;
FShowed : Boolean;
FAtualizando : Boolean;
procedure SetUTempo(const Value: Byte);
procedure Atualiza;
public
{ Public declarations }
procedure Editar(aDados: TncValidadeOrcamento);
property UTempo: Byte
read FUTempo write SetUTempo;
end;
var
FrmEditValidade: TFrmEditValidade;
implementation
uses ufmImagens, ncaFrmPri, ncaDM, ncClassesBase;
{$R *.dfm}
resourcestring
rsSemValidade = '';
rsDia = 'dia';
rsDias = 'dias';
rsMes = 'mÍs';
rsMeses = 'meses';
rsAno = 'ano';
rsAnos = 'anos';
{ TFrmEditValidade }
function IncMes(aData: TDateTime; aMeses: Integer): Tdatetime;
var
Year, Month, Day: Word;
DayTable: PDayTable;
Sign: Integer;
begin
DecodeDate(aData, Year, Month, Day);
if aMeses >= 0 then Sign := 1 else Sign := -1;
Year := Year + (aMeses div 12);
aMeses := aMeses mod 12;
Inc(Month, aMeses);
if Word(Month-1) > 11 then // if Month <= 0, word(Month-1) > 11)
begin
Inc(Year, Sign);
Inc(Month, -12 * Sign);
end;
DayTable := @MonthDays[IsLeapYear(Year)];
if Day > DayTable^[Month] then begin
Day := Day - DayTable^[Month];
Inc(Month);
if Month>12 then begin
Inc(Year);
Month := 1;
end;
end;
Result := EncodeDate(Year, Month, Day);
end;
procedure TFrmEditValidade.Atualiza;
procedure SelLB(L: TcxLabel; Sel: Boolean);
begin
if Sel then begin
L.Style.TextStyle := [fsUnderline];
L.Style.TextColor := clBlue;
end else begin
L.Style.TextStyle := [];
L.Style.TextColor := clGray;
end;
end;
begin
if FAtualizando then Exit;
FAtualizando := True;
try
lbValidoPor.Enabled := not cbSemValidade.Checked;
lbValidoAte.Enabled := lbValidoPor.Enabled;
edTempo.Enabled := lbValidoPor.Enabled;
edAte.Enabled := edTempo.Enabled;
lbDias.Enabled := edAte.Enabled;
lbMeses.Enabled := edAte.Enabled;
lbAnos.Enabled := edAte.Enabled;
if FShowed then
if FLastChangeAte then begin
UTempo := utempo_dias;
edTempo.Value := Trunc(edAte.Date-FDados.DataInicial);
end else begin
case UTempo of
utempo_dias : edAte.Date := IncDay(FDados.DataInicial, edTempo.Value);
utempo_meses : edAte.Date := IncMes(FDados.DataInicial, edTempo.Value);
utempo_anos : edAte.Date := IncYear(FDados.DataInicial, edTempo.Value);
end;
end;
SelLB(lbDias, (FUTempo=utempo_dias));
SelLB(lbMeses, (FUTempo=utempo_meses));
SelLB(lbAnos, (FUTempo=utempo_anos));
finally
FAtualizando := False;
end;
end;
procedure TFrmEditValidade.btnOkClick(Sender: TObject);
begin
if cbPadrao.Checked then begin
Dados.CM.Config.AtualizaCache;
if cbSemValidade.Checked then begin
gConfig.ValOrc_Tempo := 0;
gConfig.ValOrc_UTempo := 0;
end else begin
gConfig.ValOrc_Tempo := edTempo.Value;
gConfig.ValOrc_UTempo := UTempo;
end;
Dados.CM.SalvaAlteracoesObj(gConfig, False);
end;
end;
procedure TFrmEditValidade.cbSemValidadeClick(Sender: TObject);
begin
if cbSemValidade.Focused then Atualiza;
end;
procedure TFrmEditValidade.edAtePropertiesEditValueChanged(Sender: TObject);
begin
if edAte.Focused then begin
FLastChangeAte := True;
Atualiza;
end;
end;
procedure TFrmEditValidade.Editar(aDados: TncValidadeOrcamento);
begin
FDados := aDados;
if FDados.Modo=modo_val_data then begin
FLastChangeAte := True;
edAte.Date := FDados.Data;
UTempo := utempo_dias;
edTempo.Value := Trunc(edAte.Date - FDados.DataInicial);
end else
if FDados.Modo=modo_val_tempo then begin
FLastChangeAte := False;
UTempo := FDados.UTempo;
edTempo.Value := FDados.Tempo;
edAte.Date := FDados.ValidoAte;
end else
cbSemValidade.Checked := True;
Atualiza;
ShowModal;
if ModalResult = mrOk then begin
if cbSemValidade.Checked then
FDados.Modo := modo_val_semvalidade
else
if FLastChangeAte then
FDados.Modo := modo_val_data
else
FDados.Modo := modo_val_tempo;
FDados.UTempo := UTempo;
FDados.Data := edAte.Date;
FDados.Tempo := edTempo.Value;
end;
end;
procedure TFrmEditValidade.edTempoPropertiesEditValueChanged(Sender: TObject);
begin
if edTempo.Focused then begin
FLastChangeAte := False;
Atualiza;
end;
end;
{ TncValidadeOrcamento }
function IntPluralSing(I: Integer; aPlural, aSingular: String): String;
begin
if I>1 then
Result := IntToStr(I)+' '+aPlural else
Result := IntToStr(I)+' '+aSingular;
end;
function TncValidadeOrcamento.AsString: String;
function TempoStr: String;
begin
case utempo of
utempo_dias : Result := IntPluralSing(tempo, rsDias, rsDia);
utempo_meses : Result := IntPluralSing(tempo, rsMeses, rsMes);
utempo_anos : Result := IntPluralSing(tempo, rsAnos, rsAno);
end;
end;
begin
with FormatSettings do
case Modo of
modo_val_semvalidade : Result := rsSemValidade;
modo_val_tempo : Result := TempoStr + ' - '+FormatDateTime(ShortDateFormat, Data);
modo_val_data : Result := FormatDateTime(ShortDateFormat, Data) + ' - ' + TempoStr;
else
result := '';
end;
end;
constructor TncValidadeOrcamento.Create;
begin
Modo := modo_val_tempo;
Tempo := 1;
UTempo := utempo_dias;
Data := 0;
DataInicial := 0;
end;
function TncValidadeOrcamento.ValidoAte: TDateTime;
begin
if Modo = modo_val_data then
Result := Data
else
if Modo = modo_val_tempo then begin
Result := DataInicial;
case UTempo of
utempo_meses : Result := IncMes(DataInicial, Tempo);
utempo_anos : Result := IncYear(DataInicial, Tempo);
else
Result := IncDay(DataInicial, Tempo);
end;
end else
Result := 0;
end;
procedure TFrmEditValidade.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmEditValidade.FormCreate(Sender: TObject);
begin
FShowed := False;
FAtualizando := False;
FUTempo := utempo_dias;
cbPadrao.Visible := Dados.CM.UA.Admin;
end;
procedure TFrmEditValidade.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
Key_Esc : Close;
end;
end;
procedure TFrmEditValidade.FormShow(Sender: TObject);
begin
FShowed := True;
end;
procedure TFrmEditValidade.lbAnosClick(Sender: TObject);
begin
FLastChangeAte := False;
UTempo := utempo_anos;
end;
procedure TFrmEditValidade.lbDiasClick(Sender: TObject);
begin
FLastChangeAte := False;
utempo := utempo_dias;
end;
procedure TFrmEditValidade.lbMesesClick(Sender: TObject);
begin
FLastChangeAte := False;
UTempo := utempo_meses;
end;
procedure TFrmEditValidade.SetUTempo(const Value: Byte);
begin
if Value<>FUTempo then begin
FUTempo := Value;
Atualiza;
end;
end;
end.
|
unit const_record_1;
interface
implementation
type
TRec = record
a, b: Int32;
end;
const R: TRec = [12, 13];
var G1, G2: Int32;
procedure Test;
begin
G1 := R.a;
G2 := R.b;
end;
initialization
Test();
finalization
Assert(G1 = 12);
Assert(G2 = 13);
end. |
unit MediaProcessing.Common.Processor.FPS.ImageSize;
interface
uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global,
MediaProcessing.Common.SettingsDialog.FPS.ImageSize,MediaProcessing.Common.Processor.FPS;
type
TChangeImageSizeMode = (cismNone,cismScale,cismCustomSize);
TMediaProcessor_FpsImageSize<T: TfmMediaProcessingSettingsFpsImageSize,constructor>=class (TMediaProcessor_Fps<T>)
private
procedure Process_ScaleBmp(aDIB: pointer; aWidth,aHeight: integer; aScaleX, aScaleY: integer; out aNewWidth,aNewHeight: integer);
protected
FImageSizeMode : TChangeImageSizeMode;
FImageSizeScale : integer;
FImageSizeWidth : integer;
FImageSizeHeight : integer;
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
procedure OnLoadPropertiesToDialog(aDialog: T); override;
procedure OnSavePropertiesFromDialog(aDialog: T); override;
procedure Process_ImageSizeRGB(aDIB: pointer; var aWidth, aHeight: integer);
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses Controls,uBaseClasses,MediaProcessing.Convertor.H264.RGB.SettingsDialog;
{ TMediaProcessor_FpsImageSize }
constructor TMediaProcessor_FpsImageSize<T>.Create;
begin
inherited;
FImageSizeScale:=2;
FImageSizeMode:=cismNone;
FImageSizeWidth:=640;
FImageSizeHeight:=480;
end;
destructor TMediaProcessor_FpsImageSize<T>.Destroy;
begin
inherited;
end;
procedure TMediaProcessor_FpsImageSize<T>.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FImageSizeMode:=TChangeImageSizeMode(aReader.ReadInteger('ImageSize.ChangeMode',integer(FImageSizeMode)));
FImageSizeScale:=aReader.ReadInteger('ImageSize.Scale',FImageSizeScale);
FImageSizeWidth:=aReader.ReadInteger('ImageSize.Width',FImageSizeWidth);
FImageSizeHeight:=aReader.ReadInteger('ImageSize.Height',FImageSizeHeight);
end;
procedure TMediaProcessor_FpsImageSize<T>.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteInteger('ImageSize.ChangeMode',integer(FImageSizeMode));
aWriter.WriteInteger('ImageSize.Scale',FImageSizeScale);
aWriter.WriteInteger('ImageSize.Width',FImageSizeWidth);
aWriter.WriteInteger('ImageSize.Height',FImageSizeHeight);
end;
procedure TMediaProcessor_FpsImageSize<T>.OnLoadPropertiesToDialog(aDialog: T);
begin
inherited;
aDialog.ckChangeImageSize.Checked:=FImageSizeMode<>cismNone;
aDialog.cbImageSizeScale.ItemIndex:=aDialog.cbImageSizeScale.Items.IndexOfData(FImageSizeScale);
if aDialog.cbImageSizeScale.ItemIndex=-1 then
aDialog.cbImageSizeScale.ItemIndex:=0;
aDialog.buImageSizeScale.Checked:=FImageSizeMode=cismScale;
aDialog.buImageSizeCustomSize.Checked:=FImageSizeMode=cismCustomSize;
if FImageSizeMode=cismNone then
aDialog.buImageSizeScale.Checked:=true;
aDialog.edImageSizeWidth.Value:=FImageSizeWidth;
aDialog.edimageSizeHeight.Value:=FImageSizeHeight;
end;
procedure TMediaProcessor_FpsImageSize<T>.OnSavePropertiesFromDialog(
aDialog: T);
begin
inherited;
if not aDialog.ckChangeImageSize.Checked then
FImageSizeMode:=cismNone
else if aDialog.buImageSizeScale.Checked then
FImageSizeMode:=cismScale
else if aDialog.buImageSizeCustomSize.Checked then
FImageSizeMode:=cismCustomSize
else
Assert(false);
FImageSizeScale:=aDialog.cbImageSizeScale.CurrentItemData;
FImageSizeWidth:=aDialog.edImageSizeWidth.Value;
FImageSizeHeight:=aDialog.edimageSizeHeight.Value;
end;
procedure TMediaProcessor_FpsImageSize<T>.Process_ImageSizeRGB(aDIB: pointer; var aWidth, aHeight: integer);
var
aKX,aKY: integer;
aNewWidth, aNewHeight: integer;
begin
aNewWidth:=aWidth;
aNewHeight:=aHeight;
if FImageSizeMode=cismScale then
begin
if FImageSizeScale<>1 then
Process_ScaleBmp(aDIB,aWidth,aHeight,FImageSizeScale, FImageSizeScale,aNewWidth,aNewHeight);
end
else if FImageSizeMode=cismCustomSize then
begin
aKX:=1;
if FImageSizeWidth>0 then
begin
aKX:=Round(aWidth/FImageSizeWidth);
if aKX<1 then
aKX:=1;
end;
aKY:=1;
if FImageSizeWidth>0 then
begin
aKY:=Round(aHeight/FImageSizeHeight);
if aKY<1 then
aKY:=1;
end;
Process_ScaleBmp(aDIB,aWidth,aHeight,aKX,aKY,aNewWidth,aNewHeight);
end;
aWidth:=aNewWidth;
aHeight:=aNewHeight;
end;
procedure TMediaProcessor_FpsImageSize<T>.Process_ScaleBmp(aDIB: pointer;
aWidth, aHeight, aScaleX, aScaleY: integer; out aNewWidth,
aNewHeight: integer);
var
aBmpDIBPtr: PAnsiChar;
aStrideOld,aStrideNew: integer;
aLOld,aLNew: PAnsiChar;
yOld,xOld,yNew: integer;
const
aBPP=3;
begin
Assert(aScaleX>0);
Assert(aScaleY>0);
if (aScaleX=1) and (aScaleY=1) then
exit;
aNewHeight:=aHeight div aScaleY;
aNewWidth:=aWidth div aScaleX;
aStrideOld := aBPP*aWidth;
aStrideNew := aBPP*aNewWidth;
aBmpDIBPtr := aDIB;
yNew:=0;
for yOld :=0 to aHeight-1 do
begin
if (yOld mod aScaleY)<>0 then
continue;
aLOld:=aBmpDIBPtr+yOld*aStrideOld;
aLNew:=aBmpDIBPtr+yNew*aStrideNew;
for xOld := 0 to aWidth-1 do
begin
if (xOld mod aScaleX)=0 then
begin
case aBPP of
1: aLNew^:=aLOld^;
2: PWord(aLNew)^:=PWord(aLOld)^;
3: begin
PWord(aLNew)^:=PWord(aLOld)^;
(aLNew+2)^:=(aLOld+2)^;
end;
4: PDWord(aLNew)^:=PDWord(aLOld)^;
else
Assert(false);
end;
inc(aLNew,aBPP);
end;
inc(aLOld,aBPP);
end;
inc(yNew);
end;
end;
(*
{
Here is the routine I use in my thumbnail component and I belive it is quite
fast.
A tip to gain faster loading of jpegs is to use the TJpegScale.Scale
property. You can gain a lot by using this correct.
This routine can only downscale images no upscaling is supported and you
must correctly set the dest image size. The src.image will be scaled to fit
in dest bitmap.
}
const
FThumbSize = 150;
//Speed up by Renate Schaaf, Armido, Gary Williams...
procedure MakeThumbNail(src, dest: tBitmap);
type
PRGB24 = ^TRGB24;
TRGB24 = packed record
B: Byte;
G: Byte;
R: Byte;
end;
var
x, y, ix, iy: integer;
x1, x2, x3: integer;
xscale, yscale: single;
iRed, iGrn, iBlu, iRatio: Longword;
p, c1, c2, c3, c4, c5: tRGB24;
pt, pt1: pRGB24;
iSrc, iDst, s1: integer;
i, j, r, g, b, tmpY: integer;
RowDest, RowSource, RowSourceStart: integer;
w, h: integer;
dxmin, dymin: integer;
ny1, ny2, ny3: integer;
dx, dy: integer;
lutX, lutY: array of integer;
begin
if src.PixelFormat <> pf24bit then src.PixelFormat := pf24bit;
if dest.PixelFormat <> pf24bit then dest.PixelFormat := pf24bit;
w := Dest.Width;
h := Dest.Height;
if (src.Width <= FThumbSize) and (src.Height <= FThumbSize) then
begin
dest.Assign(src);
exit;
end;
iDst := (w * 24 + 31) and not 31;
iDst := iDst div 8; //BytesPerScanline
iSrc := (Src.Width * 24 + 31) and not 31;
iSrc := iSrc div 8;
xscale := 1 / (w / src.Width);
yscale := 1 / (h / src.Height);
// X lookup table
SetLength(lutX, w);
x1 := 0;
x2 := trunc(xscale);
for x := 0 to w - 1 do
begin
lutX[x] := x2 - x1;
x1 := x2;
x2 := trunc((x + 2) * xscale);
end;
// Y lookup table
SetLength(lutY, h);
x1 := 0;
x2 := trunc(yscale);
for x := 0 to h - 1 do
begin
lutY[x] := x2 - x1;
x1 := x2;
x2 := trunc((x + 2) * yscale);
end;
dec(w);
dec(h);
RowDest := integer(Dest.Scanline[0]);
RowSourceStart := integer(Src.Scanline[0]);
RowSource := RowSourceStart;
for y := 0 to h do
begin
dy := lutY[y];
x1 := 0;
x3 := 0;
for x := 0 to w do
begin
dx:= lutX[x];
iRed:= 0;
iGrn:= 0;
iBlu:= 0;
RowSource := RowSourceStart;
for iy := 1 to dy do
begin
pt := PRGB24(RowSource + x1);
for ix := 1 to dx do
begin
iRed := iRed + pt.R;
iGrn := iGrn + pt.G;
iBlu := iBlu + pt.B;
inc(pt);
end;
RowSource := RowSource - iSrc;
end;
iRatio := 65535 div (dx * dy);
pt1 := PRGB24(RowDest + x3);
pt1.R := (iRed * iRatio) shr 16;
pt1.G := (iGrn * iRatio) shr 16;
pt1.B := (iBlu * iRatio) shr 16;
x1 := x1 + 3 * dx;
inc(x3,3);
end;
RowDest := RowDest - iDst;
RowSourceStart := RowSource;
end;
if dest.Height < 3 then exit;
// Sharpening...
s1 := integer(dest.ScanLine[0]);
iDst := integer(dest.ScanLine[1]) - s1;
ny1 := Integer(s1);
ny2 := ny1 + iDst;
ny3 := ny2 + iDst;
for y := 1 to dest.Height - 2 do
begin
for x := 0 to dest.Width - 3 do
begin
x1 := x * 3;
x2 := x1 + 3;
x3 := x1 + 6;
c1 := pRGB24(ny1 + x1)^;
c2 := pRGB24(ny1 + x3)^;
c3 := pRGB24(ny2 + x2)^;
c4 := pRGB24(ny3 + x1)^;
c5 := pRGB24(ny3 + x3)^;
r := (c1.R + c2.R + (c3.R * -12) + c4.R + c5.R) div -8;
g := (c1.G + c2.G + (c3.G * -12) + c4.G + c5.G) div -8;
b := (c1.B + c2.B + (c3.B * -12) + c4.B + c5.B) div -8;
if r < 0 then r := 0 else if r > 255 then r := 255;
if g < 0 then g := 0 else if g > 255 then g := 255;
if b < 0 then b := 0 else if b > 255 then b := 255;
pt1 := pRGB24(ny2 + x2);
pt1.R := r;
pt1.G := g;
pt1.B := b;
end;
inc(ny1, iDst);
inc(ny2, iDst);
inc(ny3, iDst);
end;
end;
*)
end.
|
unit UnitOfBot;
interface
uses
System.SysUtils, System.Classes, Vcl.ExtCtrls, Vcl.Dialogs, Winapi.Messages,
UnitOfGLobalFunctionsWithCards;
var
DeckOfBot: TArrayOfDeck;
DeckToDropOfBot: TArrayOfDeck;
// массив с картами, которые могут быть положены в сброс
procedure CompareBotCardsWithDrop; // сравнение
function SearchForOptimalCardToDrop: byte;
// поиск оптимальной карты среди выбранных карт для дропа
procedure DeleteCardOfBotAndRefrechDrop;
// удаление карты бота и переложение ее в сброс
implementation
uses
MainFormGameUnit;
procedure CompareBotCardsWithDrop;
var
i: byte;
begin
SetLength(DeckToDropOfBot, 0);
for i := 0 to Length(DeckOfBot) - 1 do
if CanPutCardOfPlayerInDrop(DeckOfBot[i]) then
begin
SetLength(DeckToDropOfBot, Length(DeckToDropOfBot) + 1);
DeckToDropOfBot[Length(DeckToDropOfBot) - 1] := DeckOfBot[i];
end;
end;
function SearchForOptimalCardToDrop;
var
i: byte;
MaxNumber: byte;
begin
for i := 0 to Length(DeckToDropOfBot) - 1 do
begin
if StrToInt(Copy(DeckToDropOfBot[i], 3, 1)) >= 4 then
begin
Result := i;
exit;
end;
end;
for i := 0 to Length(DeckToDropOfBot) - 1 do
begin
if StrToInt(Copy(DeckToDropOfBot[i], 3, 1)) <> 0 then
begin
Result := i;
exit;
end;
end;
MaxNumber := StrToInt(Copy(DeckToDropOfBot[0], 2, 1));
Result := 0;
for i := 1 to Length(DeckToDropOfBot) - 1 do
begin
if StrToInt(Copy(DeckToDropOfBot[i], 2, 1)) > MaxNumber then
begin
MaxNumber := StrToInt(Copy(DeckToDropOfBot[i], 2, 1));
Result := i;
end;
end;
end;
procedure DeleteCardOfBotAndRefrechDrop;
var
i, NumberOfColor: byte;
str, ChoosenCard: string;
begin
ChoosenCard := DeckToDropOfBot[SearchForOptimalCardToDrop];
for i := 0 to Length(DeckOfBot) - 1 do
if (DeckOfBot[i][1] = ChoosenCard[1]) and (DeckOfBot[i][2] = ChoosenCard[2])
and (DeckOfBot[i][3] = ChoosenCard[3]) then
break;
CardOfDrop := DeckOfBot[i];
MainFormGame.HelperMemo.Lines.Add('Бот положил [' +
DecoderCard(CardOfDrop) + ']');
str := DeckOfBot[i];
DeckOfBot[i] := DeckOfBot[Length(DeckOfBot) - 1];
DeckOfBot[Length(DeckOfBot) - 1] := str;
SetLength(DeckOfDrop, Length(DeckOfDrop) + 1);
DeckOfDrop[Length(DeckOfDrop) - 1] := DeckOfBot[i];
SetLength(DeckOfBot, Length(DeckOfBot) - 1);
VisualInitializationOfTable;
end;
end.
|
unit RemoveBlankLinesInVars;
{ AFS 9 March 2003
At request, remove blank lines in procedure var declarations
(and procedure const & type declarations)
}
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is RemoveBlankLinesInVars, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses SourceToken, SwitchableVisitor;
type
TRemoveBlankLinesInVars = class(TSwitchableVisitor)
protected
function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
end;
implementation
uses JcfSettings, FormatFlags, Tokens, TokenUtils;
{ TRemoveBlankLinesInVars }
constructor TRemoveBlankLinesInVars.Create;
begin
inherited;
FormatFlags := FormatFlags + [eRemoveReturn];
end;
function TRemoveBlankLinesInVars.EnabledVisitSourceToken(const pcNode: TObject): Boolean;
var
lcSourceToken: TSourceToken;
lcNext: TSourceToken;
lcTest: TSourceToken;
liReturnCount: integer;
liMaxReturns: integer;
begin
Result := False;
lcSourceToken := TSourceToken(pcNode);
if not InProcedureDeclarations(lcSourceToken) then
exit;
lcNext := lcSourceToken.NextTokenWithExclusions([ttWhiteSpace, ttReturn, ttComment]);
if lcNext = nil then
exit;
{ don't remove blank lines before the proc header,
or before a contained fn or proc }
if lcNext.TokenType in ProcedureWords then
exit;
lcNext := lcSourceToken.NextTokenWithExclusions([ttWhiteSpace, ttReturn]);
liReturnCount := 0;
liMaxReturns := JcfFormatSettings.Returns.MaxBlankLinesInSection + 1;
lcTest := lcSourceToken;
{ remove all returns up to that point (except one) }
while (lcTest <> lcNext) do
begin
if (lcTest.TokenType = ttReturn) then
begin
// allow two returns -> 1 blank line
Inc(liReturnCount);
if (liReturnCount > liMaxReturns) then
BlankToken(lcTest);
end;
lcTest := lcTest.NextToken;
end;
end;
function TRemoveBlankLinesInVars.IsIncludedInSettings: boolean;
begin
Result := JcfFormatSettings.Returns.RemoveVarReturns;
end;
end.
|
unit AOrdemCortePendente;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, Grids, DBGrids,
Tabela, DBKeyViolation, StdCtrls, Buttons, DB, DBClient, Menus;
type
TFOrdemCortePendente = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
BFechar: TBitBtn;
GridIndice1: TGridIndice;
CortePendente: TSQL;
DataCortePendente: TDataSource;
CortePendenteCODFILIAL: TFMTBCDField;
CortePendenteSEQORDEM: TFMTBCDField;
CortePendenteSEQFRACAO: TFMTBCDField;
CortePendenteQTDPRODUTO: TFMTBCDField;
CortePendenteDATEMI: TSQLTimeStampField;
CortePendenteI_COD_CLI: TFMTBCDField;
CortePendenteC_NOM_CLI: TWideStringField;
CortePendenteC_NOM_PRO: TWideStringField;
CortePendenteC_COD_PRO: TWideStringField;
CortePendenteQTDDIAS: TIntegerField;
BImprimir: TBitBtn;
CortePendenteDATENTREGA: TSQLTimeStampField;
PopupMenu1: TPopupMenu;
Baixar1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure CortePendenteCalcFields(DataSet: TDataSet);
procedure BImprimirClick(Sender: TObject);
procedure Baixar1Click(Sender: TObject);
private
{ Private declarations }
procedure AtualizaConsulta;
public
{ Public declarations }
end;
var
FOrdemCortePendente: TFOrdemCortePendente;
implementation
uses APrincipal, FunSQL, FunData, dmRave, UnOrdemProducao, constmsg;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFOrdemCortePendente.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
AtualizaConsulta;
end;
{ **************************************************************************** }
procedure TFOrdemCortePendente.AtualizaConsulta;
begin
AdicionaSQLAbreTabela(CortePendente,'select FRA.CODFILIAL, FRA.SEQORDEM, FRA.SEQFRACAO, FRA.QTDPRODUTO, FRA.DATENTREGA, '+
' OP.DATEMI, '+
' CLI.I_COD_CLI, CLI.C_NOM_CLI, '+
' PRO.C_COD_PRO, PRO.C_NOM_PRO '+
' from FRACAOOP FRA, ORDEMPRODUCAOCORPO OP, CADCLIENTES CLI, CADPRODUTOS PRO, ORDEMCORTECORPO OCP '+
' where FRA.DATCORTE IS NULL '+
' AND OP.EMPFIL = FRA.CODFILIAL '+
' AND OP.SEQORD = FRA.SEQORDEM '+
' AND OP.CODCLI = CLI.I_COD_CLI '+
' AND OP.SEQPRO = PRO.I_SEQ_PRO '+
' AND OP.EMPFIL = OCP.CODFILIAL ' +
' AND OP.SEQORD = OCP.SEQORDEMPRODUCAO '+
' ORDER BY FRA.DATENTREGA, FRA.CODFILIAL, FRA.SEQORDEM, FRA.SEQFRACAO ');
end;
{ **************************************************************************** }
procedure TFOrdemCortePendente.Baixar1Click(Sender: TObject);
var
VpfResultado : String;
begin
VpfResultado := FunOrdemProducao.BaixaOrdemCorte(CortePendenteCODFILIAL.AsInteger,CortePendenteSEQORDEM.AsInteger,CortePendenteSEQFRACAO.AsInteger);
if VpfResultado <> '' then
aviso(VpfResultado)
else
AtualizaConsulta;
end;
procedure TFOrdemCortePendente.BFecharClick(Sender: TObject);
begin
close;
end;
procedure TFOrdemCortePendente.BImprimirClick(Sender: TObject);
begin
dtRave := TdtRave.Create(self);
dtRave.ImprimeCortePendente;
dtRave.Free;
end;
{ **************************************************************************** }
procedure TFOrdemCortePendente.CortePendenteCalcFields(DataSet: TDataSet);
begin
CortePendenteQTDDIAS.AsInteger := DiasPorPeriodo(CortePendenteDATEMI.AsDateTime,date);
end;
{ **************************************************************************** }
procedure TFOrdemCortePendente.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFOrdemCortePendente]);
end.
|
program TesteSortiereListe(input, output);
type
tNatZahl = 0..maxint;
tRefListe = ^tListe;
tListe = record
info : tNatZahl;
next : tRefListe;
end;
var
RefListe: tRefListe;
procedure SortiereListe (var ioRefListe : tRefListe);
{ sortiert eine lineare Liste aufsteigend }
var
outRefListe,
outRefListeScheife, { Zeigerdurchlauf, für die erste Schleife, läuft einmal die Liste durch }
outRefListeInsert, { Zeigerdurchlauf, für die zweite Schleife, zum Sortieren }
PredZeiger, { Vorheriger Wert des Zeigers der ersten Schleife}
Zeiger, { Aktueller Wert des Zeigers der ersten Schleife}
PredZeigerInsert, { Vorheriger Wert des Zeigers der zweiten Schleife}
ZeigerInsert: tRefListe; { Aktueller Wert des Zeigers der zweiten Schleife}
eingefuegt: boolean; { Abbruchkriterum der zweiten While-Schleife }
begin
outRefListe := ioRefListe;
if(outRefListe <> nil) then { Liste nicht leer }
begin
outRefListeScheife := outRefListe; { Initialisierung Schleifen-Zeiger, erste Schleife }
PredZeiger := outRefListeScheife; { Initialisierung Zeiger, vorheriger Wert }
Zeiger := nil;
if(outRefListeScheife^.next <> nil) then
begin
Zeiger := outRefListeScheife^.next; { Initialisierung Zeiger, aktueller Wert }
outRefListeScheife := Zeiger;
end; { if(outRefListeScheife^.next <> nil)}
if(Zeiger <> nil) then { Darf nicht leer sein, da mind. 2 Werte zum Sortieren erforderlich sind }
while(outRefListeScheife <> nil) do
begin
{ Liste ist noch unsortiert }
if(Zeiger^.info < PredZeiger^.info) then
begin
{ Kleinerer Wert gefunden, daher die Liste erneut durchlaufen,
um den Zeiger an die richtige Position einfügen}
outRefListeInsert := outRefListe;
eingefuegt := false; { Initialisierung Abbruchkriterium }
PredZeigerInsert := outRefListeInsert; { Initialisierung Zeiger, vorheriger Wert, zweite Schleife }
ZeigerInsert := nil;
if(outRefListeScheife^.next <> nil) then
begin
ZeigerInsert := outRefListeInsert^.next; { Initialisierung Zeiger, aktueller Wert, zweite Schleife }
outRefListeInsert := ZeigerInsert;
end;
{ Da (outRefListeScheife^.next = nil) ist, ist das der letzte Zeiger }
if(ZeigerInsert = nil) then
ZeigerInsert := PredZeiger;
{ Durchlaufe, bis Abbruchkriterium oder bis die zweite Schleife durchgelaufen ist }
while(outRefListeInsert <> nil) and (eingefuegt = false) do
begin
{ Falls Zeigerwert größer als der vorherige und kleiner als der nachfolgende, dann dazwischen einfügen}
if (Zeiger^.info > PredZeigerInsert^.info) and (Zeiger^.info <= ZeigerInsert^.info) then
begin
{ Zeiger zwischen den Werten der Liste einfügen}
eingefuegt := true;
PredZeiger^.next := Zeiger^.next; { Alten Wert des Zeigers puffern}
Zeiger^.next := PredZeigerInsert^.next;
PredZeigerInsert^.next := Zeiger;
Zeiger := PredZeiger; { aktuellen Zeiger der ersten Schleife mit dem nächsten Wert fortsetzen}
end {(Zeiger^.info > PredZeigerInsert^.info) and (Zeiger^.info <= ZeigerInsert^.info)}
{ Der Wert des Zeigers ist kleiner als der erste Zeigerwert, daher am Anfang einfügen}
else if(Zeiger^.info <= PredZeigerInsert^.info) then
begin
{ Zum Anfang der Liste einfügen}
eingefuegt := true;
PredZeiger^.next := Zeiger^.next;
Zeiger^.next := PredZeigerInsert;
PredZeigerInsert := Zeiger;
outRefListe := PredZeigerInsert;
Zeiger := PredZeiger; { aktuellen Zeiger der ersten Schleife mit dem nächsten Wert fortsetzen}
end { if(Zeiger^.info <= PredZeigerInsert^.info) }
else
{ sonst, vorherigen und aktuellen Zeiger setzen und mit der zweite Schleife weitermachen,
bis obere Bedingungen zutreffen, oder die Liste zu Ende läuft}
begin
PredZeigerInsert := ZeigerInsert;
ZeigerInsert := outRefListeInsert^.next;
outRefListeInsert := ZeigerInsert;
end
end
end; { if(Zeiger^.info < PredZeiger^.info) }
{ Setzen der Zeiger und weitermachen mit der ersten Schleife,
bis kleinerer Wert gefunden wurde, sodass es auch sortiert werden kann}
PredZeiger := Zeiger;
Zeiger := PredZeiger^.next;
outRefListeScheife := Zeiger;
end; { while(outRefListeScheife <> nil)}
end;
ioRefListe := outRefListe;
end;
procedure Anhaengen(var ioListe : tRefListe;
inZahl : tNatZahl);
{ Haengt inZahl an ioListe an }
var Zeiger : tRefListe;
begin
Zeiger := ioListe;
if Zeiger = nil then
begin
new(ioListe);
ioListe^.info := inZahl;
ioListe^.next := nil;
end
else
begin
while Zeiger^.next <> nil do
Zeiger := Zeiger^.next;
{ Jetzt zeigt Zeiger auf das letzte Element }
new(Zeiger^.next);
Zeiger := Zeiger^.next;
Zeiger^.info := inZahl;
Zeiger^.next := nil;
end;
end;
procedure ListeEinlesen(var outListe:tRefListe);
{ liest eine durch Leerzeile abgeschlossene Folge von Integer-
Zahlen ein und speichert diese in der linearen Liste RefListe. }
var
Liste : tRefListe;
Zeile : string;
Zahl, Code : integer;
begin
writeln('Bitte geben Sie die zu sortierenden Zahlen ein.');
writeln('Beenden Sie Ihre Eingabe mit einer Leerzeile.');
Liste := nil;
readln(Zeile);
val(Zeile, Zahl, Code); { val konvertiert String nach Integer }
while Code=0 do
begin
Anhaengen(Liste, Zahl);
readln(Zeile);
val(Zeile, Zahl, Code);
end; { while }
outListe := Liste;
end; { ListeEinlesen }
procedure GibListeAus(inListe : tRefListe);
{ Gibt die Elemente von inListe aus }
var Zeiger : tRefListe;
begin
Zeiger := inListe;
while Zeiger <> nil do
begin
writeln(Zeiger^.info);
Zeiger := Zeiger^.next;
end; { while }
end; { GibListeAus }
begin
ListeEinlesen(RefListe);
SortiereListe(RefListe);
GibListeAus(RefListe)
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit crpt_participants_info;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, JSONObjects, AbstractSerializationObjects;
type
{ TParticipantsInfo }
TParticipantsInfo = class(TJSONSerializationObject)
private
FactualAddress: string;
Fdissolved: boolean;
Femail: string;
FemissionRegistrars: string;
FfullName: string;
Fhead: TXSDStringArray;
Fid: Int64;
Finn: string;
Fkpp: string;
FlegalAddress: string;
Fname: string;
Fogrn: string;
ForganizationForm: string;
Fphone: string;
FregistrationDate: Int64;
Froles: TXSDStringArray;
FshortName: string;
Fstatus: string;
Ftypes1: string;
procedure SetactualAddress(AValue: string);
procedure Setdissolved(AValue: boolean);
procedure Setemail(AValue: string);
procedure SetemissionRegistrars(AValue: string);
procedure SetfullName(AValue: string);
procedure Sethead(AValue: TXSDStringArray);
procedure Setid(AValue: Int64);
procedure Setinn(AValue: string);
procedure Setkpp(AValue: string);
procedure SetlegalAddress(AValue: string);
procedure Setname(AValue: string);
procedure Setogrn(AValue: string);
procedure SetorganizationForm(AValue: string);
procedure Setphone(AValue: string);
procedure SetregistrationDate(AValue: Int64);
procedure Setroles(AValue: TXSDStringArray);
procedure SetshortName(AValue: string);
procedure Setstatus(AValue: string);
procedure Settypes1(AValue: string);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
destructor Destroy; override;
public
constructor Create; override;
published
property id:Int64 read Fid write Setid; //Идентификатор
property inn:string read Finn write Setinn; //ИНН
property name:string read Fname write Setname; //Наименование
property shortName:string read FshortName write SetshortName; //Краткое наименование
property fullName:string read FfullName write SetfullName; //Полное наименование
property types1:string read Ftypes1 write Settypes1; //Тип организации
property status:string read Fstatus write Setstatus; //Статус REGISTERED -Зарегистрирован;NOT_REGISTERED - Не зарегистрирован;REMOVED - Удален;RESTORED - Восстановлен;BLOCKED - Заблокирован
property kpp:string read Fkpp write Setkpp; //КПП
property ogrn:string read Fogrn write Setogrn; //ОГРН
property head:TXSDStringArray read Fhead write Sethead; //Руководители
property legalAddress:string read FlegalAddress write SetlegalAddress; //Юридический адрес
property actualAddress:string read FactualAddress write SetactualAddress; //Фактический адрес
property email:string read Femail write Setemail; //Email
property registrationDate:Int64 read FregistrationDate write SetregistrationDate; //Регистрация
property organizationForm:string read ForganizationForm write SetorganizationForm; //Форма организации: ЮЛ, ФЛ, ИП
property emissionRegistrars:string read FemissionRegistrars write SetemissionRegistrars; //Регистратор эмиссии
property dissolved:boolean read Fdissolved write Setdissolved; //Признак существования организации
property roles:TXSDStringArray read Froles write Setroles; //Роли организации
property phone:string read Fphone write Setphone; //Телефон
// property productGroupInfo:array-Тип участникаВозвращается при использовании токена администратора
end;
implementation
{ TParticipantsInfo }
procedure TParticipantsInfo.SetactualAddress(AValue: string);
begin
if FactualAddress=AValue then Exit;
FactualAddress:=AValue;
ModifiedProperty('actualAddress');
end;
procedure TParticipantsInfo.Setdissolved(AValue: boolean);
begin
if Fdissolved=AValue then Exit;
Fdissolved:=AValue;
ModifiedProperty('dissolved');
end;
procedure TParticipantsInfo.Setemail(AValue: string);
begin
if Femail=AValue then Exit;
Femail:=AValue;
ModifiedProperty('email');
end;
procedure TParticipantsInfo.SetemissionRegistrars(AValue: string);
begin
if FemissionRegistrars=AValue then Exit;
FemissionRegistrars:=AValue;
ModifiedProperty('emissionRegistrars');
end;
procedure TParticipantsInfo.SetfullName(AValue: string);
begin
if FfullName=AValue then Exit;
FfullName:=AValue;
ModifiedProperty('fullName');
end;
procedure TParticipantsInfo.Sethead(AValue: TXSDStringArray);
begin
if Fhead=AValue then Exit;
Fhead:=AValue;
ModifiedProperty('head');
end;
procedure TParticipantsInfo.Setid(AValue: Int64);
begin
if Fid=AValue then Exit;
Fid:=AValue;
ModifiedProperty('id');
end;
procedure TParticipantsInfo.Setinn(AValue: string);
begin
if Finn=AValue then Exit;
Finn:=AValue;
ModifiedProperty('inn');
end;
procedure TParticipantsInfo.Setkpp(AValue: string);
begin
if Fkpp=AValue then Exit;
Fkpp:=AValue;
ModifiedProperty('kpp');
end;
procedure TParticipantsInfo.SetlegalAddress(AValue: string);
begin
if FlegalAddress=AValue then Exit;
FlegalAddress:=AValue;
ModifiedProperty('legalAddress');
end;
procedure TParticipantsInfo.Setname(AValue: string);
begin
if Fname=AValue then Exit;
Fname:=AValue;
ModifiedProperty('name');
end;
procedure TParticipantsInfo.Setogrn(AValue: string);
begin
if Fogrn=AValue then Exit;
Fogrn:=AValue;
ModifiedProperty('ogrn');
end;
procedure TParticipantsInfo.SetorganizationForm(AValue: string);
begin
if ForganizationForm=AValue then Exit;
ForganizationForm:=AValue;
ModifiedProperty('organizationForm');
end;
procedure TParticipantsInfo.Setphone(AValue: string);
begin
if Fphone=AValue then Exit;
Fphone:=AValue;
ModifiedProperty('phone');
end;
procedure TParticipantsInfo.SetregistrationDate(AValue: Int64);
begin
if FregistrationDate=AValue then Exit;
FregistrationDate:=AValue;
ModifiedProperty('registrationDate');
end;
procedure TParticipantsInfo.Setroles(AValue: TXSDStringArray);
begin
if Froles=AValue then Exit;
Froles:=AValue;
ModifiedProperty('roles');
end;
procedure TParticipantsInfo.SetshortName(AValue: string);
begin
if FshortName=AValue then Exit;
FshortName:=AValue;
ModifiedProperty('shortName');
end;
procedure TParticipantsInfo.Setstatus(AValue: string);
begin
if Fstatus=AValue then Exit;
Fstatus:=AValue;
ModifiedProperty('status');
end;
procedure TParticipantsInfo.Settypes1(AValue: string);
begin
if Ftypes1=AValue then Exit;
Ftypes1:=AValue;
ModifiedProperty('types1');
end;
procedure TParticipantsInfo.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('id', 'id', [], '', -1, -1);
RegisterProperty('inn', 'inn', [], '', -1, -1);
RegisterProperty('name', 'name', [], '', -1, -1);
RegisterProperty('shortName', 'shortName', [], '', -1, -1);
RegisterProperty('fullName', 'fullName', [], '', -1, -1);
RegisterProperty('types1', 'types', [], '', -1, -1);
RegisterProperty('status', 'status', [], '', -1, -1);
RegisterProperty('kpp', 'kpp', [], '', -1, -1);
RegisterProperty('ogrn', 'ogrn', [], '', -1, -1);
RegisterProperty('head', 'head', [], '', -1, -1);
RegisterProperty('legalAddress', 'legalAddress', [], '', -1, -1);
RegisterProperty('actualAddress', 'actualAddress', [], '', -1, -1);
RegisterProperty('email', 'email', [], '', -1, -1);
RegisterProperty('registrationDate', 'registrationDate', [], '', -1, -1);
RegisterProperty('organizationForm', 'organizationForm', [], '', -1, -1);
RegisterProperty('emissionRegistrars', 'emissionRegistrars', [], '', -1, -1);
RegisterProperty('dissolved', 'dissolved', [], '', -1, -1);
RegisterProperty('roles', 'roles', [], '', -1, -1);
RegisterProperty('phone', 'phone', [], '', -1, -1);
// property productGroupInfo:array-Тип участникаВозвращается при использовании токена администратора
end;
procedure TParticipantsInfo.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
destructor TParticipantsInfo.Destroy;
begin
inherited Destroy;
end;
constructor TParticipantsInfo.Create;
begin
inherited Create;
FIgnoreReadUndefProps:=true;
end;
end.
|
unit u_FrameWeightNum;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TframeWeightNum = class(TFrame)
lblNum: TLabel;
lbWeightTime: TLabel;
tmrCheckOutDated: TTimer;
Label1: TLabel;
procedure tmrCheckOutDatedTimer(Sender: TObject);
private
FSampleTime: TDateTime;
FSampleWeight: Single;
procedure SetSampleWeight(const Value: Single);
function GetWeightOutofdated: Boolean;
Procedure UpdateRenderColor;
Procedure UpdateRender;
{ Private declarations }
public
{ Public declarations }
Constructor Create(AOwner: TComponent); Override;
Property SampleWeight: Single read FSampleWeight write SetSampleWeight;
Property SampleTime: TDateTime read FSampleTime;
Property WeightOutofdated: Boolean Read GetWeightOutofdated;
end;
implementation
uses
DateUtils;
{$R *.dfm}
const
CONST_VALID_COLOR: TColor = clGreen;
CONST_INVALID_COLOR: TColor = clRed;
{ TframeWeightNum }
procedure TframeWeightNum.UpdateRender;
begin
lblNum.Caption:= Format('%8.2f', [self.FSampleWeight]);
lbWeightTime.Caption:= FormatDateTime('YYYY-MM-DD HH:NN:SS', Now);
UpdateRenderColor;
end;
procedure TframeWeightNum.UpdateRenderColor;
var
AColor: TColor;
begin
if WeightOutofdated then
AColor:= CONST_INVALID_COLOR
else
AColor:= CONST_VALID_COLOR;
if lblNum.Font.Color <> AColor then
lblNum.Font.Color:= AColor;
end;
constructor TframeWeightNum.Create(AOwner: TComponent);
begin
inherited;
SetSampleWeight(0);
end;
function TframeWeightNum.GetWeightOutofdated: Boolean;
begin
Result:= SecondSpan(NOw(), FSampleTime) >= 2;
end;
procedure TframeWeightNum.SetSampleWeight(const Value: Single);
begin
FSampleWeight := Value;
FSampleTime:= Now();
UpdateRender();
end;
procedure TframeWeightNum.tmrCheckOutDatedTimer(Sender: TObject);
begin
UpdateRenderColor();
end;
end.
|
unit StackA;
interface
uses error;
type TElement = longint; { replacable element type }
const MAXS = 30;
type
TStack = record
last: integer;
E: array[1..MAXS] of TElement;
end;
procedure InitStack (var S: TStack; size:integer);
procedure CleanUpStack (var S: TStack);
procedure push (var S: TStack; E:TElement);
function pop (var S: TStack):TElement;
function top (var S: TStack):TElement;
function IsStackEmpty (var S:TStack):boolean;
implementation
procedure InitStack (var S: TStack; size:integer);
begin
if size>MAXS then FatalError('stack too large');
S.last := 0;
end;
procedure CleanUpStack (var S:TStack);
begin S.last := 0; end;
procedure push (var S:TStack; E:TElement);
begin
S.last := S.last+1;
if S.last > MAXS then FatalError('stack overflow!');
S.E[S.last] := E;
end;
function pop (var S:TStack):TElement;
begin
if IsStackEmpty(S) then FatalError('stack underflow!');
pop := S.E[S.last];
S.last := S.last-1;
end;
function top (var S:TStack):TElement;
begin
if IsStackEmpty(S) then LiteError('Stack is empty, cannot return top.')
else top := S.E[S.last];
end;
function IsStackEmpty (var S:TStack):boolean;
begin IsStackEmpty := (S.last=0); end;
end.
|
unit DataLankProtocol;
{
DataLankProtocol only serves as a guide to describe what the interface
to the TDataConnection and TQueryResult object should be.
Don't include it in a project (unless you need a quick-fix to determine
if a project has correct syntax.)
Don't override from TDataConnection or TQueryResult.
Create a DataLank.pas unit with code like this to patch through to an
implementation of your selection.
unit DataLink;
interface
uses SomeDBTools;
type
TDataConnection = TSomeDBConnection;
TQueryResult = TSomeDBCommand;
implementations
end.
See
https://github.com/stijnsanders/DataLank
for a list of implementations.
}
interface
type
TDataConnection=class(TObject)
public
constructor Create(const ConnectionInfo: WideString);
destructor Destroy override;
function Execute(const SQL: WideString;
const Values: array of Variant): integer;
function Insert(const TableName: WideString; const Values: array of Variant;
const PKFieldName: WideString=''): int64;
procedure Update(const TableName: WideString; const Values:array of Variant);
procedure BeginTrans;
procedure CommitTrans;
procedure RollbackTrans;
end;
TQueryResult=class(TObject)
private
FFirstLoad:boolean;
function GetValue(const Idx:Variant):Variant;
function IsEof:boolean;
public
constructor Create(Connection: TDataConnection; const SQL: WideString;
const Values: array of Variant);
destructor Destroy; override;
function Read:boolean;
property Fields[Idx:Variant]:Variant read GetValue; default;
property EOF: boolean read IsEof;
function GetInt(const Idx:Variant):integer;
function GetStr(const Idx:Variant):WideString;
function GetDate(const Idx:Variant):TDateTime;
function IsNull(const Idx:Variant):boolean;
end;
implementation
{ TDataConnection }
constructor TDataConnection.Create(const ConnectionInfo: WideString);
begin
inherited Create;
//create connection data
//open connection
end;
destructor TDataConnection.Destroy;
begin
//close connection
//free connection data
inherited;
end;
function TDataConnection.Insert(const TableName: WideString;
const Values: array of Variant): integer;
begin
//insert record
//catch primary key and/or auto-number
end;
function TDataConnection.Execute(const SQL: WideString;
const Values: array of Variant): integer;
begin
//prepare command and parameters
//execute SQL
end;
procedure TDataConnection.BeginTrans;
begin
Execute('BEGIN TRANSACTION',[]);
end;
procedure TDataConnection.CommitTrans;
begin
Execute('COMMIT TRANSACTION',[]);
end;
procedure TDataConnection.RollbackTrans;
begin
Execute('ROLLBACK TRANSACTION',[]);
end;
{ TQueryResult }
constructor TQueryResult.Create(Connection: TDataConnection;
const SQL: WideString; const Values: array of Variant);
begin
inherited Create;
//prepare command, set parameter values
//execute and prepare result set
FFirstRead:=true;
end;
destructor TQueryResult.Destroy;
begin
//clean-up result set data
inherited;
end;
function TQueryResult.GetValue(const Idx: Variant): Variant;
begin
//Result:=
end;
function TQueryResult.GetInt(const Idx: Variant): integer;
begin
//Result:=
end;
function TQueryResult.GetStr(const Idx: Variant): WideString;
begin
//Result:=
end;
function TQueryResult.GetDate(const Idx: Variant): TDateTime;
begin
//Result:=VarToDateTime(
end;
function TQueryResult.IsNull(const Idx: Variant): boolean;
begin
//Result:=VarIsNull(
end;
function TQueryResult.IsEof: boolean;
begin
//Result:=
end;
function TQueryResult.Read: boolean;
begin
if EOF then Result:=false else
begin
if FFirstRead then FFirstRead:=false else ;//Next;
Result:=not(EOF);
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.Cloud.AzureAPI.StorageAnalytics;
interface
{$SCOPEDENUMS ON}
uses
System.Classes, System.Generics.Collections,
Xml.XMLIntf, Xml.XMLDoc;
const
cStorageAnalyticsVersion = '1.0';
cStorageServiceProperties = 'StorageServiceProperties';
cLogging = 'Logging';
cRetentionPolicy = 'RetentionPolicy';
cMetrics = 'Metrics';
cHourMetrics = 'HourMetrics';
cMinuteMetrics = 'MinuteMetrics';
cCorsRule = 'CorsRule';
cCors = 'Cors';
cVersion = 'Version';
cEnabled = 'Enabled';
cDelete = 'Delete';
cRead = 'Read';
cWrite = 'Write';
cDays = 'Days';
cIncludeAPIs = 'IncludeAPIs';
cAllowedOrigins = 'AllowedOrigins';
cAllowedMethods = 'AllowedMethods';
cExposedHeaders = 'ExposedHeaders';
cAllowedHeaders = 'AllowedHeaders';
cMaxAgeInSeconds = 'MaxAgeInSeconds';
cStorageServiceStats = 'StorageServiceStats';
cGeoReplication = 'GeoReplication';
cStatus = 'Status';
cLastSyncTime = 'LastSyncTime';
cLiveStatus = 'live';
cBootstrapStatus = 'bootstrap';
cUnavailableStatus = 'unavailable';
type
/// <summary>Class to store CORS rules.</summary>
TCorsRule = class
private
/// <summary>The origin domains that are permitted to make a request against the storage service via CORS.</summary>
FAllowedOrigins: TStrings;
/// <summary>The methods (HTTP request verbs) that the origin domain may use for a CORS request.</summary>
FAllowedMethods: TStrings;
/// <summary>The maximum amount time that a browser should cache the preflight OPTIONS request.</summary>
FMaxAgeInSeconds: Integer;
/// <summary>The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer.</summary>
FExposedHeaders: TStrings;
/// <summary>The request headers that the origin domain may specify on the CORS request.</summary>
FAllowedHeaders: TStrings;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXMLNode(const AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
/// <summary>Return the list of allowed origins.</summary>
function GetAllowedOrigins: TArray<String>;
/// <summary>Return the list of allowed headers.</summary>
function GetAllowedHeaders: TArray<String>;
/// <summary>Return the list of allowed methods.</summary>
function GetAllowedMethods: TArray<String>;
/// <summary>Return the list of exposed methods.</summary>
function GetExposedHeaders: TArray<String>;
public
/// <summary>Creates a new instance of TCorsRule.</summary>
constructor Create;
/// <summary>Frees the lists and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Add a new origin domain to the list.</summary>
procedure AddAllowedOrigin(const AValue: string);
/// <summary>Add a new allowed header to the list.</summary>
procedure AddAllowedHeader(const AValue: string);
/// <summary>Add a new exposed header to the list.</summary>
procedure AddExposedHeader(const AValue: string);
/// <summary>Add a new allowed method to the list.</summary>
procedure AddAllowedMethod(const AValue: string);
/// <summary>The origin domains that are permitted to make a request against the storage service via CORS.</summary>
property AllowedOrigins: TArray<String> read GetAllowedOrigins;
/// <summary>The methods (HTTP request verbs) that the origin domain may use for a CORS request.</summary>
property AllowedMethods: TArray<String> read GetAllowedMethods;
/// <summary>The maximum amount time that a browser should cache the preflight OPTIONS request.</summary>
property MaxAgeInSeconds: Integer read FMaxAgeInSeconds write FMaxAgeInSeconds;
/// <summary>The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer.</summary>
property ExposedHeaders: TArray<String> read GetExposedHeaders;
/// <summary>The request headers that the origin domain may specify on the CORS request.</summary>
property AllowedHeaders: TArray<String> read GetAllowedHeaders;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
/// <summary>Class to store service properties.</summary>
TStorageServiceProperties = class
private type
/// <summary>Class to store service retetition policies.</summary>
TRetentionPolicy = class
private
/// <summary>Indicates whether a retention policy is enabled for the storage service.</summary>
FEnabled: Boolean;
/// <summary>Indicates the number of days that metrics or logging data is retained. All data older than this value will be deleted.</summary>
FDays: Integer;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXMLNode(const AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
public
/// <summary>Indicates whether a retention policy is enabled for the storage service.</summary>
property Enabled: Boolean read FEnabled write FEnabled;
/// <summary>Indicates the number of days that metrics or logging data is retained. All data older than this value will be deleted.</summary>
property Days: Integer read FDays write FDays;
/// <summary>The XML representation</summary>
property XML: string read GetXML;
end;
/// <summary>Class to store request statistics.</summary>
TMetric = class
private
/// <summary>Indicates whether metrics are enabled for the service.</summary>
FEnabled: Boolean;
/// <summary>Indicates whether metrics generate summary statistics for called API operations.</summary>
FIncludeAPI: Boolean;
/// <summary>Store a retention policy.</summary>
FRetentionPolicy: TRetentionPolicy;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXMLNode(const AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
/// <summary>Return the XML node name.</summary>
/// <returns>Return the XML node name.</returns>
function GetNodeName: string; virtual;
public
/// <summary>Creates a new instance of TMetric.</summary>
constructor Create;
/// <summary>Frees the Retention Policy and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Indicates whether metrics are enabled for the service.</summary>
property Enabled: Boolean read FEnabled write FEnabled;
/// <summary>Indicates whether metrics generate summary statistics for called API operations.</summary>
property IncludeAPI: Boolean read FIncludeAPI write FIncludeAPI;
/// <summary>Store a retention policy.</summary>
property RetentionPolicy: TRetentionPolicy read FRetentionPolicy;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
/// <summary>Class to store request statistics grouped by API in hourly.</summary>
THourMetric = class(TMetric)
private
/// <summary>Return the XML node name.</summary>
/// <returns>Return the XML node name.</returns>
function GetNodeName: string; override;
end;
/// <summary>Class to store request statistics for each minute.</summary>
TMinuteMetric = class(TMetric)
private
/// <summary>Return the XML node name.</summary>
/// <returns>Return the XML node name.</returns>
function GetNodeName: string; override;
end;
/// <summary>Class to store Azure Analytics Logging settings.</summary>
TLogging = class
private
/// <summary>Indicates whether delete requests are being logged.</summary>
FLogDelete: Boolean;
/// <summary>Indicates whether read requests are being logged.</summary>
FLogRead: Boolean;
/// <summary>Indicates whether write requests are being logged.</summary>
FLogWrite: Boolean;
/// <summary>Store a retention policy.</summary>
FRetentionPolicy: TRetentionPolicy;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXMLNode(AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
public
/// <summary>Creates a new instance of TLogging.</summary>
constructor Create;
/// <summary>Frees the Retention Policy and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Indicates whether delete requests are being logged.</summary>
property LogDelete: Boolean read FLogDelete write FLogDelete;
/// <summary>Indicates whether read requests are being logged.</summary>
property LogRead: Boolean read FLogRead write FLogRead;
/// <summary>Indicates whether write requests are being logged.</summary>
property LogWrite: Boolean read FLogWrite write FLogWrite;
/// <summary>Store a retention policy.</summary>
property RetentionPolicy: TRetentionPolicy read FRetentionPolicy;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
/// <summary>Class to store the rule list in the service.</summary>
TCors = class
private
/// <summary>Store the rule list in the service.</summary>
FRules: TList<TCorsRule>;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXMLNode(const AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
/// <summary>Return the rule list.</summary>
function GetRules: TArray<TCorsRule>;
public
/// <summary>Creates a new instance of TCors.</summary>
constructor Create;
/// <summary>Frees the Rules list and destroys the instance</summary>
destructor Destroy; override;
/// <summary>Add a new rule to the rule list.</summary>
procedure AddRule(const AValue: TCorsRule);
/// <summary>Store the rule list in the service.</summary>
property Rules: TArray<TCorsRule> read GetRules;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
private
/// <summary>Store Azure Analytics Logging settings.</summary>
FLogging: TLogging;
/// <summary>Store request statistics grouped by API in hourly.</summary>
FHourMetrics: THourMetric;
/// <summary>Store request statistics for each minute.</summary>
FMinuteMetrics: TMinuteMetric;
/// <summary>Store the rule list in the service.</summary>
FCors: TCors;
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
public
/// <summary>Creates a new instance of TStorageServiceProperties.</summary>
constructor Create;
/// <summary>Destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXML(const AValue: string);
/// <summary>Store Azure Analytics Logging settings.</summary>
property Logging: TLogging read FLogging;
/// <summary>Store request statistics grouped by API in hourly.</summary>s
property HourMetrics: THourMetric read FHourMetrics;
/// <summary>Store request statistics for each minute.</summary>
property MinuteMetrics: TMinuteMetric read FMinuteMetrics;
/// <summary>Store the rule list in the service.</summary>
property Cors: TCors read FCors;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
/// <summary>Class to store service stats</summary>
TStorageServiceStats = class
type
/// <summary>
/// The status of the secondary location. Possible values are:
/// live: Indicates that the secondary location is active and operational.
/// bootstrap: Indicates initial synchronization from the primary location to the secondary location is in progress. This typically occurs when replication is first enabled.
/// unavailable: Indicates that the secondary location is temporarily unavailable.
/// </summary>
TGRStatus = (Live, Bootstrap, Unavailable);
private type
/// <summary>Class to store the georeplication statistics.</summary>
TGeoReplication = class
private
/// <summary>The status of the secondary location.</summary>
FStatus: TGRStatus;
/// <summary>A GMT date/time value, to the second.</summary>
FLastSyncTime: string;
/// <summary>Return the status of the secondary location.</summary>
/// <param name="AValue">The description of the status.</param>
/// <returns>Return the status value.</returns>
function GetStatus(const AValue: string): TGRStatus;
/// <summary>Return the status description of the secondary location.</summary>
/// <param name="AValue">The status value.</param>
/// <returns>Return the status description.</returns>
function GetStatusDef(AValue: TGRStatus): string;
/// <summary>Initiates the class with the values from a XML node</summary>
procedure LoadFromXMLNode(const AValue: IXMLNode);
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
public
/// <summary>The status of the secondary location.</summary>
property Status: TGRStatus read FStatus write FStatus;
/// <summary>A GMT date/time value, to the second.</summary>
property LastSyncTime: string read FLastSyncTime write FLastSyncTime;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
private
/// <summary>The georeplication statistics.</summary>
FGeoReplication: TGeoReplication;
/// <summary>Return the XML representation.</summary>
/// <returns>Return the XML representation.</returns>
function GetXML: string;
public
/// <summary>Creates a new instance of TStorageServiceStats.</summary>
constructor Create;
/// <summary>Destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Initiates the class with the values from a XML node.</summary>
procedure LoadFromXML(const AValue: String);
/// <summary>The georeplication statistics.</summary>
property GeoReplication: TGeoReplication read FGeoReplication;
/// <summary>The XML representation.</summary>
property XML: string read GetXML;
end;
implementation
uses
System.SysUtils;
function WriteOpenTag(const ANAme: string): string;
begin
Result := '<' + AName + '>';
end;
function WriteCloseTag(const AName: string): string;
begin
Result := '</' + AName + '>';
end;
function WriteEmptyTag(const AName: string): string;
begin
Result := '<' + AName + '/>';
end;
function WriteValueTag(const AName, AValue: string): string;
begin
Result := WriteOpenTag(AName) + AValue + WriteCloseTag(AName);
end;
{ TStorageServiceProperties }
constructor TStorageServiceProperties.Create;
begin
FLogging := TLogging.Create;
FHourMetrics := THourMetric.Create;
FMinuteMetrics := TMinuteMetric.Create;
FCors := TCors.Create;
end;
destructor TStorageServiceProperties.Destroy;
begin
FLogging.Free;
FHourMetrics.Free;
FMinuteMetrics.Free;
FCors.Free;
inherited;
end;
function TStorageServiceProperties.GetXML: string;
begin
Result :=
WriteOpenTag(cStorageServiceProperties) +
FLogging.XML + FHourMetrics.XML + FMinuteMetrics.XML + FCors.XML +
WriteCloseTag(cStorageServiceProperties);
end;
procedure TStorageServiceProperties.LoadFromXML(const AValue: string);
var
LXmlDoc: IXMLDocument;
LRootNode: IXMLNode;
LChildNode: IXMLNode;
begin
if AValue <> '' then
begin
LXmlDoc := TXMLDocument.Create(nil);
LXmlDoc.LoadFromXML(AValue);
LRootNode := LXmlDoc.DocumentElement;
if (LRootNode <> nil) and LRootNode.NodeName.Equals(cStorageServiceProperties) and (LRootNode.HasChildNodes) then
begin
LChildNode := LRootNode.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cLogging) then
FLogging.LoadFromXMLNode(LChildNode)
else if LChildNode.NodeName.Equals(cHourMetrics) then
FHourMetrics.LoadFromXMLNode(LChildNode)
else if LChildNode.NodeName.Equals(cMinuteMetrics) then
FMinuteMetrics.LoadFromXMLNode(LChildNode)
else if LChildNode.NodeName.Equals(cCors) then
FCors.LoadFromXMLNode(LChildNode);
LChildNode := LChildNode.NextSibling;
end;
end;
end;
end;
{ TLogging }
constructor TStorageServiceProperties.TLogging.Create;
begin
FRetentionPolicy := TRetentionPolicy.Create;
end;
destructor TStorageServiceProperties.TLogging.Destroy;
begin
FRetentionPolicy.Destroy;
inherited;
end;
function TStorageServiceProperties.TLogging.GetXML: string;
begin
Result :=
WriteOpenTag(cLogging) +
WriteValueTag(cVersion, cStorageAnalyticsVersion) +
WriteValueTag(cDelete, FLogDelete.ToString(TUseBoolStrs.True)) +
WriteValueTag(cRead, FLogRead.ToString(TUseBoolStrs.True)) +
WriteValueTag(cWrite, FLogWrite.ToString(TUseBoolStrs.True)) +
FRetentionPolicy.XML +
WriteCloseTag(cLogging);
end;
procedure TStorageServiceProperties.TLogging.LoadFromXMLNode(AValue: IXMLNode);
var
LChildNode: IXMLNode;
begin
if (AValue <> nil) and AValue.NodeName.Equals(cLogging) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cDelete) then
FLogDelete := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cRead) then
FLogRead := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cWrite) then
FLogWrite := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cRetentionPolicy) then
FRetentionPolicy.LoadFromXMLNode(LChildNode);
LChildNode := LChildNode.NextSibling;
end;
end;
end;
{ TRetentionPolicy }
function TStorageServiceProperties.TRetentionPolicy.GetXML: string;
begin
Result := WriteOpenTag(cRetentionPolicy) +
WriteValueTag(cEnabled, FEnabled.ToString(TUseBoolStrs.True));
if FEnabled then
Result := Result + WriteValueTag(cDays, FDays.ToString);
Result := Result + WriteCloseTag(cRetentionPolicy);
end;
procedure TStorageServiceProperties.TRetentionPolicy.LoadFromXMLNode(const AValue: IXMLNode);
var
LChildNode: IXMLNode;
begin
if (AValue <> nil) and AValue.NodeName.Equals(cRetentionPolicy) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cEnabled) then
FEnabled := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cDays) then
FDays := LChildNode.NodeValue;
LChildNode := LChildNode.NextSibling;
end;
end;
end;
{ TMetric }
constructor TStorageServiceProperties.TMetric.Create;
begin
FRetentionPolicy := TRetentionPolicy.Create;
end;
destructor TStorageServiceProperties.TMetric.Destroy;
begin
FRetentionPolicy.Free;
inherited;
end;
function TStorageServiceProperties.TMetric.GetNodeName: string;
begin
Result := cMetrics;
end;
function TStorageServiceProperties.TMetric.GetXML: string;
begin
Result :=
WriteOpenTag(GetNodeName) +
WriteValueTag(cVersion, cStorageAnalyticsVersion) +
WriteValueTag(cEnabled, FEnabled.ToString(TUseBoolStrs.True));
if FEnabled then
Result := Result + WriteValueTag(cIncludeAPIs, FIncludeAPI.ToString(TUseBoolStrs.True));
Result := Result + FRetentionPolicy.XML + WriteCloseTag(GetNodeName);
end;
procedure TStorageServiceProperties.TMetric.LoadFromXMLNode(const AValue: IXMLNode);
var
LChildNode: IXMLNode;
begin
if (AValue <> nil) and AValue.NodeName.Equals(GetNodeName) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cEnabled) then
FEnabled := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cIncludeAPIs) then
FIncludeAPI := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cRetentionPolicy) then
FRetentionPolicy.LoadFromXMLNode(LChildNode);
LChildNode := LChildNode.NextSibling;
end;
end;
end;
{ THourMetric }
function TStorageServiceProperties.THourMetric.GetNodeName: string;
begin
Result := cHourMetrics;
end;
{ TMinuteMetric }
function TStorageServiceProperties.TMinuteMetric.GetNodeName: string;
begin
Result := cMinuteMetrics;
end;
{ TCors }
procedure TStorageServiceProperties.TCors.AddRule(const AValue: TCorsRule);
begin
FRules.Add(AValue);
end;
constructor TStorageServiceProperties.TCors.Create;
begin
FRules := TList<TCorsRule>.Create;
end;
destructor TStorageServiceProperties.TCors.Destroy;
var
Rule: TCorsRule;
begin
for Rule in FRules do
Rule.Free;
FRules.Free;
inherited;
end;
function TStorageServiceProperties.TCors.GetRules: TArray<TCorsRule>;
begin
Result := FRules.ToArray;
end;
function TStorageServiceProperties.TCors.GetXML: string;
var
Rule: TCorsRule;
begin
if FRules.Count = 0 then
Result := WriteEmptyTag(cCors)
else
begin
Result := WriteOpenTag(cCors);
for Rule in FRules do
Result := Result + Rule.XML;
Result := Result + WriteCloseTag(cCors);
end;
end;
procedure TStorageServiceProperties.TCors.LoadFromXMLNode(const AValue: IXMLNode);
var
LChildNode: IXMLNode;
LRule: TCorsRule;
begin
if (AValue <> nil) and AValue.NodeName.Equals(cCors) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cCorsRule) then
begin
LRule := TCorsRule.Create;
LRule.LoadFromXMLNode(LChildNode);
FRules.Add(LRule);
end;
LChildNode := LChildNode.NextSibling;
end;
end;
end;
{ TCorsRule }
procedure TCorsRule.AddAllowedHeader(const AValue: string);
begin
FAllowedHeaders.Add(AValue);
end;
procedure TCorsRule.AddAllowedMethod(const AValue: string);
begin
FAllowedMethods.Add(AValue);
end;
procedure TCorsRule.AddAllowedOrigin(const AValue: string);
begin
FAllowedOrigins.Add(AValue);
end;
procedure TCorsRule.AddExposedHeader(const AValue: string);
begin
FExposedHeaders.Add(AValue);
end;
constructor TCorsRule.Create;
begin
FAllowedOrigins := TStringList.Create;
FAllowedMethods := TStringList.Create;
FExposedHeaders := TStringList.Create;
FAllowedHeaders := TStringList.Create;
end;
destructor TCorsRule.Destroy;
begin
FAllowedOrigins.Free;
FAllowedMethods.Free;
FExposedHeaders.Free;
FAllowedHeaders.Free;
inherited;
end;
function TCorsRule.GetAllowedHeaders: TArray<String>;
begin
Result := FAllowedHeaders.ToStringArray;
end;
function TCorsRule.GetAllowedMethods: TArray<String>;
begin
Result := FAllowedMethods.ToStringArray;
end;
function TCorsRule.GetAllowedOrigins: TArray<String>;
begin
Result := FAllowedOrigins.ToStringArray;
end;
function TCorsRule.GetExposedHeaders: TArray<String>;
begin
Result := FExposedHeaders.ToStringArray;
end;
function TCorsRule.GetXML: string;
begin
Result :=
WriteOpenTag(cCorsRule) +
WriteValueTag(cAllowedOrigins, FAllowedOrigins.CommaText) +
WriteValueTag(cAllowedMethods, FAllowedMethods.CommaText) +
WriteValueTag(cMaxAgeInSeconds, FMaxAgeInSeconds.ToString) +
WriteValueTag(cExposedHeaders, FExposedHeaders.CommaText) +
WriteValueTag(cAllowedHeaders, FAllowedHeaders.CommaText) +
WriteCloseTag(cCorsRule);
end;
procedure TCorsRule.LoadFromXMLNode(const AValue: IXMLNode);
var
LChildNode: IXMLNode;
begin
if (AValue <> nil) and AValue.NodeName.Equals(cCorsRule) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cAllowedOrigins) then
FAllowedOrigins.CommaText := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cAllowedMethods) then
FAllowedMethods.CommaText := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cMaxAgeInSeconds) then
FMaxAgeInSeconds := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cExposedHeaders) then
FExposedHeaders.CommaText := LChildNode.NodeValue
else if LChildNode.NodeName.Equals(cAllowedHeaders) then
FAllowedHeaders.CommaText := LChildNode.NodeValue;
LChildNode := LChildNode.NextSibling;
end;
end;
end;
{ TStorageServiceStats.TGeoReplication }
function TStorageServiceStats.TGeoReplication.GetStatus(const AValue: string): TGRStatus;
begin
if AValue.Equals(cLiveStatus) then
Result := TGRStatus.Live
else if AValue.Equals(cBootstrapStatus) then
Result := TGRStatus.Bootstrap
else
Result := TGRStatus.Unavailable;
end;
function TStorageServiceStats.TGeoReplication.GetStatusDef(AValue: TGRStatus): string;
begin
case AValue of
TStorageServiceStats.TGRStatus.Live: Result := cLiveStatus;
TStorageServiceStats.TGRStatus.Bootstrap: Result := cBootstrapStatus;
TStorageServiceStats.TGRStatus.Unavailable: Result := cUnavailableStatus;
end;
end;
procedure TStorageServiceStats.TGeoReplication.LoadFromXMLNode(const AValue: IXMLNode);
var
LChildNode: IXMLNode;
begin
if (AValue <> nil) and AValue.NodeName.Equals(cGeoReplication) and (AValue.HasChildNodes) then
begin
LChildNode := AValue.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cStatus) then
FStatus := GetStatus(LChildNode.NodeValue)
else if LChildNode.NodeName.Equals(cLastSyncTime) then
FLastSyncTime := LChildNode.NodeValue;
LChildNode := LChildNode.NextSibling;
end;
end;
end;
function TStorageServiceStats.TGeoReplication.GetXML: string;
begin
Result :=
WriteOpenTag(cGeoReplication) +
WriteValueTag(cStatus, GetStatusDef(FStatus)) +
WriteValueTag(cLastSyncTime, FLastSyncTime) +
WriteCloseTag(cGeoReplication);
end;
{ TStorageServiceStats }
constructor TStorageServiceStats.Create;
begin
FGeoReplication := TGeoReplication.Create;
end;
destructor TStorageServiceStats.Destroy;
begin
FGeoReplication.Free;
inherited;
end;
procedure TStorageServiceStats.LoadFromXML(const AValue: String);
var
LXmlDoc: IXMLDocument;
LRootNode: IXMLNode;
LChildNode: IXMLNode;
begin
if AValue <> '' then
begin
LXmlDoc := TXMLDocument.Create(nil);
LXmlDoc.LoadFromXML(AValue);
LRootNode := LXmlDoc.DocumentElement;
if (LRootNode <> nil) and LRootNode.NodeName.Equals(cStorageServiceStats) and (LRootNode.HasChildNodes) then
begin
LChildNode := LRootNode.ChildNodes.First;
while LChildNode <> nil do
begin
if LChildNode.NodeName.Equals(cGeoReplication) then
FGeoReplication.LoadFromXMLNode(LChildNode);
LChildNode := LChildNode.NextSibling;
end;
end;
end;
end;
function TStorageServiceStats.GetXML: string;
begin
Result :=
WriteOpenTag(cStorageServiceStats) +
FGeoReplication.XML +
WriteCloseTag(cStorageServiceStats);
end;
end.
|
unit AHoraAgendaChamado;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, Localizacao,
ComCtrls, Mask, UnDados, DBKeyViolation, UnChamado;
type
TFHoraAgendaChamado = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
Label4: TLabel;
SpeedButton2: TSpeedButton;
SpeedButton4: TSpeedButton;
ECliente: TEditLocaliza;
Label3: TLabel;
ENumChamado: TEditColor;
ESolicitante: TEditColor;
Label7: TLabel;
Label12: TLabel;
SpeedButton3: TSpeedButton;
Label13: TLabel;
ETecnico: TEditLocaliza;
Label1: TLabel;
Bevel1: TBevel;
EData: TCalendario;
Label2: TLabel;
EHora: TMaskEditColor;
Label5: TLabel;
ECalendario: TMonthCalendar;
Localiza: TConsultaPadrao;
ValidaGravacao1: TValidaGravacao;
ECidade: TEditColor;
Label6: TLabel;
SpeedButton1: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure EDataChange(Sender: TObject);
procedure ECalendarioClick(Sender: TObject);
procedure ETecnicoChange(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure EClienteRetorno(Retorno1, Retorno2: String);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
VprAcao : Boolean;
VprDChamado : TRBDChamado;
FunChamado : TRBFuncoesChamado;
procedure CarDTela(VpaDChamado : TRBDChamado);
function DadosValidos : string;
public
{ Public declarations }
function AlteraAgenda(VpaDChamado : TRBDChamado):Boolean;
end;
var
FHoraAgendaChamado: TFHoraAgendaChamado;
implementation
uses APrincipal,FunString, ConstMsg, funDAta, ANovoCliente,
ANovoChamadoTecnico, Constantes;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFHoraAgendaChamado.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
FunChamado := TRBFuncoesChamado.cria(FPrincipal.BaseDados);
if ((varia.CNPJFilial = CNPJ_COPYLINE) or
(varia.CNPJFilial = CNPJ_Impox)) then
begin
SpeedButton1.Visible := false;
SpeedButton4.Visible := false;
end;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFHoraAgendaChamado.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Funchamado.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFHoraAgendaChamado.CarDTela(VpaDChamado : TRBDChamado);
begin
ENumChamado.AInteiro := VpaDChamado.NumChamado;
ECliente.AInteiro := VpaDChamado.CodCliente;
ESolicitante.Text := VpaDChamado.NomSolicitante;
ECliente.Atualiza;
ETecnico.AInteiro := VpaDChamado.CodTecnico;
ETecnico.Atualiza;
EHora.Text := FormatDateTime('HH:MM',VpaDChamado.DatPrevisao);
EData.DateTime := VpaDChamado.DatPrevisao;
ECalendario.Date := VpaDChamado.DatPrevisao;
end;
{******************************************************************************}
function TFHoraAgendaChamado.DadosValidos : string;
begin
result := '';
{ if DeletaChars(DeletaChars(EHora.Text,'0'),':') = '' then
result := 'HORA NÃO PREENCHIDA!!!'#13'É necessário preencher a hora do agendamento.';}
if result = '' then
begin
try
StrToTime(EHora.Text)
except
result := 'HORA INVÁLIDA!!!'#13'A hora digitada não está em um formato válido.';
end;
end;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.BCancelarClick(Sender: TObject);
begin
vpracao := false;
CLOSE;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.BGravarClick(Sender: TObject);
var
VpfResultado : String;
begin
VpfResultado := DadosValidos;
if VpfResultado = '' then
FunChamado.AlteraAgendaTecnico(VprDChamado.CodFilial,VprDChamado.NumChamado,ETecnico.AInteiro,MontaData(dia(EData.Date),mes(EData.Date),ano(EData.Date))+StrToTime(EHora.text));
if Vpfresultado = '' then
begin
VprAcao := true;
VprDChamado.CodTecnico := ETecnico.AInteiro;
close;
end
else
aviso(VpfREsultado);
end;
{******************************************************************************}
function TFHoraAgendaChamado.AlteraAgenda(VpaDChamado : TRBDChamado):Boolean;
begin
VprDChamado := VpaDChamado;
CarDTela(VpaDChamado);
ShowModal;
result := Vpracao;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.EDataChange(Sender: TObject);
begin
ECalendario.Date := EData.DateTime;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.ECalendarioClick(Sender: TObject);
begin
EData.DateTime := ECalendario.Date;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.ETecnicoChange(Sender: TObject);
begin
ValidaGravacao1.execute;
end;
procedure TFHoraAgendaChamado.SpeedButton4Click(Sender: TObject);
begin
if ECliente.AInteiro <> 0 then
begin
FNovoCliente := TFNovoCliente.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoCliente'));
FNovoCliente.ConsultaCliente(ECliente.AInteiro);
FNovoCliente.free;
end;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.EClienteRetorno(Retorno1, Retorno2: String);
begin
ECidade.Text := Retorno1;
end;
{******************************************************************************}
procedure TFHoraAgendaChamado.SpeedButton1Click(Sender: TObject);
begin
FNovoChamado := TFNovoChamado.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoChamado'));
FNovoChamado.ConsultaChamado(VprDChamado.CodFilial,VprDChamado.NumChamado);
FNovoChamado.free;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFHoraAgendaChamado]);
end.
|
{***************************************************************
*
* Project : NewsReader
* Unit Name: mainform
* Purpose :
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:30:19
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit mainform;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QComCtrls, QStdCtrls, QActnList,
QMenus, QExtCtrls, QImgList,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ActnList, Menus,
ExtCtrls, ImgList,
{$ENDIF}
windows, messages, SysUtils, Classes, IdComponent, IdTCPConnection,
IdTCPClient, IdMessageClient, IdNNTP, IdBaseComponent, IdIntercept,
IdSSLIntercept, IdSSLOpenSSL, IdMessage, ToolWin, IdAntiFreezeBase,
IdAntiFreeze;
type
TForm1 = class(TForm)
IdOSSLNNTP: TIdConnectionInterceptOpenSSL;
IdNNTP1: TIdNNTP;
mmnuMainProgram: TMainMenu;
ActionList1: TActionList;
actConnected: TAction;
actExit: TAction;
File1: TMenuItem;
Connected1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
actOptions: TAction;
View1: TMenuItem;
actOptions1: TMenuItem;
StatusBar1: TStatusBar;
pnlTopPains: TPanel;
lvNewsGroups: TListView;
lvArticles: TListView;
spltrTopPains: TSplitter;
ToolBar1: TToolBar;
spltrMessageList: TSplitter;
ToolButton1: TToolButton;
ImageList1: TImageList;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
pnlMessageView: TPanel;
redtArticle: TRichEdit;
lvMessageParts: TListView;
sptrlMessageParts: TSplitter;
IdAntiFreeze1: TIdAntiFreeze;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
acStop: TAction;
Stop1: TMenuItem;
IdMessage1: TIdMessage;
procedure IdNNTP1NewsgroupList(const ANewsgroup: string; const ALow,
AHigh: Cardinal; const AType: string; var ACanContinue: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure lvNewsGroupsClick(Sender: TObject);
procedure lvArticlesClick(Sender: TObject);
procedure actConnectedExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actOptionsExecute(Sender: TObject);
procedure IdNNTP1Status(axSender: TObject; const axStatus: TIdStatus;
const asStatusText: string);
procedure IdNNTP1Work(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
procedure IdNNTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
procedure FormCreate(Sender: TObject);
procedure IdOSSLNNTPGetPassword(var Password: string);
procedure IdOSSLNNTPStatusInfo(Msg: string);
procedure IdNNTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
procedure acStopExecute(Sender: TObject);
procedure lvMessagePartsClick(Sender: TObject);
private
FNewsGroupsRetrieved: Integer;
procedure OriginalArticleView;
function ParseXOVERItem(ALine: string): TListItem;
public
FStopped: Boolean;
end;
var
Form1: TForm1;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
uses
IdGlobal, IniFiles, setup, ConnectThread;
procedure TForm1.IdNNTP1NewsgroupList(const ANewsgroup: string; const ALow,
AHigh: Cardinal; const AType: string; var ACanContinue: Boolean);
var
li: TListItem;
begin
Inc(FNewsGroupsRetrieved);
StatusBar1.SimpleText := Format('Retreived %d newsgroups',
[FNewsGroupsRetrieved]);
li := lvNewsGroups.Items.Add;
li.Caption := ANewsgroup;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
Ini: TIniFile;
begin
{make sure that we aren't connected to the server}
IdNNTP1.Disconnect;
{Save our newsreader settings}
Ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
Ini.WriteString('Server', 'Host_Name', IdNNTP1.Host);
Ini.WriteInteger('Server', 'Port', IdNNTP1.Port);
Ini.WriteString('Server', 'User_ID', IdNNTP1.UserId);
Ini.WriteString('Server', 'Password', IdNNTP1.Password);
Ini.WriteBool('Server', 'Use_SSL', IdNNTP1.InterceptEnabled);
Ini.WriteString('Server', 'Certificate', IdOSSLNNTP.SSLOptions.CertFile);
Ini.WriteString('Server', 'Root', IdOSSLNNTP.SSLOptions.RootCertFile);
Ini.WriteString('Server', 'Key', IdOSSLNNTP.SSLOptions.KeyFile);
finally
Ini.Free;
end;
end;
procedure TForm1.lvNewsGroupsClick(Sender: TObject);
var
idx: Integer;
strs: TStringList;
begin
if Screen.Cursor <> crDefault then
begin
exit;
end;
Screen.Cursor := crHourGlass;
try
if (lvNewsGroups.Selected <> nil) then
try
// reconnect
if not IdNNTP1.Connected then
begin
ConnectThreaded(IdNNTP1);
end;
strs := TStringList.Create;
try
IdNNTP1.SelectGroup(lvNewsGroups.Selected.Caption);
lvArticles.Items.Clear;
{Get article information from Lowest to Highest articles}
IdNNTP1.SendXOVER(IntToStr(IdNNTP1.MsgLow) + '-' +
IntToStr(IdNNTP1.MsgHigh), strs);
lvArticles.Items.BeginUpdate;
try
lvArticles.Items.Clear;
idx := 0;
while idx < Strs.Count do
begin
ParseXOVERItem(Strs[idx]);
Inc(idx);
end;
finally
lvArticles.Items.EndUpdate;
end;
finally
FreeAndNil(strs);
end;
except
IdNNTP1.Disconnect;
end;
finally Screen.Cursor := crDefault;
end;
end;
function TForm1.ParseXOVERItem(ALine: string): TListItem;
var
Subject, From, References, MsgId, ExtraData: string;
ArticleIndex, ByteCount, LineCount: Cardinal;
Date: TDateTime;
begin
ParseXOVER(ALine, ArticleIndex, Subject, From, Date, MsgId, References,
ByteCount, LineCount, ExtraData);
Result := lvArticles.Items.Add;
{ Article Index }
{We use the data property to store the integer.
I know typecasting can be ugly}
Result.Data := Pointer(ArticleIndex);
{ Subject }
Result.Caption := Subject;
{ From }
Result.SubItems.Add(From);
{ Date }
Result.SubItems.Add(DateTimeToStr(Date));
{Line Count}
Result.SubItems.Add(IntToStr(LineCount));
{Message ID -workaround because the GetArticle does not seem to work with
article indexes}
Result.SubItems.Add(MsgId);
end;
procedure TForm1.lvArticlesClick(Sender: TObject);
var
partIdx: Integer;
li: TListItem;
begin
if Screen.Cursor <> crDefault then
begin
exit;
end;
Screen.Cursor := crHourGlass;
try
if lvArticles.Selected <> nil then
begin
lvMessageParts.Items.Clear;
{We to typecast the Selected.Data which is the article index}
IdNNTP1.GetArticle(Integer(lvArticles.Selected.Data), '', IdMessage1);
OriginalArticleView;
if IdMessage1.MessageParts.Count > 0 then
begin
redtArticle.Lines.AddStrings(TIdText(IdMessage1.MessageParts.Items[0]).Body);
if IdMessage1.MessageParts.Count > 1 then
begin
sptrlMessageParts.Visible := True;
lvMessageParts.Visible := True;
li := lvMessageParts.Items.Add;
li.Caption := 'Original View';
for PartIdx := 0 to IdMessage1.MessageParts.Count - 1 do
begin
li := lvMessageParts.Items.Add;
if IdMessage1.MessageParts[PartIdx] is TIdText then
begin
li.Caption := 'Text Part';
end
else
begin
li.Caption := (IdMessage1.MessageParts[PartIdx] as
TIdAttachment).FileName;
end;
end;
end
else
begin
{Hide the message part list}
lvMessageParts.Visible := False;
sptrlMessageParts.Visible := False;
end;
end;
end;
finally Screen.Cursor := crDefault;
end;
end;
procedure TForm1.actConnectedExecute(Sender: TObject);
var
idx: Integer;
li: TListItem;
NewsGroup: string;
Hi, Lo: Cardinal;
Stat: string;
NewsList: TStringList;
begin
if Screen.Cursor <> crDefault then
begin
exit;
end;
Screen.Cursor := crHourGlass;
try
{This works as a toggle menu item}
if not IdNNTP1.Connected then
begin
IdNNTP1.Connect;
try
NewsList := TStringList.Create;
try
{Get newsgroup list}
IdNNTP1.GetNewsgroupList(NewsList);
{process newsgroups after list}
idx := 0;
while idx < NewsList.Count do
begin
li := lvNewsGroups.Items.Add;
ParseNewsGroup(NewsList[idx], NewsGroup, Hi, Lo, Stat);
{Newsgroup name}
li.Caption := Newsgroup;
{Article estimated to be in newsgroup}
{if lo is greater than Hi, we have no articles}
if (Lo >= Hi) then
li.SubItems.Add('None')
else
li.SubItems.Add(IntToStr(Hi - Lo));
{Newsgroup status}
{This should never be nil but just in case, we check}
if Length(LowerCase(Stat[1])) > 0 then
case Stat[1] of
'y': li.SubItems.Add('Permitted');
'n': li.SubItems.Add('Read-Only');
'm': li.SubItems.Add('Moderated');
end;
Inc(idx);
end;
finally
NewsList.Free;
end;
except
IdNNTP1.Disconnect;
end; // try finally
end // if Not Connected then
else
begin
{Close the connection}
IdNNTP1.Disconnect;
{Clear the List Views}
lvNewsGroups.Items.Clear;
lvArticles.Items.Clear;
end; //else .. if Not IdNNTP1.Connected then
finally Screen.Cursor := crDefault;
end;
end;
procedure TForm1.actExitExecute(Sender: TObject);
begin
Close;
end;
procedure TForm1.actOptionsExecute(Sender: TObject);
begin
with TfrmNewsSetup.Create(Application) do
try
edtServer.Text := IdNNTP1.Host;
spnedtPort.Value := IdNNTP1.Port;
edtUserID.Text := IdNNTP1.UserId;
edtPassword.Text := IdNNTP1.Password;
chkUseSSL.Checked := IdNNTP1.InterceptEnabled;
edtCert.Text := IdOSSLNNTP.SSLOptions.CertFile;
edtRoot.Text := IdOSSLNNTP.SSLOptions.RootCertFile;
edtKey.Text := IdOSSLNNTP.SSLOptions.KeyFile;
if ShowModal = mrOk then
begin
IdNNTP1.Host := edtServer.Text;
IdNNTP1.Port := spnedtPort.Value;
IdNNTP1.UserId := edtUserID.Text;
IdNNTP1.Password := edtPassword.Text;
IdNNTP1.InterceptEnabled := chkUseSSL.Checked;
IdOSSLNNTP.SSLOptions.CertFile := edtCert.Text;
IdOSSLNNTP.SSLOptions.RootCertFile := edtRoot.Text;
IdOSSLNNTP.SSLOptions.KeyFile := edtKey.Text;
end; //if ShowModal = mrOk then
finally
Free;
end;
end;
procedure TForm1.IdNNTP1Status(axSender: TObject;
const axStatus: TIdStatus; const asStatusText: string);
begin
StatusBar1.SimpleText := asStatusText;
case axStatus of
hsConnected: actConnected.Checked := True;
hsDisconnected: actConnected.Checked := False;
end;
end;
procedure TForm1.IdNNTP1Work(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
if not FStopped then
begin
if AWorkMode = wmRead then
begin // if AWorkMode = wmRead then
StatusBar1.SimpleText := Format('Received %d from %s. Please wait...',
[AWorkCount, IdNNTP1.Host]);
end
else
begin
StatusBar1.SimpleText := Format('Sent %d to %s. Please wait...',
[AWorkCount, IdNNTP1.Host]);
end; //else..if AWorkMode = wmRead then
end
else
begin
StatusBar1.SimpleText := 'Stopping...';
IdNNTP1.Binding.CloseSocket;
Screen.Cursor := crDefault
end;
end;
procedure TForm1.IdNNTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
acStop.enabled := false;
StatusBar1.SimpleText := 'Ready';
end;
procedure TForm1.FormCreate(Sender: TObject);
var
Ini: TIniFile;
begin
{Retrieve our previous newsreader settings}
Ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
IdNNTP1.Host := Ini.ReadString('Server', 'Host_Name', IdNNTP1.Host);
IdNNTP1.Port := Ini.ReadInteger('Server', 'Port', IdNNTP1.Port);
IdNNTP1.UserId := Ini.ReadString('Server', 'User_ID', IdNNTP1.UserId);
IdNNTP1.Password := Ini.ReadString('Server', 'Password', IdNNTP1.Password);
IdNNTP1.InterceptEnabled := Ini.ReadBool('Server', 'Use_SSL', False);
IdOSSLNNTP.SSLOptions.CertFile := Ini.ReadString('Server', 'Certificate',
IdOSSLNNTP.SSLOptions.CertFile);
IdOSSLNNTP.SSLOptions.RootCertFile := Ini.ReadString('Server', 'Root',
IdOSSLNNTP.SSLOptions.RootCertFile);
IdOSSLNNTP.SSLOptions.KeyFile := Ini.ReadString('Server', 'Key',
IdOSSLNNTP.SSLOptions.KeyFile);
finally
Ini.Free;
end;
end;
procedure TForm1.IdOSSLNNTPGetPassword(var Password: string);
begin
Password := 'aaaa';
end;
procedure TForm1.IdOSSLNNTPStatusInfo(Msg: string);
begin
StatusBar1.SimpleText := Msg;
end;
procedure TForm1.IdNNTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
begin
FStopped := false;
acStop.enabled := true;
Application.ProcessMessages;
end;
procedure TForm1.acStopExecute(Sender: TObject);
begin
FStopped := true;
Screen.Cursor := crDefault
end;
procedure TForm1.OriginalArticleView;
begin
redtArticle.Lines.Clear;
redtArticle.Lines := IdMessage1.Headers;
redtArticle.Lines.Add('');
end;
procedure TForm1.lvMessagePartsClick(Sender: TObject);
begin
if lvMessageParts.Selected <> nil then
begin
if lvMessageParts.Selected.Index = 0 then
OriginalArticleView
else
begin
if IdMessage1.MessageParts[lvMessageParts.Selected.Index - 1] is TIdText
then
begin
redtArticle.Lines.Assign(TIdText(IdMessage1.MessageParts[lvMessageParts.Selected.Index - 1]).Body);
end;
end;
end;
end;
end.
|
unit account_c;
{This file was generated on 27 Oct 2000 17:52:20 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file }
{C:\Examples\IDL2PA~1\Arrays\account.idl. }
{Delphi Pascal unit : account_c }
{derived from IDL module : default }
interface
uses
CORBA,
account_i;
type
TArrayTypeHelper = class;
TAccountHelper = class;
TAccountStub = class;
TArrayTypeHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : account_i.ArrayType);
class function Extract(const _A: CORBA.Any): account_i.ArrayType;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : account_i.ArrayType;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : account_i.ArrayType);
end;
TAccountHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : account_i.Account);
class function Extract(var _A: CORBA.Any) : account_i.Account;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read (const _Input : CORBA.InputStream) : account_i.Account;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : account_i.Account);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : account_i.Account;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : account_i.Account; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : account_i.Account; overload;
end;
TAccountStub = class(CORBA.TCORBAObject, account_i.Account)
public
function balance ( const myArray : account_i.ArrayType): Single; virtual;
end;
implementation
class procedure TArrayTypeHelper.Insert(var _A: CORBA.Any; const _Value : account_i.ArrayType);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TArrayTypeHelper.Write(_Output, _Value);
ORB.PutAny(_A, TArrayTypeHelper.TypeCode, _Output);
end;
class function TArrayTypeHelper.Extract(const _A : CORBA.Any): account_i.ArrayType;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TArrayTypeHelper.Read(_Input);
end;
class function TArrayTypeHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateArrayTC(3, ORB.CreateTC(Integer(tk_short)));
end;
class function TArrayTypeHelper.RepositoryId: string;
begin
Result := 'IDL:ArrayType:1.0';
end;
class function TArrayTypeHelper.Read(const _Input: CORBA.InputStream) : account_i.ArrayType;
var
I0 : Cardinal;
begin
for I0 := 0 to 2 do
begin
_Input.ReadShort(Result[I0]);
end;
end;
class procedure TArrayTypeHelper.Write(const _Output: CORBA.OutputStream; const _Value: account_i.ArrayType);
var
I0 : Cardinal;
begin
for I0 := 0 to 2 do
begin
_Output.WriteShort(_Value[I0]);
end;
end;
class procedure TAccountHelper.Insert(var _A : CORBA.Any; const _Value : account_i.Account);
begin
_A := Orb.MakeObjectRef( TAccountHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TAccountHelper.Extract(var _A : CORBA.Any): account_i.Account;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TAccountHelper.Narrow(_obj, True);
end;
class function TAccountHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'Account');
end;
class function TAccountHelper.RepositoryId : string;
begin
Result := 'IDL:Account:1.0';
end;
class function TAccountHelper.Read(const _Input : CORBA.InputStream) : account_i.Account;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TAccountHelper.Write(const _Output : CORBA.OutputStream; const _Value : account_i.Account);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TAccountHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : account_i.Account;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(account_i.Account, Result) = 0) then
exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TAccountStub.Create(_Obj);
end;
class function TAccountHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : account_i.Account;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TAccountHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : account_i.Account;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
function TAccountStub.balance ( const myArray : account_i.ArrayType): Single;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('balance',True, _Output);
account_c.TArrayTypeHelper.Write(_Output, myArray);
inherited _Invoke(_Output, _Input);
_Input.ReadFloat(Result);
end;
initialization
end. |
unit GrievanceCondoCopyDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls, Grids, Wwtable;
type
TGrievanceCondoCopyDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
GrievanceTable: TTable;
InformationLabel: TLabel;
ParcelGroupBox: TGroupBox;
ParcelGrid: TStringGrid;
ClearButton: TBitBtn;
AddButton: TBitBtn;
DeleteButton: TBitBtn;
CurrentExemptionsTable: TTable;
GrievanceExemptionsTable: TTable;
CurrentAssessmentTable: TTable;
GrievanceExemptionsAskedTable: TwwTable;
GrievanceSpecialDistrictsTable: TTable;
CurrentSpecialDistrictsTable: TTable;
ParcelTable: TTable;
SwisCodeTable: TTable;
PriorAssessmentTable: TTable;
LawyerCodeTable: TTable;
GrievanceLookupTable: TTable;
GrievanceExemptionsAskedLookupTable: TTable;
GroupBox1: TGroupBox;
Label1: TLabel;
EditAskingPercent: TEdit;
procedure OKButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ClearButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LawyerCode, UnitName,
OriginalSwisSBLKey,
PriorYear, GrievanceYear : String;
GrievanceNumber : LongInt;
AskingPercent : Double;
SwisSBLKeyList : TStringList;
Procedure SetNumParcelsLabel(NumParcels : Integer);
Procedure AddOneParcel(SwisSBLKey : String);
Procedure CreateOneGrievance(SwisSBLKey : String;
AskingPercent : Double);
end;
var
GrievanceCondoCopyDialog: TGrievanceCondoCopyDialog;
implementation
{$R *.DFM}
uses WinUtils, Utilitys, PASUtils, GlblVars, GlblCnst,
PASTypes, GrievanceUtilitys, Prog;
{===============================================================}
Procedure TGrievanceCondoCopyDialog.FormShow(Sender: TObject);
var
TempRepresentative : String;
PriorProcessingType, GrievanceProcessingType : Integer;
Quit : Boolean;
begin
UnitName := 'GrievanceCondoCopyDialogUnit';
SwisSBLKeyList := TStringList.Create;
{FXX10082003-1(2.07j1): Don't base the processing type of the current and prior on
the current grievance year, but the year of this grievance.}
GrievanceProcessingType := GetProcessingTypeForTaxRollYear(GrievanceYear);
PriorYear := IntToStr(StrToInt(GrievanceYear) - 1);
PriorProcessingType := GetProcessingTypeForTaxRollYear(PriorYear);
OpenTablesForForm(Self, GrievanceProcessingType);
OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName,
GrievanceProcessingType, Quit);
OpenTableForProcessingType(CurrentAssessmentTable, AssessmentTableName,
GrievanceProcessingType, Quit);
OpenTableForProcessingType(PriorAssessmentTable, AssessmentTableName,
PriorProcessingType, Quit);
OpenTableForProcessingType(CurrentExemptionsTable, ExemptionsTableName,
GrievanceProcessingType, Quit);
OpenTableForProcessingType(CurrentSpecialDistrictsTable, SpecialDistrictTableName,
GrievanceProcessingType, Quit);
If (Trim(LawyerCode) = '')
then TempRepresentative := LawyerCode
else TempRepresentative := '';
InformationLabel.Caption := 'Please enter the additional parcels that should have a grievance created ' +
'with grievance # ' + IntToStr(GrievanceNumber);
If (TempRepresentative = '')
then InformationLabel.Caption := InformationLabel.Caption + '.'
else InformationLabel.Caption := InformationLabel.Caption + ' and representative = ' +
TempRepresentative;
end; {FormShow}
{============================================================}
Procedure TGrievanceCondoCopyDialog.SetNumParcelsLabel(NumParcels : Integer);
begin
ParcelGroupBox.Caption := ' ' + IntToStr(NumParcels) + ' Parcels: ';
end; {SetNumParcelsLabel}
{============================================================}
Function FindLastItem(ParcelGrid : TStringGrid) : Integer;
var
I : Integer;
begin
Result := 0;
with ParcelGrid do
For I := 0 to (RowCount - 1) do
If (Deblank(Cells[0, I]) <> '')
then Result := Result + 1;
end; {FindLastItem}
{============================================================}
Procedure TGrievanceCondoCopyDialog.AddOneParcel(SwisSBLKey : String);
var
LastItem : Integer;
begin
LastItem := FindLastItem(ParcelGrid);
with ParcelGrid do
begin
If (LastItem = (RowCount - 1))
then RowCount := RowCount + 1;
Cells[0, LastItem] := ConvertSwisSBLToDashDot(SwisSBLKey);
end; {with ParcelGrid do}
ParcelGrid.Row := LastItem + 1;
end; {AddOneParcel}
{===============================================================}
Procedure TGrievanceCondoCopyDialog.ClearButtonClick(Sender: TObject);
begin
If (MessageDlg('Are you sure that you want to clear all of the parcel IDs?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then ClearStringGrid(ParcelGrid);
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {ClearButtonClick}
{===============================================================}
Procedure TGrievanceCondoCopyDialog.AddButtonClick(Sender: TObject);
var
SwisSBLKey : String;
I : Integer;
begin
If ExecuteParcelLocateDialog(SwisSBLKey, True, False, 'Locate Parcel(s)',
True, SwisSBLKeyList)
then
For I := 0 to (SwisSBLKeyList.Count - 1) do
If (Deblank(SwisSBLKeyList[I]) <> '')
then AddOneParcel(SwisSBLKeyList[I]);
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {AddButtonClick}
{===============================================================}
Procedure TGrievanceCondoCopyDialog.DeleteButtonClick(Sender: TObject);
var
TempRow, I : Integer;
begin
TempRow := ParcelGrid.Row;
{FXX07211999-5: Delete leaves 'X' in grid.}
with ParcelGrid do
begin
For I := (TempRow + 1) to (RowCount - 1) do
Cells[0, (I - 1)] := Cells[0, I];
{Blank out the last row.}
Cells[0, (RowCount - 1)] := '';
end; {with ParcelGrid do}
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {DeleteButtonClick}
{===============================================================}
Procedure TGrievanceCondoCopyDialog.CreateOneGrievance(SwisSBLKey : String;
AskingPercent : Double);
var
SBLRec : SBLRecord;
PriorAssessmentFound, GrievanceExists : Boolean;
begin
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
[GrievanceYear, SwisCode, Section,
SubSection, Block, Lot, Sublot, Suffix]);
FindKeyOld(SwisCodeTable, ['SwisCode'], [Copy(SwisSBLKey, 1, 6)]);
FindKeyOld(CurrentAssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[GrievanceYear, SwisSBLKey]);
with SBLRec do
PriorAssessmentFound := FindKeyOld(PriorAssessmentTable,
['TaxRollYr', 'SwisSBLKey'],
[PriorYear, SwisSBLKey]);
SetRangeOld(CurrentExemptionsTable, ['TaxRollYr', 'SwisSBLKey'],
[GrievanceYear, SwisSBLKey], [GrievanceYear, SwisSBLKey]);
SetRangeOld(CurrentSpecialDistrictsTable, ['TaxRollYr', 'SwisSBLKey'],
[GrievanceYear, SwisSBLKey], [GrievanceYear, SwisSBLKey]);
SetRangeOld(GrievanceExemptionsAskedLookupTable,
['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber', 'ExemptionCode'],
[OriginalSwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber), ' '],
[OriginalSwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber), '99999']);
{FXX01222004-1(2.07l1): Check to make sure that the grievance does not exist before copying it.}
GrievanceExists := FindKeyOld(GrievanceTable, ['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber'],
[SwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber)]);
FindKeyOld(GrievanceTable, ['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber'],
[OriginalSwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber)]);
If GrievanceExists
then MessageDlg('This grievance already exists on parcel ' + ConvertSwisSBLToDashDot(SwisSBLKey) + '.' + #13 +
'No new grievance was created on this parcel.' + #13 +
'Press OK to continue the copy.', mtWarning, [mbOK], 0)
else
with GrievanceLookupTable do
try
Append;
FieldByName('TaxRollYr').Text := GrievanceYear;
FieldByName('GrievanceNumber').AsInteger := GrievanceNumber;
FieldByName('SwisSBLKey').Text := SwisSBLKey;
FieldByName('LawyerCode').Text := LawyerCode;
FieldByName('CurrentName1').Text := ParcelTable.FieldByName('Name1').Text;
FieldByName('CurrentName2').Text := ParcelTable.FieldByName('Name2').Text;
FieldByName('CurrentAddress1').Text := ParcelTable.FieldByName('Address1').Text;
FieldByName('CurrentAddress2').Text := ParcelTable.FieldByName('Address2').Text;
FieldByName('CurrentStreet').Text := ParcelTable.FieldByName('Street').Text;
FieldByName('CurrentCity').Text := ParcelTable.FieldByName('City').Text;
FieldByName('CurrentState').Text := ParcelTable.FieldByName('State').Text;
FieldByName('CurrentZip').Text := ParcelTable.FieldByName('Zip').Text;
FieldByName('CurrentZipPlus4').Text := ParcelTable.FieldByName('ZipPlus4').Text;
If (Deblank(LawyerCode) = '')
then
begin
{They are representing themselves.}
FieldByName('PetitName1').Text := ParcelTable.FieldByName('Name1').Text;
FieldByName('PetitName2').Text := ParcelTable.FieldByName('Name2').Text;
FieldByName('PetitAddress1').Text := ParcelTable.FieldByName('Address1').Text;
FieldByName('PetitAddress2').Text := ParcelTable.FieldByName('Address2').Text;
FieldByName('PetitStreet').Text := ParcelTable.FieldByName('Street').Text;
FieldByName('PetitCity').Text := ParcelTable.FieldByName('City').Text;
FieldByName('PetitState').Text := ParcelTable.FieldByName('State').Text;
FieldByName('PetitZip').Text := ParcelTable.FieldByName('Zip').Text;
FieldByName('PetitZipPlus4').Text := ParcelTable.FieldByName('ZipPlus4').Text;
end
else SetPetitionerNameAndAddress(GrievanceLookupTable, LawyerCodeTable, LawyerCode);
FieldByName('PropertyClassCode').Text := ParcelTable.FieldByName('PropertyClassCode').Text;
FieldByName('OwnershipCode').Text := ParcelTable.FieldByName('OwnershipCode').Text;
FieldByName('ResidentialPercent').AsFloat := ParcelTable.FieldByName('ResidentialPercent').AsFloat;
FieldByName('RollSection').Text := ParcelTable.FieldByName('RollSection').Text;
FieldByName('HomesteadCode').Text := ParcelTable.FieldByName('HomesteadCode').Text;
FieldByName('LegalAddr').Text := ParcelTable.FieldByName('LegalAddr').Text;
FieldByName('LegalAddrNo').Text := ParcelTable.FieldByName('LegalAddrNo').Text;
{FXX01162003-3: Need to include the legal address integer.}
try
FieldByName('LegalAddrInt').AsInteger := ParcelTable.FieldByName('LegalAddrInt').AsInteger;
except
end;
FieldByName('CurrentLandValue').AsInteger := CurrentAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('CurrentTotalValue').AsInteger := CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
FieldByName('CurrentFullMarketVal').AsInteger := Round(ComputeFullValue(CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger,
SwisCodeTable,
ParcelTable.FieldByName('PropertyClassCode').Text,
ParcelTable.FieldByName('OwnershipCode').Text,
False));
If PriorAssessmentFound
then
begin
FieldByName('PriorLandValue').AsInteger := PriorAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('PriorTotalValue').AsInteger := PriorAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
end;
FieldByName('PetitReason').Text := GrievanceTable.FieldByName('PetitReason').Text;
FieldByName('PetitSubreasonCode').Text := GrievanceTable.FieldByName('PetitSubreasonCode').Text;
TMemoField(FieldByName('PetitSubreason')).Assign(TMemoField(GrievanceTable.FieldByName('PetitSubreason')));
TMemoField(FieldByName('Notes')).Assign(TMemoField(GrievanceTable.FieldByName('Notes')));
FieldByName('PreventUpdate').AsBoolean := GrievanceTable.FieldByName('PreventUpdate').AsBoolean;
FieldByName('NoHearing').AsBoolean := GrievanceTable.FieldByName('NoHearing').AsBoolean;
FieldByName('AppearanceNumber').AsInteger := GrievanceTable.FieldByName('AppearanceNumber').AsInteger;
{CHG12152005-1(2.9.4.3): Add the ability to put in an asking value.}
If _Compare(AskingPercent, 0, coGreaterThan)
then FieldByName('PetitTotalValue').AsInteger := Round(FieldByName('CurrentTotalValue').AsInteger * (AskingPercent / 100));
Post;
CopyTableRange(GrievanceExemptionsAskedLookupTable, GrievanceExemptionsAskedTable,
'TaxRollYr', ['SwisSBLKey'], [SwisSBLKey]);
CopyTableRange(CurrentExemptionsTable, GrievanceExemptionsTable,
'TaxRollYr', ['GrievanceNumber'], [IntToStr(GrievanceNumber)]);
CopyTableRange(CurrentSpecialDistrictsTable, GrievanceSpecialDistrictsTable,
'TaxRollYr', ['GrievanceNumber'], [IntToStr(GrievanceNumber)]);
except
SystemSupport(005, GrievanceTable,
'Error adding grievance for parcel ' +
ConvertSwisSBLToDashDot(SwisSBLKey) + '.',
UnitName, GlblErrorDlgBox);
end;
end; {CreateOneGrievance}
{===============================================================}
Procedure TGrievanceCondoCopyDialog.OKButtonClick(Sender: TObject);
var
Continue : Boolean;
I : Integer;
begin
Continue := True;
If (SwisSBLKeyList.Count = 0)
then
begin
MessageDlg('No parcels have been specified to create grievances for.',
mtError, [mbOK], 0);
Continue := False
end
else
begin
try
AskingPercent := StrToFloat(EditAskingPercent.Text);
except
AskingPercent := 0;
end;
ProgressDialog.UserLabelCaption := 'Copying grievance #' + IntToStr(GrievanceNumber);
ProgressDialog.Start(SwisSBLKeyList.Count, True, True);
For I := 0 to (SwisSBLKeyList.Count - 1) do
begin
ProgressDialog.Update(Self, SwisSBLKeyList[I]);
Application.ProcessMessages;
CreateOneGrievance(SwisSBLKeyList[I], AskingPercent);
end; {For I := 0 to (SwisSBLKeyList.Count - 1) do}
ProgressDialog.Finish;
end; {else of If (SwisSBLKeyList.Count = 0)}
If Continue
then
begin
MessageDlg('The grievance has been copied to all of the specified parcels.',
mtInformation, [mbOK], 0);
ModalResult := mrOK;
end;
end; {OKButtonClick}
{======================================================}
Procedure TGrievanceCondoCopyDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
SwisSBLKeyList.Free;
Action := caFree;
end;
end.
|
{
Задача, создание архива в памяти и преобразование в форму для отправки письма.
Скорее всего все операции будут делаться в памяти, так что операции будут ограничены потоками...
Функционал для создания письма:
- Создать поток архива
- Добавить в поток файл
Функционал для чтения письма:
- Открыть поток с ахривом
- Выделить файл из потока-архива в отдельный поток
}
unit Engine.Tar;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LibTar;
const
ERRORTAR_NOT_OPEN_FILE = 'Для выполнения текущей операции следует предварительно открыть файл *.TAR.';
type
TActionForTar = (aftClosed, aftRead, aftWrite);
{ TCustomTar }
TCustomTar = class
private
{: Проекция архива в памяти}
fArchiveStream: TMemoryStream;
{: Для записи в архива}
fTarWriter: TTarWriter;
{: Для чтение из архива}
fTarReader: TTarArchive;
{: Для поиска в архиве}
fTarRec: TTarDirRec;
public
constructor Create;
destructor Destroy; override;
{: Добавление нового файла из потока в поток-архив}
function AddFile(TarFileName: string; Stream: TStream): boolean; overload;
{: Добавление нового файла с диска в поток-архив}
function AddFile(TarFileName: string; FilePath: string): boolean; overload;
{: Извлечение файла из потока}
function ExtractFile(TarFileName: string; var Stream: TStream): boolean;
{: Извлечение файла из потока}
function ExtractFile(TarFileName: string; FilePath: string): boolean;
{: Сохранение архива в файл}
procedure StoreToFile(FilePath: string);
{: Сохранение архива в поток}
procedure StoreToStream(var Stream: TStream);
{: Загрузка архива в файл}
procedure LoadFromFile(FilePath: string);
{: Загрузка архива в поток}
procedure LoadFromStream(var Stream: TStream);
end;
implementation
{ TCustomTar }
constructor TCustomTar.Create;
begin
fArchiveStream := TMemoryStream.Create;
end;
destructor TCustomTar.Destroy;
begin
fArchiveStream.Free;
end;
function TCustomTar.AddFile(TarFileName: string; Stream: TStream): boolean;
// Добавление файла в поток-архива
begin
Result := True;
try
try
fTarWriter := TTarWriter.Create(fArchiveStream);
fTarWriter.AddStream(Stream, TarFileName, Now);
except
Result := False;
end;
finally
fTarWriter.Free;
end;
end;
function TCustomTar.AddFile(TarFileName: string; FilePath: string): boolean;
// Добавление файла в поток-архива
begin
Result := True;
try
try
fTarWriter := TTarWriter.Create(fArchiveStream);
fTarWriter.AddFile(FilePath, TarFileName);
except
Result := False;
end;
finally
fTarWriter.Free;
end;
end;
function TCustomTar.ExtractFile(TarFileName: string; var Stream: TStream): boolean;
// Извлечение файла
begin
Result := True;
try
try
fTarReader := TTarArchive.Create(fArchiveStream);
fTarReader.Reset;
fTarRec.Name := TarFileName;
fTarReader.FindNext(fTarRec);
fTarReader.ReadFile(Stream);
except
Result := False;
end;
finally
fTarReader.Free;
end;
end;
function TCustomTar.ExtractFile(TarFileName: string; FilePath: string): boolean;
// Извлечение файла
begin
Result := True;
try
try
fTarReader := TTarArchive.Create(fArchiveStream);
fTarReader.Reset;
fTarRec.Name := TarFileName;
fTarReader.FindNext(fTarRec);
fTarReader.ReadFile(FilePath);
except
Result := False;
end;
finally
fTarReader.Free;
end;
end;
procedure TCustomTar.StoreToFile(FilePath: string);
// Сохранение в файл
begin
fArchiveStream.SaveToFile(FilePath);
end;
procedure TCustomTar.StoreToStream(var Stream: TStream);
// Сохранение в поток
begin
fArchiveStream.SaveToStream(Stream);
end;
procedure TCustomTar.LoadFromFile(FilePath: string);
// Загрузка из файла
begin
fArchiveStream.LoadFromFile(FilePath);
end;
procedure TCustomTar.LoadFromStream(var Stream: TStream);
// Загрузка из потока
begin
fArchiveStream.LoadFromStream(Stream);
end;
end.
|
{**********************************************}
{ TBarSeries Component Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeBarEdit;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
Chart, Series, TeeProcs, TeCanvas, TeePenDlg;
type
TBarSeriesEditor = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
LStyle: TLabel;
CBBarStyle: TComboFlat;
BBarPen: TButtonPen;
BBarBrush: TButton;
GroupBox2: TGroupBox;
CBColorEach: TCheckBox;
BBarColor: TButtonColor;
BGradient: TButton;
BTickLines: TButtonPen;
LBevel: TLabel;
EBevel: TEdit;
UDBevel: TUpDown;
CBDarkBar: TCheckBox;
Label1: TLabel;
Label3: TLabel;
SEBarwidth: TEdit;
SEBarOffset: TEdit;
UDBarWidth: TUpDown;
UDBarOffset: TUpDown;
Label2: TLabel;
Edit1: TEdit;
UDDepth: TUpDown;
CBBarSideMargins: TCheckBox;
CBMarksAutoPosition: TCheckBox;
procedure FormShow(Sender: TObject);
procedure SEBarwidthChange(Sender: TObject);
procedure CBBarStyleChange(Sender: TObject);
procedure BBarBrushClick(Sender: TObject);
procedure CBColorEachClick(Sender: TObject);
procedure CBDarkBarClick(Sender: TObject);
procedure CBBarSideMarginsClick(Sender: TObject);
procedure SEBarOffsetChange(Sender: TObject);
procedure CBMarksAutoPositionClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BGradientClick(Sender: TObject);
procedure EBevelChange(Sender: TObject);
procedure Edit1Change(Sender: TObject);
private
{ Private declarations }
CreatingForm : Boolean;
Bar : TCustomBarSeries;
FStackEditor : TCustomForm;
Procedure AddStackBarEditor;
Procedure CheckControls;
Procedure RefreshShape;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeBrushDlg, TeeEdiGrad, TeeEdiSeri, TeeStackBarEdit, TeeConst;
procedure TBarSeriesEditor.FormShow(Sender: TObject);
begin
Bar:=TCustomBarSeries(Tag);
if Assigned(Bar) then
begin
With Bar do
begin
CBBarStyle.ItemIndex :=Ord(BarStyle);
UDBarWidth.Position :=BarWidthPercent;
UDBarOffset.Position :=OffsetPercent;
UDDepth.Position :=DepthPercent;
CBColorEach.Checked :=ColorEachPoint;
CBMarksAutoPosition.Checked:=AutoMarkPosition;
CBDarkBar.Checked :=Dark3D;
CBBarSideMargins.Checked:=SideMargins;
BBarPen.LinkPen(BarPen);
BTickLines.LinkPen(TickLines);
UDBevel.Position :=BevelSize;
end;
CheckControls;
BBarColor.LinkProperty(Bar,'SeriesColor');
RefreshShape;
AddStackBarEditor;
end;
CreatingForm:=False;
end;
Procedure TBarSeriesEditor.AddStackBarEditor;
Begin
if (not Assigned(FStackEditor)) and Assigned(Parent) and
(Parent.Owner is TFormTeeSeries) then
FStackEditor:=TFormTeeSeries(Parent.Owner).InsertSeriesForm(
TStackBarSeriesEditor,1,TeeMsg_Stack,Bar);
end;
Procedure TBarSeriesEditor.RefreshShape;
Begin
BBarColor.Enabled:=not Bar.ColorEachPoint;
if BBarColor.Enabled then BBarColor.Repaint;
end;
procedure TBarSeriesEditor.SEBarWidthChange(Sender: TObject);
begin
if not CreatingForm then
{$IFDEF CLX}
if Assigned(Bar) then
{$ENDIF}
Bar.BarWidthPercent:=UDBarWidth.Position;
end;
Procedure TBarSeriesEditor.CheckControls;
begin
BGradient.Enabled:=(Bar.BarStyle=bsRectGradient) or (Bar.BarStyle=bsRectangle);
EnableControls(Bar.BarStyle=bsBevel,[LBevel,EBevel,UDBevel]);
end;
procedure TBarSeriesEditor.CBBarStyleChange(Sender: TObject);
begin
if not CreatingForm then
begin
Bar.BarStyle:=TBarStyle(CBBarStyle.ItemIndex);
CheckControls;
end;
end;
procedure TBarSeriesEditor.BBarBrushClick(Sender: TObject);
begin
EditChartBrush(Self,Bar.BarBrush);
end;
procedure TBarSeriesEditor.CBColorEachClick(Sender: TObject);
begin
if not CreatingForm then
begin
Bar.ColorEachPoint:=CBColorEach.Checked;
RefreshShape;
end;
end;
procedure TBarSeriesEditor.CBDarkBarClick(Sender: TObject);
begin
if not CreatingForm then Bar.Dark3D:=CBDarkBar.Checked;
end;
procedure TBarSeriesEditor.CBBarSideMarginsClick(Sender: TObject);
begin
if not CreatingForm then Bar.SideMargins:=CBBarSideMargins.Checked;
end;
procedure TBarSeriesEditor.SEBarOffsetChange(Sender: TObject);
begin
if not CreatingForm then
{$IFDEF CLX}
if Assigned(Bar) then
{$ENDIF}
Bar.OffsetPercent:=UDBarOffset.Position;
end;
procedure TBarSeriesEditor.CBMarksAutoPositionClick(Sender: TObject);
begin
Bar.AutoMarkPosition:=CBMarksAutoPosition.Checked;
end;
procedure TBarSeriesEditor.FormCreate(Sender: TObject);
begin
CreatingForm:=True;
Align:=alClient;
end;
procedure TBarSeriesEditor.BGradientClick(Sender: TObject);
begin
Bar.BarStyle:=bsRectGradient;
CBBarStyle.ItemIndex:=6;
EditTeeGradient(Self,Bar.Gradient,True,True);
end;
procedure TBarSeriesEditor.EBevelChange(Sender: TObject);
begin
if not CreatingForm then
Bar.BevelSize:=UDBevel.Position;
end;
procedure TBarSeriesEditor.Edit1Change(Sender: TObject);
begin
if not CreatingForm then
{$IFDEF CLX}
if Assigned(Bar) then
{$ENDIF}
Bar.DepthPercent:=UDDepth.Position;
end;
initialization
RegisterClass(TBarSeriesEditor);
end.
|
unit UnitTCifrador;
interface
uses
SysUtils, StrUtils;
type
TCifrador = class
clave : array[0..9] of byte;//La clave es una secuencia de 10 digitos
mensaje: string;//El mensaje es el texto sin cifrar
cifra: string;//El resultado de cifrar el texto plano
KeyPointer:byte;//apunta a uno de los digitos de la clave para cifrar un caracter del texto plano
constructor crear(m:string);
function getClave: string;
function getMensaje: string;
function getCifra: string;
function letraAnum(c:char):byte;
function numAletra(b:byte):char;
//**********Version 5**********
function nv5Anum(c:char):byte;
function numAnv5(b:byte):char;
//**********Version 5**********
function parAnum(numero,letra:char):integer;
function cifrado(x,a:integer):integer;
function descifrado(y,a:integer):integer;
procedure incrementarPointer;
procedure generarClave;
//**********Version 5**********
procedure generarClaveBR1;
//**********Version 5**********
function insertarClave(s:string):boolean;
procedure cifrar;
function descifrar:string;
end;
implementation
constructor TCifrador.crear(m:string);//Se recibe el mensaje como entrada
begin
mensaje:=m;
cifra:='';
KeyPointer:=0;
randomize;
end;
function TCifrador.getClave: string;//Devuelve la clave
var
i:integer;
begin
result:='';
for i:=0 to 9 do
result:=result+inttostr(clave[i]);
end;
function TCifrador.getMensaje: string;//Devuelve el mensaje sin cifrar
begin
result:=mensaje;
end;
function TCifrador.getCifra: string;//Devuelve el mensaje cifrado
begin
result:=cifra;
end;
function TCifrador.letraAnum(c:char):byte;//da el equivalente numerico de una letra
begin
result:=0;//**********Version 5**********modificacion
case c of
'a':result:=1;//**********Version 5**********
'b':result:=2;
'c':result:=3;
'd':result:=4;
'e':result:=5;
'f':result:=6;
'g':result:=7;
'h':result:=8;
'i':result:=9;
'j':result:=10;
'k':result:=11;
'l':result:=12;
'm':result:=13;
'n':result:=14;
'o':result:=15;
'p':result:=16;
'q':result:=17;
'r':result:=18;
's':result:=19;
't':result:=20;
'u':result:=21;
'v':result:=22;
'w':result:=23;
'x':result:=24;
'y':result:=25;
'z':result:=26;
' ':result:=27;
end;
end;
function TCifrador.numAletra(b:byte):char;//da la letra equivalente a un numero
begin
result:='?';//**********Version 5**********modificacion
case b of
1:result:='a';//**********Version 5**********
2:result:='b';
3:result:='c';
4:result:='d';
5:result:='e';
6:result:='f';
7:result:='g';
8:result:='h';
9:result:='i';
10:result:='j';
11:result:='k';
12:result:='l';
13:result:='m';
14:result:='n';
15:result:='o';
16:result:='p';
17:result:='q';
18:result:='r';
19:result:='s';
20:result:='t';
21:result:='u';
22:result:='v';
23:result:='w';
24:result:='x';
25:result:='y';
26:result:='z';
27:result:=' ';
end;
end;
//**********Version 5**********
function TCifrador.nv5Anum(c:char):byte;
begin
result := 12;
case c of
'0':result:=0;
'1':result:=1;
'2':result:=2;
'3':result:=3;
'4':result:=4;
'5':result:=5;
'6':result:=6;
'7':result:=7;
'8':result:=8;
'9':result:=9;
'%':result:=10;
'$':result:=11;
end;
end;
function TCifrador.numAnv5(b:byte):char;
begin
result := '#';
case b of
0:result:='0';
1:result:='1';
2:result:='2';
3:result:='3';
4:result:='4';
5:result:='5';
6:result:='6';
7:result:='7';
8:result:='8';
9:result:='9';
10:result:='%';
11:result:='$';
end;
end;
//**********Version 5**********
function TCifrador.parAnum(numero,letra:char):integer;//convierte un par en su equivalente numerico
begin
//el numero indica la cantidad de saltos sobre los 26 caracteres
//y la letra la cantidad que se le debe sumar a esa cantidad de saltos
//Esta funcion devuelve un numero listo para descifrar con la funcion de descifrado
result:=(nv5Anum(numero)*26)+letraAnum(letra);//**********Version 5**********modificado
end;
function TCifrador.cifrado(x,a:integer):integer;
begin
a:=a+2;//**********Version 5**********
result:=(x+2)*a-x;//x es el numero a cifrar, a es uno de los 10 digitosde la clave
end;
function TCifrador.descifrado(y,a:integer):integer;
begin
a:=a+2;//**********Version 5**********
result:=(y-(2*a))div(a-1);//y es el numero a descifrar, a es uno de los 10 digitosde la clave
end;
procedure TCifrador.incrementarPointer;//Incrementa el puntero de la clave
begin
if KeyPointer>8 then
KeyPointer:=0
else
inc(KeyPointer);
end;
procedure TCifrador.generarClave;
var
i:byte;
begin
//Genera una clave aleatoria de 10 digitos en el rango de 0 a 9
for i:=0 to 9 do
clave[i]:=random(10);//**********Version 5**********modificado
end;
//**********Version 5**********
//Este algoritmo genera una clave de 10 digitos a partir del aņo, el mes, el dia,
//el dia de la semana codificado a numero y la hora (sin minutos)
procedure TCifrador.generarClaveBR1;
var
fecha:TDateTime;
myYear, myMonth, myDay, myDayOfWeek : Word;
rHora:real;
iHora:integer;
sAnho,sMes,sDia,sDiaSemana,sHora:string;
begin
//Obtener la fecha y la hora actual
fecha:=Now;
rHora:=Time;
//decodificar la fecha en partes
myDayOfWeek:=DayOfWeek(fecha);
DecodeDate(fecha, myYear, myMonth, myDay);
//obtener la hora
rHora:=rHora*1440;//cantidad de minutos que lleva el dia
iHora:=Round(rHora);//cantidad de minutos redondeada
iHora:=iHora div 60;//la hora que se usa para la clave
//Convertir todo a formato string de 2 digitos
sAnho:=copy(inttostr(myYear),3,2);
sMes:=RightStr('0'+inttostr(myMonth),2);
sDia:=RightStr('0'+inttostr(myDay),2);
sDiaSemana:=RightStr('0'+inttostr(myDayOfWeek),2);
sHora:=RightStr('0'+inttostr(iHora),2);
//se asigna a la clave del objeto la composicion de las partes calculadas aqui
clave[0]:=strtoint(sAnho[1]);
clave[1]:=strtoint(sAnho[2]);
clave[2]:=strtoint(sMes[1]);
clave[3]:=strtoint(sMes[2]);
clave[4]:=strtoint(sDia[1]);
clave[5]:=strtoint(sDia[2]);
clave[6]:=strtoint(sDiaSemana[1]);
clave[7]:=strtoint(sDiaSemana[2]);
clave[8]:=strtoint(sHora[1]);
clave[9]:=strtoint(sHora[2]);
end;
//**********Version 5**********
function TCifrador.insertarClave(s:string):boolean;
var
i:byte;
claveAux : array[0..9] of char;
begin
//Inserta una clave de 10 digitos en el rango de 0 a 9
result:=true;
if length(s)<>10 then
result:=false
else begin
for i:=0 to 9 do begin
if ( (s[i]<>'1')and(s[i]<>'2')and(s[i]<>'3')and(s[i]<>'4')and(s[i]<>'5')
and(s[i]<>'6')and(s[i]<>'7')and(s[i]<>'8')and(s[i]<>'9')and(s[i]<>'0') ) then
result:=false;
claveAux[i]:=s[i];
end;
end;
if result then
for i:=0 to 9 do
clave[i]:=strtoint(claveAux[i]);
end;
procedure TCifrador.cifrar;
var
i,valor:integer;//es un numero cifrado el cual se convertira en el par cifrado
par:string;//es un par cifrado que compone el mensaje cifrado(compuesto por un digito y una letra)
begin
for i:=1 to length(mensaje) do begin
valor:=cifrado(letraAnum(mensaje[i]), clave[KeyPointer]);
incrementarPointer;
par:=numAnv5(valor div 26);//**********Version 5**********modificado
par:=par+numAletra(valor mod 26);
cifra:=cifra+par;
end;
end;
function TCifrador.descifrar:string;
var
i:integer;
letra,numero:char;//los componentes de un par cifrado
begin
result:='';
KeyPointer:=0;
i:=0;
while i < length(cifra) do begin
inc(i);
numero:=cifra[i];
inc(i);
letra:=cifra[i];
result:=result+numAletra(descifrado(parAnum(numero,letra),clave[KeyPointer]));
incrementarPointer;
end;
end;
end.
|
unit Model.Entities;
interface
uses
SysUtils,
Generics.Collections,
Aurelius.Mapping.Attributes,
Aurelius.Mapping.Metadata,
Aurelius.Types.Blob,
Aurelius.Types.DynamicProperties,
Aurelius.Types.Nullable,
Aurelius.Types.Proxy;
type
TBook = class;
TCategory = class;
[Entity]
[Table('BOOKS')]
TBook = class
strict private
FID: Integer;
[Column('BOOKNAME', [TColumnProp.Required])]
[DBTypeMemo]
FBookName: String;
[Column('BOOKLINK', [])]
[DBTypeMemo]
FBookLink: Nullable<String>;
[Association([TAssociationProp.Lazy], CascadeTypeAll - [TCascadeType.Remove])]
[JoinColumn('BOOKS_CATEGORY_ID', [], 'ID')]
FBooksCategory: Proxy<TCategory>;
function GetBooksCategory: TCategory;
procedure SetBooksCategory(const Value: TCategory);
public
property ID: Integer read FID write FID;
property BookName: String read FBookName write FBookName;
property BookLink: Nullable<String> read FBookLink write FBookLink;
property BooksCategory: TCategory read GetBooksCategory write SetBooksCategory;
public
constructor Create(ABookName: string); overload;
constructor Create(ABookName: string; ABookLink: Nullable<string>); overload;
end;
[Entity]
[Table('CATEGORIES')]
TCategory = class
strict private
FID: Integer;
[Column('CATEGORYNAME', [TColumnProp.Required])]
[DBTypeMemo]
FCategoryName: String;
[Association([TAssociationProp.Lazy], CascadeTypeAll - [TCascadeType.Remove])]
FParent: Proxy<TCategory>;
[ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAllRemoveOrphan)]
FBooks: Proxy<TList<TBook>>;
function GetBooks: TList<TBook>;
function GetParent: TCategory;
procedure SetParent(const Value: TCategory);
public
constructor Create; overload;
constructor Create(AName: string); overload;
destructor Destroy; override;
property ID: Integer read FID write FID;
property CategoryName: String read FCategoryName write FCategoryName;
property Parent: TCategory read GetParent write SetParent;
property Books: TList<TBook> read GetBooks;
end;
implementation
{ TBook}
constructor TBook.Create(ABookName: string);
begin
FBookName := ABookName;
end;
constructor TBook.Create(ABookName: string; ABookLink: Nullable<string>);
begin
Create(ABookName);
FBookLink := ABookLink;
end;
function TBook.GetBooksCategory: TCategory;
begin
Result := FBooksCategory.Value;
end;
procedure TBook.SetBooksCategory(const Value: TCategory);
begin
FBooksCategory.Value := Value;
end;
{ TCategory}
function TCategory.GetParent: TCategory;
begin
Result := FParent.Value;
end;
procedure TCategory.SetParent(const Value: TCategory);
begin
FParent.Value := Value;
end;
constructor TCategory.Create;
begin
inherited;
FBooks.SetInitialValue(TList<TBook>.Create);
end;
constructor TCategory.Create(AName: string);
begin
Create;
FCategoryName := AName;
end;
destructor TCategory.Destroy;
begin
FBooks.DestroyValue;
inherited;
end;
function TCategory.GetBooks: TList<TBook>;
begin
Result := FBooks.Value;
end;
end.
|
unit View.List.ToFuel;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.List.Base, Data.DB,
System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, Vcl.Grids,
Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TShowReport = procedure of object;
type
TfrmListToFuel = class(TfrmList)
btnReport: TButton;
actReport: TAction;
procedure edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure actReportExecute(Sender: TObject);
private
FOnShowReport: TShowReport;
procedure SetOnShowReport(const Value: TShowReport);
{ Private declarations }
public
property OnShowReport: TShowReport read FOnShowReport write SetOnShowReport;
end;
implementation
uses
Model.Register.ToFuel;
{$R *.dfm}
procedure TfrmListToFuel.actReportExecute(Sender: TObject);
begin
inherited;
OnShowReport;
end;
procedure TfrmListToFuel.edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
OnFilterList(FFilterField[cbbFilterField.ItemIndex], edtValue.Text);
end;
procedure TfrmListToFuel.SetOnShowReport(const Value: TShowReport);
begin
FOnShowReport := Value;
end;
end.
|
unit Rx.Observable.Zip;
interface
uses SyncObjs, Rx, Rx.Subjects, Generics.Collections, Rx.Implementations,
Rx.Fibers;
type
TInterceptor<T> = class(TObservableImpl<T>)
private
FOnNextIntercept: TOnNext<T>;
FOnErrorIntercept: TOnError;
FOnCompletedIntercept: TOnCompleted;
public
procedure OnNext(const Data: T); override;
procedure OnError(E: IThrowable); override;
procedure OnCompleted; override;
end;
IJoinStrategy<X, Y> = interface
function OnNext(const Left: X): TZip<X, Y>; overload;
function OnNext(const Right: Y): TZip<X, Y>; overload;
procedure OnCompletedLeft;
procedure OnCompletedRight;
procedure OnErrorLeft(Error: IThrowable);
procedure OnErrorRight(Error: IThrowable);
function GetError: IThrowable;
function IsCompleted: Boolean;
end;
TJoinStrategy<X, Y> = class(TInterfacedObject, IJoinStrategy<X, Y>)
strict private
FCompletedLeft: Boolean;
FCompletedRight: Boolean;
FError: IThrowable;
protected
property CompletedLeft: Boolean read FCompletedLeft write FCompletedLeft;
property CompletedRight: Boolean read FCompletedRight write FCompletedRight;
property Error: IThrowable read FError write FError;
public
function OnNext(const Left: X): TZip<X, Y>; overload; dynamic; abstract;
function OnNext(const Right: Y): TZip<X, Y>; overload; dynamic; abstract;
procedure OnCompletedLeft; dynamic;
procedure OnCompletedRight; dynamic;
procedure OnErrorLeft(Error: IThrowable); dynamic;
procedure OnErrorRight(Error: IThrowable); dynamic;
function GetError: IThrowable; dynamic;
function IsCompleted: Boolean; dynamic;
end;
TSyncStrategy<X, Y> = class(TJoinStrategy<X, Y>)
strict private
FLeftBuffer: TList<TSmartVariable<X>>;
FRightBuffer: TList<TSmartVariable<Y>>;
public
constructor Create;
destructor Destroy; override;
function OnNext(const Left: X): TZip<X, Y>; overload; override;
function OnNext(const Right: Y): TZip<X, Y>; overload; override;
function IsCompleted: Boolean; override;
end;
TCombineLatestStrategy<X, Y> = class(TJoinStrategy<X, Y>)
strict private
FLeft: TSmartVariable<X>;
FRight: TSmartVariable<Y>;
FLeftExists: Boolean;
FRightExists: Boolean;
public
function OnNext(const Left: X): TZip<X, Y>; overload; override;
function OnNext(const Right: Y): TZip<X, Y>; overload; override;
end;
TFastStream = (fsA, fsB);
TWithLatestFromStrategy<X, Y> = class(TJoinStrategy<X, Y>)
strict private
FFastStream: TFastStream;
FLeft: TSmartVariable<X>;
FRight: TSmartVariable<Y>;
FLeftExists: Boolean;
FRightExists: Boolean;
procedure AfterOnNext;
public
constructor Create(FastStream: TFastStream);
function OnNext(const Left: X): TZip<X, Y>; overload; override;
function OnNext(const Right: Y): TZip<X, Y>; overload; override;
end;
TAMBStrategy<X, Y> = class(TJoinStrategy<X, Y>)
strict private
FLeft: TSmartVariable<X>;
FRight: TSmartVariable<Y>;
FLeftExists: Boolean;
FRightExists: Boolean;
public
function OnNext(const Left: X): TZip<X, Y>; overload; override;
function OnNext(const Right: Y): TZip<X, Y>; overload; override;
end;
TAMBWithStrategy<X, Y> = class(TJoinStrategy<X, Y>)
strict private
FFastStream: TFastStream;
FLeft: TSmartVariable<X>;
FRight: TSmartVariable<Y>;
FLeftExists: Boolean;
FRightExists: Boolean;
procedure AfterOnNext;
public
constructor Create(FastStream: TFastStream);
function OnNext(const Left: X): TZip<X, Y>; overload; override;
function OnNext(const Right: Y): TZip<X, Y>; overload; override;
end;
IJoiner = interface
procedure OnSubscribe(Subscriber: IInterface);
end;
TJoiner<X, Y> = class(TInterfacedObject, IObserver<X>, IObserver<Y>, IJoiner)
type
TZip = TZip<X, Y>;
TXValue = TSmartVariable<X>;
TYValue = TSmartVariable<Y>;
TOnNextRoutine = procedure(Data: TObject) of object;
TOnErrorRoutine = procedure(E: IThrowable) of object;
TOnCompletedRoutine = procedure of object;
strict private
class threadvar Route: Boolean;
class threadvar RouteLeft: ISubscriber<X>;
class threadvar RouteRight: ISubscriber<Y>;
var
FLeftIcp: TInterceptor<X>;
FRightIcp: TInterceptor<Y>;
FRoutine: TOnNextRoutine;
FOnError: TOnErrorRoutine;
FOnCompleted: TOnCompletedRoutine;
FLock: TCriticalSection;
FStrategy: IJoinStrategy<X, Y>;
function GetStrategy: IJoinStrategy<X, Y>;
procedure Lock; inline;
procedure UnLock; inline;
procedure OnNextRight(const Right: Y);
procedure SetStrategy(Value: IJoinStrategy<X, Y>);
procedure RouteLeftFiberExecute(Fiber: TCustomFiber);
procedure RouteRightFiberExecute(Fiber: TCustomFiber);
procedure OnErrorLeft(E: IThrowable);
procedure OnErrorRight(E: IThrowable);
procedure OnCompletedLeft;
procedure OnCompletedRight;
procedure CheckCompletition;
public
constructor Create(Left: IObservable<X>; Right: IObservable<Y>;
const Routine: TOnNextRoutine; const OnError: TOnErrorRoutine;
const OnCompleted: TOnCompletedRoutine);
destructor Destroy; override;
property Strategy: IJoinStrategy<X, Y> read FStrategy write SetStrategy;
procedure OnNext(const Left: X); overload;
procedure OnNext(const Right: Y); overload;
procedure OnError(E: IThrowable);
procedure OnCompleted;
procedure OnSubscribe(Subscriber: IInterface);
end;
TOnceSubscriber<Z: class; X, Y> = class(TInterfacedObject, ISubscriber<Z>, ISubscriber<X>, ISubscriber<Y>)
strict private
FLeftBuffer: TList<TJoiner<X, Y>.TXValue>;
FRightBuffer: TList<TJoiner<X, Y>.TYValue>;
FDest: ISubscriber<Z>;
FFiberLeft: TCustomFiber;
FFiberRight: TCustomFiber;
FStrategy: IJoinStrategy<X, Y>;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Dest: ISubscriber<Z>; Strategy: IJoinStrategy<X, Y>); overload;
constructor Create(Dest: ISubscriber<Z>; Strategy: IJoinStrategy<X, Y>;
FiberLeft, FiberRight: TCustomFiber); overload;
destructor Destroy; override;
procedure OnNext(const Left: X); overload;
procedure OnNext(const Right: Y); overload;
procedure OnNext(const A: Z); overload;
procedure OnError(E: IThrowable);
procedure OnCompleted;
procedure Unsubscribe;
function IsUnsubscribed: Boolean;
procedure SetProducer(P: IProducer);
end;
TZipObserver<T: class> = class(TPublishSubject<T>)
strict private
FJoiner: IJoiner;
protected
procedure OnSubscribe(Subscriber: ISubscriber<T>); override;
public
destructor Destroy; override;
procedure Setup(Joiner: IJoiner);
procedure OnNextIcp(Data: TObject);
end;
implementation
{ TInterceptor<T> }
procedure TInterceptor<T>.OnCompleted;
begin
FOnCompletedIntercept
end;
procedure TInterceptor<T>.OnError(E: IThrowable);
begin
FOnErrorIntercept(E)
end;
procedure TInterceptor<T>.OnNext(const Data: T);
begin
FOnNextIntercept(Data)
end;
{ TJoiner<X, Y> }
constructor TJoiner<X, Y>.Create(Left: IObservable<X>; Right: IObservable<Y>;
const Routine: TOnNextRoutine;
const OnError: TOnErrorRoutine;
const OnCompleted: TOnCompletedRoutine);
begin
FLock := TCriticalSection.Create;
FLeftIcp := TInterceptor<X>.Create;
with FLeftIcp do begin
FOnNextIntercept := Self.OnNext;
FOnErrorIntercept := Self.OnErrorLeft;
FOnCompletedIntercept := Self.OnCompletedLeft;
end;
FRightIcp := TInterceptor<Y>.Create;
with FRightIcp do begin
FOnNextIntercept := Self.OnNextRight;
FOnErrorIntercept := Self.OnErrorRight;
FOnCompletedIntercept := Self.OnCompletedRight;
end;
//
FRoutine := Routine;
FOnError := OnError;
FOnCompleted := OnCompleted;
FLeftIcp.Merge(Left);
FRightIcp.Merge(Right);
end;
destructor TJoiner<X, Y>.Destroy;
begin
FStrategy := nil;
FLeftIcp.Free;
FRightIcp.Free;
FLock.Free;
inherited;
end;
function TJoiner<X, Y>.GetStrategy: IJoinStrategy<X, Y>;
begin
if not Assigned(FStrategy) then
FStrategy := TSyncStrategy<X, Y>.Create;
Result := FStrategy;
end;
procedure TJoiner<X, Y>.Lock;
begin
FLock.Acquire;
end;
procedure TJoiner<X, Y>.OnCompleted;
begin
if Route then begin
RouteLeft.OnCompleted;
RouteRight.OnCompleted;
end
else begin
Lock;
try
FOnCompleted()
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.OnError(E: IThrowable);
begin
if Route then begin
RouteLeft.OnError(E);
RouteRight.OnError(E);
end
else begin
Lock;
try
FOnError(E)
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.OnNext(const Right: Y);
var
Left: X;
Zip: TZip;
begin
if Route then
RouteRight.OnNext(Right)
else begin
Lock;
try
Zip := GetStrategy.OnNext(Right);
if Assigned(Zip) then
FRoutine(Zip);
CheckCompletition
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.CheckCompletition;
begin
if GetStrategy.IsCompleted then
if GetStrategy.GetError <> nil then
FOnError(GetStrategy.GetError)
else
FOnCompleted;
end;
procedure TJoiner<X, Y>.OnNextRight(const Right: Y);
begin
OnNext(Right)
end;
procedure TJoiner<X, Y>.OnSubscribe(Subscriber: IInterface);
var
LeftFiber, RightFiber: TFiber;
Once: TOnceSubscriber<TZip<X,Y>, X, Y>;
Sbscr: ISubscriber<TZip<X,Y>>;
begin
LeftFiber := TFiber.Create(RouteLeftFiberExecute);
RightFiber := TFiber.Create(RouteRightFiberExecute);
Sbscr := ISubscriber<TZip<X,Y>>(Subscriber);
Once := TOnceSubscriber<TZip<X,Y>, X, Y>.Create(Sbscr, FStrategy, LeftFiber, RightFiber);
Route := True;
RouteLeft := Once;
RouteRight := Once;
try
while not (LeftFiber.IsTerminated or RightFiber.IsTerminated) do begin
LeftFiber.Invoke;
RightFiber.Invoke;
end
finally
Route := False;
TJoiner<X, Y>.RouteLeft := nil;
TJoiner<X, Y>.RouteRight := nil;
Sbscr := nil;
LeftFiber.Free;
RightFiber.Free;
end;
end;
procedure TJoiner<X, Y>.RouteLeftFiberExecute(Fiber: TCustomFiber);
begin
FLeftIcp.Subscribe(RouteLeft)
end;
procedure TJoiner<X, Y>.RouteRightFiberExecute(Fiber: TCustomFiber);
begin
FRightIcp.Subscribe(RouteRight)
end;
procedure TJoiner<X, Y>.SetStrategy(Value: IJoinStrategy<X, Y>);
begin
FStrategy := Value;
end;
procedure TJoiner<X, Y>.OnErrorLeft(E: IThrowable);
begin
if Route then
RouteLeft.OnError(E)
else begin
Lock;
try
GetStrategy.OnErrorLeft(E);
if GetStrategy.IsCompleted then
FOnError(GetStrategy.GetError)
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.OnErrorRight(E: IThrowable);
begin
if Route then
RouteRight.OnError(E)
else begin
Lock;
try
GetStrategy.OnErrorRight(E);
if GetStrategy.IsCompleted then
FOnError(GetStrategy.GetError)
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.OnCompletedLeft;
begin
if Route then
RouteLeft.OnCompleted
else begin
Lock;
try
GetStrategy.OnCompletedLeft;
if GetStrategy.IsCompleted then
FOnCompleted
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.OnCompletedRight;
begin
if Route then
RouteRight.OnCompleted
else begin
Lock;
try
GetStrategy.OnCompletedRight;
if GetStrategy.IsCompleted then
FOnCompleted
finally
Unlock;
end;
end;
end;
procedure TJoiner<X, Y>.UnLock;
begin
FLock.Release;
end;
procedure TJoiner<X, Y>.OnNext(const Left: X);
var
Right: Y;
Zip: TZip;
begin
if Route then
RouteLeft.OnNext(Left)
else begin
Lock;
try
Zip := GetStrategy.OnNext(Left);
if Assigned(Zip) then
FRoutine(Zip);
CheckCompletition;
finally
Unlock;
end;
end;
end;
{ TZip<T> }
destructor TZipObserver<T>.Destroy;
begin
FJoiner := nil;
inherited;
end;
procedure TZipObserver<T>.OnNextIcp(Data: TObject);
begin
Self.OnNext(Data)
end;
procedure TZipObserver<T>.OnSubscribe(Subscriber: ISubscriber<T>);
begin
if Assigned(FJoiner) then
FJoiner.OnSubscribe(Subscriber);
end;
procedure TZipObserver<T>.Setup(Joiner: IJoiner);
begin
FJoiner := Joiner;
end;
{ TOnceSubscriber<X, Y> }
constructor TOnceSubscriber<Z, X, Y>.Create(Dest: ISubscriber<Z>; Strategy: IJoinStrategy<X, Y>);
begin
FLeftBuffer := TList<TJoiner<X, Y>.TXValue>.Create;
FRightBuffer := TList<TJoiner<X, Y>.TYValue>.Create;
FDest := Dest;
FStrategy := Strategy;
end;
constructor TOnceSubscriber<Z, X, Y>.Create(Dest: ISubscriber<Z>; Strategy: IJoinStrategy<X, Y>;
FiberLeft, FiberRight: TCustomFiber);
begin
Create(Dest, Strategy);
FFiberLeft := FiberLeft;
FFiberRight := FiberRight;
end;
destructor TOnceSubscriber<Z, X, Y>.Destroy;
begin
FDest := nil;
FLeftBuffer.Free;
FRightBuffer.Free;
inherited;
end;
function TOnceSubscriber<Z, X, Y> ._AddRef: Integer;
begin
Result := inherited _AddRef;
end;
function TOnceSubscriber<Z, X, Y> ._Release: Integer;
begin
Result := inherited _Release;
end;
function TOnceSubscriber<Z, X, Y> .IsUnsubscribed: Boolean;
begin
Result := FDest = nil;
end;
procedure TOnceSubscriber<Z, X, Y> .OnCompleted;
begin
if not IsUnsubscribed then begin
FDest.OnCompleted;
Unsubscribe;
end;
end;
procedure TOnceSubscriber<Z, X, Y> .OnError(E: IThrowable);
begin
if not IsUnsubscribed then begin
FDest.OnError(E);
Unsubscribe;
end;
end;
procedure TOnceSubscriber<Z, X, Y>.OnNext(const A: Z);
begin
if not IsUnsubscribed then
FDest.OnNext(A)
end;
procedure TOnceSubscriber<Z, X, Y> .OnNext(const Left: X);
var
Zip: TZip<X, Y>;
begin
try
if IsUnsubscribed then
Exit;
Zip := FStrategy.OnNext(Left);
if Assigned(Zip) then
Self.OnNext(Zip)
finally
if Assigned(FFiberLeft) then
FFiberLeft.Yield
end;
end;
procedure TOnceSubscriber<Z, X, Y> .OnNext(const Right: Y);
var
Zip: TZip<X, Y>;
Ref: TSmartVariable<Z>;
begin
try
if IsUnsubscribed then
Exit;
Zip := FStrategy.OnNext(Right);
if Assigned(Zip) then begin
Ref := TObject(Zip);
Self.OnNext(Zip);
end;
finally
if Assigned(FFiberRight) then
FFiberRight.Yield;
end;
end;
procedure TOnceSubscriber<Z, X, Y> .SetProducer(P: IProducer);
begin
// nothing
end;
procedure TOnceSubscriber<Z, X, Y> .Unsubscribe;
begin
FDest := nil
end;
{ TSyncStrategy<X, Y> }
function TSyncStrategy<X, Y>.OnNext(const Left: X): TZip<X, Y>;
var
Right: Y;
begin
Result := nil;
if FRightBuffer.Count > 0 then begin
Right := FRightBuffer[0].Get;
FRightBuffer.Delete(0);
Result := TZip<X, Y>.Create(Left, Right);
end
else
FLeftBuffer.Add(Left)
end;
constructor TSyncStrategy<X, Y>.Create;
begin
FLeftBuffer := TList<TSmartVariable<X>>.Create;
FRightBuffer := TList<TSmartVariable<Y>>.Create;
end;
destructor TSyncStrategy<X, Y>.Destroy;
begin
FLeftBuffer.Free;
FRightBuffer.Free;
inherited;
end;
function TSyncStrategy<X, Y>.OnNext(const Right: Y): TZip<X, Y>;
var
Left: X;
begin
Result := nil;
if FLeftBuffer.Count > 0 then begin
Left := FLeftBuffer[0].Get;
FLeftBuffer.Delete(0);
Result := TZip<X, Y>.Create(Left, Right);
end
else
FRightBuffer.Add(Right)
end;
function TSyncStrategy<X, Y>.IsCompleted: Boolean;
begin
if CompletedLeft then
Result := FLeftBuffer.Count = 0
else if CompletedRight then
Result := FRightBuffer.Count = 0
else
Result := False;
end;
{ TCombineLatestStrategy<X, Y> }
function TCombineLatestStrategy<X, Y>.OnNext(const Left: X): TZip<X, Y>;
begin
FLeftExists := True;
FLeft := Left;
if FLeftExists and FRightExists then
Result := TZip<X, Y>.Create(FLeft, FRight)
else
Result := nil;
end;
function TCombineLatestStrategy<X, Y>.OnNext(const Right: Y): TZip<X, Y>;
begin
FRightExists := True;
FRight := Right;
if FLeftExists and FRightExists then
Result := TZip<X, Y>.Create(FLeft, FRight)
else
Result := nil;
end;
{ TWithLatestFromStrategy<X, Y> }
procedure TWithLatestFromStrategy<X, Y>.AfterOnNext;
begin
if FFastStream = fsA then
FLeftExists := False
else
FRightExists := False
end;
function TWithLatestFromStrategy<X, Y>.OnNext(const Left: X): TZip<X, Y>;
begin
FLeftExists := True;
FLeft := Left;
if FLeftExists and FRightExists then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
AfterOnNext;
end
else
Result := nil;
end;
constructor TWithLatestFromStrategy<X, Y>.Create(FastStream: TFastStream);
begin
FFastStream := FastStream;
end;
function TWithLatestFromStrategy<X, Y>.OnNext(const Right: Y): TZip<X, Y>;
begin
FRightExists := True;
FRight := Right;
if FLeftExists and FRightExists then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
AfterOnNext;
end
else
Result := nil;
end;
{ TAMBWithStrategy<X, Y> }
procedure TAMBWithStrategy<X, Y>.AfterOnNext;
begin
FLeftExists := False;
FRightExists := False;
end;
function TAMBWithStrategy<X, Y>.OnNext(const Left: X): TZip<X, Y>;
begin
if not FLeftExists then begin
FLeftExists := True;
FLeft := Left;
end;
if FLeftExists and FRightExists and (FFastStream = fsB) then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
AfterOnNext;
end
else
Result := nil;
end;
constructor TAMBWithStrategy<X, Y>.Create(FastStream: TFastStream);
begin
FFastStream := FastStream;
end;
function TAMBWithStrategy<X, Y>.OnNext(const Right: Y): TZip<X, Y>;
begin
if not FRightExists then begin
FRightExists := True;
FRight := Right;
end;
if FLeftExists and FRightExists and (FFastStream = fsA) then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
AfterOnNext;
end
else
Result := nil;
end;
{ TAMBStrategy<X, Y> }
function TAMBStrategy<X, Y>.OnNext(const Left: X): TZip<X, Y>;
begin
if not FLeftExists then begin
FLeftExists := True;
FLeft := Left;
end;
if FLeftExists and FRightExists then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
FLeftExists := False;
FRightExists := False;
end
else
Result := nil;
end;
function TAMBStrategy<X, Y>.OnNext(const Right: Y): TZip<X, Y>;
begin
if not FRightExists then begin
FRightExists := True;
FRight := Right;
end;
if FLeftExists and FRightExists then begin
Result := TZip<X, Y>.Create(FLeft, FRight);
FLeftExists := False;
FRightExists := False;
end
else
Result := nil;
end;
{ TJoinStrategy<X, Y> }
procedure TJoinStrategy<X, Y>.OnCompletedLeft;
begin
FCompletedLeft := True;
end;
procedure TJoinStrategy<X, Y>.OnCompletedRight;
begin
FCompletedRight := True;
end;
procedure TJoinStrategy<X, Y>.OnErrorLeft(Error: IThrowable);
begin
FCompletedLeft := True;
if not Assigned(FError) then
FError := Error;
end;
procedure TJoinStrategy<X, Y>.OnErrorRight(Error: IThrowable);
begin
FCompletedRight := True;
if not Assigned(FError) then
FError := Error;
end;
function TJoinStrategy<X, Y>.GetError: IThrowable;
begin
Result := FError
end;
function TJoinStrategy<X, Y>.IsCompleted: Boolean;
begin
Result := FCompletedLeft or FCompletedRight
end;
end.
|
unit ADAPT.UnitTests.Maths.SIUnits;
interface
{$I ADAPT.inc}
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
DUnitX.TestFramework,
ADAPT.Intf,
ADAPT.Math.SIUnits;
type
[TestFixture]
TAdaptUnitTestMathSIUnits = class(TObject)
public
[Test]
procedure OneMegaToOneGigaExplicit;
[Test]
[TestCase('10 to 1 Deca', '10,simOne,1,simDeca')]
[TestCase('100 to 1 Hecta', '100,simOne,1,simHecto')]
[TestCase('20 to 2 Deca', '20,simOne,2,simDeca')]
[TestCase('1 Deca to 1 Deca', '1,simDeca,1,simDeca')]
[TestCase('1000 to 1 Kilo', '1000,simOne,1,simKilo')]
[Testcase('1000 Mega to 1 Giga', '1000,simMega,1,simGiga')]
procedure MagnitudeBest(const AInputValue: ADFloat; const AMagnitude: TADSIMagnitude; const AExpectedOutputValue: ADFloat; const AExpectedOutputMagnitude: TADSIMagnitude);
end;
implementation
{ TAdaptUnitTestMathSIUnits }
procedure TAdaptUnitTestMathSIUnits.OneMegaToOneGigaExplicit;
var
LOutputValue: ADFloat;
begin
LOutputValue := SIMagnitudeConvert(1000, simMega, simGiga);
Assert.IsTrue(LOutputValue = 1, Format('1000MB SHOULD be 1GB, but got %n', [LOutputValue]));
end;
procedure TAdaptUnitTestMathSIUnits.MagnitudeBest(const AInputValue: ADFloat; const AMagnitude: TADSIMagnitude; const AExpectedOutputValue: ADFloat; const AExpectedOutputMagnitude: TADSIMagnitude);
var
LOutputValue: ADFloat;
LOutputMagnitude: TADSIMagnitude;
begin
SIMagnitudeToBest(AInputValue, AMagnitude, LOutputValue, LOutputMagnitude);
Assert.IsTrue((LOutputValue = AExpectedOutputValue) and (LOutputMagnitude = AExpectedOutputMagnitude), Format('Expected Value "%n" (got "%n") and Magnitude "%s" (got "%s")', [AExpectedOutputValue, LOutputValue, AD_UNIT_MAGNITUDE_NAMES_SI[AExpectedOutputMagnitude, unLong], AD_UNIT_MAGNITUDE_NAMES_SI[LOutputMagnitude, unLong]]));
end;
initialization
TDUnitX.RegisterTestFixture(TAdaptUnitTestMathSIUnits);
end.
|
unit Import;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Recs,
StdCtrls;
type
TImportForm = class(TForm)
rbBinkD: TRadioButton;
rbBinkPlus: TRadioButton;
rbTMail: TRadioButton;
rbXenia: TRadioButton;
bOK: TButton;
bCancel: TButton;
bHelp: TButton;
rbFrontDoor: TRadioButton;
rbMainDoor: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure bHelpClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetImportType(const ATitle: string; Passwords: Boolean): TAlienCfgType;
implementation uses xBase, LngTools;
{$R *.DFM}
function GetImportType(const ATitle: string; Passwords: Boolean): TAlienCfgType;
var
ImportForm: TImportForm;
const
FHelpCtx: array[Boolean] of Integer = (IDH_IMPORTNODES, IDH_IMPORTPWD);
begin
Result := actNone;
ImportForm := TImportForm.Create(Application);
ImportForm.HelpContext := FHelpCtx[Passwords];
ImportForm.Caption := ATitle;
if not Passwords then
begin
ImportForm.rbFrontDoor.Enabled := False;
ImportForm.rbMainDoor.Enabled := False;
end;
if ImportForm.ShowModal = mrOK then
if ImportForm.rbBinkD.Checked then Result := actBinkD else
if ImportForm.rbBinkPlus.Checked then Result := actBinkPlus else
if ImportForm.rbTMail.Checked then Result := actTMail else
if ImportForm.rbXenia.Checked then Result := actXenia else
if ImportForm.rbFrontDoor.Checked then Result := actFrontDoor else
if ImportForm.rbMainDoor.Checked then Result := actMainDoor;
FreeObject(ImportForm);
end;
procedure TImportForm.FormCreate(Sender: TObject);
begin
FillForm(Self, rsImportForm);
end;
procedure TImportForm.bHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
unit LZW;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
{function CompressStr(var bin:String):String;
function DeCompressStr(var bin:String):String;}
function CompressStream(var bin:TMemoryStream):TMemorystream;
function DecompressStream(var bin:TMemoryStream):TMemorystream; //Experemental
function GetbyteStr(src:byte):string;
implementation
//Алгоритм Лемпеля — Зива — Велча
type
TDictPtr=^TDictEl;
TDictEl=record
num:word; //индексы от 0 до 65535
data:string;
next:TDictPtr;
end;
TbyteBufer=record
data:Longword; //временное хранение байта и оставшейся части
shift:byte; //сдвиг, или сколько уже занято бит
end;
function GetbyteStr(src:byte):string;
var
ct:byte;
begin
GetbyteStr:='';
for ct:=0 to 7 do
if odd(src shr ct) then GetbyteStr:='1'+GetbyteStr
else GetbyteStr:='0'+GetbyteStr;
end;
function GetWordStr(src:longword):string;
var
ct:byte;
begin
GetWordStr:='';
for ct:=0 to 31 do
if odd(src shr ct) then GetWordStr:='1'+GetWordStr
else GetWordStr:='0'+GetWordStr;
end;
procedure addToDict(var Last:TDictPtr; id:byte; data:string);
var
tmp:TDictPtr;
begin
new(tmp);
tmp^.data:=data;
tmp^.num:=id;
tmp^.next:=nil;
if (last<>nil) then last^.next:=tmp;
last:=tmp;
end;
function GetPtrbyData(DRoot:TDictPtr; Data:string):TDictPtr;
begin
GetPtrbyData:=nil;
while (GetPtrbyData=nil) and (DRoot<>nil) do
begin
if (Droot^.data=data) then GetPtrbyData:=Droot
else DRoot:=DRoot^.next;
end;
end;
function GetPtrbyId(DRoot:TDictPtr; id:byte):TDictPtr;
begin
GetPtrbyId:=nil;
while (GetPtrbyId=nil) and (DRoot<>nil) do
begin
if (Droot^.num=id) then GetPtrbyId:=Droot
else DRoot:=DRoot^.next;
end;
end;
procedure WriteData(var buf:TbyteBufer; data:word; datalen:byte);
var
w_data:Longword;
begin
// writeln('****Запрос на запись, данные=',GetbyteStr(data),' длинна=',datalen,'****');
//writeln('ДО =',GetWordStr(buf.data));
dec(buf.shift,datalen); //коррекция сдвига
w_data:=(data shl (buf.shift+1)); //поправка к сдвиг записи! если 1->0 2->1 3->2...
buf.data:=buf.data or w_data; // 1000 or 0100 = 1100
//writeln('ПОСЛЕ=',GetWordStr(buf.data));
end;
{function ExtractByteBuf(var buf:TbyteBufer):byte; //ВНИМАНИЕ ИЗМЕНЯЕТ БУФЕР!
begin
writeln('******Запрос на извлечение из БУФЕРА!*******');
{выдаем}
ExtractByteBuf:=buf.data shr 8; //берем старший ;)
{снимаем выданное с учета!!}
buf.data:=buf.data shl 8;
writeln('::='+GetByteStr(ExtractByteBuf));
if (buf.shift<=8) then inc(buf.shift,8)
else buf.shift:=15;
end; }
function ExtractData(var buf:TbyteBufer; data_len:byte):word; //ВНИМАНИЕ ИЗМЕНЯЕТ БУФЕР! EXPEREMENTAL
begin
// writeln('******Запрос на извлечение из БУФЕРА! длинна=',data_len,'****');
{выдаем}
//writeln('ДО =',GetWordStr(buf.data));
ExtractData:=buf.data shr (32-data_len); //берем старшие data_len бит ;)
//writeln('Выдаю=',GetByteStr(ExtractData));
{снимаем выданное с учета!!}
buf.data:=buf.data shl data_len;
// writeln('ПОСЛЕ=',GetWordStr(buf.data));
if (buf.shift+data_len<=31) then inc(buf.shift,data_len)
else buf.shift:=31;
end;
function GETIndexLength(max:word):byte; //1-16
begin
{вычислить длинну индекса}
case max of
0..1: GETIndexLength:=1;
2..3: GETIndexLength:=2;
4..7: GETIndexLength:=3;
8..15: GETIndexLength:=4;
16..31: GETIndexLength:=5;
32..63: GETIndexLength:=6;
64..127: GETIndexLength:=7;
128..255: GETIndexLength:=8;
256..511: GETIndexLength:=9;
512..1023: GETIndexLength:=10;
1024..2047: GETIndexLength:=11;
2048..4095: GETIndexLength:=12;
4096..8191: GETIndexLength:=13;
8192..16383: GETIndexLength:=14;
16384..32767:GETIndexLength:=15;
32768..65535:GETIndexLength:=16;
end;
end;
function CompressStream(var bin:TMemoryStream):TMemorystream; //stable
var
DictF,DictL,SearchRez:TDictPtr;
bufer:TbyteBufer; //временно храним байт + остаток
load_bufer,back_bufer:string; //сюда загрузим байты из потока
//flags
cur_dict_id:word;
index_len:byte;
found, error, full_stream:boolean;
begin
{ini}
CompressStream:=TmemoryStream.Create;
error:=false;
cur_dict_id:=0;
bufer.data:=0;
bufer.shift:=30; {[31..0] 1 бит(старший) зарезервирован под хранение информ о не/четности конца цепи
нечетной будем считать вид: <code>|nil четной: <code>|<c byte> => full_stream }
full_stream:=true;
{ini dictonary}
DictF:=nil;
addToDict(DictF,cur_dict_id,''); //первый в словаре - пустой
DictL:=DictF;
while ((bin.Position<bin.Size) and (not error)) do
begin
load_bufer:='';
found :=true;
while ((found) and (bin.Position<bin.Size)) do //пока такая комбинация в словаре берем еще
begin
load_bufer:=load_bufer+char(bin.ReadByte);
SearchRez:=GetPtrbyData(DictF, load_bufer);
found:=(SearchRez<>nil);
end;
// writeln('**load_bufer=',load_bufer);
{цикл завершися: либо комбинация уникальна, либо иcкать болше нечего}
if (length(load_bufer)>0) then
begin
{установи дилинну записи индекса
тк пока новой записью мы пользоваться не сможем -> см по старому индексу}
index_len:=GETIndexLength(cur_dict_id);
{конец потока?}
if (found) then
begin
// writeln('loadbufer не уникален!');
{пишем индекс}
WriteData(bufer,SearchRez^.num,index_len); //кинем в буфер индекс
{сброс первых 8 бит (если надо)}
if (bufer.shift<24) then
CompressStream.WriteByte(ExtractData(bufer,8));
{получается цепь нечетная!! заполним 1-й первый бит на выходе}
full_stream:=false;
end
ELSE
{запись уникальна, выполняй добавление запись и пр...}
begin
{только теперь пишем словарь}
// writeln('loadbufer уникален!');
inc(cur_dict_id); //даем приращение id
addToDict(DictL,cur_dict_id,load_bufer); //пишем в словарь
write(cur_dict_id,', ');
{записываем входной байт НО со сдвигом, необходимым для записи индекса}
{вычислим предыдущую комбинацию и её байт}
back_bufer:=copy(load_bufer,1,length(load_bufer)-1);
SearchRez:=GetPtrbyData(DictF, back_bufer);
// writeln('backbufer=',back_bufer);
error:=(SearchRez=nil);
if (not error) then
begin
// writeln('пишем индекс back=',SearchRez^.num);
WriteData(bufer,SearchRez^.num,index_len); //кинем в буфер индекс
{нужен ли сброс???}
if (bufer.shift<24) then //fixed <8 not <=8) -- DERECATED now 32 bit bufer
CompressStream.WriteByte(ExtractData(bufer,8));
{запись входного БАЙТА отрежь последний бит!}
load_bufer:=load_bufer[length(load_bufer)];
// writeln('Запись входного байта=',load_bufer);
WriteData(bufer,byte(load_bufer[1]),8);
CompressStream.WriteByte(ExtractData(bufer,8)); //8 записал, сбрось
end;
END;
end; //конец "если буфер не пуст"
end; //конец главный цикл
{finalization}
{сбросим буфер в код если там хоть что-то есть и подведем итоги}
while (bufer.shift<31) do //critical fix!
CompressStream.WriteByte(ExtractData(bufer,8));
if (not full_stream) then
begin
CompressStream.Position:=0;
index_len:=(compressStream.ReadByte or 128); //пишем 1-у в старший бит
CompressStream.Position:=0;
CompressStream.WriteByte(index_len);
end;
{убери словарь за собой:)) }
while (DictF<>nil) do
begin
// writeln('deleted =',DictF^.data);
SearchRez:=DictF;
DictF:=DictF^.next;
dispose(SearchRez);
end;
writeln('Готово: исход=',bin.Size,' сжат=',CompressStream.Size);
{end}
end;
function DecompressStream(var bin:TMemoryStream):TMemorystream; //Experemental
var
DictF,DictL,SearchRez:TDictPtr;
bufer:TbyteBufer; //временно храним байт + остаток
write_bufer:string; //сюда восстанавливаем части кода
//flags
index_len, need_len:byte;
cur_dict_id:word;
error, full_stream:boolean;
begin
{ini}
DecompressStream:=TmemoryStream.Create;
error:=false;
cur_dict_id:=0;
bufer.data:=0;
bufer.shift:=31; {32-битный буфер вместо 16-биного}
{ini dictonary}
DictF:=nil;
addToDict(DictF,cur_dict_id,''); //первый в словаре - пустой
DictL:=DictF;
{извлечем бит чет/нечет}
if (bin.Position<bin.Size) then
begin
WriteData(bufer,bin.ReadByte,8); //загрузим 1-е 8 бит
full_stream:=(ExtractData(bufer, 1)=0);
end;
{готово, перейдем к циклической обработке, пока буфер НЕ пуст!}
while ((bufer.shift<31) and (not error)) do
begin
write_bufer:='';
{заполняй буфер, если нечем то EOL}
while ((bufer.shift>6) and ((bin.Position<bin.Size))) do
begin
writeln('****гружу...');
WriteData(bufer,bin.ReadByte,8);
end;
{вычислить длинну индекса}
index_len:=GETIndexLength(cur_dict_id);
{сколько нужно данных?? index_len+8bit обычто
НО если поток не полон то +0 только в хвосте}
need_len:=index_len;
if (full_stream) then inc(need_len,8)
else
if (bufer.shift<24) then inc(need_len,8); //те есть 8 бит в буфере, то возьмем их, нет, так нет ;)
writeln('нужно данных=',need_len,' бит, имеем ',31-bufer.shift);
{***есть столько данных? да -начинаем распоковку, нет ...}
IF (bufer.shift<(32-need_len)) then //== bufer.shift<=(31-need_len)
BEGIN
{в буфере достаточно данных, обрабатываем}
SearchRez:=GetPtrbyId(DictF,ExtractData(bufer, index_len));
dec(need_len,index_len);
error:=(SearchRez=nil);
if (NOT ERROR) then
begin
write_bufer:=SearchRez^.data;
writeln('в словаре взято=',write_bufer);
if (need_len=8) then
write_bufer:=write_bufer+char(ExtractData(bufer, 8));
writeln('++ взято всего=',write_bufer);
end;
{от пустого буфера смысла нет}
if (length(write_bufer)>0) then
begin
//а нужно ли писать в словарь??
if (GetPtrbyData(DictF,write_bufer)=nil) then
begin
inc(cur_dict_id);
addToDict(DictL,cur_dict_id,write_bufer); //пишем в словарь
writeln('Добавлено в словарь id=',cur_dict_id,' data=',write_bufer);
end;
DecompressStream.WriteBuffer(write_bufer[1],length(write_bufer));
end;
END
else begin writeln('что-то пошло не так...'); error:=true; end;
writeln('состояние буфера на момент конца цикла:=',GetWordStr(bufer.data));
end; //main loop
{убери словарь за собой:)) }
while (DictF<>nil) do
begin
SearchRez:=DictF;
DictF:=DictF^.next;
dispose(SearchRez);
end;
if error then writeln('операция отменена! ошибка чтения');
end;
end.
|
// PROGRAMME DE DEMONSTRATION DE L'UNITE ALPHA UTILS
// Auteur : Bacterius
// Amusez-vous bien ! (voir AlphaUtils.pas pour plus d'infos pratiques)
unit Main; // Header unité
interface
uses // Les quelques unités (fournies avec Delphi ou avec mon zip) nécessaires pour lancer le programme
Windows, SysUtils, Classes, Forms, Dialogs,
ComCtrls, StdCtrls, Controls, AlphaUtils, Menus, ImgList;
type
TMainForm = class(TForm) // Type fiche
TrayWndBox: TGroupBox; // Boîte de contrôle "Barre des tâches"
TrayWndLbl: TLabel; // Indicateur de descripteur de fenêtre pour la barre des tâches
CompatibleLbl: TLabel; // Indicateur de compatibilité "layering" pour la barre des tâches
AlphaLbl: TLabel; // Indicateur de valeur alpha pour la barre des tâches
AlphaBar: TTrackBar; // Barre de transparence pour la barre des tâches
QuitBtn: TButton; // Bouton "Quitter"
BonusBox: TGroupBox; // Boîte de contrôle "Bonus"
BonusLbl: TLabel; // Label d'information pour le bonus
BonusBar: TTrackBar; // Barre de transparence pour le bonus
BonusLbl2: TLabel; // Label d'information 2 pour le bonus
ReturnToDefaultBtn: TButton; // Bouton "Remettre par défaut"
PopupBtn: TButton; // Bouton ">>" pour afficher le menu déroulant surgissant
PopupMenu: TPopupMenu; // Objet Popup Menu (menu déroulant surgissant)
TrayAlphaMenu: TMenuItem; // Elément popup "Transparence de la barre des tâches"
Tray100AlphaMenu: TMenuItem; // Elément popup "Transparence 100%" pour la barre des tâches
Tray75AlphaMenu: TMenuItem; // Elément popup "Transparence 75%" pour la barre des tâches
Tray50AlphaMenu: TMenuItem; // Elément popup "Transparence 50%" pour la barre des tâches
Tray25AlphaMenu: TMenuItem; // Elément popup "Transparence 25%" pour la barre des tâches
Tray0AlphaMenu: TMenuItem; // Elément popup "Transparence 0%" pour la barre des tâches
AppAlphaMenu: TMenuItem; // Elément popup "Transparence de la fiche"
App100AlphaMenu: TMenuItem; // Elément popup "Transparence 100%" pour la fiche
App75AlphaMenu: TMenuItem; // Elément popup "Transparence 75%" pour la fiche
App50AlphaMenu: TMenuItem; // Elément popup "Transparence 50%" pour la fiche
App25AlphaMenu: TMenuItem; // Elément popup "Transparence 25%" pour la fiche
App0AlphaMenu: TMenuItem; // Elément popup "Transparence 0%" pour la fiche
SeparatorMenu: TMenuItem; // Elément popup séparateur
QuitMenu: TMenuItem;
PopupImgList: TImageList; // Elément popup "Quitter"
procedure FormCreate(Sender: TObject); // On crée la fiche
procedure AlphaBarChange(Sender: TObject); // On change la trackbar de la barre des tâches
procedure QuitBtnClick(Sender: TObject); // Clic sur le bouton Quitter
procedure BonusBarChange(Sender: TObject); // Changement de la position de la barre "Bonus"
procedure FormKeyPress(Sender: TObject; var Key: Char); // Clic sur une touche
procedure FormClose(Sender: TObject; var Action: TCloseAction); // Fermeture de la fiche
procedure ReturnToDefaultBtnClick(Sender: TObject); // Clic sur le bouton "Remettre par défaut"
procedure PopupBtnClick(Sender: TObject); // Clic sur le bouton ">>"
procedure QuitMenuClick(Sender: TObject); // Clic sur le menu popup "Quitter"
procedure DefineAlpha(Sender: TObject); // Procédure qui gère les transparences prédéfinies dans le popup
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
MainForm: TMainForm; // Variable fiche
TrayWnd: HWND; // Handle de la barre des tâches (on ne va pas la chercher dix fois !)
TrayOldStyle: Integer; // Style de la barre des tâches avant PrepareLayering (important)
// La transparence de la barre des tâches ne sera pas conservée, pour une raison simple :
// on remet le style par défaut "sans layering" à la fermeture, et ça annule toute
// transparence. Mais si on veut conserver la transparence, on enlève ReleaseLayering dans
// le OnClose. On peut rétablir, de toute façon, plus tard, le style avec une autre paire
// de PrepareLayering et ReleaseLayering.
// Remarque : SupportsLayering teste si le layering est présent dans le style de la fiche.
// Ici, on sait que la barre des tâches et notre fiche ne supportent de toute façon pas
// le layering, mais je mets la vérification pour montrer comment il faut faire.
implementation
{$R *.dfm} // Link avec le fichier fiche
procedure TMainForm.FormCreate(Sender: TObject); // On crée la fiche
Var
Alpha: Byte; // Variable pour contenir la transparence de la barre des tâches
Dummy: Integer; // Variable utile juste pour la compilation, ne sert à rien
begin
DoubleBuffered := True; // On évite les scintillements
TrayWndBox.DoubleBuffered := True; // Idem
AlphaBar.DoubleBuffered := True; // Idem
BonusBox.DoubleBuffered := True; // Idem
BonusBar.DoubleBuffered := True; // Idem
TrayWnd := GetTrayHWnd; // On récupère le descripteur de fenêtre.
if not SupportsLayering(Handle) then // Si notre fenêtre ne supporte pas le layering, alors on l'applique
if not PrepareLayering(Handle, TrayOldStyle) then // Si erreur de préparation de NOTRE fiche ...
begin
Height := 175; // On réduit la taille pour cacher la boîte Bonus
MessageDlg('La fiche ne supporte pas la transparence, vous n''aurez pas accès au bonus.', mtError, [mbOK], 0);
// On affiche le message
end;
Alpha := 255; // Opaque
if Height <> 175 then SetWindowAlpha(Handle, Alpha); // Si on a accès au bonus, alors on met à 255 (0 par défaut)
if not SupportsLayering(TrayWnd) then // Si la barre des tâches ne supporte pas le layering, alors on l'applique
begin
CompatibleLbl.Caption := 'Gère la transparence : Non.'; // Si elle ne gère pas, alors on l'indique (ça peut quand même marcher)
if not PrepareLayering(TrayWnd, Dummy) then // Si erreur de préparation ... (Dummy sert juste à pouvoir compiler)
begin
MessageDlg('Impossible de préparer la barre des tâches !', mtError, [mbOK], 0);
// On en informe l'utilisateur ...
Close; // Et on quitte l'application !
end
end
else CompatibleLbl.Caption := 'Gère la transparence : Oui.'; // Sinon, on dit que la barre des tâches est compatible.
TrayWndLbl.Caption := 'Descripteur de fenêtre (HWND) : ' + IntToStr(TrayWnd) + '.';
// On marque le descripteur de fenêtre dans le label prévu à cet effet ...
GetWindowAlpha(TrayWnd, Alpha); // On récupère la transparence ...
case Alpha of // On essaye de varier un petit peu les messages quand même !
255: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + ' (Opaque).';
1..254: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + '.';
0: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + ' (Invisible).';
end;
AlphaBar.Position := Alpha; // On récupère la transparence de la barre des tâches, et on place la trackbar comme telle
end;
procedure TMainForm.AlphaBarChange(Sender: TObject); // On change la trackbar de la barre des tâches
Var
Alpha: Byte; // Variable pour contenir la transparence
begin
Alpha := AlphaBar.Position; // On donne à Alpha la transparence souhaitée par la position de la barre
SetWindowAlpha(TrayWnd, Alpha); // On définit la transparence
GetWindowAlpha(TrayWnd, Alpha); // On récupère la transparence
AlphaBar.Position := Alpha; // On replace la barre d'après la transparence réelle de la barre des tâches
case Alpha of // On affiche quelques messages différents selon ...
255: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + ' (Opaque).';
1..254: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + '.';
0: AlphaLbl.Caption := 'Valeur alpha actuelle : ' + IntToStr(Alpha) + ' (Invisible).';
end;
end;
procedure TMainForm.QuitBtnClick(Sender: TObject); // Clic sur le bouton Quitter
begin
Close; // On lance OnClose !!
end;
procedure TMainForm.BonusBarChange(Sender: TObject); // Changement de la position de la barre "Bonus"
Var
Alpha: Byte; // Variable qui contient la transparence de notre fiche
begin
BonusLbl.Caption := 'Bougez la barre pour changer la transparence de la fiche sans AlphaBlend avec une valeur définie par la barre ci-dessous (valeur définie à ' + IntToStr(BonusBar.Position) + ').'; // On modifie le label !
Alpha := BonusBar.Position; // On donne à Alpha la valeur de transparence voulue
SetWindowAlpha(Handle, Alpha); // On définit la transparence !
end;
procedure TMainForm.FormKeyPress(Sender: TObject; var Key: Char); // Clic sur une touche
Var
Alpha: Byte; // Variable qui contient la transparence de notre fiche
begin
if Height = 175 then Exit; // Si bonus non accessible, on quitte
if (Key <> 'r') and (Key <> 'R') then Exit; // Si pas la touche "R" ou la touche "r", on quitte
// Si on est arrivé jusque là c'est que la touche pressée est "R" ou "r", et qu'on a accès au bonus
Alpha := 255; // Opacité
BonusBar.Position := 255; // On fixe la barre à opacité
SetWindowAlpha(Handle, Alpha); // On définit la transparence à 255 pour rétablir.
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); // Fermeture de la fiche
begin
ReleaseLayering(TrayWnd, TrayOldStyle); // On remet la barre des tâches comme avant !
end;
procedure TMainForm.ReturnToDefaultBtnClick(Sender: TObject); // Clic sur le bouton "Remettre par défaut"
begin
AlphaBar.Position := 255; // On remet la transparence de la barre des tâches à la valeur par défaut (c'est-à-dire 255)
BonusBar.Position := 255; // On remet la transparence de notre fiche à la valeur par défaut (c'est-à-dire 255)
end;
procedure TMainForm.PopupBtnClick(Sender: TObject); // Clic sur le bouton ">>"
Var
P: TPoint; // Variable pour récupérer la position de la souris au moment du clic
begin
GetCursorPos(P); // On récupère la position de la souris
PopupMenu.Popup(P.X, P.Y); // On fait apparaître le popup à l'endroit de la souris ;)
end;
procedure TMainForm.DefineAlpha(Sender: TObject); // Procédure qui gère les transparences prédéfinies dans le popup
Var
Alpha: Byte; // Variable qui contient la transparence calculée
begin
if not (Sender is TMenuItem) then Exit; // Si Sender n'est pas un TMenuItem, on s'en va
with Sender as TMenuItem do // On prend Sender (typé TMenuItem) comme référence
begin
Alpha := Round((Tag / 100) * 255); // Petit calcul pour obtenir la valeur alpha (0..255) à partir du pourcentage (contenu dans le Tag de Sender)
case GroupIndex of // Selon le GroupIndex de Sender (1 pour la barre des tâches, 2 pour la fiche)
1: AlphaBar.Position := Alpha; // Si 1 (barre des tâches), on redéfinit la transparence de la barre des tâches
2: BonusBar.Position := Alpha; // Si 2 (notre fiche), on redéfinit la transparence de notre fiche
end;
end;
end;
procedure TMainForm.QuitMenuClick(Sender: TObject); // Clic sur le menu popup "Quitter"
begin
Close; // On appelle OnClose !
end;
end. // Fin de fichier
|
unit regUtils;
interface
uses registry, Forms, Windows, SysUtils;
Procedure SaveToRegistryWindowInfo(NameOfProject:string;Form:TForm);
Function LoadFromRegistryWindowInfo(NameOfProject:string;var Form:TForm):boolean;
Procedure SaveToRegistryCardsSorting(NameOfProject:string;SortBySuit,SortByValue,AutomaticSort:boolean);
Function LoadFromRegistryCardsSorting(NameOfProject:string;var SortBySuit,SortByValue,AutomaticSort:boolean):boolean;
Procedure SaveToRegistryChooseOptions(NameOfProject:string;ComboBox,RadioButtons,IsGo:boolean);
Function LoadFromRegistryChooseOptions(NameOfProject:string;var ComboBox,RadioButtons,IsGo:boolean):boolean;
Procedure SaveToRegistryString(NameOfProject,NameOfParameter,Value:string);overload;
Procedure SaveToRegistryString(HRootKey:Cardinal;HKey,HParam,HValue:string);overload;
Function LoadFromRegistryString(NameOfProject,NameOfParameter:string;var Value:string):boolean;overload;
Function LoadFromRegistryString(NameOfProject,NameOfParameter:string):string;overload;
Function LoadFromRegistryString(HRootKey:Cardinal;HKey,HParam:string;var HValue:string):boolean;overload;
Function LoadFromRegistryString(HRootKey:Cardinal;HKey,HParam:string):string;overload;
Procedure SaveToRegistryInteger(NameOfProject,NameOfParameter:string;Value:Integer);overload;
Procedure SaveToRegistryInteger(HRootKey:Cardinal;HKey,HParam:string;HValue:Integer);overload;
Function LoadFromRegistryInteger(HRootKey:Cardinal;HKey,HParam:string;var HValue:Integer):boolean;overload;
Function LoadFromRegistryInteger(NameOfProject,NameOfParameter:string;var Value:Integer):boolean;overload;
Function LoadFromRegistryInteger(NameOfProject,NameOfParameter:string):Integer;overload;
Function LoadFromRegistryInteger(HRootKey:Cardinal;HKey,HParam:string):Integer;overload;
Procedure SaveToRegistryBool(NameOfProject,NameOfParameter:string;Value:Boolean);
Function LoadFromRegistryBool(NameOfProject,NameOfParameter:string;var Value:Boolean):boolean;overload;
Function LoadFromRegistryBool(NameOfProject,NameOfParameter:string):Boolean;overload;
Procedure SaveToRegistryStrings(NameOfProject:string;
NamesOfStrings:array of string;Strings:array of string);
Function LoadFromRegistryStrings(NameOfProject:string;
NamesOfStrings:array of string;var Strings:array of string):boolean;
Procedure SaveToRegistryBools(NameOfProject:string;
NamesOfBools:array of string;Bools:array of boolean);
Function LoadFromRegistryBools(NameOfProject:string;
NamesOfBools:array of string;var Bools:array of boolean):boolean;
Procedure SaveToRegistryIntegers(NameOfProject:string;
NamesOfIntegers:array of string;Integers:array of integer);
Function LoadFromRegistryIntegers(NameOfProject:string;
NamesOfIntegers:array of string;var Integers:array of integer):boolean;
Procedure CreateUninstallInfo(NameOfProject,DisplayName,UninstallString:string);
Function ClearRegistry(NameOfProject:string):boolean;
Function CheckRegistry(NameOfProject:string):boolean;
Function CheckKey(Root:LongWord;NameOfKey:string):boolean;
Function CheckValue(Root:LongWord;NameOfKey,NameOfValue:string):boolean;
Procedure CreateFileAssociation(Ext,ExtType,ExtDescript,FileIcon,FileOpen:string);
{example
CreateFileAssociation('.x?*','Cool***XXX???Type',
'It is a very cool, xxx, ***, &&&, ??? UNKNOWN BEFORE!!! type',
ParamStr(0)+',1',ParamStr(0)+' "%1"');
}
Procedure CancelFileAssociation(Ext,ExtType,PathToProgram:string);
{example
CancelFileAssociation('.x?*','Cool***XXX???Type',ParamStr(0));
}
Procedure CreateEditMenu(Ext,FileEdit:string);
Procedure DeleteEditMenu(Ext:string);
type
THandlerException=Procedure(E:Exception) of object;
var
OnRegistryException:THandlerException=nil;
implementation
var
reg:TRegistry;
Procedure SaveToRegistryWindowInfo(NameOfProject:string;Form:TForm);
begin
reg := TRegistry.Create;
with reg, Form do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject+'\WindowsInfo',true);
WriteInteger('Left',Left);
WriteInteger('Top',Top);
WriteInteger('Width',Width);
WriteInteger('Height',Height);
WriteBool('Maximized',WindowState=wsMaximized);
reg.Free
end
end;
Function LoadFromRegistryWindowInfo(NameOfProject:string;var Form:TForm):boolean;
begin
reg := TRegistry.Create;
with reg, Form do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject+'\WindowsInfo');
if result then
begin
OpenKey('\Software\'+NameOfProject+'\WindowsInfo',true);
Left := ReadInteger('Left');
Top := ReadInteger('Top');
Width := ReadInteger('Width');
Height := ReadInteger('Height');
if ReadBool('Maximized') then
WindowState := wsMaximized
else
WindowState := wsNormal
end;
reg.Free
end
end;
Procedure SaveToRegistryCardsSorting(NameOfProject:string;SortBySuit,SortByValue,AutomaticSort:boolean);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject+'\CardsSorting',true);
WriteBool('SortBySuit',SortBySuit);
WriteBool('SortByValue',SortByValue);
WriteBool('AutomaticSort',AutomaticSort);
reg.Free
end
end;
Function LoadFromRegistryCardsSorting(NameOfProject:string;var SortBySuit,SortByValue,AutomaticSort:boolean):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject+'\CardsSorting');
if result then
begin
OpenKey('\Software\'+NameOfProject+'\CardsSorting',true);
SortBySuit := ReadBool('SortBySuit');
SortByValue := ReadBool('SortByValue');
AutomaticSort := ReadBool('AutomaticSort')
end;
reg.Free
end
end;
Procedure SaveToRegistryChooseOptions(NameOfProject:string;ComboBox,RadioButtons,IsGo:boolean);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject+'\ChooseOptions',true);
WriteBool('ComboBox',ComboBox);
WriteBool('RadioButtons',RadioButtons);
WriteBool('IsGo',IsGo);
reg.Free
end
end;
Function LoadFromRegistryChooseOptions(NameOfProject:string;var ComboBox,RadioButtons,IsGo:boolean):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject+'\ChooseOptions');
if result then
begin
OpenKey('\Software\'+NameOfProject+'\ChooseOptions',true);
ComboBox := ReadBool('ComboBox');
RadioButtons := ReadBool('RadioButtons');
IsGo := ReadBool('IsGo');
end;
reg.Free
end
end;
Procedure SaveToRegistryString(NameOfProject,NameOfParameter,Value:string);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
WriteString(NameOfParameter,Value);
reg.Free
end
end;
Function LoadFromRegistryString(NameOfProject,NameOfParameter:string;var Value:string):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
Value := ReadString(NameOfParameter)
end;
reg.Free
end
end;
Function LoadFromRegistryString(NameOfProject,NameOfParameter:string):string;overload;
begin
LoadFromRegistryString(NameOfProject,NameOfParameter,Result)
end;
Procedure SaveToRegistryStrings(NameOfProject:string;
NamesOfStrings:array of string;Strings:array of string);
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfStrings) to High(NamesOfStrings) do
WriteString(NamesOfStrings[i],Strings[i]);
reg.Free
end
end;
Function LoadFromRegistryStrings(NameOfProject:string;
NamesOfStrings:array of string;var Strings:array of string):boolean;
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfStrings) to High(NamesOfStrings) do
Strings[i] := ReadString(NamesOfStrings[i])
end;
reg.Free
end
end;
Procedure SaveToRegistryBools(NameOfProject:string;
NamesOfBools:array of string;Bools:array of boolean);
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfBools) to High(NamesOfBools) do
WriteBool(NamesOfBools[i],Bools[i]);
reg.Free
end
end;
Function LoadFromRegistryBools(NameOfProject:string;
NamesOfBools:array of string;var Bools:array of boolean):boolean;
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfBools) to High(NamesOfBools) do
Bools[i] := ReadBool(NamesOfBools[i])
end;
reg.Free
end
end;
Procedure SaveToRegistryIntegers(NameOfProject:string;
NamesOfIntegers:array of string;Integers:array of integer);
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfIntegers) to High(NamesOfIntegers) do
WriteInteger(NamesOfIntegers[i],Integers[i]);
reg.Free
end
end;
Function LoadFromRegistryIntegers(NameOfProject:string;
NamesOfIntegers:array of string;var Integers:array of integer):boolean;
var
i:word;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
for i := Low(NamesOfIntegers) to High(NamesOfIntegers) do
Integers[i] := ReadInteger(NamesOfIntegers[i])
end;
reg.Free
end
end;
Procedure CreateUninstallInfo(NameOfProject,DisplayName,UninstallString:string);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
OpenKey('\Software\Microsoft\Windows\CurrentVersion\Uninstall\'+NameOfProject,true);
WriteString('DisplayName',DisplayName);
WriteString('UninstallString',UninstallString);
reg.Free
end
end;
Function ClearRegistry(NameOfProject:string):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
DeleteKey('\Software\'+NameOfProject);
DeleteKey('\Software\Microsoft\Windows\CurrentVersion\Uninstall\'+NameOfProject)
end;
reg.Free
end
end;
Function CheckRegistry(NameOfProject:string):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
reg.Free
end
end;
Procedure CreateFileAssociation(Ext,ExtType,ExtDescript,FileIcon,FileOpen:string);
var
reg:TRegistry;
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_CLASSES_ROOT;
reg.OpenKey(Ext,true);
reg.WriteString('',ExtType);
reg.CloseKey;
reg.OpenKey(ExtType,true);
reg.WriteString('',ExtDescript);
reg.CloseKey;
reg.OpenKey(ExtType+'\DefaultIcon',true);
reg.WriteString('',FileIcon);
reg.CloseKey;
reg.OpenKey(ExtType+'\shell\open\command',true);
reg.WriteString('',FileOpen);
reg.CloseKey;
reg.Free
end;
Procedure CancelFileAssociation(Ext,ExtType,PathToProgram:string);
var
reg:TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CLASSES_ROOT;
reg.DeleteKey(Ext);
reg.DeleteKey(ExtType);
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKey('Software\Microsoft\Windows\ShellNoRoam\MUICache',false);
reg.DeleteValue(PathToProgram);
finally
reg.Free
end
end;
procedure SaveToRegistryInteger(NameOfProject, NameOfParameter: string;
Value: Integer);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
WriteInteger(NameOfParameter,Value);
reg.Free
end
end;
function LoadFromRegistryInteger(NameOfProject, NameOfParameter: string;
var Value: Integer): boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
Value := ReadInteger(NameOfParameter)
end;
reg.Free
end
end;
function LoadFromRegistryInteger(NameOfProject,
NameOfParameter: string): Integer;
begin
LoadFromRegistryInteger(NameOfProject,NameOfParameter,Result)
end;
procedure SaveToRegistryBool(NameOfProject, NameOfParameter: string;
Value: Boolean);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('\Software\'+NameOfProject,true);
WriteBool(NameOfParameter,Value);
reg.Free
end
end;
function LoadFromRegistryBool(NameOfProject, NameOfParameter: string;
var Value: Boolean): boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := KeyExists('\Software\'+NameOfProject);
if result then
begin
OpenKey('\Software\'+NameOfProject,true);
try
Value := ReadBool(NameOfParameter)
except
on E:ERegistryException do
if @OnRegistryException<>nil then
OnRegistryException(E)
end
end;
reg.Free
end
end;
function LoadFromRegistryBool(NameOfProject,
NameOfParameter: string): Boolean;
begin
LoadFromRegistryBool(NameOfProject,NameOfParameter,Result)
end;
Function CheckKey(Root:LongWord;NameOfKey:string):boolean;
begin
reg := TRegistry.Create;
with reg do
begin
reg.RootKey := Root;
Result := KeyExists(NameOfKey);
reg.Free
end
end;
procedure CreateEditMenu(Ext, FileEdit: string);
var
ExtType:string;
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_CLASSES_ROOT;
reg.OpenKey(Ext,false);
ExtType:=reg.readString('');
reg.CloseKey;
reg.OpenKey(ExtType+'\shell\edit\command',true);
reg.WriteString('',FileEdit);
reg.CloseKey;
reg.Free
end;
procedure DeleteEditMenu(Ext: string);
var
ExtType:string;
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_CLASSES_ROOT;
reg.OpenKey(Ext,false);
ExtType:=reg.readString('');
reg.CloseKey;
reg.DeleteKey(ExtType+'\shell\edit\command');
reg.Free
end;
function CheckValue(Root: LongWord; NameOfKey,
NameOfValue: string): boolean;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(NameOfKey,false);
Result := ValueExists(NameOfValue);
reg.Free
end
end;
Procedure SaveToRegistryString(HRootKey:Cardinal;HKey,HParam,HValue:string);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HRootKey;
OpenKey(HKey,true);
WriteString(HParam,HValue);
reg.Free
end
end;
Function LoadFromRegistryString(HRootKey:Cardinal;HKey,HParam:string;var HValue:string):boolean;overload;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HRootKey;
Result := KeyExists(HKey);
if result then
begin
OpenKey(HKey,true);
HValue := ReadString(HParam)
end;
reg.Free
end
end;
Function LoadFromRegistryString(HRootKey:Cardinal;HKey,HParam:string):string;overload;
begin
LoadFromRegistryString(HRootKey,HKey,HParam,Result)
end;
Procedure SaveToRegistryInteger(HRootKey:Cardinal;HKey,HParam:string;HValue:Integer);
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HRootKey;
OpenKey(HKey,true);
WriteInteger(HParam,HValue);
reg.Free
end
end;
Function LoadFromRegistryInteger(HRootKey:Cardinal;HKey,HParam:string;var HValue:Integer):boolean;overload;
begin
reg := TRegistry.Create;
with reg do
begin
RootKey := HRootKey;
Result := KeyExists(HKey);
if result then
begin
OpenKey(HKey,true);
HValue := ReadInteger(HParam)
end;
reg.Free
end
end;
Function LoadFromRegistryInteger(HRootKey:Cardinal;HKey,HParam:string):Integer;overload;
begin
LoadFromRegistryInteger(HRootKey,HKey,HParam,Result)
end;
end.
|
unit SIP_Monitor;
interface
function GetTick64:Int64;
function SIPMonitorStatus:String;
type
TSIPMonitor=record
Status_RS,
Status_GSM,
Count_GSM,
Status_Mail,
Count_Mail,
Status_SIP:Int64;
GSM_Registration:String;
end;
var
SIPMonitor:TSIPMonitor;
implementation
uses Windows, SysUtils, Util;
var
OldTick:Int64=0;
TickCount:Int64=0;
function GetTick64:Int64;
var NewTick:Int64;
begin
NewTick:=GetTickCount;
if NewTick>=OldTick then
TickCount:=TickCount-OldTick+NewTick
else
TickCount:=TickCount-OldTick+NewTick+High(DWORD);
Result:=TickCount;
OldTick:=NewTick;
end;
function SIPMonitorStatus:String;
var X:TSIPMonitor;
Tick:Int64;
function Status(A,B:Int64):String;
begin
if A>B then
Result:='false'
else
Result:='true';
end;
begin
X:=SIPMonitor;
Tick:=GetTick64;
Result:=Format('{rs:%s, gsm:%s, mail:%s, sip:%s, gsmcount:"%d", mailcount:"%d", gsmreg:%s}',[
Status(Tick,X.Status_RS+5000),
Status(Tick,X.Status_GSM+10000),
Status(Tick,X.Status_Mail+60000),
Status(Tick,X.Status_SIP+150000),
X.Count_GSM,
X.Count_Mail,
StrEscape(X.GSM_Registration)
])
end;
end.
|
unit HeidiTestRunner;
interface
uses
SysUtils,
Classes,
XMLTestRunner,
TestFramework,
TestLogMgr,
WebReport,
BDSUtils;
type
THeidiTestListener = class(TXMLTestListener)
private
function MakeUTCTime(DateTime: TDateTime): TDateTime;
public
procedure TestingEnds(testResult: TTestResult); override;
end;
TFileLoadFormater = class(TLogFormatter)
public
function FormatOutput(T: TEventType; const Desc, Expect, Recv: string; const Expected: Boolean=true): string; override;
end;
TDUnitTestManager = record
Author: String;
TestingArea: String;
Context: String;
end;
HeidiReportException = class(Exception);
{: Run the given test suite
}
function RunTest(suite: ITest; outputFile:String=DEFAULT_FILENAME) : TTestResult; overload;
function RunRegisteredTests(outputFile:String=DEFAULT_FILENAME) : TTestResult; overload;
var
TestManager: TDUnitTestManager;
implementation
uses MSXML, ActiveX, Windows;
{ THeidiTestListener }
function THeidiTestListener.MakeUTCTime(DateTime: TDateTime): TDateTime;
var
TZI: TTimeZoneInformation;
begin
case GetTimeZoneInformation(TZI) of
TIME_ZONE_ID_STANDARD:
Result := DateTime + (TZI.Bias/60/24);
TIME_ZONE_ID_DAYLIGHT:
Result := DateTime + (TZI.Bias/60/24) + TZI.DaylightBias;
else
Result := DateTime;
end;
end;
procedure THeidiTestListener.TestingEnds(testResult: TTestResult);
var
LogManager: TTestLogManager;
aHandler : TLogHandler;
begin
inherited;
LogManager := TTestLogManager.Create(nil);
try
LogManager.Handlers[0].Active := False;
LogManager.Product.Sku := BDSUtils.GetSKU;
LogManager.Product.Build := BDSUtils.GetVersion;
LogManager.Machine.OSVersion := BDSUtils.GetOSVersion;
LogManager.Machine.Locale := BDSUtils.GetBDSLocale;
LogManager.Suite.TestingArea := TestManager.TestingArea;
LogManager.Suite.Name := ExtractFileName(ParamStr(0));
LogManager.Suite.Author := TestManager.Author;
LogManager.Suite.LogFile := FileName;
LogManager.Suite.Context := TestManager.Context;
with LogManager.Stats do
begin
Failed := testResult.failureCount;
Aborted := testResult.errorCount;
Passed := testResult.runCount - Failed - Aborted;
Ended := MakeUTCTime(now);
Started := MakeUTCTime(Self.StartTime);
end;
aHandler := LogManager.Handlers.Add(TWebServiceLogHandler);
aHandler.Formatter := LogManager.Formatters.Add(TFileLoadFormater);
try
LogManager.BeginLogging;
LogManager.EndLogging;
except
on e: exception do
raise HeidiReportException.CreateFmt('Failed to report test result to Heidi: %s', [e.Message]);
end;
finally
LogManager.Free;
end;
end;
function RunTest(suite: ITest; outputFile:String=DEFAULT_FILENAME): TTestResult;
begin
Result := TestFramework.RunTest(suite, [THeidiTestListener.Create(outputFile)]);
end;
function RunRegisteredTests(outputFile:String=DEFAULT_FILENAME): TTestResult;
begin
Result := HeidiTestRunner.RunTest(registeredTests, outputFile);
end;
{ TFileLoadFormater }
function TFileLoadFormater.FormatOutput(T: TEventType; const Desc, Expect,
Recv: string; const Expected: Boolean): string;
var
fileContents : TStringList;
begin
if FileExists(Desc) then
begin
fileContents := TStringList.Create;
try
fileContents.LoadFromFile(Desc);
Result := fileContents.Text;
finally
fileContents.Free;
end;
end;
end;
initialization
TestManager.Author := 'Unknown Author';
TestManager.TestingArea := 'Unknown DUnit';
TestManager.Context := '';
end.
|
unit AExcluiProdutoDuplicado;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Buttons, StdCtrls, Localizacao, UnProdutos,
UnDadosLocaliza;
type
TFExcluiProdutoDuplicado = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
EProdutoExcluido: TRBEditLocaliza;
Label1: TLabel;
Label2: TLabel;
SpeedButton1: TSpeedButton;
Label3: TLabel;
EProdutoDestino: TRBEditLocaliza;
SpeedButton2: TSpeedButton;
Label4: TLabel;
BExcluir: TBitBtn;
BFechar: TBitBtn;
ELog: TMemoColor;
Label5: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BExcluirClick(Sender: TObject);
procedure EProdutoExcluidoRetorno(VpaColunas: TRBColunasLocaliza);
procedure EProdutoDestinoRetorno(VpaColunas: TRBColunasLocaliza);
private
{ Private declarations }
VprSeqProdutoAExcluir,
VprSeqProdutoDestino : Integer;
public
{ Public declarations }
end;
var
FExcluiProdutoDuplicado: TFExcluiProdutoDuplicado;
implementation
uses APrincipal;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFExcluiProdutoDuplicado.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFExcluiProdutoDuplicado.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFExcluiProdutoDuplicado.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFExcluiProdutoDuplicado.BExcluirClick(Sender: TObject);
begin
if (VprSeqProdutoAExcluir <> 0) and (VprSeqProdutoDestino <> 0) then
FunProdutos.ExcluiProdutoDuplicado(VprSeqProdutoAExcluir,VprSeqProdutoDestino,ELog.Lines );
end;
{******************************************************************************}
procedure TFExcluiProdutoDuplicado.EProdutoExcluidoRetorno(
VpaColunas: TRBColunasLocaliza);
begin
if VpaColunas[2].AValorRetorno <> '' then
VprSeqProdutoAExcluir := StrToInt(VpaColunas[2].AValorRetorno)
else
VprSeqProdutoAExcluir := 0;
end;
{******************************************************************************}
procedure TFExcluiProdutoDuplicado.EProdutoDestinoRetorno(
VpaColunas: TRBColunasLocaliza);
begin
if VpaColunas[2].AValorRetorno <> '' then
VprSeqProdutoDestino := StrToInt(VpaColunas[2].AValorRetorno)
else
VprSeqProdutoDestino := 0;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFExcluiProdutoDuplicado]);
end.
|
unit OpenPortForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, RzPanel,
RzDlgBtn,VaComm, VaClasses,Main;
type
TForm4 = class(TForm)
baudrateSelection: TComboBox;
databitsSelection: TComboBox;
stopbitsSelection: TComboBox;
StaticText1: TStaticText;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
paritySelection: TComboBox;
comPortTVaComm: TVaComm;
CloseButton: TButton;
Ok: TButton;
procedure FormCreate(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure OkClick(Sender: TObject);
private
{ Private declarations }
public
function GetPortSettings:string;
{ Public declarations }
end;
var
Form4: TForm4;
implementation
{$R *.dfm}
procedure TForm4.FormCreate(Sender: TObject);
begin
//Initialize Baudrate selection
baudrateSelection.Items.Add('9600');
baudrateSelection.Items.Add('19200');
baudrateSelection.Items.Add('38400');
baudrateSelection.Items.Add('57600');
baudrateSelection.Items.Add('115200');
baudrateSelection.ItemIndex := 0;
//Initialize Databits selection
databitsSelection.Items.Add('4');
databitsSelection.Items.Add('5');
databitsSelection.Items.Add('6');
databitsSelection.Items.Add('7');
databitsSelection.Items.Add('8');
databitsSelection.ItemIndex := 4;
//Initialize Partiy selection
paritySelection.Items.Add('None');
paritySelection.Items.Add('Odd');
paritySelection.Items.Add('Even');
paritySelection.Items.Add('Mark');
paritySelection.Items.Add('Space');
paritySelection.ItemIndex := 0;
//Initialize Stopbits selection
stopbitsSelection.Items.Add('1');
stopbitsSelection.Items.Add('1.5');
stopbitsSelection.Items.Add('2');
stopbitsSelection.ItemIndex := 0;
end;
//Open the selected with the selected settings and enable all the parameters.
procedure TForm4.OkClick(Sender: TObject);
var portValue:string;
begin
//Get port number.
portValue:=Form1.portComboBox.Items[Form1.portComboBox.ItemIndex];
comPortTVaComm.PortNum:=StrToInt(portValue[length(portValue)]);
//Call setting function.
GetPortSettings;
comPortTVaComm.Open;
Form1.RunTimeClickButton.Enabled:=True;
Form1.ConnectLabel.Caption := 'Ansluten';
Form1.ApdStatusLight1.Lit := True;
Form1.saveClickButton.Enabled:=True;
Form1.resetClickButton.Enabled:=True;
Form1.ResetAllClickButton.Enabled:=True;
Form1.deleteTextClickButton.Enabled:=True;
Form1.textAreaRadioGroup.Enabled:=True;
Form1.okClickButton.Enabled:=True;
Form1.lightIntensityTrackBar.Enabled:=True;
Form1.baudrateComboBox.Enabled:=True;
Form1.textAreaRadioGroup.ItemIndex:=0;
Form1.GameButton.Enabled:=True;
Form4.Hide;
end;
//Set all settings for the Port.
{ These are the settings that works for the TVaComm Component
TVaBaudrate = (brUser, br110, br300, br600, br1200, br2400, br4800, br9600, br14400,
br19200, br38400, br56000, br57600, br115200, br128000, br256000);
TVaParity = (paNone, paOdd, paEven, paMark, paSpace);
TVaDatabits = (db4, db5, db6, db7, db8);
TVaStopbits = (sb1, sb15, sb2);
}
function TForm4.GetPortSettings;
begin
//Get the Baudrate
if baudrateSelection.ItemIndex=0 then
comPortTVaComm.Baudrate:=br9600
else if baudrateSelection.ItemIndex=1 then
comPortTVaComm.Baudrate:=br19200
else if baudrateSelection.ItemIndex=2 then
comPortTVaComm.Baudrate:=br38400
else if baudrateSelection.ItemIndex=3 then
comPortTVaComm.Baudrate:=br57600
else if baudrateSelection.ItemIndex=4 then
comPortTVaComm.Baudrate:=br115200;
//Get the databits
if databitsSelection.ItemIndex=0 then
comPortTVaComm.Databits:=db4
else if databitsSelection.ItemIndex=1 then
comPortTVaComm.Databits:=db5
else if databitsSelection.ItemIndex=2 then
comPortTVaComm.Databits:=db6
else if databitsSelection.ItemIndex=3 then
comPortTVaComm.Databits:=db7
else if databitsSelection.ItemIndex=4 then
comPortTVaComm.Databits:=db8;
//Get Parity selection
if paritySelection.ItemIndex=0 then
comPortTVaComm.Parity:=paNone
else if paritySelection.ItemIndex=1 then
comPortTVaComm.Parity:=paOdd
else if paritySelection.ItemIndex=2 then
comPortTVaComm.Parity:=paEven
else if paritySelection.ItemIndex=3 then
comPortTVaComm.Parity:=paMark
else if paritySelection.ItemIndex=4 then
comPortTVaComm.Parity:=paSpace;
//Get Stopbits selection
if stopbitsSelection.ItemIndex=0 then
comPortTVaComm.Stopbits:=sb1
else if stopbitsSelection.ItemIndex=1 then
comPortTVaComm.Stopbits:=sb15
else if stopbitsSelection.ItemIndex=2 then
comPortTVaComm.Stopbits:=sb2;
end;
procedure TForm4.CloseButtonClick(Sender: TObject);
begin
Form4.Hide;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
/// <summary> DBX DataSnap Connection Support </summary>
/// <remarks>
/// This unit contains the TDSProviderConnection component which provides
/// connectivity to a DataSnap server using DBX.
/// <para>
///
/// To Use:
/// - Add TDSProviderConnection to a DataSnap client application along
/// with a TClientDataSet and a TSQLConnection.
///
/// - Configure the TSQLConnection with the appropriate connection settings.
///
/// - Connect the TDSProviderConnection to the TSQLConnection.
///
/// - Set the ServerClassName property to the name of the TRemoteDataModule.
///
/// - Connect the TDSProviderConnection to the TSQLConnection.
///
///
/// At this point the DataSnap client should be configured and ready to use
/// just like any other DataSnap client. See the documentation for DataSnap
/// for additional information.
/// </para>
///
/// </remarks>
unit Datasnap.DSConnect;
interface
uses
{$IFNDEF POSIX}
Winapi.ActiveX,
{$ENDIF}
System.Classes,
Datasnap.DBClient,
Data.DBXCommon,
Datasnap.Midas,
Data.SqlExpr;
type
{ TDSProviderConnection }
///<summary>
/// Implementation of <c>TCustomRemoteServer</c> that provides
/// a connection to a DataSnap server using TDBXCommand server method calls.
///</summary>
{$IFNDEF POSIX}
TDSProviderConnection = class(TCustomRemoteServer, IAppServer, ISupportErrorInfo)
{$ELSE}
TDSProviderConnection = class(TCustomRemoteServer, IAppServer)
{$ENDIF}
private
FAppServer: IAppServer;
FServerClassName: string;
FSQLConnection: TSQLConnection;
FApplyUpdatesCommand: TDBXCommand;
FGetRecordsCommand: TDBXCommand;
FDataRequestCommand: TDBXCommand;
FGetProviderNamesCommand: TDBXCommand;
FGetParamsCommand: TDBXCommand;
FRowRequestCommand: TDBXCommand;
FExecuteCommand: TDBXCommand;
FRowRequest: TDBXCommand;
procedure SetSQLConnection(const Value: TSQLConnection);
procedure SetServerClassName(const Value: string);
function GetDBXConnection: TDBXConnection;
procedure FreeCommands;
procedure ConnectChange(Sender: TObject; Connecting: Boolean);
protected
procedure DoConnect; override;
procedure DoDisconnect; override;
function GetConnected: Boolean; override;
procedure SetConnected(Value: Boolean); override;
function GetCommandObject(const ProcedureName: string): TDBXCommand;
property Connection: TDBXConnection read GetDBXConnection;
protected
{ IAppServer }
function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant; safecall;
function AS_GetRecords(const ProviderName: WideString; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: WideString;
var Params, OwnerData: OleVariant): OleVariant; safecall;
function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall;
function AS_GetProviderNames: OleVariant; safecall;
function AS_GetParams(const ProviderName: WideString;
var OwnerData: OleVariant): OleVariant; safecall;
function AS_RowRequest(const ProviderName: WideString; Row: OleVariant;
RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall;
procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString;
var Params, OwnerData: OleVariant); safecall;
{$IFNDEF POSIX}
{ ISupportErrorInfo }
function InterfaceSupportsErrorInfo(const iid: TGUID): HResult; stdcall;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
///<summary>
/// Get the IAppServer interface implemented by this component.
///</summary>
property AppServer: IAppServer read FAppServer;
function GetServer: IAppServer; override;
{$IFNDEF POSIX}
function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override;
{$ENDIF}
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
published
///<summary>
/// The class name of the Remote DataModule class on the server (excludes leading "T").
///</summary>
property ServerClassName: string read FServerClassName write SetServerClassName;
///<summary>
/// The state of the connection.
///</summary>
property Connected;
///<summary>
/// Associated TSQLConnection used to connect to the server.
///</summary>
property SQLConnection: TSQLConnection read FSQLConnection write SetSQLConnection;
end;
implementation
uses
{$IFNDEF POSIX}
System.Win.ComObj,
{$ENDIF}
Data.DBXClientResStrs,
Data.DSUtil,
System.SysUtils,
System.Variants;
const
// IAppServer method names
SAS_ApplyUpdates = 'AS_ApplyUpdates';
SAS_GetRecords = 'AS_GetRecords';
SAS_DataRequest = 'AS_DataRequest';
SAS_GetProviderNames = 'AS_GetProviderNames:';
SAS_GetParams = 'AS_GetParams';
SAS_RowRequest = 'AS_RowRequest';
SAS_Execute = 'AS_Execute';
{ TDSProviderConnection }
procedure TDSProviderConnection.ConnectChange(Sender: TObject;
Connecting: Boolean);
begin
if Sender = FSQLConnection then
begin
if Connecting then
DoConnect
else
DoDisconnect;
end;
end;
constructor TDSProviderConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAppServer := Self as IAppServer;
end;
destructor TDSProviderConnection.Destroy;
begin
FAppServer := nil;
FreeCommands;
inherited;
end;
procedure TDSProviderConnection.DoConnect;
begin
// Missing FSQLConnection check is in SetConnected. Nil check below is "just in case".
if FSQLConnection <> nil then
FSQLConnection.Connected := True;
SetAppServer(FAppServer);
end;
procedure TDSProviderConnection.DoDisconnect;
begin
SetAppServer(NULL);
FreeCommands;
// Multiple TDSProviderConnections can share this...
// if FSQLConnection <> nil then
// FSQLConnection.Connected := False;
end;
procedure TDSProviderConnection.FreeCommands;
begin
FreeAndNil(FApplyUpdatesCommand);
FreeAndNil(FGetRecordsCommand);
FreeAndNil(FDataRequestCommand);
FreeAndNil(FGetProviderNamesCommand);
FreeAndNil(FGetParamsCommand);
FreeAndNil(FRowRequestCommand);
FreeAndNil(FExecuteCommand);
FreeAndNil(FRowRequest);
end;
function TDSProviderConnection.GetCommandObject(const ProcedureName: string): TDBXCommand;
begin
SetConnected(True);
Result := Connection.CreateCommand;
Result.CommandType := TDBXCommandTypes.DSServerMethod;
Result.Text := Format('%s.%s', [ServerClassName, ProcedureName]);
Result.Prepare;
end;
function TDSProviderConnection.GetConnected: Boolean;
begin
Result := Assigned(FSQLConnection) and FSQLConnection.Connected;
end;
function TDSProviderConnection.GetDBXConnection: TDBXConnection;
begin
if FSQLConnection <> nil then
Result := FSQLConnection.DBXConnection
else
Result := nil;
end;
function TDSProviderConnection.GetServer: IAppServer;
begin
Connected := True;
Result := FAppServer;
SetAppServer(Result);
end;
function TDSProviderConnection.AS_ApplyUpdates(const ProviderName: WideString;
Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant;
var
Command: TDBXCommand;
begin
if FApplyUpdatesCommand = nil then
FApplyUpdatesCommand := GetCommandObject(SAS_ApplyUpdates);
Command := FApplyUpdatesCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.AsVariant := Delta;
Command.Parameters[2].Value.SetInt32(MaxErrors);
Command.Parameters[3].Value.SetInt32(ErrorCount);
Command.Parameters[4].Value.AsVariant := OwnerData;
Command.Parameters[5].Value.SetNull; // Result
// Invoke the server method
Command.ExecuteUpdate;
// Assign output and result parameters
ErrorCount := Command.Parameters[3].Value.GetInt32;
OwnerData := Command.Parameters[4].Value.AsVariant;
Result := Command.Parameters[5].Value.AsVariant;
end;
function TDSProviderConnection.AS_DataRequest(const ProviderName: WideString;
Data: OleVariant): OleVariant;
var
Command: TDBXCommand;
begin
if FDataRequestCommand = nil then
FDataRequestCommand := GetCommandObject(SAS_DataRequest);
Command := FDataRequestCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.AsVariant := Data;
Command.Parameters[2].Value.SetNull; // Result
// Invoke the server method
Command.ExecuteUpdate;
// Assign output and result parameters
Result := Command.Parameters[2].Value.AsVariant;
end;
procedure TDSProviderConnection.AS_Execute(const ProviderName, CommandText: WideString;
var Params, OwnerData: OleVariant);
var
Command: TDBXCommand;
begin
if FExecuteCommand = nil then
FExecuteCommand := GetCommandObject(SAS_Execute);
Command := FExecuteCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.SetWideString(CommandText);
Command.Parameters[2].Value.AsVariant := Params;
Command.Parameters[3].Value.AsVariant := OwnerData;
// Invoke the server method
Command.ExecuteUpdate;
// Assign output parameters
Params := Command.Parameters[2].Value.AsVariant;
OwnerData := Command.Parameters[3].Value.AsVariant;
end;
function TDSProviderConnection.AS_GetParams(const ProviderName: WideString;
var OwnerData: OleVariant): OleVariant;
var
Command: TDBXCommand;
begin
if FGetParamsCommand = nil then
FGetParamsCommand := GetCommandObject(SAS_GetParams);
Command := FGetParamsCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.AsVariant := OwnerData;
Command.Parameters[2].Value.SetNull; // Result
// Invoke the server method
Command.ExecuteUpdate;
// Assign output parameters
OwnerData := Command.Parameters[1].Value.AsVariant;
Result := Command.Parameters[2].Value.AsVariant;
end;
function TDSProviderConnection.AS_GetProviderNames: OleVariant;
var
Command: TDBXCommand;
begin
if FGetProviderNamesCommand = nil then
FGetProviderNamesCommand := GetCommandObject(SAS_GetProviderNames);
Command := FGetProviderNamesCommand;
// Setup input parameters
Command.Parameters[0].Value.SetNull;
// Invoke the server method
Command.ExecuteUpdate;
// Assign the result parameter
StrListToVarArray(Command.Parameters[0].Value.GetWideString, Result);
end;
function TDSProviderConnection.AS_GetRecords(const ProviderName: WideString;
Count: Integer; out RecsOut: Integer; Options: Integer;
const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant;
var
Command: TDBXCommand;
begin
if FGetRecordsCommand = nil then
FGetRecordsCommand := GetCommandObject(SAS_GetRecords);
Command := FGetRecordsCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.SetInt32(Count);
Command.Parameters[2].Value.SetInt32(RecsOut);
Command.Parameters[3].Value.SetInt32(Options);
Command.Parameters[4].Value.SetWideString(CommandText);
Command.Parameters[5].Value.AsVariant := Params;
Command.Parameters[6].Value.AsVariant := OwnerData;
Command.Parameters[7].Value.SetNull; // Result
// Invoke the server method
Command.ExecuteUpdate;
// Assign output and result parameters
RecsOut := Command.Parameters[2].Value.GetInt32;
Params := Command.Parameters[5].Value.AsVariant;
OwnerData := Command.Parameters[6].Value.AsVariant;
Result := Command.Parameters[7].Value.AsVariant;
end;
function TDSProviderConnection.AS_RowRequest(const ProviderName: WideString;
Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant;
var
Command: TDBXCommand;
begin
if FRowRequestCommand = nil then
FRowRequestCommand := GetCommandObject(SAS_RowRequest);
Command := FRowRequestCommand;
// Setup input parameters
Command.Parameters[0].Value.SetWideString(ProviderName);
Command.Parameters[1].Value.AsVariant := Row;
Command.Parameters[2].Value.SetInt32(RequestType);
Command.Parameters[3].Value.AsVariant := OwnerData;
Command.Parameters[4].Value.SetNull; // Result
// Invoke the server method
Command.ExecuteUpdate;
// Assign output and result parameters
OwnerData := Command.Parameters[3].Value.AsVariant;
Result := Command.Parameters[4].Value.AsVariant;
end;
{$IFNDEF POSIX}
function TDSProviderConnection.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HandleSafeCallException(ExceptObject, ExceptAddr, IAppServer, '', '');
end;
function TDSProviderConnection.InterfaceSupportsErrorInfo(const iid: TGUID): HResult;
begin
if IsEqualGUID(IAppServer, iid) then
Result := S_OK else
Result := S_FALSE;
end;
{$ENDIF}
procedure TDSProviderConnection.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FSQLConnection) then
FSQLConnection := nil;
end;
procedure TDSProviderConnection.SetConnected(Value: Boolean);
begin
if (not (csReading in ComponentState)) and
(Value and not Connected) and
((FServerClassName = '') or
(FSQLConnection = nil)) then
raise Exception.CreateResFmt(@SMissingServerSettings, [Name]);
inherited;
end;
procedure TDSProviderConnection.SetServerClassName(const Value: string);
begin
if Value <> FServerClassName then
begin
FreeCommands;
FServerClassName := Value;
end;
end;
procedure TDSProviderConnection.SetSQLConnection(const Value: TSQLConnection);
begin
if Assigned(FSQLConnection) then
begin
FSQLConnection.RemoveFreeNotification(Self);
FSQLConnection.RemoveConnectNotification(Self);
end;
FSQLConnection := Value;
if Value <> nil then
begin
Value.FreeNotification(Self);
Value.AddConnectNotification(Self, ConnectChange);
end;
end;
end.
|
unit TestLayoutBare;
{ AFS 1 March 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
a 'bare' block is one that does not have begin..end around it
This unit tests layout for statments with bare blocks
IMHO doing things this way in real code is not cool,
use begin-end blocks to make things clear
}
interface
implementation
{ block layout }
function NastyElse(var foo, bar: boolean): integer;
begin
if Foo then
Result := -1
else
end;
function NastyElse2(var foo, bar: boolean): integer;
begin
if Foo then
if bar then
Result := -1
else
else
Result := 2;
end;
{ these lttle tests have one statement block per procedure
and omit the semicolon after the final statement, which is legal but ugly }
procedure LittleTest1;
var
iA, iB: integer;
liLoop: integer;
begin
if iA > 5 then for liLoop := 1 to 10 do iA := iA + Random (2) else while IA < 50 do iA := iA + Random (5)
end;
procedure LittleTest2;
var
iA, iB: integer;
bA: Boolean;
begin
if iA > 20 then
bA := False
else if IB > 6 then
BA := True
else
BA := False
end;
procedure LittleTest3;
var
iA, iB: integer;
liLoop: integer;
begin
if IB < 15 then
while iA < 10 do
for liLoop := 0 to 3 do
begin iA := iA + Random (10); end
end;
procedure LittleTest4;
var iA: integer;
begin repeat iA := iA + Random (10) until IA > 100; end;
procedure IfElseTest;
var
iA, IB: integer;
BA: boolean;
begin
if iA > 20 then
bA := False
else if IB > 6 then
BA := True
else if IA < 6 then
BA := False;
if iA > 20 then
if IB > 5 then
bA := False
else if IB > 6 then
BA := True
else
BA := False;
end;
procedure LittleTest5_1;
var
iA, iB: integer;
bA: boolean;
begin
if iA > 5 then
if iA > 20 then
BA := True
else
BA := False
end;
procedure LittleTest5_2;
var
iA, iB: integer;
bA: boolean;
begin
if iA > 5 then
if iA > 20 then
BA := True
else
BA := False
else
ba := True
end;
procedure LittleTest5_3;
var
iA, iB: integer;
bA: Boolean;
begin
if iA > 20 then if IB > 6 then BA := True
else BA := False else ba := True
end;
procedure LittleTest6;
var
iA, iB: integer;
bA: boolean;
begin
if iA > 5 then
if iA > 20 then
if IB > 6 then
BA := True
else
BA := False
else
ba := True
else
ba := False
end;
procedure Mixem;
var
iA, IB: integer;
begin
iA := Random (10);
iB := Random (10);
{ alternate blocked and naked }
if IA > 3 then
if IA > 4 then
begin
ib := 10;
end;
if IA > 4 then
begin
if IA > 5 then
if IA > 6 then
begin
if IA > 7 then
if IA > 8 then
begin
if IA > 9 then
ib := 10;
end;
end;
end;
if IA > 3 then
if IA > 4 then
begin
if IA > 5 then
if IA > 6 then
begin
if IA > 7 then
if IA > 8 then
begin
if IA > 9 then
ib := 10;
end;
end;
end;
end;
procedure LayoutBare;
var
iA, IB: integer;
bA: Boolean;
liLoop, liLoop2: integer;
begin
iA := Random (10);
iB := Random (10);
if iA > 5 then
bA :=True
else
bA := False;
for liLoop := 0 to 10 do
iA := iA + Random (10);
for liLoop := 0 to 10 do
if iB < 15 then
iA := iA - Random (10);
if iB < 15 then
while iA < 10 do
iA := iA + Random (10);
for liLoop := 0 to 3 do
for liLoop2 := 0 to 3 do
iA := iA - Random (10);
if IB < 15 then
while iA < 10 do
for liLoop := 0 to 3 do
begin iA := iA + Random (10); end;
if iA > 20 then
if IB > 5 then
bA := False
else
if IB > 6 then
BA := True
else
BA := False;
repeat iA := iA + Random (10) until IA > 100;
end;
end.
|
{-------------------------------------------------------------------------------
HtmlViewer6TestForm.pas, (C) 03/2011 by Bernd Gabriel, all rights reserved
mailto: info@fast-function-factory.de
-------------------------------------------------------------------------------}
unit HtmlViewer6TestForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, ComCtrls,
// shared units
TntDialogs,
// own units
HtmlBoxes,
HtmlBuffer,
HtmlDocument,
HtmlDraw,
HtmlElements,
HtmlGlobals,
HtmlImages,
HtmlParser,
HtmlSymbols,
HtmlViewer,
StyleTypes,
UrlSubs, ExtCtrls;
type
TFormHtmlViewer12Test = class(TForm)
dlgFileOpen: TTntOpenDialog;
menu: TMainMenu;
menuFile: TMenuItem;
menuFileOpen: TMenuItem;
HtmlViewer: THtmlViewer12;
PageControl: TPageControl;
HtmlTab: TTabSheet;
CssTab: TTabSheet;
CssMemo: TMemo;
BegaSplitter1: TSplitter;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure menuFileOpenClick(Sender: TObject);
private
FName: ThtString;
FStream: TStream;
FBuffer: TBuffer;
FDocument: THtmlDocument;
FParser: THtmlParser;
FView: THtmlBox;
FBufferCache: ThtBufferCache;
FImageCache: ThtImageCache;
public
procedure Load(FileName: ThtString);
end;
var
FormHtmlViewer12Test: TFormHtmlViewer12Test;
implementation
{$R *.dfm}
{ TFormHtmlViewer12Test }
//-- BG ---------------------------------------------------------- 28.03.2011 --
procedure TFormHtmlViewer12Test.menuFileOpenClick(Sender: TObject);
begin
dlgFileOpen.FileName := FName;
if dlgFileOpen.Execute then
Load(dlgFileOpen.FileName);
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure TFormHtmlViewer12Test.FormCreate(Sender: TObject);
// simple test example with parsing a document:
procedure InitTest;
begin
Load('HtmlViewer12Test.html');
end;
//var
// Image: ThtImage;
// ImageName: string;
// ImageIndex: Integer;
begin
FBufferCache := ThtBufferCache.Create;
FImageCache := ThtImageCache.Create;
// ImageName := 'pengbrew.png';
// Image := LoadImageFromFile(ImageName, TrPng);
// if Image <> nil then
// FImageCache.AddObject(ImageName, Image);
//
// FView := THtmlBodyBox.Create(nil, THtmlBodyControl.Create(HtmlViewer));
// FView.BoundsRect := Rect(4, 8, 404, 308);
// FView.Margins := RectIntegers(16, 22, 4, 8);
// FView.BorderWidths := RectIntegers(4, 8, 16, 0);
// FView.Padding := RectIntegers(6, 2, 4, 10);
// FView.BorderColors := RectColors(clRed, clAqua, clGreen, clOlive);
// FView.BorderStyles := RectStyles(bssSolid, bssDashed, bssDouble, bssGroove);
// FView.Color := clNone;
// FView.Text := 'HtmlViewer ' + ThtChar(8805) + ' 12';
// FView.Alignment := taCenter;
// FView.Font.Style := [fsItalic];
// FView.Font.Color := clCaptionText;
// FView.Font.Size := 16;
// ImageIndex := FImageCache.IndexOf(ImageName);
// if ImageIndex >= 0 then
// begin
// FView.Image := FImageCache.GetImage(ImageIndex);
// FView.Image.EndUse; // Both FView and GetImage have started a use, but one is required only.
// end
// else
// FView.Image := ErrorImage;
// FView.Tiled := True;
// FView.TileWidth := 100;
// FView.TileHeight := 100;
// HtmlViewer.AddView(FView);
InitTest;
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure TFormHtmlViewer12Test.FormDestroy(Sender: TObject);
begin
if FView <> nil then
begin
FView.Image := nil;
FView.Free;
end;
FBufferCache.Free;
FImageCache.Free;
Load('');
end;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.Load(FileName: ThtString);
begin
CssMemo.Clear;
FreeAndNil(FParser);
FreeAndNil(FDocument);
FreeAndNil(FBuffer);
FreeAndNil(FStream);
FName := FileName;
if Length(FName) > 0 then
begin
FStream := TFileStream.Create(FName, fmOpenRead + fmShareDenyNone);
FBuffer := TBuffer.Create(FStream, 'file://' + DosToHtml(FName));
FDocument := THtmlDocument.Create;
FParser := THtmlParser.Create(FBuffer);
FParser.ParseHtmlDocument(FDocument);
CssMemo.Lines.Text := FDocument.RuleSets.ToString;
end;
end;
end.
|
{
ID: a2peter1
PROG: rect1
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'rect1';
MaxN = 1000;
MaxC = 2500;
type
rect = record
A,B,C,D,
color : longint;
end;{rect}
var
X,Y,N,i,r : longint;
ls : array[0..MaxN] of rect;
area : array[0..MaxC] of longint;
procedure update(A,B,C,D,lvl: longint);
begin
for lvl := lvl to N do
if (A < ls[lvl].C) and (B < ls[lvl].D) and
(C > ls[lvl].A) and (D > ls[lvl].B) then
begin
if A < ls[lvl].A then
begin
update(A,B,ls[lvl].A,D,lvl + 1);
A := ls[lvl].A;
end;{then}
if C > ls[lvl].C then
begin
update(ls[lvl].C,B,C,D,lvl + 1);
C := ls[lvl].C;
end;{then}
if B < ls[lvl].B then update(A,B,C,ls[lvl].B,lvl + 1);
if D > ls[lvl].D then update(A,ls[lvl].D,C,D,lvl + 1);
exit;
end;{then}
inc(area[ls[r].color],(C - A) * (D - B));
end;{update}
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(X,Y,N);
for i := 1 to N do
with ls[i] do readln(A,B,C,D,color);
ls[0].color := 1;
ls[0].C := X; ls[0].D := Y;
for r := N downto 0 do
with ls[r] do update(A,B,C,D,r + 1);
for i := 1 to MaxC do
if area[i] > 0 then writeln(i,' ',area[i]);
close(output);
end.{main}
|
unit u_J16LevelWithoutFilterImp;
interface
uses
Classes, SysUtils, StrUtils, u_ExamineImp, u_J08TaskIntf, u_J08Task, u_J16CommonDef;
type
TLevelWithoutFilterMeasure = Class(TCustomExamineItem, IStatText2XLS)
Private
// FLog: TLO1MesureLog;
Procedure InternalCheck(const Value: Boolean; const ExceptionInfo: String);
Private
FLevelDataFileList: TStringList;
procedure CallBack_TextFileFound(const FileName: string; const Info: TSearchRec;
var Abort: Boolean);
Protected //inteface IStatText2XLS
Procedure DoStatText2XLS;
Protected
Procedure Init; Override;
Procedure DoProcess; Override;
Public
End;
implementation
uses
u_GPIB_DEV2, u_J16Receiver, u_ExamineGlobal, u_J08WeakGlobal, PlumUtils, u_J16Utils,
u_CommonDef, CnCommon, XLSReadWriteII5, XLSSheetData5, Xc12Utils5;
{ TLevelWithoutFilterMeasure }
procedure TLevelWithoutFilterMeasure.CallBack_TextFileFound(
const FileName: string; const Info: TSearchRec; var Abort: Boolean);
begin
self.FLevelDataFileList.Add(FileName);
Log(FileName);
end;
procedure TLevelWithoutFilterMeasure.DoProcess;
{------------------------------------------------------------------------------
分别在AM和FM下,用对应的单音频率在不同的幅度下输入,读取对应的上报LEVEL值,读到的
值以序号为文件名,用STRINGLIST的方式存储在文本目录中,供以后统计使用
----------------------------------------------------------------------------}
const
CONST_MODULS: Array[0..1] of TJ08_ModuType = (mtAM, mtFM);
CONST_MODULS_FREQS: Array[0..1] of Integer = (15000, 98000);
CONST_TEST_LEVELS: Array[0..21] of Integer = (0, -10, -20, -30, -40, -50, -60,
-70, -80, -90, -100, -100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0);
var
InsLost: Double;
CurrStep, TotalStep: Integer;
var
SG: ISignalGenerator;
Radio: IJ08Receiver;
Calibrator: ISlopeCalibrate;
bid, pid, sid: integer;
LevelRead: Double;
var
LevelsMeasured: Array[0..1] of Array of Single;
Procedure SaveLevelsMeasured2TextFile;
var
i, j : integer;
TextFileName: String;
StrList: TStringList;
TextDir: STring;
begin
TextDir:= TextDir_NoFilter();
if Not DirectoryExists(TextDir) then
begin
ForceDirectories(TextDir);
end;
TextFileName:= TextDir + ProductSN + '.无滤波器.txt';
StrList:= TStringList.Create;
try
for i := 0 to Length(LevelsMeasured) - 1 do
for j := 0 to Length(LevelsMeasured[i]) - 1 do
begin
//FM不进行首尾0dBm激励的测试
if i = 1 then
begin
if (j = 0) or (j = Length(CONST_TEST_LEVELS) - 1) then
continue;
end;
StrList.Add(IntToStr(Trunc(LevelsMeasured[i, j])));
end;
StrList.SaveToFile(TextFileName);
finally
StrList.Free;
end;
Log('记录数据文件: ' + TextFileName);
end;
var
i, k: Integer;
UIOption: TLevelWithoutFilterOption;
begin
Log('------无滤波器电平读数测试(自动切换)------------');
get_UI.SyncUI(@UIOption);
CurrStep:= 0;
TotalStep:= 43;
InsLost:= FUI.ExamineItem.InlineInsertLost;
Radio:= TJ16Receiver.Create;
Calibrator:= Radio as ISlopeCalibrate;
SetLength( LevelsMeasured[0], Length(CONST_TEST_LEVELS));
SetLength( LevelsMeasured[1], Length(CONST_TEST_LEVELS));
try
{$IFNDEF Debug_Emu}
SG:= TMG36XX.Create;
With SG do
begin
pid:= 3;
Iden:= 'SG';
LoadInstrumentParam(bid, pid, sid);
Connnect(bid, pid, sid);
end;
{$ENDIF}
if not Radio.ReceiverTrunedOn then
Radio.OpenReceiver;
WaitMS(100);
Radio.Internal_SetFMThreshold(UIOption.FMThreshold[0], UIOption.FMThreshold[1],
UIOption.FMThreshold[2], UIOption.FMThreshold[3]);
WaitMS(100);
Radio.Internal_SetAMThreshold(UIOption.AMThreshold[0], UIOption.AMThreshold[1],
UIOption.AMThreshold[2], UIOption.AMThreshold[3]);
WaitMS(100);
InternalCheck(Radio.SetHiGain(damAuto, dmmAttent), '设置自动增益模式失败');
Calibrator.SetCoeffValid( True );
WaitMS(100);
Calibrator.LevelDataFormat( 1 );
WaitMS(100);
Log('打开接收机,并设置为自动切换模式,上报校准后数据');
for i:= 0 to Length(CONST_MODULS) - 1 do
begin
{$IFNDEF Debug_Emu}
SG.SetFreqency(CONST_MODULS_FREQS[i] / 1000);
SG.SetOnOff(True);
{$ENDIF}
Log(Format('信号源输出 %.0fMHz', [CONST_MODULS_FREQS[i] / 1000]));
WaitMS(200);
{$IFNDEF Debug_Emu}
InternalCheck(Radio.SetFrequency(CONST_MODULS[i], CONST_MODULS_FREQS[i] * 1000),
'设置频率失败');
{$ENDIF}
Log(Format('接收机设置: %s %d KHz', [CONST_STR_MODUL[CONST_MODULS[i]],
CONST_MODULS_FREQS[i]
]));
for k := 0 to Length(CONST_TEST_LEVELS) - 1 do
begin
if CONST_MODULS[i] = mtFM then
begin
//FM不进行首尾0dBm激励的测试
if (k = 0) or (k = Length(CONST_TEST_LEVELS) - 1) then
continue;
end;
{$IFNDEF Debug_Emu}
SG.SetLevelDbm(CONST_TEST_LEVELS[k] + InsLost);
{$ENDIF}
WaitMS(UIOption.StableDelay);
if CONST_MODULS[i] = mtAM then
begin
if Radio.AMData.DevManualMode = dmmAttent then
begin
WaitMS(500);
end;
end
else if CONST_MODULS[i] = mtFM then
begin
if Radio.FMData.DevManualMode = dmmAttent then
begin
WaitMS(500);
end;
end;
{$IFDEF DEBUG_emu}
LevelsMeasured[i, k]:= CONST_TEST_LEVELS[k] * 9 + 34 + Random(10) - 5;
{$ELSE}
InternalCheck(Radio.ReadLevel(LevelRead, CONST_MODULS[i]), '读取电平值失败');
LevelsMeasured[i, k]:= LevelRead;
{$ENDIF}
Log(Format(' %6.0f @%5d dBm', [LevelsMeasured[i, k], CONST_TEST_LEVELS[k]]));
// if k = 0 then
// begin
// CoeffSrc[i, j].AX:= CONST_LEVELS_PER_MODE[j, k];
// CoeffSrc[i, j].AY:= SampledLevels[i, j, k];
// end
// else
// begin
// CoeffSrc[i, j].BX:= CONST_LEVELS_PER_MODE[j, k];
// CoeffSrc[i, j].BY:= SampledLevels[i, j, k];
// end;
Inc(CurrStep);
FUI.set_Percent((CurrStep / TotalStep) * 100);
CheckWishStop();
end;
end;
//save to text file
SaveLevelsMeasured2TextFile();
Inc(CurrStep);
FUI.set_Percent((CurrStep / TotalStep) * 100); //curr step count value should be 13
CheckWishStop();
Log('完成');
finally
Set_Status(esComplete);
end;
end;
procedure TLevelWithoutFilterMeasure.DoStatText2XLS;
var
Level: Array[0..1] of Array[0..21] of Integer;
LevelStrs: TStringList;
Procedure ReadLevelValue(FileName: String);
var
Ptr: PInteger;
i: Integer;
begin
Ptr:= @Level[0, 0];
LevelStrs.LoadFromFile(FileName);
if LevelStrs.Count <> 42 then
Raise Exception.Create('数据记录的行数不正确');
for i := 0 to LevelStrs.Count - 1 do
begin
Ptr^:= StrToInt(LevelStrs[i]);
Inc(Ptr);
end;
end;
var
i, iline: Integer;
iCol: Integer;
iRow: Integer;
SN: String;
StatXLSFileName: String;
ASheet: TXLSWorksheet;
rs: TResourceStream;
wb: TXLSReadWriteII5;
CalcExp: String;
//const
// AM_ROW_STR = '1';
// FM_ROW_STR = '24';
begin
Log('统计文本被调用');
FLevelDataFileList:= TStringList.Create;
LevelStrs:= TStringList.Create;
try
CnCommon.FindFile(TextDir_NoFilter(), '*.无滤波器.txt', CallBack_TextFileFound);
FLevelDataFileList.Sort();
//每个文件共44个数
Log('共找到' + IntToStr(FLevelDataFileList.Count) + '个文件');
//把文件中的数据填充到EXCEL中, 前22个是AM数据, 从B2开始(B1是标题),
//后22是FM数据,从B25开始((B24是标题))
if FLevelDataFileList.Count > 0 then
begin
wb:= TXLSReadWriteII5.Create(Nil);
try
StatXLSFileName:= TextDir_NoFilter() + '\数据统计.xlsx';
// if FileExists(StatXLSFileName) then
// begin
// wb.LoadFromFile(StatXLSFilename);
// end
// else
begin
rs:= TResourceStream.Create(HInstance, 'StatTemplate', 'MYFILE');
try
wb.LoadFromStream(rs);
finally
rs.Free;
end;
end;
ASheet:= wb.Sheets[0];
//B01: iCol = 1, iRow = 0
//B24: iCol = 1, iRow = 23
iCol:= 1;
for i := 0 to FLevelDataFileList.Count - 1 do
begin
ReadLevelValue(FLevelDataFileList[i]);
SN:= ExtractFileName(FLevelDataFileList[i]);
SetLength(SN, Length(SN) - Length(ExtractFileExt(SN)));
SetLength(SN, Length(SN) - Length(ExtractFileExt(SN)));
//Level[0]数组填充到B2开始的列,B1为SN号
iRow:= 0;
ASheet.ClearCell(iCol, iRow);
ASheet.AsString[iCol, iRow]:= SN;
for iLine := 0 to Length(Level[0]) - 1 do
begin
ASheet.ClearCell(iCol, iRow + iLine + 1);
ASheet.AsInteger[iCol, iRow + iLine + 1]:= Level[0, iLine];
end;
//Level[1]数组填充到B25开始的列,B24为SN号
iRow:= 23;
ASheet.AsString[iCol, iRow]:= SN;
for iLine := 0 to Length(Level[1]) - 3 do
begin
ASheet.ClearCell(iCol, iRow + iLine + 1);
//ASheet.AsString[iCol, iRow + iLine + 1]:= '0';
ASheet.AsInteger[iCol, iRow + iLine + 1]:= Level[1, iLine];
end;
//RefStrToColRow()
Inc(iCol);
end;
//填写公式, 每行的最小最大和差值
//COL: 1~iCol
//ROW: 1~22, 24~43
ASheet.AsString[iCol + 0, 0]:= '最小值';
ASheet.AsString[iCol + 1, 0]:= '最大值';
ASheet.AsString[iCol + 2, 0]:= '差值';
for i := 1 to 22 do
begin
CalcExp:= 'Min(' + ColRowToRefStr(1, i) + ':' + ColRowToRefStr(iCol - 1, i) +')';
ASheet.AsFormula[iCol + 0, i]:= CalcExp;
CalcExp:= 'Max(' + ColRowToRefStr(1, i) + ':' + ColRowToRefStr(iCol - 1, i) +')';
ASheet.AsFormula[iCol + 1, i]:= CalcExp;
CalcExp:= ColRowToRefStr(iCol + 1, i) + ' - ' + ColRowToRefStr(iCol + 0, i);
ASheet.AsFormula[iCol + 2, i]:= CalcExp;
end;
ASheet.AsString[iCol + 0, 23]:= '最小值';
ASheet.AsString[iCol + 1, 23]:= '最大值';
ASheet.AsString[iCol + 2, 23]:= '差值';
for i := 24 to 43 do
begin
CalcExp:= 'Min(' + ColRowToRefStr(1, i) + ':' + ColRowToRefStr(iCol - 1, i) +')';
ASheet.AsFormula[iCol + 0, i]:= CalcExp;
CalcExp:= 'Max(' + ColRowToRefStr(1, i) + ':' + ColRowToRefStr(iCol - 1, i) +')';
ASheet.AsFormula[iCol + 1, i]:= CalcExp;
CalcExp:= ColRowToRefStr(iCol + 1, i) + ' - ' + ColRowToRefStr(iCol + 0, i);
ASheet.AsFormula[iCol + 2, i]:= CalcExp;
end;
wb.SaveToFile(StatXLSFileName);
Log('统计完成: ' + StatXLSFileName);
finally
wb.Free;
end;
end;
finally
LevelStrs.Free;
FLevelDataFileList.Free;
end;
end;
procedure TLevelWithoutFilterMeasure.Init;
begin
inherited;
//FExamineCaption:= '电平测试'#$D#$A'(无滤波器)';
FExamineCaption:= '无滤波器电平';
// FExamineCaption:= '一本振';
// ExtractFileFromRes('LIB_INOUT32', 'inpout32.dll');
// ExtractFileFromRes('LIB_ELEXS', 'ELEXS.dll');
// ExtractFileFromRes('EXE_LO1', '一本振.exe');
end;
procedure TLevelWithoutFilterMeasure.InternalCheck(const Value: Boolean;
const ExceptionInfo: String);
begin
if Not Value then
Raise Exception.Create(ExceptionInfo);
end;
end.
|
unit Geometry;
interface
uses
Bitmaps, Points, Textures, EngineTypes;
procedure CreateSector (var S: Sector; PC : integer; const Pts : array of PPoint); // указатели на точки; nil=конец грани
procedure InitSectorNormals (var S: Sector);
function CenterSector (const S: Sector): Point;
implementation
uses Memory;
procedure InitSectorNormals (var S: Sector);
var
f : integer;
i : integer;
begin
for f := 0 to S.CFaces-1 do with S.Faces[f] do begin
INorm := ToPoint(0,0,0);
Assert(CPoints>=3);
for i := 2 to CPoints-1 do
INorm := Add(INorm, Cross( Sub(Points[i]^,Points[0]^), Sub(Points[i-1]^,Points[0]^)));
INorm := Scale(INorm, 1/LengthP(INorm));
INormC := 0;
for i := 0 to CPoints-1 do
INormC := INormC + Dot(Points[i]^, INorm);
INormC := INormC/CPoints;
end;
end;
procedure CreateSector (var S: Sector; PC : integer; const Pts : array of PPoint); // указатели на точки; nil=конец грани
var
i,l,f : integer;
cpc : integer;
procedure Connect(p1,p2 : PPoint);
var
i : integer;
begin
for i := 0 to l-1 do begin
Assert( not ((S.Lines[i].p1 = p1) and (S.Lines[i].p2 = p2)) );
if (S.Lines[i].p1 = p2) and (S.Lines[i].p2 = p1) then begin
Assert(S.Lines[i].f2 = nil);
S.Lines[i].f2 := @S.Faces[f];
Exit;
end;
end;
Inc(l);
S.Lines[l-1].p1 := p1;
S.Lines[l-1].p2 := p2;
S.Lines[l-1].f1 := @S.Faces[f];
S.Lines[l-1].f2 := nil;
end;
function NoNilLines : boolean;
var i : integer;
begin
Result := true;
for i := 0 to l-1 do
if (S.Lines[i].f1=nil) or (S.Lines[i].f1=nil) then begin
Result := false;
exit;
end;
end;
begin
S.CFaces := 0;
S.ID := 0;
S.inProcess := 0;
S.CLines := 0;
for i := 0 to PC-1 do begin
if Pts[i]=nil then Inc(S.CFaces) else Inc(S.CLines);
end;
S.CLines := S.CLines div 2; // эн точек на грань - эн линий на грань - каждая линия к 2 граням
S.Faces := Alloc(S.CFaces*sizeof(Face));
S.FConvex := nil;
S.LConvex := nil;
S.Gravity := 0;
S.Skybox := False;
for i := 0 to S.CFaces-1 do begin
S.Faces[i].inProcess := false;
S.Faces[i].Id := i;
S.Faces[i].CPoints := 0;
S.Faces[i].Points := nil;
S.Faces[i].NextSector := nil;
S.Faces[i].INorm := ToPoint(0,0,0);
S.Faces[i].INormC := 0;
end;
S.Lines := Alloc(S.CLines*sizeof(Line));
// определяем количества точек
f := 0;
for i := 0 to PC-1 do begin
if Pts[i]<>nil then inc(S.Faces[f].CPoints)
else Inc(f);
end;
for f := 0 to S.CFaces-1 do with S.Faces[f] do Points := Alloc(CPoints*sizeof(PPoint));
// определяем масивы точек
f := 0;
cpc := 0;
for i := 0 to PC-1 do begin
if Pts[i]<>nil then begin
S.Faces[f].Points[cpc] := Pts[i];
Inc(cpc);
end else begin
Inc(f);
cpc := 0;
end;
end;
// соединяем точки линиями
l := 0;
for f := 0 to S.CFaces-1 do with S.Faces[f] do begin
for i := 0 to CPoints-1 do
Connect(Points[i], Points[(i+1) mod CPoints]);
end;
// проверяем, что круто соединились
Assert(NoNilLines);
Assert(f=S.CFaces);
Assert(l=S.CLines);
Assert((f>0) or (PC=0));
// вычисляем нормали
InitSectorNormals(S);
end;
function CenterSector (const S: Sector): Point;
var
i,j,c: integer;
begin
Result := ToPoint(0,0,0);
c := 0;
for i := 0 to S.CFaces-1 do begin
for j := 0 to S.Faces[i].CPoints-1 do begin
Result := Add(Result, S.Faces[i].Points[j]^);
Inc(c);
end;
end;
Result := Scale(Result, 1/c);
end;
end.
|
unit DirectoryStat;
interface
uses Classes,
sysUtils,
InternalTypes;
type
tDirectoryStat = class(tStringList)
private
fSize : TUInt64;
function GetTypeExtension(Index : Integer) : String;
procedure SetTypeExtension(Index : Integer; S : String);
function GetFileInfoFromIndex(Index : Integer) : tFileInfoArray;
function GetFileInfo(S : String) : tFileInfoArray;
public
constructor Create();
destructor Destroy; override;
function AddFileStat(info : TSearchRec; LimIndex : Integer; TypeExt : String): UInt64;
procedure DumpData;
function GetJSON() : AnsiString;
property Size: TUInt64 read FSize write FSize;
property TypeExtension[Index : integer] : String read GetTypeExtension write SetTypeExtension;
property FileInfoFromIndex [Index : integer] : tFileInfoArray read GetFileInfoFromIndex;
property FileInfo [S : String] : tFileInfoArray read GetFileInfo;
end;
implementation
constructor tDirectoryStat.Create();
begin
fSize := TUInt64.Create(0);
end;
destructor tDirectoryStat.Destroy;
begin
fSize.free;
inherited Destroy;
end;
function tDirectoryStat.GetTypeExtension(Index : Integer) : String;
begin
Result := Strings[Index];
end;
procedure tDirectoryStat.SetTypeExtension(Index : Integer; S : String);
begin
Strings[Index] := S;
end;
function tDirectoryStat.GetFileInfoFromIndex(Index : Integer) : tFileInfoArray;
begin
Result := Objects[Index] as tFileInfoArray;
end;
function tDirectoryStat.GetFileInfo(S : String) : tFileInfoArray;
var i : Integer;
begin
I := IndexOf(S);
if I <> -1 then
Result := Objects[i] as tFileInfoArray
else
Result := nil;
end;
function tDirectoryStat.AddFileStat(info : TSearchRec; LimIndex : Integer; TypeExt : String): UInt64;
var FInfoA : tFileInfoArray;
var i : integer;
begin
if TypeExt='' then
TypeExt := '_n/a_';
FInfoA := FileInfo[TypeExt];
if not assigned(FInfoA) then
begin
FInfoA := tFileInfoArray.Create;
i := AddObject(TypeExt,FInfoA);
// writeln('added [',i,'] TypeExt=',TypeExt);
end;
FInfoA.TakeAccount(info,LimIndex);
end;
procedure tDirectoryStat.DumpData;
var i : Integer;
begin
for i:=0 to pred(count) do
writeln(' TypeExt[',i,'] ',Strings[i],':>',FileInfoFromIndex[i].GetData);
end;
function tDirectoryStat.GetJSON() : AnsiString;
var i : integer;
begin
Result := '"DirStat" : [';
for i:=0 to pred(count) do
Result := Result + '{ "TypeExtName" : "' + Strings[i] +'", '+
FileInfoFromIndex[i].GetJSON + '}' + VirguleLast[i<>pred(count)];
Result := Result + ']'
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.