text stringlengths 14 6.51M |
|---|
unit csImportRequest;
{ Запрос на импорт }
interface
uses
CSRequests,
Classes,
DT_Types;
type
TcsImportRequest = class(TcsRequest)
private
function pm_GetDeleteIncluded: Boolean;
function pm_GetIsAnnotation: Boolean;
function pm_GetIsRegion: Boolean;
function pm_GetSourceFiles: TStrings;
function pm_GetSourceFolder: String;
procedure pm_SetDeleteIncluded(const Value: Boolean);
procedure pm_SetIsAnnotation(const Value: Boolean);
procedure pm_SetIsRegion(const Value: Boolean);
procedure pm_SetSourceFiles(const Value: TStrings);
procedure pm_SetSourceFolder(const Value: String);
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
published
property DeleteIncluded: Boolean read pm_GetDeleteIncluded write pm_SetDeleteIncluded;
property IsAnnotation: Boolean read pm_GetIsAnnotation write pm_SetIsAnnotation;
property IsRegion: Boolean read pm_GetIsRegion write pm_SetIsRegion;
property SourceFiles: TStrings read pm_GetSourceFiles write pm_SetSourceFiles;
property SourceFolder: String read pm_GetSourceFolder write pm_SetSourceFolder;
end;
const
reqSourceFolder = reqChildProperty;
reqDeleteIncluded = reqChildProperty + 1;
reqIsAnnotation = reqChildProperty + 2;
reqIsRegion = reqChildProperty + 3;
reqSourceFiles = reqChildProperty + 4;
implementation
uses
csRequestTypes,
ddAppConfigUtils,
ddAppConfigTypes;
{
********************************* TcsRequest **********************************
}
constructor TcsImportRequest.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
Tasktype:= cs_rtImport;
AppendNode(Data,
makeFolderName('Исходная папка', '',
makeBoolean('Подключенные', False,
MakeBoolean('Аннотации', False,
MakeBoolean('Региональные', False,
MakeStrings('Исходные файлы',
nil))))));
end;
function TcsImportRequest.pm_GetDeleteIncluded: Boolean;
begin
Result := Data.Items[reqDeleteIncluded].BooleanValue;
end;
function TcsImportRequest.pm_GetIsAnnotation: Boolean;
begin
Result := Data.Items[reqIsAnnotation].BooleanValue;
end;
function TcsImportRequest.pm_GetIsRegion: Boolean;
begin
Result := Data.Items[reqIsRegion].BooleanValue;
end;
function TcsImportRequest.pm_GetSourceFiles: TStrings;
begin
Result := Data.Items[reqSourceFiles].ObjectValue as TStrings;
end;
function TcsImportRequest.pm_GetSourceFolder: String;
begin
Result := Data.Items[reqSourceFolder].StringValue;
end;
procedure TcsImportRequest.pm_SetDeleteIncluded(const Value: Boolean);
begin
Data.Items[reqDeleteIncluded].BooleanValue:= Value;
end;
procedure TcsImportRequest.pm_SetIsAnnotation(const Value: Boolean);
begin
Data.Items[reqIsAnnotation].BooleanValue:= Value;
end;
procedure TcsImportRequest.pm_SetIsRegion(const Value: Boolean);
begin
Data.Items[reqIsRegion].BooleanValue:= Value;
end;
procedure TcsImportRequest.pm_SetSourceFiles(const Value: TStrings);
begin
(Data.Items[reqSourceFiles].ObjectValue as TStrings).Assign(Value)
end;
procedure TcsImportRequest.pm_SetSourceFolder(const Value: String);
begin
Data.Items[reqSourceFolder].StringValue:= Value;
end;
end.
|
unit CacheNameUtils;
interface
procedure TranslateChars(var str : string; fCh, tCh : char);
function GetObjectFolder(const World : string; X, Y : integer) : string;
function GetCoordWildcards(X, Y : Integer) : string;
implementation
uses
CacheObjects, SysUtils, SpecialChars;
const
ClearMask = integer(not((1 shl 6) - 1));
procedure TranslateChars(var str : string; fCh, tCh : char);
var
i : integer;
begin
for i := 0 to pred(length(str)) do
if pchar(str)[i] = fCh
then pchar(str)[i] := tCh;
end;
function GetObjectFolder(const World : string; X, Y : integer) : string;
begin
result := GetCacheRootPath + 'Worlds\' + World + '\Map\' + IntToStr(X and ClearMask) + BackSlashChar + IntToStr(Y and ClearMask) + '\';
end;
function GetCoordWildcards(X, Y: Integer) : string;
begin
result := IntToStr(X) + BackSlashChar + IntToStr(Y) + BackSlashChar + '*';
end;
end.
|
{ Mark Sattolo, 428500, CSI-1100A, prof: Dr. S. Boyd }
{ Tutorial #1, TA: Chris Lankester }
{ Assignment 5, Question 1(b) }
program GetRoots (input,output);
{ Prompt for three integers A, B and C, then calculate and display the real roots, if any, }
{ of the quadratic equation Ax^2 + Bx + C = 0; or inform the user that there are no real roots. }
{ Data Dictionary
GIVENS: A, B, C - three integers.
RESULTS: FirstRoot, SecondRoot - the real roots of the equation Ax^2 + Bx + C = 0.
NoRoots - a boolean which is true if there are no real roots of the equation,
and false otherwise.
INTERMEDIATES: none
USES: SQR, SQRT - functions which calculate square and square root, respectively. }
var
A, B, C : integer;
BP2, DISC, RTDISC, FirstRoot, SecondRoot : real;
NoRoots : boolean;
begin
{ Read in the algorithm's givens. }
writeln('Please enter the values for A, B and C.');
readln(A, B, C);
{ set initial values for results and intermediates }
NoRoots := false;
BP2 := SQR(B);
DISC := BP2 - (4 * A * C);
{ begin the calculations for the different cases }
if A = 0 then
begin
if B > 0 then
begin
FirstRoot := (-C / B);
SecondRoot := FirstRoot
end { if B > 0 }
else
NoRoots := true;
end { if A = 0 }
else if DISC < 0 then
begin
NoRoots := true;
FirstRoot := 0;
SecondRoot := 0
end { if DISC < 0 }
else
begin
RTDISC := SQRT(DISC);
FirstRoot := (-B + RTDISC)/(2*A);
SecondRoot := (-B - RTDISC)/(2*A);
end; { else DISC < 0 }
{ Write out the results }
writeln;
writeln('*******************************************************');
writeln('Mark Sattolo, 428500, CSI-1100A');
writeln(' prof: Dr. S. Boyd, Tutorial #1, TA: Chris Lankester');
writeln('Assignment 5, Question 1(b)');
writeln('*******************************************************');
writeln;
writeln;
if B < 0 then
if C < 0 then
writeln('The polynomial is: ', A, 'x^2 - ', Abs(B), 'x - ', Abs(C), ' = 0')
else
writeln('The polynomial is: ', A, 'x^2 - ', Abs(B), 'x + ', C, ' = 0')
else if C < 0 then
writeln('The polynomial is: ', A, 'x^2 + ', B, 'x - ', Abs(C), ' = 0')
else
writeln('The polynomial is: ', A, 'x^2 + ', B, 'x + ', C, ' = 0');
if NoRoots then
writeln('Sorry, there are no real roots.')
else
if FirstRoot = SecondRoot then
writeln('The root is: x = ', FirstRoot:2:1)
else
writeln('The roots are: x = ', FirstRoot:2:1, ' and x = ', SecondRoot:2:1)
end. |
program TESTSETH ( OUTPUT ) ;
(********)
(*$A+ *)
(********)
const CH_CONST = X'D9' ;
CH_BLANK = X'40' ;
I_NEGATIV1 = - 13 ;
I_NEGATIV2 = - 15 ;
type OPTYPE = ( PCTS , PCTI , PLOD , PSTR , PLDA , PLOC , PSTO , PLDC ,
PLAB , PIND , PINC , PPOP , PCUP , PENT , PRET , PCSP ,
PIXA , PEQU , PNEQ , PGEQ , PGRT , PLEQ , PLES , PUJP ,
PFJP , PXJP , PCHK , PNEW , PADI , PADR , PSBI , PSBR ,
PSCL , PFLT , PFLO , PTRC , PNGI , PNGR , PSQI , PSQR ,
PABI , PABR , PNOT , PAND , PIOR , PDIF , PINT , PUNI ,
PINN , PMOD , PODD , PMPI , PMPR , PDVI , PDVR , PMOV ,
PLCA , PDEC , PSTP , PSAV , PRST , PCHR , PORD , PDEF ,
PRND , PCRD , PXPO , PBGN , PEND , PASE , PSLD , PSMV ,
PMST , PUXJ , PXLB , PCST , PDFC , PPAK , PADA , PSBA ,
UNDEF_OP ) ;
SET1 = set of CHAR ;
SET2 = set of 'A' .. 'I' ;
SET3 = set of '0' .. '9' ;
FARBE = ( ROT , GELB , GRUEN , BLAU ) ;
SET4 = set of FARBE ;
SET5 = set of 10 .. 50 ;
SET6 = set of 0 .. 255 ;
SET7 = set of 100 .. 200 ;
SET9 = set of 300 .. 400 ;
SET10 = set of 0 .. 300 ;
SET11 = set of 0 .. 1999 ;
SET12 = set of OPTYPE ;
TARRAY = array [ - 20 .. - 10 ] of INTEGER ;
const X1 : SET1 =
[ 'A' .. 'J' , 'S' .. 'Z' ] ;
X2 : SET1 =
[ '3' .. '7' ] ;
X5 : array [ 1 .. 5 ] of SET1 =
( [ '0' .. '9' ] , [ 'A' .. 'F' ] , [ 'J' .. 'M' ] , [ '0' .. '5'
] , [ 'S' .. 'V' ] ) ;
var S1 : SET1 ;
S2 : SET2 ;
S3 : SET3 ;
S4 : SET4 ;
S5 : SET5 ;
S6 : SET6 ;
S : SET6 ;
S7 : SET7 ;
S9 : SET9 ;
S10 : SET10 ;
S11 : SET11 ;
S12 : SET12 ;
I : INTEGER ;
CH : CHAR ;
R : REAL ;
S21 : SET1 ;
S24 : SET4 ;
procedure PRINT_SET ( S : SET1 ) ;
var C : CHAR ;
CP : -> CHAR ;
I : INTEGER ;
begin (* PRINT_SET *)
WRITE ( 'set: ' ) ;
for C := CHR ( 0 ) to CHR ( 255 ) do
if C in S then
WRITE ( C ) ;
WRITELN ;
WRITE ( 'set in hex: ' ) ;
CP := ADDR ( S ) ;
for I := 1 to 32 do
begin
WRITE ( ORD ( CP -> ) : 1 , ' ' ) ;
CP := PTRADD ( CP , 1 ) ;
end (* for *) ;
WRITELN ;
end (* PRINT_SET *) ;
procedure PRINT_SET6 ( S : SET6 ) ;
var C : INTEGER ;
CP : -> CHAR ;
I : INTEGER ;
begin (* PRINT_SET6 *)
WRITE ( 'set: ' ) ;
for C := 0 to 255 do
if C in S then
WRITE ( C : 1 , ' ' ) ;
WRITELN ;
WRITE ( 'set in hex: ' ) ;
CP := ADDR ( S ) ;
for I := 1 to 32 do
begin
WRITE ( ORD ( CP -> ) : 1 , ' ' ) ;
CP := PTRADD ( CP , 1 ) ;
end (* for *) ;
WRITELN ;
end (* PRINT_SET6 *) ;
procedure PRINT_SET5 ( S : SET5 ) ;
var C : INTEGER ;
CP : -> CHAR ;
I : INTEGER ;
begin (* PRINT_SET5 *)
WRITE ( 'set: ' ) ;
for C := 0 to 255 do
if C in S then
WRITE ( C : 1 , ' ' ) ;
WRITELN ;
WRITE ( 'set in hex: ' ) ;
CP := ADDR ( S ) ;
for I := 1 to 7 do
begin
WRITE ( ORD ( CP -> ) : 1 , ' ' ) ;
CP := PTRADD ( CP , 1 ) ;
end (* for *) ;
WRITELN ;
end (* PRINT_SET5 *) ;
begin (* HAUPTPROGRAMM *)
WRITELN ( '-13 div 8 = ' , - 13 DIV 8 ) ;
WRITELN ( '-13 mod 8 = ' , - 13 MOD 8 ) ;
I := - 17 + 13 ;
WRITELN ( 'i sollte -4 sein: ' , I ) ;
R := - 3.2 + 0.4 ;
WRITELN ( 'r sollte -2.8 sein: ' , R : 6 : 1 ) ;
CH := 'A' ;
S1 := [ 'J' .. 'R' , CH ] ;
WRITELN ( 'test01' ) ;
CH := 'A' ;
S1 := [ 'B' , CH , 'A' .. 'R' , CH ] ;
PRINT_SET ( S1 ) ;
CH := 'A' ;
WRITELN ( 'test02' ) ;
S1 := X1 ;
PRINT_SET ( S1 ) ;
WRITELN ( 'test03' ) ;
S1 := X2 ;
PRINT_SET ( S1 ) ;
/*****************************************/
/* WRITELN ( 'test04' ) ; */
/* CH := 'A' ; */
/* S1 := [ 'B' , CH .. 'R' , CH ] ; */
/* PRINT_SET ( S1 ) ; */
/* WRITELN ( 'test05' ) ; */
/* CH := 'A' ; */
/* S1 := [ 'B' , 'A' .. CH ] ; */
/* PRINT_SET ( S1 ) ; */
/*****************************************/
WRITELN ( 'test06' ) ;
S1 := [ 'B' , 'A' .. CH_CONST ] ;
PRINT_SET ( S1 ) ;
WRITELN ( 'test07' ) ;
S1 := [ 'B' , CH_BLANK .. 'A' ] ;
PRINT_SET ( S1 ) ;
WRITELN ( 'test08' ) ;
S1 := [ 'J' .. 'R' ] ;
PRINT_SET ( S1 ) ;
WRITELN ( 'test09' ) ;
PRINT_SET ( X1 ) ;
PRINT_SET ( [ 'A' .. 'D' ] ) ;
WRITELN ( 'test10' ) ;
CH := 'X' ;
S1 := [ CH ] ;
PRINT_SET ( S1 ) ;
WRITELN ( 'test11' ) ;
S2 := [ 'C' .. 'E' ] ;
PRINT_SET ( S2 ) ;
WRITELN ( 'test12' ) ;
S3 := [ '1' .. '6' ] ;
S3 := S3 + [ '7' ] ;
S3 := S3 - [ '5' ] ;
PRINT_SET ( S3 ) ;
S4 := [ GELB , BLAU ] ;
WRITELN ( 'test13' ) ;
S5 := [ 20 .. 30 ] ;
S := S5 ;
PRINT_SET5 ( S5 ) ;
PRINT_SET6 ( S ) ;
WRITELN ( 'test14' ) ;
S6 := S5 ;
S5 := S6 ;
S := S6 ;
PRINT_SET6 ( S ) ;
WRITELN ( 'test15' ) ;
S7 := [ 120 .. 140 ] ;
S := S7 ;
PRINT_SET6 ( S ) ;
S12 := [ PADI , PADA ] ;
/**************************/
/* weitere aktionen: term */
/**************************/
S1 := X1 ;
S1 := [ 'B' .. 'F' , 'T' , 'V' ] ;
S1 := [ X'42' .. 'F' , 'T' , 'V' ] ;
S1 := X1 * [ 'B' .. 'F' , 'T' , 'V' ] ;
S1 := S21 ;
S4 := [ GELB , BLAU ] ;
S24 := [ ROT ] ;
S4 := [ GELB , BLAU ] * S24 ;
/**********************************/
/* tests mit sets > 256 elementen */
/**********************************/
S9 := [ 320 .. 360 ] ;
S11 := [ 1959 .. 1977 ] ;
S10 := [ 270 .. 280 ] ;
S10 := S10 + [ 100 .. 120 ] ;
WRITELN ( 'test16' ) ;
for I := 0 to 300 do
if I in S10 then
WRITE ( I : 1 , ' ' ) ;
WRITELN ;
WRITELN ( 'test17' ) ;
for I := 0 to 2000 do
if I in S11 then
WRITE ( I : 1 , ' ' ) ;
WRITELN ;
if CH in [ '+' , '-' , '*' , '/' ] then
WRITELN ( 'arithm. operator' ) ;
end (* HAUPTPROGRAMM *) .
|
unit FrameDayChartViewer;
interface
uses
Classes, Controls, Graphics, Forms, Messages, SysUtils, Windows,
define_DealItem, define_price, define_datasrc,
BaseApp, BaseForm, StockDayDataAccess, UIDealItemNode,
BaseRule, Rule_CYHT, Rule_BDZX, Rule_Boll, Rule_Std, Rule_MA, ExtCtrls;
type
TDataChartViewerData = record
StockDayDataAccess: StockDayDataAccess.TStockDayDataAccess;
WeightMode: TRT_WeightMode;
//fRule_Boll_Price: TRule_Boll_Price;
Rule_CYHT_Price: TRule_CYHT_Price;
Rule_BDZX_Price: TRule_BDZX_Price;
Rule_Boll: TRule_Boll_Price;
DataSrc: TDealDataSource;
end;
TfmeDayChartViewer = class(TfrmBase)
pbChart: TPaintBox;
procedure pbChartPaint(Sender: TObject);
private
{ Private declarations }
fDataChartData: TDataChartViewerData;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize(App: TBaseApp); override;
procedure SetData(ADataType: integer; AData: Pointer); override;
procedure SetStockItem(AStockItem: PStockItemNode);
end;
implementation
{$R *.dfm}
uses
StockDayData_Load,
define_dealstore_file,
define_stock_quotes;
constructor TfmeDayChartViewer.Create(AOwner: TComponent);
begin
inherited;
FillChar(fDataChartData, SizeOf(fDataChartData), 0);
fDataChartData.DataSrc := Src_163;
end;
destructor TfmeDayChartViewer.Destroy;
begin
inherited;
end;
procedure TfmeDayChartViewer.Initialize(App: TBaseApp);
begin
inherited;
end;
procedure TfmeDayChartViewer.SetData(ADataType: integer; AData: Pointer);
begin
SetStockItem(AData);
end;
procedure TfmeDayChartViewer.SetStockItem(AStockItem: PStockItemNode);
begin
fDataChartData.StockDayDataAccess := AStockItem.StockDayDataAccess;
if nil = fDataChartData.StockDayDataAccess then
fDataChartData.StockDayDataAccess := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.StockItem, fDataChartData.DataSrc, fDataChartData.WeightMode);
fDataChartData.Rule_BDZX_Price := AStockItem.Rule_BDZX_Price;
fDataChartData.Rule_CYHT_Price := AStockItem.Rule_CYHT_Price;
fDataChartData.Rule_Boll := AStockItem.Rule_Boll;
pbChart.Repaint;
end;
procedure TfmeDayChartViewer.pbChartPaint(Sender: TObject);
type
TDrawLine = record
Y1: integer;
Y2: integer;
end;
function GetCoordPosition(ARect: TRect; AHigh, ALow, AValue: double): integer;
begin
Result := ARect.Bottom - Trunc(((AValue - ALow) / (AHigh - ALow)) * (ARect.Bottom - ARect.Top));
end;
var
tmpBgRect: TRect;
tmpPriceRect: TRect;
tmpAnalysisRect: TRect;
tmpCandleRect: TRect;
tmpPaintBox: TPaintBox;
tmpCandleWidth: integer;
tmpDayQuote: PRT_Quote_Day;
tmpPaintCount: integer;
tmpFirstDayIndex: integer;
i: integer;
tmpMaxPrice: integer;
tmpMinPrice: integer;
tmpX: integer;
tmpX0: integer;
tmpY: integer;
tmpLineBoll: TDrawLine;
tmpLineBoll_UB: TDrawLine;
tmpLineBoll_LB: TDrawLine;
tmpLineCYHT_SD: TDrawLine;
tmpLineCYHT_SK: TDrawLine;
tmpYLine: integer;
tmpAnalysisMaxValue: double;
tmpAnalysisMinValue: double;
begin
tmpPaintBox := TPaintBox(Sender);
tmpBgRect.Left := 0;
tmpBgRect.Right := tmpPaintBox.Width;
tmpBgRect.Top := 0;
tmpBgRect.Bottom := tmpPaintBox.Height;
tmpPaintBox.Canvas.Brush.Color := clBlack;
tmpPaintBox.Canvas.FillRect(tmpBgRect);
tmpPriceRect.Left := 1;
tmpPriceRect.Right := tmpBgRect.Right;
tmpPriceRect.Top := 1;
tmpPriceRect.Bottom:= tmpBgRect.Bottom - 80;
tmpAnalysisRect.Left := 1;
tmpAnalysisRect.Right := tmpBgRect.Right;
tmpAnalysisRect.Top := tmpPriceRect.Bottom + 1;
tmpAnalysisRect.Bottom:= tmpBgRect.Bottom - 1;
tmpMaxPrice := 0;
tmpMinPrice := 0;
tmpAnalysisMaxValue := 0;
tmpAnalysisMinValue := 0;
tmpX0 := 0;
tmpCandleWidth := 5;
tmpPaintBox.Canvas.Brush.Color := clRed;
tmpPaintBox.Canvas.FrameRect(tmpPriceRect);
if nil <> fDataChartData.StockDayDataAccess then
begin
if 0 < fDataChartData.StockDayDataAccess.RecordCount then
begin
tmpPaintCount := (tmpPriceRect.Right - tmpPriceRect.Left) div (tmpCandleWidth + 1);
if fDataChartData.StockDayDataAccess.RecordCount > tmpPaintCount then
begin
tmpFirstDayIndex := fDataChartData.StockDayDataAccess.RecordCount - tmpPaintCount;
end else
begin
tmpFirstDayIndex := 0;
tmpPaintCount := fDataChartData.StockDayDataAccess.RecordCount;
end;
(*//
if nil <> fDataChartData.Rule_BDZX_Price then
begin
tmpAnalysisMaxValue := fDataChartData.Rule_BDZX_Price.Ret_AD1_EMA.MaxF;
if tmpAnalysisMaxValue < fDataChartData.Rule_BDZX_Price.Ret_AK_Float.MaxValue then
tmpAnalysisMaxValue := fDataChartData.Rule_BDZX_Price.Ret_AK_Float.MaxValue;
if tmpAnalysisMaxValue < fDataChartData.Rule_BDZX_Price.Ret_AJ.MaxValue then
tmpAnalysisMaxValue := fDataChartData.Rule_BDZX_Price.Ret_AJ.MaxValue;
tmpAnalysisMinValue := fDataChartData.Rule_BDZX_Price.Ret_AD1_EMA.MinF;
if tmpAnalysisMinValue > fDataChartData.Rule_BDZX_Price.Ret_AK_Float.MinValue then
tmpAnalysisMinValue := fDataChartData.Rule_BDZX_Price.Ret_AK_Float.MinValue;
if tmpAnalysisMinValue > fDataChartData.Rule_BDZX_Price.Ret_AJ.MinValue then
tmpAnalysisMinValue := fDataChartData.Rule_BDZX_Price.Ret_AJ.MinValue;
tmpYLine1_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
20);
tmpPaintBox.Canvas.Pen.Color := clWhite;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine1_1);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine1_1);
tmpYLine1_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
80);
tmpPaintBox.Canvas.Pen.Color := clBlue;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine1_1);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine1_1);
tmpYLine1_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
100);
tmpPaintBox.Canvas.Pen.Color := clGreen;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine1_1);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine1_1);
end;
//*)
//(*//
if nil <> fDataChartData.Rule_CYHT_Price then
begin
tmpAnalysisMaxValue := fDataChartData.Rule_CYHT_Price.EMA_SK.MaxF;
if tmpAnalysisMaxValue < fDataChartData.Rule_CYHT_Price.EMA_SD.MaxF then
tmpAnalysisMaxValue := fDataChartData.Rule_CYHT_Price.EMA_SD.MaxF;
tmpAnalysisMinValue := fDataChartData.Rule_CYHT_Price.EMA_SK.MinF;
if tmpAnalysisMinValue > fDataChartData.Rule_CYHT_Price.EMA_SD.MinF then
tmpAnalysisMinValue := fDataChartData.Rule_CYHT_Price.EMA_SD.MinF;
tmpYLine := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
20);
tmpPaintBox.Canvas.Pen.Color := clWhite;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine);
tmpYLine := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
80);
tmpPaintBox.Canvas.Pen.Color := clBlue;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine);
tmpYLine := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
100);
tmpPaintBox.Canvas.Pen.Color := clGreen;
tmpPaintBox.Canvas.MoveTo(tmpAnalysisRect.Left, tmpYLine);
tmpPaintBox.Canvas.LineTo(tmpAnalysisRect.Right, tmpYLine);
end;
//*)
i := tmpFirstDayIndex;
while i < tmpFirstDayIndex + tmpPaintCount do
begin
tmpDayQuote := fDataChartData.StockDayDataAccess.RecordItem[i];
if 0 = tmpMaxPrice then
begin
tmpMaxPrice := tmpDayQuote.PriceRange.PriceHigh.Value;
end else
begin
if tmpMaxPrice < tmpDayQuote.PriceRange.PriceHigh.Value then
tmpMaxPrice := tmpDayQuote.PriceRange.PriceHigh.Value;
end;
if 0 = tmpMinPrice then
begin
tmpMinPrice := tmpDayQuote.PriceRange.PriceLow.Value;
end else
begin
if tmpMinPrice > tmpDayQuote.PriceRange.PriceLow.Value then
if 0 < tmpDayQuote.PriceRange.PriceLow.Value then
tmpMinPrice := tmpDayQuote.PriceRange.PriceLow.Value;
end;
Inc(i);
end;
i := tmpFirstDayIndex;
tmpCandleRect.Left := tmpPriceRect.Left + 1;
while i < tmpFirstDayIndex + tmpPaintCount do
begin
tmpDayQuote := fDataChartData.StockDayDataAccess.RecordItem[i];
tmpCandleRect.Right := tmpCandleRect.Left + tmpCandleWidth;
tmpX := (tmpCandleRect.Left + tmpCandleRect.Right) div 2;
//(*//
if tmpDayQuote.PriceRange.PriceOpen.Value = tmpDayQuote.PriceRange.PriceClose.Value then
begin
tmpPaintBox.Canvas.Brush.Color := clWhite;
tmpCandleRect.Top := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceClose.Value);
tmpCandleRect.Bottom := tmpCandleRect.Top + 1;
tmpPaintBox.Canvas.FrameRect(tmpCandleRect);
tmpPaintBox.Canvas.Pen.Color := tmpPaintBox.Canvas.Brush.Color;
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceHigh.Value);
tmpPaintBox.Canvas.MoveTo(tmpX, tmpY);
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceLow.Value);
tmpPaintBox.Canvas.LineTo(tmpX, tmpY);
end else
begin
if tmpDayQuote.PriceRange.PriceOpen.Value < tmpDayQuote.PriceRange.PriceClose.Value then
begin
tmpPaintBox.Canvas.Brush.Color := clred;
tmpCandleRect.Top := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceClose.Value);
tmpCandleRect.Bottom := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceOpen.Value);
tmpPaintBox.Canvas.FrameRect(tmpCandleRect);
tmpPaintBox.Canvas.Pen.Color := tmpPaintBox.Canvas.Brush.Color;
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceHigh.Value);
tmpPaintBox.Canvas.MoveTo(tmpX, tmpY);
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceClose.Value);
tmpPaintBox.Canvas.LineTo(tmpX, tmpY);
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceOpen.Value);
tmpPaintBox.Canvas.MoveTo(tmpX, tmpY);
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceLow.Value);
tmpPaintBox.Canvas.LineTo(tmpX, tmpY);
end else
begin
tmpPaintBox.Canvas.Brush.Color := clgreen;
tmpCandleRect.Top := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceOpen.Value);
tmpCandleRect.Bottom := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceClose.Value);
tmpPaintBox.Canvas.FillRect(tmpCandleRect);
tmpPaintBox.Canvas.Pen.Color := tmpPaintBox.Canvas.Brush.Color;
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceHigh.Value);
tmpPaintBox.Canvas.MoveTo(tmpX, tmpY);
tmpY := GetCoordPosition(tmpPriceRect, tmpMaxPrice, tmpMinPrice, tmpDayQuote.PriceRange.PriceLow.Value);
tmpPaintBox.Canvas.LineTo(tmpX, tmpY);
end;
end;
//*)
//(*//
if nil <> fDataChartData.Rule_Boll then
begin
if i > tmpFirstDayIndex then
begin
tmpLineBoll.Y2 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.Boll[i]);
tmpLineBoll_UB.Y2 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.UB[i]);
tmpLineBoll_LB.Y2 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.LB[i]);
if (tmpPriceRect.Top < tmpLineBoll.Y1) and
(tmpPriceRect.Bottom > tmpLineBoll.Y1) and
(tmpPriceRect.Top < tmpLineBoll.Y2) and
(tmpPriceRect.Bottom > tmpLineBoll.Y2) then
begin
tmpPaintBox.Canvas.Pen.Color := clWhite;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpLineBoll.Y1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpLineBoll.Y2);
end;
if (tmpPriceRect.Top < tmpLineBoll_UB.Y1) and
(tmpPriceRect.Bottom > tmpLineBoll_UB.Y1) and
(tmpPriceRect.Top < tmpLineBoll_UB.Y2) and
(tmpPriceRect.Bottom > tmpLineBoll_UB.Y2) then
begin
tmpPaintBox.Canvas.Pen.Color := clYellow;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpLineBoll_UB.Y1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpLineBoll_UB.Y2);
end;
if (tmpPriceRect.Top < tmpLineBoll_LB.Y1) and
(tmpPriceRect.Bottom > tmpLineBoll_LB.Y1) and
(tmpPriceRect.Top < tmpLineBoll_LB.Y2) and
(tmpPriceRect.Bottom > tmpLineBoll_LB.Y2) then
begin
tmpPaintBox.Canvas.Pen.Color := clRed;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpLineBoll_LB.Y1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpLineBoll_LB.Y2);
end;
tmpLineBoll.Y1 := tmpLineBoll.Y2;
tmpLineBoll_UB.Y1 := tmpLineBoll_UB.Y2;
tmpLineBoll_LB.Y1 := tmpLineBoll_LB.Y2;
end else
begin
tmpLineBoll.Y1 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.Boll[i]);
tmpLineBoll_UB.Y1 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.UB[i]);
tmpLineBoll_LB.Y1 := GetCoordPosition(tmpPriceRect,
tmpMaxPrice,
tmpMinPrice,
fDataChartData.Rule_Boll.LB[i]);
end;
// tmpLineBoll
end;
//*)
(*//
if nil <> fDataChartData.Rule_BDZX_Price then
begin
if i > tmpFirstDayIndex then
begin
try
tmpYLine1_2 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AD1_EMA.ValueF[i]);
tmpYLine2_2 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AJ.value[i]);
tmpYLine3_2 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AK_Float.value[i]);
tmpPaintBox.Canvas.Pen.Color := clYellow;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpYLine1_1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpYLine1_2);
tmpPaintBox.Canvas.Pen.Color := clRed;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpYLine2_1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpYLine2_2);
tmpPaintBox.Canvas.Pen.Color := clWhite;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpYLine3_1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpYLine3_2);
tmpX0 := tmpX;
tmpYLine1_1 := tmpYLine1_2;
tmpYLine2_1 := tmpYLine2_2;
tmpYLine3_1 := tmpYLine3_2;
except
end;
end else
begin
tmpYLine1_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AD1_EMA.ValueF[i]);
tmpYLine2_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AJ.value[i]);
tmpYLine3_1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_BDZX_Price.Ret_AK_Float.value[i]);
tmpX0 := tmpX;
end;
end;
//*)
//(*//
if nil <> fDataChartData.Rule_CYHT_Price then
begin
if i > tmpFirstDayIndex then
begin
try
tmpLineCYHT_SK.Y2 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_CYHT_Price.SK[i]);
tmpLineCYHT_SD.Y2 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_CYHT_Price.SD[i]);
tmpPaintBox.Canvas.Pen.Color := clYellow;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpLineCYHT_SK.Y1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpLineCYHT_SK.Y2);
tmpPaintBox.Canvas.Pen.Color := clRed;
tmpPaintBox.Canvas.MoveTo(tmpX0, tmpLineCYHT_SD.Y1);
tmpPaintBox.Canvas.LineTo(tmpX, tmpLineCYHT_SD.Y2);
tmpLineCYHT_SK.Y1 := tmpLineCYHT_SK.Y2;
tmpLineCYHT_SD.Y1 := tmpLineCYHT_SD.Y2;
except
end;
end else
begin
tmpLineCYHT_SK.Y1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_CYHT_Price.SK[i]);
tmpLineCYHT_SD.Y1 := GetCoordPosition(tmpAnalysisRect,
tmpAnalysisMaxValue,
tmpAnalysisMinValue,
fDataChartData.Rule_CYHT_Price.SD[i]);
end;
end;
tmpX0 := tmpX;
//*)
tmpCandleRect.Left := tmpCandleRect.Right + tmpCandleWidth;
Inc(i);
tmpCandleRect.Left := tmpCandleRect.Right + 1;
end;
end;
end;
end;
end.
|
unit Unit2;
interface
type
TStudent = class
private
FName: string;
FAge: Integer;
FId: string;
procedure SetName(const Value: string);
procedure SetAge(const Value: Integer);
procedure SetId(const Value: string);
public
property Name: string read FName write SetName;
property Age: Integer read FAge write SetAge;
property Id: string read FId write SetId;
constructor Create(FId: string; FName: string; FAge: Integer);
end;
implementation
{ TStudent }
constructor TStudent.Create(FId: string; FName: string; FAge: Integer);
begin
Self.FId := FId;
Self.Name := FName;
Self.Age := FAge;
end;
procedure TStudent.SetAge(const Value: Integer);
begin
FAge := Value;
end;
procedure TStudent.SetId(const Value: string);
begin
FId:=Value;
end;
procedure TStudent.SetName(const Value: string);
begin
FName := Value;
end;
end.
|
unit Philosopher;
interface
uses
Classes,
FMX.Objects,
System.SyncObjs;
type
Tmode = (phThinking, phHungry, phEating); // Состояния философа
TPhilosophers = class(TThread) // Объект философа, наследник от "потока"
private
procedure goThink; // Метод "думать"
procedure goEat; // Метод "кушать"
procedure takeStick; // Взять вилку
procedure putStick; // Положить вилку
procedure testOponents(i: integer); // Проверить, можно ли взять вилку
function FindNumber: integer; // по ид потока определям место на столе
protected
procedure Execute; override; // рабочий метод
end;
implementation
uses
System.SysUtils,
Unit3,
System.UITypes;
var
CriticalSection: TCriticalSection; // критическая секция
procedure TPhilosophers.Execute;
begin
while (not Terminated) do
begin
takeStick;
goEat;
putStick;
goThink;
end;
end;
procedure TPhilosophers.goThink;
begin
sleep(Random(10 * 1000));
end;
procedure TPhilosophers.takeStick;
var
i: integer;
Pie: TPie;
begin
i := FindNumber;
Pie := TPie(Form3.FindComponent('Pie' + i.toString));
CriticalSection.Acquire;
try
state[i] := phHungry;
Pie.Fill.Color := TAlphaColorRec.Blueviolet;
testOponents(i);
finally
CriticalSection.Release;
end;
end;
procedure TPhilosophers.goEat;
begin
sleep(Random(10 * 1000));
end;
procedure TPhilosophers.putStick;
var
i, left, right: integer;
Pie: TPie;
begin
i := FindNumber;
Pie := TPie(Form3.FindComponent('Pie' + i.toString));
CriticalSection.Acquire;
try
state[i] := phThinking;
Pie.Fill.Color := TAlphaColorRec.Sienna;
left := i + 1;
if left = 6 then
left := 1;
right := i - 1;
if right = 0 then
right := 5;
testOponents(left);
testOponents(right);
finally
CriticalSection.Release;
end;
end;
// процедура проверки доступности палочек для еды
procedure TPhilosophers.testOponents(i: integer);
var
left, right: integer;
Pie: TPie;
begin
left := i + 1;
if left = 6 then
left := 1;
right := i - 1;
if right = 0 then
right := 5;
if (state[i] = phHungry) and (state[left] <> phEating) and
(state[right] <> phEating) then
begin
state[i] := phEating;
Pie := TPie(Form3.FindComponent('Pie' + i.toString));
Pie.Fill.Color := TAlphaColorRec.Blue;
end;
end;
// дополнительная функция, позволяющая определить номер философа по
// идентификатору потока.
function TPhilosophers.FindNumber: integer;
var
i: integer;
begin
for i := 1 to 5 do
if PHID[i] = ThreadID then
begin
FindNumber := i;
break;
end;
end;
initialization
CriticalSection := TCriticalSection.Create;
finalization
CriticalSection.Free;
end.
|
{$PIC ON}
library laz_lib_fpc3;
{$mode objfpc}{$H+}
uses
Math, // For Floor
Interfaces, // needed for DebugLn to LogCat
LCLproc, // for DebugLn to be compiled
classes, // for TStringList
SysUtils;
type
AndroidIntArray = array[0..300] of Longint; // 300 - any value
AndroidDoubleArray = array[0..300] of Double;
const
AndroidDataFileName = '/data/data/org.testjni.android/lib/libbin.so';
var
tmpInt: Integer;
tmpDouble: Double;
function pas_double2double(d1: Double): Double; CDECL; EXPORT;
begin
Result := 0.1 * d1;
end;
function pas_int2double(int1: Longint): Double; CDECL; EXPORT;
begin
DebugLn('in pas_int2double int1=' + IntToStr(int1));
Result := 6.0 * int1;
end;
procedure pas_void_void; CDECL; EXPORT;
begin
tmpInt := tmpInt + 1;
DebugLn('in pas_void_void tmpInt =' + IntToStr(tmpInt));
end;
function pas_int_int(int1: Longint): Longint; CDECL; EXPORT;
begin
Result := 4 * int1;
end;
function pas_intvardouble(int1: Longint; var d1: Double): Longint; CDECL; EXPORT;
begin
d1 := 7.0 * int1;
Result := 10 * int1;
end;
function pas_double2int(double_in: Double): Longint; CDECL; EXPORT;
var
DoubleTmp: Double;
begin
DoubleTmp := double_in;
Result := floor(doubleTmp);
end;
function pas_loadbinlib(int_in: Longint): Longint; CDECL; EXPORT;
var
aStringList: TStringList;
begin
DebugLn('In pas_loadbinlib int_in=' + IntToStr(int_in));
if not (FileExists(AndroidDataFileName)) then
begin
DebugLn(AndroidDataFileName + ' not found');
Result:=-2;
exit;
end
else
// Load your data here
begin
try
aStringList:= TStringList.Create;
try
aStringList.LoadFromFile(AndroidDataFileName);
DebugLn('In pas_loadbinlib aStringList.Text=' + aStringList.Text);
Result:= Length(aStringList.Text);
finally
aStringList.Free;
end;
except
Result:=-1;
end;
end;
end;
function pas_intarraymult(aMultiplier: Longint; var anIntArray: AndroidIntArray): Longint; CDECL; EXPORT;
var
I: Integer;
begin
DebugLn('In pas_intarraymult aMultiplier=' + IntToStr(aMultiplier));
;
I := 0;
while (anIntArray[I] >= 0) do
begin
anIntArray[I] := anIntArray[I] * aMultiplier;
I := I + 1;
end;
Result := I;
end;
function pas_doublearraymult(dMultiplier: float; var aDoubleArray: AndroidDoubleArray): Longint; CDECL; EXPORT;
var
I: Integer;
begin
Result := -1;
try
I := 0;
while (aDoubleArray[I] > 0) do
begin
aDoubleArray[I] := aDoubleArray[I] * dMultiplier;
I := I + 1;
end;
Result := I;
except
Result := -1;
end;
end;
exports pas_int_int;
exports pas_void_void;
exports pas_int2double;
exports pas_intvardouble;
exports pas_double2int;
exports pas_double2double;
exports pas_loadbinlib;
exports pas_intarraymult;
exports pas_doublearraymult;
begin
tmpDouble := 0.0;
tmpInt := 0;
end.
|
unit gaelco_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m68000,main_engine,controls_engine,gfx_engine,ym_3812,m6809,
oki6295,gaelco_hw_decrypt,rom_engine,pal_engine,sound_engine;
function iniciar_gaelco_hw:boolean;
implementation
const
//Big Karnak
bigkarnak_rom:array[0..1] of tipo_roms=(
(n:'d16';l:$40000;p:0;crc:$44fb9c73),(n:'d19';l:$40000;p:$1;crc:$ff79dfdd));
bigkarnak_sound:tipo_roms=(n:'d5';l:$10000;p:0;crc:$3b73b9c5);
bigkarnak_gfx:array[0..7] of tipo_roms=(
(n:'h5' ;l:$80000;p:$0;crc:$20e239ff),(n:'h5'; l:$80000;p:$80000;crc:$20e239ff),
(n:'h10';l:$80000;p:$100000;crc:$ab442855),(n:'h10';l:$80000;p:$180000;crc:$ab442855),
(n:'h8' ;l:$80000;p:$200000;crc:$83dce5a3),(n:'h8'; l:$80000;p:$280000;crc:$83dce5a3),
(n:'h6' ;l:$80000;p:$300000;crc:$24e84b24),(n:'h6'; l:$80000;p:$380000;crc:$24e84b24));
bigkarnak_adpcm:tipo_roms=(n:'d1';l:$40000;p:0;crc:$26444ad1);
//Thunder Hoop
thoop_rom:array[0..1] of tipo_roms=(
(n:'th18dea1.040';l:$80000;p:0;crc:$59bad625),(n:'th161eb4.020';l:$40000;p:$1;crc:$6add61ed));
thoop_gfx:array[0..3] of tipo_roms=(
(n:'c09' ;l:$100000;p:$0;crc:$06f0edbf),(n:'c10'; l:$100000;p:$100000;crc:$2d227085),
(n:'c11';l:$100000;p:$200000;crc:$7403ef7e),(n:'c12';l:$100000;p:$300000;crc:$29a5ca36));
thoop_adpcm:tipo_roms=(n:'sound';l:$100000;p:0;crc:$99f80961);
//Squash
squash_rom:array[0..1] of tipo_roms=(
(n:'squash.d18';l:$20000;p:0;crc:$ce7aae96),(n:'squash.d16';l:$20000;p:$1;crc:$8ffaedd7));
squash_gfx:array[0..3] of tipo_roms=(
(n:'squash.c09' ;l:$80000;p:$0;crc:$0bb91c69),(n:'squash.c10'; l:$80000;p:$80000;crc:$892a035c),
(n:'squash.c11';l:$80000;p:$100000;crc:$9e19694d),(n:'squash.c12';l:$80000;p:$180000;crc:$5c440645));
squash_adpcm:tipo_roms=(n:'squash.d01';l:$80000;p:0;crc:$a1b9651b);
//Biomechanical Toy
biomtoy_rom:array[0..1] of tipo_roms=(
(n:'d18';l:$80000;p:0;crc:$4569ce64),(n:'d16';l:$80000;p:$1;crc:$739449bd));
biomtoy_gfx:array[0..7] of tipo_roms=(
(n:'h6' ;l:$80000;p:$0;crc:$9416a729),(n:'j6'; l:$80000;p:$80000;crc:$e923728b),
(n:'h7';l:$80000;p:$100000;crc:$9c984d7b),(n:'j7';l:$80000;p:$180000;crc:$0e18fac2),
(n:'h9' ;l:$80000;p:$200000;crc:$8c1f6718),(n:'j9'; l:$80000;p:$280000;crc:$1c93f050),
(n:'h10';l:$80000;p:$300000;crc:$aca1702b),(n:'j10';l:$80000;p:$380000;crc:$8e3e96cc));
biomtoy_adpcm:array[0..1] of tipo_roms=(
(n:'c1';l:$80000;p:0;crc:$0f02de7e),(n:'c3';l:$80000;p:$80000;crc:$914e4bbc));
//DIP
gaelco_dip:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';number:11;dip:((dip_val:$07;dip_name:'4C 1C'),(dip_val:$08;dip_name:'3C 1C'),(dip_val:$09;dip_name:'2C 1C'),(dip_val:$0f;dip_name:'1C 1C'),(dip_val:$06;dip_name:'2C 3C'),(dip_val:$0e;dip_name:'1C 2C'),(dip_val:$0d;dip_name:'1C 3C'),(dip_val:$0c;dip_name:'1C 4C'),(dip_val:$0b;dip_name:'1C 5C'),(dip_val:$0a;dip_name:'1C 6C'),(dip_val:$00;dip_name:'Free Play (If Coin B too)'),(),(),(),(),())),
(mask:$f0;name:'Coin B';number:11;dip:((dip_val:$70;dip_name:'4C 1C'),(dip_val:$80;dip_name:'3C 1C'),(dip_val:$90;dip_name:'2C 1C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$60;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$00;dip_name:'Free Play (If Coin A too)'),(),(),(),(),())),());
bigkarnak_dsw_2:array [0..5] of def_dip=(
(mask:$07;name:'Difficulty';number:8;dip:((dip_val:$07;dip_name:'0'),(dip_val:$06;dip_name:'1'),(dip_val:$05;dip_name:'2'),(dip_val:$04;dip_name:'3'),(dip_val:$03;dip_name:'4'),(dip_val:$02;dip_name:'5'),(dip_val:$01;dip_name:'6'),(dip_val:$00;dip_name:'7'),(),(),(),(),(),(),(),())),
(mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'1'),(dip_val:$10;dip_name:'2'),(dip_val:$08;dip_name:'3'),(dip_val:$00;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Impact';number:2;dip:((dip_val:$40;dip_name:'On'),(dip_val:$0;dip_name:'Off'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Service';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
bigkarnak_dsw_3:array [0..1] of def_dip=(
(mask:$2;name:'Service';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
thoop_dsw_1:array [0..4] of def_dip=(
(mask:$07;name:'Coin A';number:8;dip:((dip_val:$02;dip_name:'6C 1C'),(dip_val:$03;dip_name:'5C 1C'),(dip_val:$04;dip_name:'4C 1C'),(dip_val:$05;dip_name:'3C 1C'),(dip_val:$06;dip_name:'2C 1C'),(dip_val:$01;dip_name:'3C 2C'),(dip_val:$00;dip_name:'4C 3C'),(dip_val:$07;dip_name:'1C 1C'),(),(),(),(),(),(),(),())),
(mask:$38;name:'Coin B';number:8;dip:((dip_val:$38;dip_name:'1C 1C'),(dip_val:$00;dip_name:'3C 4C'),(dip_val:$08;dip_name:'2C 3C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(dip_val:$10;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$40;name:'2 Credits to Start, 1 to Continue';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Free Play';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
thoop_dsw_2:array [0..6] of def_dip=(
(mask:$03;name:'Difficulty';number:4;dip:((dip_val:$03;dip_name:'Easy'),(dip_val:$02;dip_name:'Normal'),(dip_val:$01;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$04;name:'Player Controls';number:2;dip:((dip_val:$4;dip_name:'2 Joysticks'),(dip_val:$0;dip_name:'1 Joysticks'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'4'),(dip_val:$8;dip_name:'3'),(dip_val:$10;dip_name:'2'),(dip_val:$18;dip_name:'1'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Service';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
squash_dsw_1:array [0..4] of def_dip=(
(mask:$07;name:'Coin A';number:8;dip:((dip_val:$02;dip_name:'6C 1C'),(dip_val:$03;dip_name:'5C 1C'),(dip_val:$04;dip_name:'4C 1C'),(dip_val:$05;dip_name:'3C 1C'),(dip_val:$06;dip_name:'2C 1C'),(dip_val:$01;dip_name:'3C 2C'),(dip_val:$00;dip_name:'4C 3C'),(dip_val:$07;dip_name:'1C 1C'),(),(),(),(),(),(),(),())),
(mask:$38;name:'Coin B';number:8;dip:((dip_val:$38;dip_name:'1C 1C'),(dip_val:$00;dip_name:'3C 4C'),(dip_val:$08;dip_name:'2C 3C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(dip_val:$10;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$40;name:'2 Player Continue';number:2;dip:((dip_val:$40;dip_name:'2 Credits / 5 Games'),(dip_val:$0;dip_name:'1 Credit / 3 Games'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Free Play';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
squash_dsw_2:array [0..4] of def_dip=(
(mask:$03;name:'Difficulty';number:4;dip:((dip_val:$02;dip_name:'Easy'),(dip_val:$03;dip_name:'Normal'),(dip_val:$01;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$0c;name:'Number of Faults';number:4;dip:((dip_val:$8;dip_name:'4'),(dip_val:$c;dip_name:'5'),(dip_val:$4;dip_name:'6'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Service';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
biomtoy_dsw_2:array [0..4] of def_dip=(
(mask:$1;name:'Service';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Lives';number:4;dip:((dip_val:$20;dip_name:'1'),(dip_val:$10;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$0;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$40;dip_name:'Easy'),(dip_val:$c0;dip_name:'Normal'),(dip_val:$80;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),());
var
scroll_x0,scroll_y0,scroll_x1,scroll_y1:word;
rom:array[0..$7ffff] of word;
video_ram:array[0..$1fff] of word;
sprite_ram:array[0..$7ff] of word;
main_ram:array[0..$7fff] of word;
sound_latch,gaelco_dec_val:byte;
oki_rom:array[0..$c,0..$ffff] of byte;
procedure draw_sprites_bk(pri:byte);
var
x,i,color,attr,attr2,nchar:word;
flipx,flipy:boolean;
y,a,priority:byte;
begin
for i:=$1 to $1ff do begin
attr:=sprite_ram[(i*4)-1];
if (attr and $ff)=$f0 then continue; //el sprite no se va a ver...
attr2:=sprite_ram[(i*4)+1];
color:=(attr2 and $7e00) shr 9;
if (color>=$38) then priority:=4
else priority:=(attr and $3000) shr 12;
if pri<>priority then continue;
y:=240-(attr and $ff);
color:=color shl 4;
flipx:=(attr and $4000)<>0;
flipy:=(attr and $8000)<>0;
x:=(attr2 and $1ff)-15;
nchar:=sprite_ram[(i*4)+2];
if (attr and $800)<>0 then begin
put_gfx_sprite(nchar,color,flipx,flipy,0);
actualiza_gfx_sprite(x,y,17,0);
end else begin
nchar:=nchar and $fffc;
a:=(byte(flipx) shl 1) or byte(flipy);
put_gfx_sprite_diff((nchar+0) xor a,color,flipx,flipy,0,0,0);
put_gfx_sprite_diff((nchar+2) xor a,color,flipx,flipy,0,8,0);
put_gfx_sprite_diff((nchar+1) xor a,color,flipx,flipy,0,0,8);
put_gfx_sprite_diff((nchar+3) xor a,color,flipx,flipy,0,8,8);
actualiza_gfx_sprite_size(x,y,17,16,16);
end;
end;
end;
procedure draw_all_bigk;
var
f,color,sx,sy,pos,x,y,nchar,atrib1,atrib2:word;
pant,h:byte;
begin
for f:=0 to $164 do begin
y:=f div 21;
x:=f mod 21;
//Draw back
//Calcular posicion
sx:=x+((scroll_x0 and $1f0) shr 4);
sy:=y+((scroll_y0 and $1f0) shr 4);
pos:=(sx and $1f)+((sy and $1f)*32);
//Calcular color
atrib2:=video_ram[$1+(pos*2)];
color:=atrib2 and $3f;
if (gfx[1].buffer[pos] or buffer_color[color]) then begin
pant:=((atrib2 shr 6) and $3)+1;
atrib1:=video_ram[$0+(pos*2)];
nchar:=$4000+((atrib1 and $fffc) shr 2);
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,pant,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0);
if pant<>4 then put_gfx_trans_flip_alt(x*16,y*16,nchar,color shl 4,pant+4,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0,pant);
for h:=1 to 4 do
if (h<>pant) then begin
put_gfx_block_trans(x*16,y*16,h,16,16);
if h<>4 then put_gfx_block_trans(x*16,y*16,h+4,16,16)
end;
gfx[1].buffer[pos]:=false;
end;
//Draw Front
//Calcular posicion
sx:=x+((scroll_x1 and $1f0) shr 4);
sy:=y+((scroll_y1 and $1f0) shr 4);
pos:=(sx and $1f)+((sy and $1f)*32);
//Calcular color
atrib2:=video_ram[$801+(pos*2)];
color:=atrib2 and $3f;
if (gfx[1].buffer[pos+$400] or buffer_color[color]) then begin
pant:=((atrib2 shr 6) and $3)+9;
atrib1:=video_ram[$800+(pos*2)];
nchar:=$4000+((atrib1 and $fffc) shr 2);
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,pant,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0);
if pant<>12 then put_gfx_trans_flip_alt(x*16,y*16,nchar,color shl 4,pant+4,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0,pant-8);
for h:=9 to 12 do
if (h<>pant) then begin
put_gfx_block_trans(x*16,y*16,h,16,16);
if h<>12 then put_gfx_block_trans(x*16,y*16,h+4,16,16);
end;
gfx[1].buffer[pos+$400]:=false;
end;
end;
end;
procedure update_video_bigk;
begin
fill_full_screen(17,0);
draw_all_bigk;
scroll_x_y(4,17,scroll_x0 and $f,scroll_y0 and $f); //PRI0
scroll_x_y(12,17,scroll_x1 and $f,scroll_y1 and $f); //PRI0
draw_sprites_bk(3);
//scroll_x_y(8,17,scroll_x0 and $f,scroll_y0 and $f); //Totalmente transparente!
//scroll_x_y(16,17,scroll_x1 and $f,scroll_y1 and $f); //Totalmente transparente!
scroll_x_y(3,17,scroll_x0 and $f,scroll_y0 and $f); //PRI1
scroll_x_y(11,17,scroll_x1 and $f,scroll_y1 and $f); //PRI1
draw_sprites_bk(2);
scroll_x_y(7,17,scroll_x0 and $f,scroll_y0 and $f); //PRI1 encima sprites
scroll_x_y(15,17,scroll_x1 and $f,scroll_y1 and $f); //PRI1 encima sprites
scroll_x_y(2,17,scroll_x0 and $f,scroll_y0 and $f); //PRI2
scroll_x_y(10,17,scroll_x1 and $f,scroll_y1 and $f); //PRI2
draw_sprites_bk(1);
scroll_x_y(6,17,scroll_x0 and $f,scroll_y0 and $f); //PRI2 encima sprites
scroll_x_y(14,17,scroll_x1 and $f,scroll_y1 and $f); //PRI2 encima sprites
scroll_x_y(1,17,scroll_x0 and $f,scroll_y0 and $f); //PRI3
scroll_x_y(9,17,scroll_x1 and $f,scroll_y1 and $f); //PRI3
draw_sprites_bk(0);
scroll_x_y(5,17,scroll_x0 and $f,scroll_y0 and $f); //PRI3 encima sprites
scroll_x_y(13,17,scroll_x1 and $f,scroll_y1 and $f); //PRI3 encima sprites
draw_sprites_bk(4);
actualiza_trozo_final(0,16,320,240,17);
fillchar(buffer_color[0],MAX_COLOR_BUFFER,0);
end;
procedure eventos_gaelco_hw;
begin
if event.arcade then begin
//P1
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $Fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $Fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
//P2
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $Fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80);
end;
end;
procedure cambiar_color(tmp_color,numero:word);
var
color:tcolor;
begin
color.b:=pal5bit(tmp_color shr 10);
color.g:=pal5bit(tmp_color shr 5);
color.r:=pal5bit(tmp_color);
set_pal_color(color,numero);
buffer_color[(numero shr 4) and $3f]:=true;
end;
//Big Karnak
procedure bigk_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=m6809_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 511 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
m6809_0.run(frame_s);
frame_s:=frame_s+m6809_0.tframes-m6809_0.contador;
if f=255 then begin
m68000_0.irq[6]:=HOLD_LINE;
update_video_bigk;
end;
end;
eventos_gaelco_hw;
video_sync;
end;
end;
function bigk_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:bigk_getword:=rom[direccion shr 1];
$100000..$103fff:bigk_getword:=video_ram[(direccion and $3fff) shr 1];
$440000..$440fff:bigk_getword:=sprite_ram[(direccion and $fff) shr 1];
$200000..$2007ff:bigk_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$700000:bigk_getword:=marcade.dswa;
$700002:bigk_getword:=marcade.dswb;
$700004:bigk_getword:=marcade.in0;
$700006:bigk_getword:=marcade.in1;
$700008:bigk_getword:=marcade.dswc;
$ff8000..$ffffff:bigk_getword:=main_ram[(direccion and $7fff) shr 1];
end;
end;
procedure bigk_putword(direccion:dword;valor:word);
begin
case direccion of
0..$7ffff:; //ROM
$100000..$100fff:if video_ram[(direccion and $fff) shr 1]<>valor then begin
video_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) div 4]:=true;
end;
$101000..$101fff:if video_ram[(direccion and $1fff) shr 1]<>valor then begin
video_ram[(direccion and $1fff) shr 1]:=valor;
gfx[1].buffer[((direccion and $fff) shr 2)+$400]:=true;
end;
$102000..$103fff:video_ram[(direccion and $3fff) shr 1]:=valor;
$108000:if scroll_y0<>(valor and $1ff) then begin
if abs((scroll_y0 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_y0:=valor and $1ff;
end;
$108002:if scroll_x0<>((valor+4) and $1ff) then begin
if abs((scroll_x0 and $1f0)-((valor+4) and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_x0:=(valor+4) and $1ff;
end;
$108004:if scroll_y1<>(valor and $1ff) then begin
if abs((scroll_y1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_y1:=valor and $1ff;
end;
$108006:if scroll_x1<>(valor and $1ff) then begin
if abs((scroll_x1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_x1:=valor and $1ff;
end;
$10800c:;
$200000..$2007ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
cambiar_color(valor,(direccion and $7ff) shr 1);
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
end;
$440000..$440fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
//70000a..70003b:;
$70000e:begin
sound_latch:=valor and $ff;
m6809_0.change_firq(HOLD_LINE);
end;
$ff8000..$ffffff:main_ram[(direccion and $7fff) shr 1]:=valor;
end;
end;
function bigk_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$7ff,$c00..$ffff:bigk_snd_getbyte:=mem_snd[direccion];
$800,$801:bigk_snd_getbyte:=oki_6295_0.read;
$a00:bigk_snd_getbyte:=ym3812_0.status;
$b00:bigk_snd_getbyte:=sound_latch;
end;
end;
procedure bigk_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7ff:mem_snd[direccion]:=valor;
$800,$801:oki_6295_0.write(valor);
$a00:ym3812_0.control(valor);
$a01:ym3812_0.write(valor);
$c00..$ffff:; //ROM
end;
end;
procedure bigk_sound_update;
begin
ym3812_0.update;
oki_6295_0.update;
end;
//Thunder Hoop
procedure draw_sprites_thoop(pri:byte);
var
x,i,color,attr,attr2,nchar:word;
flipx,flipy:boolean;
y,a,priority:byte;
begin
for i:=$1 to $1ff do begin
attr:=sprite_ram[(i*4)-1];
if (attr and $ff)=$f0 then continue; //El sprite no se va a ver
priority:=(attr shr 12) and $3;
if pri<>priority then continue;
attr2:=sprite_ram[(i*4)+1];
color:=(attr2 and $7e00) shr 9;
y:=240-(attr and $ff);
color:=color shl 4;
flipx:=(attr and $4000)<>0;
flipy:=(attr and $8000)<>0;
x:=(attr2 and $1ff)-15;
nchar:=sprite_ram[(i*4)+2];
if (attr and $800)<>0 then begin
put_gfx_sprite(nchar,color,flipx,flipy,0);
actualiza_gfx_sprite(x,y,17,0);
end else begin
nchar:=nchar and $fffc;
a:=(byte(flipx) shl 1) or byte(flipy);
put_gfx_sprite_diff((nchar+0) xor a,color,flipx,flipy,0,0,0);
put_gfx_sprite_diff((nchar+2) xor a,color,flipx,flipy,0,8,0);
put_gfx_sprite_diff((nchar+1) xor a,color,flipx,flipy,0,0,8);
put_gfx_sprite_diff((nchar+3) xor a,color,flipx,flipy,0,8,8);
actualiza_gfx_sprite_size(x,y,17,16,16);
end;
end;
end;
procedure draw_all_thoop;
var
f,color,sx,sy,x,y,nchar,atrib1,atrib2,pos:word;
pant,h:byte;
begin
for f:=0 to $164 do begin
y:=f div 21;
x:=f mod 21;
//Draw back
//Calcular posicion
sx:=x+((scroll_x0 and $1f0) shr 4);
sy:=y+((scroll_y0 and $1f0) shr 4);
pos:=(sx and $1f)+((sy and $1f)*32);
//Calcular color
atrib2:=video_ram[$1+(pos*2)];
color:=atrib2 and $3f;
if (gfx[1].buffer[pos] or buffer_color[color]) then begin
pant:=((atrib2 shr 6) and $3)+1;
atrib1:=video_ram[$0+(pos*2)];
nchar:=$4000+((atrib1 and $fffc) shr 2);
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,pant,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0);
for h:=1 to 4 do if (h<>pant) then put_gfx_block_trans(x*16,y*16,h,16,16);
gfx[1].buffer[pos]:=false;
end;
//Draw Front
//Calcular posicion
sx:=x+((scroll_x1 and $1f0) shr 4);
sy:=y+((scroll_y1 and $1f0) shr 4);
pos:=(sx and $1f)+((sy and $1f)*32);
//Calcular color
atrib2:=video_ram[$801+(pos*2)];
color:=atrib2 and $3f;
if (gfx[1].buffer[pos+$400] or buffer_color[color]) then begin
pant:=((atrib2 shr 6) and $3)+5;
atrib1:=video_ram[$800+(pos*2)];
nchar:=$4000+((atrib1 and $fffc) shr 2);
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,pant,1,(atrib1 and 1)<>0,(atrib1 and 2)<>0);
for h:=5 to 8 do if (h<>pant) then put_gfx_block_trans(x*16,y*16,h,16,16);
gfx[1].buffer[pos+$400]:=false;
end;
end;
end;
procedure update_video_thoop;
begin
fill_full_screen(17,0);
draw_all_thoop;
scroll_x_y(4,17,scroll_x0 and $f,scroll_y0 and $f);
scroll_x_y(8,17,scroll_x1 and $f,scroll_y1 and $f);
draw_sprites_thoop(3);
scroll_x_y(3,17,scroll_x0 and $f,scroll_y0 and $f);
scroll_x_y(7,17,scroll_x1 and $f,scroll_y1 and $f);
draw_sprites_thoop(2);
draw_sprites_thoop(1);
scroll_x_y(2,17,scroll_x0 and $f,scroll_y0 and $f);
scroll_x_y(6,17,scroll_x1 and $f,scroll_y1 and $f);
draw_sprites_thoop(0);
scroll_x_y(1,17,scroll_x0 and $f,scroll_y0 and $f);
scroll_x_y(5,17,scroll_x1 and $f,scroll_y1 and $f);
actualiza_trozo_final(0,16,320,240,17);
fillchar(buffer_color[0],MAX_COLOR_BUFFER,0);
end;
procedure thoop_principal;
var
frame_m:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 511 do begin
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
if f=255 then begin
m68000_0.irq[6]:=HOLD_LINE;
update_video_thoop;
end;
end;
eventos_gaelco_hw;
video_sync;
end;
end;
function thoop_getword(direccion:dword):word;
begin
case direccion of
0..$fffff:thoop_getword:=rom[direccion shr 1];
$100000..$103fff:thoop_getword:=video_ram[(direccion and $3fff) shr 1];
$440000..$440fff:thoop_getword:=sprite_ram[(direccion and $fff) shr 1];
$200000..$2007ff:thoop_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$700000:thoop_getword:=marcade.dswb;
$700002:thoop_getword:=marcade.dswa;
$700004:thoop_getword:=marcade.in0;
$700006:thoop_getword:=marcade.in1;
$70000e:thoop_getword:=oki_6295_0.read;
$ff0000..$ffffff:thoop_getword:=main_ram[(direccion and $ffff) shr 1];
end;
end;
procedure thoop_putword(direccion:dword;valor:word);
var
dec:word;
ptemp:pbyte;
begin
case direccion of
0..$fffff:; //ROM
$100000..$100fff:begin
dec:=gaelco_dec((direccion and $fff) shr 1,valor,gaelco_dec_val,$4228,m68000_0.r.pc.l);
if video_ram[(direccion and $fff) shr 1]<>dec then begin
video_ram[(direccion and $fff) shr 1]:=dec;
gfx[1].buffer[(direccion and $fff) shr 2]:=true;
end;
end;
$101000..$101fff:begin
dec:=gaelco_dec((direccion and $1fff) shr 1,valor,gaelco_dec_val,$4228,m68000_0.r.pc.l);
if video_ram[(direccion and $1fff) shr 1]<>dec then begin
video_ram[(direccion and $1fff) shr 1]:=dec;
gfx[1].buffer[((direccion and $fff) shr 2)+$400]:=true;
end;
end;
$102000..$103fff:begin
dec:=gaelco_dec((direccion and $1fff) shr 1,valor,gaelco_dec_val,$4228,m68000_0.r.pc.l);
video_ram[(direccion and $3fff) shr 1]:=dec;
end;
$108000:if scroll_y0<>(valor and $1ff) then begin
if abs((scroll_y0 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_y0:=valor and $1ff;
end;
$108002:if scroll_x0<>((valor+4) and $1ff) then begin
if abs((scroll_x0 and $1f0)-((valor+4) and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_x0:=(valor+4) and $1ff;
end;
$108004:if scroll_y1<>(valor and $1ff) then begin
if abs((scroll_y1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_y1:=valor and $1ff;
end;
$108006:if scroll_x1<>(valor and $1ff) then begin
if abs((scroll_x1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_x1:=valor and $1ff;
end;
$10800c:;
$200000..$2007ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
cambiar_color(valor,(direccion and $7ff) shr 1);
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
end;
$440000..$440fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$70000c:begin
ptemp:=oki_6295_0.get_rom_addr;
inc(ptemp,$30000);
copymemory(ptemp,@oki_rom[(valor and $f),0],$10000);
end;
$70000e:oki_6295_0.write(valor);
$ff0000..$ffffff:main_ram[(direccion and $ffff) shr 1]:=valor;
end;
end;
//Biomechanical Toy
procedure biomtoy_putword(direccion:dword;valor:word);
var
ptemp:pbyte;
begin
case direccion of
0..$fffff:; //ROM
$100000..$100fff:if video_ram[(direccion and $fff) shr 1]<>valor then begin
video_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 2]:=true;
end;
$101000..$101fff:if video_ram[(direccion and $1fff) shr 1]<>valor then begin
video_ram[(direccion and $1fff) shr 1]:=valor;
gfx[1].buffer[((direccion and $fff) shr 2)+$400]:=true;
end;
$102000..$103fff:video_ram[(direccion and $3fff) shr 1]:=valor;
$108000:if scroll_y0<>(valor and $1ff) then begin
if abs((scroll_y0 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_y0:=valor and $1ff;
end;
$108002:if scroll_x0<>((valor+4) and $1ff) then begin
if abs((scroll_x0 and $1f0)-((valor+4) and $1f0))>15 then fillchar(gfx[1].buffer[0],$400,1);
scroll_x0:=(valor+4) and $1ff;
end;
$108004:if scroll_y1<>(valor and $1ff) then begin
if abs((scroll_y1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_y1:=valor and $1ff;
end;
$108006:if scroll_x1<>(valor and $1ff) then begin
if abs((scroll_x1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[1].buffer[$400],$400,1);
scroll_x1:=valor and $1ff;
end;
$10800c:;
$200000..$2007ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
cambiar_color(valor,(direccion and $7ff) shr 1);
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
end;
$440000..$440fff:sprite_ram[(direccion and $fff) shr 1]:=valor;
$70000c:begin
ptemp:=oki_6295_0.get_rom_addr;
inc(ptemp,$30000);
copymemory(ptemp,@oki_rom[(valor and $f),0],$10000);
end;
$70000e:oki_6295_0.write(valor); //OKI
$ff0000..$ffffff:main_ram[(direccion and $ffff) shr 1]:=valor;
end;
end;
procedure thoop_sound_update;
begin
oki_6295_0.update;
end;
//Main
procedure reset_gaelco_hw;
begin
m68000_0.reset;
if main_vars.tipo_maquina=78 then begin
m6809_0.reset;
ym3812_0.reset;
end;
oki_6295_0.reset;
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$ffff;
scroll_x0:=1;
scroll_y0:=1;
scroll_x1:=1;
scroll_y1:=1;
sound_latch:=0;
end;
function iniciar_gaelco_hw:boolean;
var
ptemp,ptemp2,ptemp3,memoria_temp:pbyte;
f,pants:byte;
const
pt_x:array[0..15] of dword=(0,1,2,3,4,5,6,7, 16*8+0,16*8+1,16*8+2,16*8+3,16*8+4,16*8+5,16*8+6,16*8+7);
pt_y:array[0..15] of dword=(0*8,1*8,2*8,3*8,4*8,5*8,6*8,7*8, 8*8,9*8,10*8,11*8,12*8,13*8,14*8,15*8);
procedure convert_sprites;
begin
init_gfx(0,8,8,$20000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,8*8,0*$100000*8,1*$100000*8,2*$100000*8,3*$100000*8);
convert_gfx(0,0,memoria_temp,@pt_x,@pt_y,false,false);
end;
procedure convert_tiles;
var
f:byte;
begin
init_gfx(1,16,16,$8000);
gfx[1].trans[0]:=true;
for f:=1 to 3 do gfx[1].trans_alt[f,0]:=true;
for f:=8 to 15 do gfx[1].trans_alt[1,f]:=true;
for f:=4 to 15 do gfx[1].trans_alt[2,f]:=true;
for f:=2 to 15 do gfx[1].trans_alt[3,f]:=true;
gfx_set_desc_data(4,0,32*8,0*$100000*8,1*$100000*8,2*$100000*8,3*$100000*8);
convert_gfx(1,0,memoria_temp,@pt_x,@pt_y,false,false);
end;
begin
case main_vars.tipo_maquina of
78:llamadas_maquina.bucle_general:=bigk_principal;
101,173,174:begin
llamadas_maquina.bucle_general:=thoop_principal;
llamadas_maquina.fps_max:=57.42;
end;
end;
llamadas_maquina.reset:=reset_gaelco_hw;
iniciar_gaelco_hw:=false;
iniciar_audio(false);
if main_vars.tipo_maquina=78 then pants:=15
else pants:=8;
for f:=1 to pants do begin
screen_init(f,336,272,true);
screen_mod_scroll(f,336,336,511,272,272,511);
end;
//Final
screen_init(17,512,512,false,true);
iniciar_video(320,240);
marcade.dswa:=$00ff;
//Main CPU
m68000_0:=cpu_m68000.create(12000000,$200);
getmem(memoria_temp,$400000);
case main_vars.tipo_maquina of
78:begin //Big Karnak
//Main CPU
if not(roms_load16w(@rom,bigkarnak_rom)) then exit;
m68000_0.change_ram16_calls(bigk_getword,bigk_putword);
//Sound CPU
if not(roms_load(@mem_snd,bigkarnak_sound)) then exit;
m6809_0:=cpu_m6809.Create(2000000,$200,TCPU_M6809);
m6809_0.change_ram_calls(bigk_snd_getbyte,bigk_snd_putbyte);
m6809_0.init_sound(bigk_sound_update);
//Sound Chips
ym3812_0:=ym3812_chip.create(YM3812_FM,4000000);
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH,1);
//Cargar ADPCM ROMS
if not(roms_load(oki_6295_0.get_rom_addr,bigkarnak_adpcm)) then exit;
//Sprites
if not(roms_load(memoria_temp,bigkarnak_gfx)) then exit;
convert_sprites;
//Tiles
convert_tiles;
marcade.dswb:=$00ce;
marcade.dswc:=$00ff;
marcade.dswa_val:=@gaelco_dip;
marcade.dswb_val:=@bigkarnak_dsw_2;
marcade.dswc_val:=@bigkarnak_dsw_3;
end;
101:begin //Thunder Hoop
//Main CPU
if not(roms_load16w(@rom,thoop_rom)) then exit;
m68000_0.change_ram16_calls(thoop_getword,thoop_putword);
m68000_0.init_sound(thoop_sound_update);
//Sound Chips
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH,2);
//Cargar ADPCM ROMS
if not(roms_load(memoria_temp,thoop_adpcm)) then exit;
copymemory(oki_6295_0.get_rom_addr,memoria_temp,$40000);
ptemp2:=memoria_temp;
for f:=0 to $f do begin
copymemory(@oki_rom[f,0],ptemp2,$10000);
inc(ptemp2,$10000);
end;
//Sprites
getmem(ptemp,$400000);
if not(roms_load(ptemp,thoop_gfx)) then exit;
//Ordenar los GFX
ptemp3:=ptemp;
for f:=3 downto 0 do begin
ptemp2:=memoria_temp;inc(ptemp2,$100000*f);copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,($100000*f)+$80000);copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,($100000*f)+$40000);copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,($100000*f)+$c0000);copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
end;
freemem(ptemp);
convert_sprites;
//Tiles
convert_tiles;
gaelco_dec_val:=$e;
marcade.dswb:=$00cf;
marcade.dswa_val:=@thoop_dsw_1;
marcade.dswb_val:=@thoop_dsw_2;
end;
173:begin //Squash
//Main CPU
if not(roms_load16w(@rom,squash_rom)) then exit;
m68000_0.change_ram16_calls(thoop_getword,thoop_putword);
m68000_0.init_sound(thoop_sound_update);
//Sound Chips
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH,2);
//Cargar ADPCM ROMS
if not(roms_load(memoria_temp,squash_adpcm)) then exit;
copymemory(oki_6295_0.get_rom_addr,memoria_temp,$40000);
ptemp2:=memoria_temp;
for f:=0 to $7 do begin
copymemory(@oki_rom[f,0],ptemp2,$10000);
inc(ptemp2,$10000);
end;
//Sprites
getmem(ptemp,$400000);
if not(roms_load(ptemp,squash_gfx)) then exit;
//Ordenar los GFX
ptemp3:=ptemp;
for f:=3 downto 0 do begin
ptemp2:=memoria_temp;inc(ptemp2,$100000*f);copymemory(ptemp2,ptemp3,$80000);
ptemp2:=memoria_temp;inc(ptemp2,($100000*f)+$80000);copymemory(ptemp2,ptemp3,$80000);inc(ptemp3,$80000);
end;
freemem(ptemp);
convert_sprites;
//Tiles
convert_tiles;
gaelco_dec_val:=$f;
marcade.dswb:=$00df;
marcade.dswa_val:=@squash_dsw_1;
marcade.dswb_val:=@squash_dsw_2;
end;
174:begin //Biomechanical Toy
//Main CPU
if not(roms_load16w(@rom,biomtoy_rom)) then exit;
m68000_0.change_ram16_calls(thoop_getword,biomtoy_putword);
m68000_0.init_sound(thoop_sound_update);
//Sound Chips
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH,2);
//Cargar ADPCM ROMS
if not(roms_load(memoria_temp,biomtoy_adpcm)) then exit;
copymemory(oki_6295_0.get_rom_addr,memoria_temp,$40000);
ptemp2:=memoria_temp;
for f:=0 to $f do begin
copymemory(@oki_rom[f,0],ptemp2,$10000);
inc(ptemp2,$10000);
end;
//Sprites
getmem(ptemp,$400000);
if not(roms_load(ptemp,biomtoy_gfx)) then exit;
//Ordenar los GFX
ptemp3:=ptemp; //orig
for f:=0 to 3 do begin
ptemp2:=memoria_temp;inc(ptemp2,$040000+(f*$100000));copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,$0c0000+(f*$100000));copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,$000000+(f*$100000));copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
ptemp2:=memoria_temp;inc(ptemp2,$080000+(f*$100000));copymemory(ptemp2,ptemp3,$40000);inc(ptemp3,$40000);
end;
freemem(ptemp);
convert_sprites;
//Tiles
convert_tiles;
marcade.dswb:=$00fb;
marcade.dswa_val:=@gaelco_dip;
marcade.dswb_val:=@biomtoy_dsw_2;
end;
end;
freemem(memoria_temp);
//final
reset_gaelco_hw;
iniciar_gaelco_hw:=true;
end;
end.
|
unit l3FormatObjectInfoHelper;
// Модуль: "w:\common\components\rtl\Garant\L3\l3FormatObjectInfoHelper.pas"
// Стереотип: "Service"
// Элемент модели: "Tl3FormatObjectInfoHelper" MUID: (551BCBFD0240)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
{$If NOT Defined(NoVCL)}
uses
l3IntfUses
, l3ProtoObject
, l3RTTI
;
(*
Ml3FormatObjectInfoHelper = interface
{* Контракт сервиса Tl3FormatObjectInfoHelper }
function Format(anObject: TObject;
aShortInfo: Boolean;
anObjectPropFound: TRTTIInfoObjectPropertyFoundCallBack): AnsiString;
end;//Ml3FormatObjectInfoHelper
*)
type
Il3FormatObjectInfoHelper = interface
{* Интерфейс сервиса Tl3FormatObjectInfoHelper }
function Format(anObject: TObject;
aShortInfo: Boolean;
anObjectPropFound: TRTTIInfoObjectPropertyFoundCallBack): AnsiString;
end;//Il3FormatObjectInfoHelper
Tl3FormatObjectInfoHelper = {final} class(Tl3ProtoObject)
private
f_Alien: Il3FormatObjectInfoHelper;
{* Внешняя реализация сервиса Il3FormatObjectInfoHelper }
protected
procedure pm_SetAlien(const aValue: Il3FormatObjectInfoHelper);
procedure ClearFields; override;
public
function Format(anObject: TObject;
aShortInfo: Boolean;
anObjectPropFound: TRTTIInfoObjectPropertyFoundCallBack): AnsiString;
class function Instance: Tl3FormatObjectInfoHelper;
{* Метод получения экземпляра синглетона Tl3FormatObjectInfoHelper }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property Alien: Il3FormatObjectInfoHelper
write pm_SetAlien;
{* Внешняя реализация сервиса Il3FormatObjectInfoHelper }
end;//Tl3FormatObjectInfoHelper
{$IfEnd} // NOT Defined(NoVCL)
implementation
{$If NOT Defined(NoVCL)}
uses
l3ImplUses
, l3FormatActionInfoHelper
, Controls
, ActnList
, TypInfo
, l3HugeMessageDlgWithWikiHelper
, SysUtils
, l3Base
//#UC START# *551BCBFD0240impl_uses*
//#UC END# *551BCBFD0240impl_uses*
;
var g_Tl3FormatObjectInfoHelper: Tl3FormatObjectInfoHelper = nil;
{* Экземпляр синглетона Tl3FormatObjectInfoHelper }
procedure Tl3FormatObjectInfoHelperFree;
{* Метод освобождения экземпляра синглетона Tl3FormatObjectInfoHelper }
begin
l3Free(g_Tl3FormatObjectInfoHelper);
end;//Tl3FormatObjectInfoHelperFree
procedure Tl3FormatObjectInfoHelper.pm_SetAlien(const aValue: Il3FormatObjectInfoHelper);
begin
Assert((f_Alien = nil) OR (aValue = nil));
f_Alien := aValue;
end;//Tl3FormatObjectInfoHelper.pm_SetAlien
function Tl3FormatObjectInfoHelper.Format(anObject: TObject;
aShortInfo: Boolean;
anObjectPropFound: TRTTIInfoObjectPropertyFoundCallBack): AnsiString;
//#UC START# *551BCC1F00E6_551BCBFD0240_var*
procedure lp_AddInfo(var theInfo: AnsiString;
const aCaption: AnsiString;
const aValue: AnsiString;
aNewLine: Boolean = False);
begin
if Length(aValue) > 0 then
begin
if Length(theInfo) > 0 then
if aNewLine
then theInfo := theInfo + #13#10
else theInfo := theInfo + ', ';
theInfo := theInfo + aCaption + ':' + aValue;
end;
end;
function lp_FormatLinkToObject(anObject: TObject): AnsiString;
begin
Result := '$' + IntToHex(Integer(anObject), 8);
if Assigned(anObjectPropFound) then
anObjectPropFound(anObject, Result)
else
Result := Tl3HugeMessageDlgWithWikiHelper.Instance.FormatLink(Result, IntToStr(Integer(anObject)));
end;
var
l_Control: TControl;
l_ActionProp: TObject;
//#UC END# *551BCC1F00E6_551BCBFD0240_var*
begin
//#UC START# *551BCC1F00E6_551BCBFD0240_impl*
if Assigned(f_Alien) then
Result := f_Alien.Format(anObject, aShortInfo, anObjectPropFound)
else
Result := '';
if Length(Result) = 0 then
if aShortInfo then
begin
if Assigned(anObject) and (anObject is TControl) then
begin
l_Control := TControl(anObject);
lp_AddInfo(Result, 'name', l_Control.Name);
lp_AddInfo(Result, 'class', l_Control.ClassName);
if Assigned(l_Control.Owner) then
lp_AddInfo(Result, 'Owner', lp_FormatLinkToObject(l_Control.Owner), True);
if Assigned(l_Control.Parent) then
lp_AddInfo(Result, 'Parent', lp_FormatLinkToObject(l_Control.Parent), True);
try
l_ActionProp := GetObjectProp(l_Control, 'Action', TCustomAction);
except
l_ActionProp := nil;
end;
if Assigned(l_ActionProp) then
lp_AddInfo(Result, 'Action', Tl3FormatActionInfoHelper.Instance.Format(TCustomAction(l_ActionProp)), True);
end;//Assigned(aControl)
end
else
Result := L3FormatRTTIInfo(anObject, True, anObjectPropFound, Tl3HugeMessageDlgWithWikiHelper.Instance.CanUseWiki);
//#UC END# *551BCC1F00E6_551BCBFD0240_impl*
end;//Tl3FormatObjectInfoHelper.Format
class function Tl3FormatObjectInfoHelper.Instance: Tl3FormatObjectInfoHelper;
{* Метод получения экземпляра синглетона Tl3FormatObjectInfoHelper }
begin
if (g_Tl3FormatObjectInfoHelper = nil) then
begin
l3System.AddExitProc(Tl3FormatObjectInfoHelperFree);
g_Tl3FormatObjectInfoHelper := Create;
end;
Result := g_Tl3FormatObjectInfoHelper;
end;//Tl3FormatObjectInfoHelper.Instance
class function Tl3FormatObjectInfoHelper.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_Tl3FormatObjectInfoHelper <> nil;
end;//Tl3FormatObjectInfoHelper.Exists
procedure Tl3FormatObjectInfoHelper.ClearFields;
begin
Alien := nil;
inherited;
end;//Tl3FormatObjectInfoHelper.ClearFields
{$IfEnd} // NOT Defined(NoVCL)
end.
|
{-------------------------------------------------- Progressive Path Tracing ---------------------------------------------------
This unit contains various miscellaneous functions used during path tracing (mainly during initialization). These functions
include mapping a file to memory, or getting the number of processors installed on the system.
-------------------------------------------------------------------------------------------------------------------------------}
unit Utils;
interface
uses Windows, SysUtils, Classes;
procedure IncPtr(var P: Pointer; const N: Longword);
procedure DecPtr(var P: Pointer; const N: Longword);
function MapFile(const FilePath: String; var H, M, Len: Longword): Pointer;
procedure UnmapFile(const H, M: Longword; const P: Pointer);
function ProcessorCount: Longword;
function GetWorkerSeed(const Worker: Longword): Longword;
implementation
{ Increments P by N bytes. }
procedure IncPtr(var P: Pointer; const N: Longword);
begin
P := Ptr(Longword(P) + N);
end;
{ Decrements P by N bytes. }
procedure DecPtr(var P: Pointer; const N: Longword);
begin
P := Ptr(Longword(P) - N);
end;
{ Maps a file to a pointer. }
function MapFile(const FilePath: String; var H, M, Len: Longword): Pointer;
begin
Result := nil;
Len := 0;
{ Open a file handle to the requested file, with read-only attributes. }
H := CreateFile(PChar(FilePath), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, $0);
{ If we couldn't open the file, throw an exception. }
if H = INVALID_HANDLE_VALUE then CloseHandle(H) else
begin
{ Retreive the size of the file - up to 4 Gb! }
Len := GetFileSize(H, nil);
{ If the file is empty, we can't map it, so we need to check for this. }
if Len > 0 then
begin
{ So we create a file mapping towards this file handle, still read-only. }
M := CreateFileMapping(H, nil, PAGE_READONLY, 0, 0, nil);
{ If the mapping succeeded, get a pointer. }
if M > 0 then Result := MapViewOfFile(M, FILE_MAP_READ, 0, 0, 0);
end;
end;
end;
{ Unmaps a file from memory. }
procedure UnmapFile(const H, M: Longword; const P: Pointer);
begin
UnmapViewOfFile(P);
CloseHandle(M);
CloseHandle(H);
end;
{ Returns the processor count in the system (this includes cores, not sure if hyperthreading is taken into account). }
function ProcessorCount: Longword;
Var
Sys: SYSTEM_INFO;
begin
GetSystemInfo(Sys);
Result := Sys.dwNumberOfProcessors;
end;
{ Returns a different pseudorandom seed depending on the worker. }
function GetWorkerSeed(const Worker: Longword): Longword;
begin
Result := GetTickCount * (Worker + GetTickCount) * (Worker shl 7 + GetTickCount) - $5A5A5A5A;
end;
end.
|
unit ChannelList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, IRCViewIntf;
type
{ TUser }
TUser = class
private
FNickNameInChannel: string;
FNickName: string;
procedure SetNickName(AValue: string);
procedure SetNickNameInChannel(AValue: string);
public
Tab: TObject;
Node: TObject;
property NickNameInChannel: string read FNickNameInChannel write SetNickNameInChannel;
property NickName: string read FNickName write SetNickName;
constructor Create(const ANickName: string);
end;
{ TUserList }
TUserList = class(specialize TFPGObjectList<TUser>)
function UserByNick(const NickName: string): TUser;
end;
{ TChannel }
TChannel = class
public
Name: string;
Tab: TObject;
Node: TObject;
Users: TUserList;
procedure RemoveUser(User: TUser);
constructor Create(const ChannelName: string);
destructor Destroy; override;
end;
{ TChannelList }
TChannelList = class(specialize TFPGObjectList<TChannel>)
private
FView: IIRCView;
FNickName: string;
public
constructor Create(View: IIRCView);
function AutoComplete(const ChannelName: string; const SearchString: string): string;
function ChannelByName(const Name: string): TChannel;
procedure RemoveUserFromAllChannels(const NickName: string);
procedure ClearChannels;
procedure RemoveUserFromChannel(const ChannelName, Nickname: string);
procedure NickNameChanged(const OldNickName, NewNickName: string);
procedure Quit(const ANickName, AReason: string);
procedure Parted(const ANickname, AHost, AChannel, APartMessage: string);
procedure Joined(const ANickname, AHost, AChannel: string);
property View: IIRCView read FView;
property NickName: string read FNickName write FNickName;
end;
implementation
uses strutils, IRCUtils;
{ TUserList }
resourcestring
StrQuit = '* %s %s';
StrParted = '* Parted: ';
StrJoined = '* Joined: ';
function TUserList.UserByNick(const NickName: string): TUser;
begin
for Result in Self do
if Result.NickName = NickName then
Exit;
Result := nil;
end;
procedure TUser.SetNickNameInChannel(AValue: string);
begin
if FNickNameInChannel = AValue then
Exit;
FNickNameInChannel := AValue;
FNickName := StringReplace(AValue, '@', '', []);
FNickName := StringReplace(FNickName, '+', '', []);
end;
procedure TUser.SetNickName(AValue: string);
begin
if FNickName = AValue then
Exit;
FNickName := AValue;
if TIRCUtils.IsOp(FNickNameInChannel) then
FNickNameInChannel := '@' + AValue
else if TIRCUtils.IsVoice(FNickNameInChannel) then
FNickNameInChannel := '+' + AValue
else
FNickNameInChannel := AValue;
end;
constructor TUser.Create(const ANickName: string);
begin
inherited Create;
NickNameInChannel := ANickName;
end;
{ TUserList }
procedure TChannel.RemoveUser(User: TUser);
begin
User.Node.Free;
Users.Extract(User).Free;
end;
constructor TChannel.Create(const ChannelName: string);
begin
Name := ChannelName;
Users := TUserList.Create;
end;
destructor TChannel.Destroy;
begin
Users.Free;
inherited Destroy;
end;
{ TChannelList }
constructor TChannelList.Create(View: IIRCView);
begin
inherited Create;
FView := View;
end;
function TChannelList.AutoComplete(const ChannelName: string; const SearchString: string): string;
var
User: TUser;
Channel: TChannel;
begin
Result := '';
for Channel in Self do
if Channel.Name = ChannelName then
for User in Channel.Users do
if AnsiStartsText(SearchString, User.NickName) then
Exit(User.NickName)
end;
function TChannelList.ChannelByName(const Name: string): TChannel;
begin
for Result in Self do
if AnsiCompareText(Result.Name, Name) = 0 then
Exit;
Result := nil;
end;
procedure TChannelList.RemoveUserFromAllChannels(const NickName: string);
var
Channel: TChannel;
begin
for Channel in Self do
RemoveUserFromChannel(Channel.Name, NickName);
end;
procedure TChannelList.ClearChannels;
var
Channel: TChannel;
I: Integer;
begin
for Channel in Self do
for I := Channel.Users.Count -1 downto 0 do
Channel.RemoveUser(Channel.Users[I]);
FView.NotifyChanged;
end;
procedure TChannelList.RemoveUserFromChannel(const ChannelName, Nickname: string);
var
User: TUser;
Channel: TChannel;
RemoveChannel: Boolean;
begin
Channel := ChannelByName(ChannelName);
if Channel = nil then
Exit;
User := Channel.Users.UserByNick(Nickname);
if (User <> nil) then
begin
RemoveChannel := User.NickName = FNickName;
Channel.RemoveUser(User);
if RemoveChannel then
begin
Channel.Node.Free;
Channel.Tab.Free;
Extract(Channel).Free;
end;
FView.NotifyChanged;
end;
end;
procedure TChannelList.NickNameChanged(const OldNickName, NewNickName: string);
var
User: TUser;
Channel: TChannel;
begin
for Channel in Self do
for User in Channel.Users do
if User.NickName = OldNickName then
begin
User.NickName := NewNickName;
if (User.Tab <> nil) then
FView.UpdateTabCaption(User.Tab, NewNickName);
if (User.Node <> nil) then
begin
FView.UpdateNodeText(User.Node, User.NickNameInChannel);
FView.NotifyChanged;
end;
end;
end;
procedure TChannelList.Quit(const ANickName, AReason: string);
begin
RemoveUserFromAllChannels(ANickName);
FView.ServerMessage(Format(StrQuit, [ANickname, AReason]));
end;
procedure TChannelList.Parted(const ANickname, AHost, AChannel, APartMessage: String);
begin
RemoveUserFromChannel(AChannel, ANickname);
FView.ServerMessage(StrParted + ANickname + ' - ' + ' -' + AHost + ': ' + APartMessage + ' - ' + AChannel);
end;
procedure TChannelList.Joined(const ANickname, AHost, AChannel: string);
var
Channel: TChannel;
User: TUser;
begin
Channel := ChannelByName(AChannel);
if Channel = nil then
begin
Channel := TChannel.Create(AChannel);
Add(Channel);
Channel.Tab := FView.GetTab(AChannel);
Channel.Node := FView.GetNode(AChannel, nil);
end;
if NickName <> ANickname then
begin
User := TUser.Create(ANickname);
Channel.Users.Add(User);
User.Node := FView.GetNode(User.NickName, Channel.Node);
end;
FView.ServerMessage(StrJoined + ANickname + ' - ' + AHost + ' - ' + AChannel);
FView.NotifyChanged
end;
end.
|
{ Mark Sattolo 428500
CSI-1100A DGD-1 TA: Chris Lankester
Assignment 8, Question 2 }
program UseCheckPal (input,output);
{ ****************************************************************************** }
procedure CheckPal(S:string; var Pal:boolean);
{ Check to see if a given string S is a palindrome. }
{ Data Dictionary
Givens: S - a string.
Results: Pal - a boolean which is true if S is a palindrome, and false otherwise.
Intermediates: first, last - the first and last characters in S. }
var
first, last : char;
N : integer;
begin { procedure CheckPal }
N := length(S);
if N <= 1 then
Pal := true
else
begin
first := S[1];
last := S[N];
if first = last then
begin
S := copy(S, 2, N-2);
CheckPal(S, Pal);
end { if first = last }
else
Pal := false;
end; { else N <= 1 }
end; { procedure CheckPal }
{ ****************************************************************************** }
{ program UseCheckPal: call CheckPal to find if a given string is a palindrome. }
{ Data Dictionary
Givens: S - a string.
Intermediates: (none)
Results: PalYes - a boolean which is true if S is a palindrome, and false otherwise.
Uses: CheckPal }
var
S : string;
PalYes : boolean;
begin
{ Read in the program's givens. }
write('Please enter a string: ');
readln(S);
{ call procedure }
CheckPal(S, PalYes);
{ write out the results }
writeln;
writeln('************************************************');
writeln('Mark Sattolo 428500');
writeln('CSI-1100A DGD-1 TA: Chris Lankester');
writeln('Assignment 8, Question 2');
writeln('************************************************');
writeln;
write('Your string IS ');
if not PalYes then
write('NOT ');
writeln('a palindrome.');
end.
|
unit uUtils;
interface
uses Classes, Graphics, Jpeg, Windows, SysUtils, Grids;
type
TSplitResult = array of string;
TKeyAndValue = record
Key, Value: string;
end;
const
ConfNumHistoryItems = 10;
var
Path, LastImageFileName: string;
IsWindowMode: Boolean = False;
MainScript: string = 'Main.pas';
function qbTryStrToInt(S: string; Default: Integer): Integer;
function IsNumber(const D: string): Boolean;
function StrCountPos(const SubText: string; Text: string): Integer;
function StrGetBefore(SubStr, Str: string): string;
function StrGetAfter(SubStr, Str: string): string;
procedure SplitStringToTStringList(var AStringList: TStringList; const vString,
cSeparator: string);
function GetKeyAndValue(const AKeyAndValue: string; const ADivider: string =
'='): TKeyAndValue;
function AddBackSlash(const S: string): string;
function RemoveBackSlash(const S: string): string;
function AdvLowerCase(const s: string): string;
function AdvUpperCase(const s: string): string;
function AdvLoCase(ch: char): char;
function AdvUpCase(ch: char): char;
procedure InsSLToSL(const A: TStringList; const P: Integer; var B: TStringList);
procedure AddLast(var S: string; const Ch: string);
function LastPos(SubStr, S: string): Integer;
function StrReplace(const S, Srch, Replace: string): string;
procedure SaveItemToHistory(s: string; History: TStringList);
procedure MakeDir(const DirName: string);
procedure Box(const BoxStrMessage: string; BoxTitle: string = ''); overload;
procedure Box(const BoxIntMessage: Integer; const BoxTitle: string = '');
overload;
procedure Box(const BoxBoolMessage: Boolean; const BoxTitle: string = '');
overload;
function StrLeft(S: string; I: Integer): string;
function StrRight(S: string; I: Integer): string;
function GetINIKey(S, Key: string): string;
function GetINIValue(S, Key: string; Default: string = ''): string;
function Split(S: string; D: string): TSplitResult;
function Explode(const cSeparator, vString: string): TSplitResult;
function Implode(const cSeparator: string; const cArray: TSplitResult): string;
overload;
function Implode(const cArray: TSplitResult): string; overload;
function GetSplitResult(SplitString, SplitDiv: string; Index: Integer): string;
function GetTempPath: string;
//function RGB(R, G, B: Integer): String;
function HexToInt(Value: string; Pos: Integer; Size: Integer): Integer;
function RGBToColor(aRGB: string): TColor;
function IsColor(const S: string): Boolean;
procedure SgInit(SG: TStringGrid);
function ColRowInSG(SG: TStringGrid; ACol, ARow: Integer): Boolean;
implementation
procedure SgInit(SG: TStringGrid);
begin
SG.DefaultColWidth := 32;
SG.DefaultRowHeight := 32;
SG.FixedCols := 0;
SG.FixedRows := 0;
SG.GridLineWidth := 0;
SG.DefaultDrawing := False;
sg.Options := SG.Options + [goThumbTracking];
SG.Options := SG.Options - [goEditing];
end;
function ColRowInSG(SG: TStringGrid; ACol, ARow: Integer): Boolean;
begin
Result := (ACol in [0..SG.ColCount - 1]) and (ARow in [0..SG.RowCount - 1]);
end;
function RGB(R, G, B: Integer): string;
begin
if (R < 0) then
R := 0;
if (G < 0) then
G := 0;
if (B < 0) then
B := 0;
if (R > 255) then
R := 255;
if (G > 255) then
G := 255;
if (B > 255) then
B := 255;
Result := '#' + IntToHex(R, 2) + IntToHex(G, 2) + IntToHex(B, 2);
end;
function HexToInt(Value: string; Pos: Integer; Size: Integer): Integer;
var
i: Integer;
begin
Result := 0;
if Length(Value) < Pos + Size - 1 then
exit;
for i := Pos to Pos + Size - 1 do
begin
case Value[i] of
'1': Result := Result * 16 + 1;
'2': Result := Result * 16 + 2;
'3': Result := Result * 16 + 3;
'4': Result := Result * 16 + 4;
'5': Result := Result * 16 + 5;
'6': Result := Result * 16 + 6;
'7': Result := Result * 16 + 7;
'8': Result := Result * 16 + 8;
'9': Result := Result * 16 + 9;
'A', 'a': Result := Result * 16 + 10;
'B', 'b': Result := Result * 16 + 11;
'C', 'c': Result := Result * 16 + 12;
'D', 'd': Result := Result * 16 + 13;
'E', 'e': Result := Result * 16 + 14;
'F', 'f': Result := Result * 16 + 15;
end;
end;
end;
function RGBToColor(aRGB: string): TColor;
begin
if Length(aRGB) < 6 then
raise EConvertError.Create('Not a valid RGB value');
if aRGB[1] = '#' then
aRGB := Copy(aRGB, 2, Length(aRGB));
if Length(aRGB) <> 6 then
raise EConvertError.Create('Not a valid RGB value');
Result := HexToInt(aRGB, 0, 7);
// asm
// mov EAX, Result
// BSwap EAX
// shr EAX, 8
// mov Result, EAX
// end;
end;
function IsColor(const S: string): Boolean;
var
R: string;
L: Integer;
begin
Result := False;
R := UpperCase(Trim(S));
if (R = '') then
Exit;
L := Length(R);
if (L < 7) then
Exit;
if (R[1] <> '#') then
Exit;
Result := True;
end;
//
function qbTryStrToInt(S: string; Default: Integer): Integer;
begin
try
Result := StrToInt(S);
except
Result := Default;
end;
end;
// Строка число или нет?
function IsNumber(const D: string): Boolean;
var
I: Integer;
begin
result := false;
for I := 1 to length(D) do
if not (D[i] in ['0'..'9']) then
exit;
result := true;
end;
// Подсчёт количества вхождений строки в строке
function StrCountPos(const SubText: string; Text: string): Integer;
begin
if (Length(subtext) = 0) or (Length(Text) = 0) or (Pos(subtext, Text) = 0)
then
Result := 0
else
Result := (Length(Text) - Length(StrReplace(Text, subtext, ''))) div
Length(subtext);
end;
function StrGetBefore(SubStr, Str: string): string;
begin
if pos(substr, str) > 0 then
result := copy(str, 1, pos(substr, str) - 1)
else
result := '';
end;
function StrGetAfter(SubStr, Str: string): string;
begin
if pos(substr, str) > 0 then
result := copy(str, pos(substr, str) + length(substr), length(str))
else
result := '';
end;
// Разбить строку по разделителю и занести в список TStringList
procedure SplitStringToTStringList(var AStringList: TStringList; const vString,
cSeparator: string);
var
H: TSplitResult;
I: Integer;
begin
H := Split(Trim(vString), cSeparator);
for I := 0 to High(H) do
AStringList.Append(Trim(H[I]));
end;
// Получаем одновременно и ключ, и его значение в записи TKeyAndValue
function GetKeyAndValue(const AKeyAndValue: string; const ADivider: string =
'='): TKeyAndValue;
var
I: Integer;
begin
Result.Key := '';
Result.Value := '';
I := Pos(ADivider, AKeyAndValue);
if (I = 0) then
Exit;
Result.Key := Copy(AKeyAndValue, 1, I - 1);
Result.Value := Copy(AKeyAndValue, I + 1, Length(AKeyAndValue));
end;
// Добавляем конечный \
function AddBackSlash(const S: string): string;
begin
Result := S;
if Result[Length(Result)] <> '\' then
Result := Result + '\';
end;
// Удаляем конечный \
function RemoveBackSlash(const S: string): string;
begin
Result := S;
if Result[Length(Result)] = '\' then
Delete(Result, Length(Result), 1);
end;
// В нижний регистр
function AdvLowerCase(const s: string): string;
var
i: integer;
begin
result := s;
for i := 1 to length(result) do
if (result[i] in ['A'..'Z', 'А'..'Я']) then
result[i] := chr(ord(result[i]) + 32)
else if (result[i] in ['І']) then
result[i] := 'і';
end;
// В верхний регистр
function AdvUpperCase(const s: string): string;
var
i: integer;
begin
result := s;
for i := 1 to length(result) do
if (result[i] in ['a'..'z', 'а'..'я']) then
result[i] := chr(ord(result[i]) - 32)
else if (result[i] in ['і']) then
result[i] := 'І';
end;
// Символ в нижний регистр
function AdvLoCase(ch: char): char;
begin
if (ch in ['A'..'Z', 'А'..'Я']) then
result := chr(ord(ch) + 32)
else if (ch = 'І') then
result := 'і'
else
result := ch;
end;
// Символ в верхний регистр
function AdvUpCase(ch: char): char;
begin
if (ch in ['a'..'z', 'а'..'я']) then
result := chr(ord(ch) - 32)
else if (ch = 'і') then
result := 'І'
else
result := ch;
end;
// Вставляем список A в список B в позицию P
procedure InsSLToSL(const A: TStringList; const P: Integer; var B: TStringList);
var
C: TStringList;
I: Integer;
begin
C := TStringList.Create;
for I := 0 to P do
C.Append(B[I]);
C.AddStrings(A);
for I := P + 1 to B.Count - 1 do
C.Append(B[I]);
B.Assign(C);
C.Free;
end;
// Добавить последнюю строку
procedure AddLast(var S: string; const Ch: string);
begin
if (Copy(S, Length(S) - Length(Ch) + 1, Length(Ch)) <> Ch) then
S := Trim(S) + Ch;
end;
// Нахождение последнего вхождения подстроки в строку
function LastPos(SubStr, S: string): Integer;
var
Found, Len, Pos: Integer;
begin
Pos := Length(S);
Len := Length(SubStr);
Found := 0;
while (Pos > 0) and (Found = 0) do
begin
if Copy(S, Pos, Len) = SubStr then
Found := Pos;
Dec(Pos);
end;
Result := Found;
end;
function StrReplace(const S, Srch, Replace: string): string;
var
I: Integer;
Source: string;
begin
Source := S;
Result := '';
repeat
I := Pos(Srch, Source);
if I > 0 then
begin
Result := Result + Copy(Source, 1, I - 1) + Replace;
Source := Copy(Source, I + Length(Srch), MaxInt);
end
else
Result := Result + Source;
until I <= 0;
end;
procedure SaveItemToHistory(S: string; History: TStringList);
var
i: integer;
begin
S := Trim(S);
if (S = '') then
Exit;
if Length(s) > 0 then
begin
if History.IndexOf(s) > -1 then
History.Delete(History.IndexOf(s));
History.Insert(0, s);
if History.Count > ConfNumHistoryItems then
for i := History.Count downto ConfNumHistoryItems do
History.Delete(i - 1);
end;
end;
procedure MakeDir(const DirName: string);
begin
if not DirectoryExists(Path + DirName) then
MkDir(Path + DirName);
end;
procedure Box(const BoxStrMessage: string; BoxTitle: string = ''); overload;
begin
MessageBox(0, PChar(BoxStrMessage), PChar(BoxTitle), MB_OK);
end;
procedure Box(const BoxIntMessage: Integer; const BoxTitle: string = '');
overload;
begin
MessageBox(0, PChar(IntToStr(BoxIntMessage)), PChar(BoxTitle), MB_OK);
end;
procedure Box(const BoxBoolMessage: Boolean; const BoxTitle: string = '');
overload;
begin
MessageBox(0, PChar(BoolToStr(BoxBoolMessage)), PChar(BoxTitle), MB_OK);
end;
// Копия строки слева
function StrLeft(S: string; I: Integer): string;
begin
Result := Copy(S, 1, I);
end;
// Копия строки справа
function StrRight(S: string; I: Integer): string;
var
L: Integer;
begin
L := Length(S);
Result := Copy(S, L - I + 1, L);
end;
// Ключ
function GetINIKey(S, Key: string): string;
var
P: Integer;
begin
P := Pos(Key, S);
if (P <= 0) then
begin
Result := S;
Exit;
end;
Result := StrLeft(S, P - 1);
end;
// Значение ключа
function GetINIValue(S, Key: string; Default: string = ''): string;
var
L, P, K: Integer;
begin
P := Pos(Key, S);
if (P <= 0) then
begin
Result := Default;
Exit;
end;
L := Length(S);
K := Length(Key);
Result := StrRight(S, L - P - K + 1);
end;
// Разбить строку в массив TSplitResult, аналог Split
function Explode(const cSeparator, vString: string): TSplitResult;
var
I: Integer;
S: string;
begin
S := vString;
SetLength(Result, 0);
I := 0;
while Pos(cSeparator, S) > 0 do
begin
SetLength(Result, Length(Result) + 1);
Result[I] := Copy(S, 1, Pos(cSeparator, S) - 1);
Inc(I);
S := Copy(S, Pos(cSeparator, S) + Length(cSeparator), Length(S));
end;
SetLength(Result, Length(Result) + 1);
Result[I] := Copy(S, 1, Length(S));
end;
// Соединить массив TSplitResult в одну строку, аналог Join
function Implode(const cSeparator: string; const cArray: TSplitResult): string;
overload;
var
I: Integer;
begin
Result := '';
for I := 0 to Length(cArray) - 1 do
begin
Result := Result + cSeparator + cArray[I];
end;
System.Delete(Result, 1, Length(cSeparator));
end;
function Implode(const cArray: TSplitResult): string; overload;
begin
Result := Implode('', cArray);
end;
// Разделить строку на подстроки разделителем D
function Split(S: string; D: string): TSplitResult;
var
R: TSplitResult;
K: Integer;
Key: string;
RR: Boolean;
procedure DS(RS: string);
begin
Inc(K);
SetLength(R, K);
R[K - 1] := RS;
end;
begin
K := 0;
if not (Pos(D, S) > 0) then
begin
DS(S);
Result := R;
Exit;
end;
repeat
Key := GetINIKey(S, D);
S := GetINIValue(S, D);
DS(Key);
RR := Pos(D, S) > 0;
if not RR then
DS(S);
until not RR;
Result := R;
end;
// Возвращает строку TSplitResult из позиции Index
function GetSplitResult(SplitString, SplitDiv: string; Index: Integer): string;
var
SR: TSplitResult;
begin
SR := Split(SplitString, SplitDiv);
Result := SR[Index];
end;
// Временный системный каталог
function GetTempPath: string;
var
Buffer: array[0..1023] of Char;
begin
SetString(Result, Buffer, Windows.GetTempPath(SizeOf(Buffer) - 1, Buffer));
end;
initialization
Path := ExtractFilePath(ParamStr(0));
LastImageFileName := '';
finalization
end.
|
unit frmAutoHide;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TAutoHideForm = class(TForm)
btnOK: TBitBtn;
lblInfo: TLabel;
tmrHide: TTimer;
tmrAlpha: TTimer;
procedure FormShow(Sender: TObject);
procedure tmrHideTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tmrAlphaTimer(Sender: TObject);
private
m_Info: string;
m_IsHiding: Boolean;
public
property Info: string read m_Info write m_Info;
end;
var
AutoHideForm: TAutoHideForm;
implementation
{$R *.dfm}
procedure TAutoHideForm.FormCreate(Sender: TObject);
begin
m_IsHiding := False;
end;
procedure TAutoHideForm.FormShow(Sender: TObject);
begin
lblInfo.Caption := m_Info;
end;
procedure TAutoHideForm.tmrAlphaTimer(Sender: TObject);
const
AlphaStep = 10;
begin
tmrAlpha.Enabled := False;
//SetForegroundWindow(Self.Handle);
if Self.AlphaBlendValue >= AlphaStep then
begin
Self.AlphaBlendValue := Self.AlphaBlendValue - AlphaStep;
tmrAlpha.Enabled := True;
end
else
begin
ModalResult := mrOk;
end;
end;
procedure TAutoHideForm.tmrHideTimer(Sender: TObject);
begin
tmrHide.Enabled := False;
tmrAlpha.Enabled := True;
end;
end.
|
unit uVersao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.StdCtrls,
Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls, uDMVersao,
uVersaoController, Vcl.Mask, Vcl.DBCtrls, uFuncoesSIDomper, Vcl.OleCtnrs, uFraCliente,
uFraUsuario, uFraTipo, uFraStatus, uEnumerador, Vcl.Menus, uPosicaoBotao, uFiltroVersao,
uFraProduto, uProduto;
type
TfrmVersao = class(TfrmBaseCadastro)
PageControl1: TPageControl;
tsPrincipal: TTabSheet;
Panel7: TPanel;
edtCodigo: TDBEdit;
Label4: TLabel;
Label5: TLabel;
edtNome: TDBEdit;
Label6: TLabel;
DBEdit1: TDBEdit;
edtCodUsuario: TDBEdit;
Label10: TLabel;
DBEdit7: TDBEdit;
edtCodTipo: TDBEdit;
Label12: TLabel;
DBEdit10: TDBEdit;
btnTipo: TSpeedButton;
edtCodStatus: TDBEdit;
Label13: TLabel;
DBEdit12: TDBEdit;
btnStatus: TSpeedButton;
Label14: TLabel;
DBMemo1: TDBMemo;
dlgAbrirArquivo: TOpenDialog;
tsFiltroUsuario: TTabSheet;
Panel9: TPanel;
FraUsuario: TFraUsuario;
tsFiltroTipo: TTabSheet;
tsFiltroStatus: TTabSheet;
Panel10: TPanel;
Panel11: TPanel;
FraTipo: TFraTipo;
FraStatus: TFraStatus;
Label39: TLabel;
edtDataInicial: TMaskEdit;
edtDataFinal: TMaskEdit;
Label40: TLabel;
Label20: TLabel;
edtVersao: TDBEdit;
Label7: TLabel;
Label8: TLabel;
edtDataLibInicial: TMaskEdit;
edtDataLibFinal: TMaskEdit;
lblMensagem: TLabel;
pmRelatorio: TPopupMenu;
Estatsticas1: TMenuItem;
DocumentospLiberao1: TMenuItem;
GroupBox2: TGroupBox;
Label9: TLabel;
cbModelo: TComboBox;
tsFiltroProduto: TTabSheet;
Panel8: TPanel;
FraProduto: TFraProduto;
Label11: TLabel;
edtCodProduto: TDBEdit;
DBEdit2: TDBEdit;
btnProduto: TSpeedButton;
procedure edtDescricaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnFiltroClick(Sender: TObject);
procedure dbDadosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnFecharEdicaoClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure btnStatusClick(Sender: TObject);
procedure btnTipoClick(Sender: TObject);
procedure cbbCamposChange(Sender: TObject);
procedure DBMemo1Enter(Sender: TObject);
procedure DBMemo1Exit(Sender: TObject);
procedure DBMemo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtCodStatusExit(Sender: TObject);
procedure edtCodTipoExit(Sender: TObject);
procedure edtCodTipoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtCodUsuarioExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tsFiltroShow(Sender: TObject);
procedure tsGeralShow(Sender: TObject);
procedure dbDadosTitleClick(Column: TColumn);
procedure FraTipoedtCodigoEnter(Sender: TObject);
procedure FraTipobtnProcClick(Sender: TObject);
procedure FraStatusedtCodigoEnter(Sender: TObject);
procedure FraStatusbtnProcClick(Sender: TObject);
procedure Estatsticas1Click(Sender: TObject);
procedure DocumentospLiberao1Click(Sender: TObject);
procedure btnFiltrarClick(Sender: TObject);
procedure btnProdutoClick(Sender: TObject);
procedure edtCodProdutoExit(Sender: TObject);
private
{ Private declarations }
FController: TVersaoController;
procedure Localizar(ATexto: string);
procedure BuscarUsuario(AId, ACodigo: Integer);
procedure BuscarTipo(AId, ACodigo: Integer);
procedure BuscarStatus(AId, ACodigo: Integer);
procedure BuscarProduto(AId, ACodigo: Integer);
procedure BuscarObservacao;
procedure BuscarStatusDesenvolvimento;
public
{ Public declarations }
constructor create(APesquisar: Boolean = False);
procedure Impressao(ATipo, AIdVersao: Integer);
procedure ImpressaoVersao(AIdVersao: Integer);
procedure ImpressaoDocumento(AIdVersao: Integer);
end;
var
frmVersao: TfrmVersao;
implementation
{$R *.dfm}
uses uGrade, uDM, uImagens, uClienteController, uUsuario, uCliente,
uUsuarioController, uTipo, uTipoController, uStatusController, uStatus,
uFiltroVisita, uObservacao, uObsevacaoController, uProdutoController;
procedure TfrmVersao.btnEditarClick(Sender: TObject);
begin
FController.Editar(dbDados.Columns[0].Field.AsInteger, Self);
inherited;
if edtNome.Enabled then
edtNome.SetFocus;
end;
procedure TfrmVersao.btnExcluirClick(Sender: TObject);
begin
if TFuncoes.Confirmar('Excluir Registro?') then
begin
FController.Excluir(dm.IdUsuario, dbDados.Columns[0].Field.AsInteger);
inherited;
end;
end;
procedure TfrmVersao.btnFecharEdicaoClick(Sender: TObject);
begin
FController.Cancelar;
inherited;
end;
procedure TfrmVersao.btnFiltrarClick(Sender: TObject);
begin
inherited;
edtDataInicial.SetFocus;
end;
procedure TfrmVersao.btnFiltroClick(Sender: TObject);
begin
inherited;
Localizar(edtDescricao.Text);
end;
procedure TfrmVersao.btnImprimirClick(Sender: TObject);
var
Controller: TVersaoController;
Filtro: TFiltroVersao;
begin
TFuncoes.DataValida(edtDataInicial.Text);
TFuncoes.DataValida(edtDataFinal.Text);
TFuncoes.DataValida(edtDataLibInicial.Text);
TFuncoes.DataValida(edtDataLibFinal.Text);
FController.Imprimir(dm.IdUsuario);
Filtro := TFiltroVersao.Create;
Controller := TVersaoController.Create;
try
Filtro.DataInicial := edtDataInicial.Text;
Filtro.DataFinal := edtDataFinal.Text;
Filtro.DataLiberacaoInicial := edtDataLibInicial.Text;
Filtro.DataLiberacaoFinal := edtDataLibFinal.Text;
Filtro.IdCliente := '';
Filtro.IdTipo := FraTipo.RetornoSelecao();
Filtro.IdStatus := FraStatus.RetornoSelecao();
Filtro.IdUsuario := FraUsuario.RetornoSelecao();
Filtro.IdProduto := FraProduto.RetornoSelecao();
Filtro.IdVersao := 0;
if cbModelo.ItemIndex = 0 then
Controller.Relatorio03(0, Filtro);
finally
FreeAndNil(Controller);
FreeAndNil(Filtro);
end;
inherited;
end;
procedure TfrmVersao.btnNovoClick(Sender: TObject);
begin
FController.Novo(dm.IdUsuario);
inherited;
edtNome.SetFocus;
end;
procedure TfrmVersao.btnProdutoClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmProduto.create(true));
if dm.IdSelecionado > 0 then
BuscarProduto(dm.IdSelecionado, 0);
end;
procedure TfrmVersao.btnSalvarClick(Sender: TObject);
begin
FController.Salvar(dm.IdUsuario);
FController.FiltrarCodigo(FController.CodigoAtual());
inherited;
end;
procedure TfrmVersao.BuscarObservacao;
var
obs: TObservacaoController;
begin
if edtVersao.Enabled = False then
Exit;
TFuncoes.CriarFormularioModal(TfrmObservacao.create(true, prVersao));
if dm.IdSelecionado > 0 then
begin
FController.ModoEdicaoInsercao;
obs := TObservacaoController.Create;
try
obs.LocalizarId(dm.IdSelecionado);
FController.Model.CDSCadastroVer_Descricao.AsString :=
FController.Model.CDSCadastroVer_Descricao.AsString + ' ' + obs.Model.CDSCadastroObs_Descricao.AsString;
finally
FreeAndNil(obs);
end;
end;
end;
procedure TfrmVersao.BuscarProduto(AId, ACodigo: Integer);
var
obj: TProdutoController;
begin
obj := TProdutoController.Create;
try
try
obj.Pesquisar(AId, ACodigo);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodProduto.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroVer_Produto.AsString := obj.Model.CDSCadastroProd_Id.AsString;
FController.Model.CDSCadastroProd_Codigo.AsString := obj.Model.CDSCadastroProd_Codigo.AsString;
FController.Model.CDSCadastroProd_Nome.AsString := obj.Model.CDSCadastroProd_Nome.AsString;
FreeAndNil(obj);
end;
edtCodProduto.Modified := False;
end;
procedure TfrmVersao.BuscarStatus(AId, ACodigo: Integer);
var
obj: TStatusController;
begin
obj := TStatusController.Create;
try
try
obj.Pesquisar(AId, ACodigo, prVersao);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodStatus.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroVer_Status.AsString := obj.Model.CDSCadastroSta_Id.AsString;
FController.Model.CDSCadastroSta_Codigo.AsString := obj.Model.CDSCadastroSta_Codigo.AsString;
FController.Model.CDSCadastroSta_Nome.AsString := obj.Model.CDSCadastroSta_Nome.AsString;
FreeAndNil(obj);
end;
edtCodStatus.Modified := False;
end;
procedure TfrmVersao.BuscarStatusDesenvolvimento;
var
iCodStatus: Integer;
begin
iCodStatus := FController.BuscarStatusVersaoDesenvolvimento();
if iCodStatus > 0 then
begin
FraStatus.edtCodigo.Text := IntToStr(iCodStatus);
FraStatus.Adiciona();
end;
end;
procedure TfrmVersao.BuscarTipo(AId, ACodigo: Integer);
var
obj: TTipoController;
begin
obj := TTipoController.Create;
try
try
obj.Pesquisar(AId, ACodigo, prVersao);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodTipo.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroVer_Tipo.AsString := obj.Model.CDSCadastroTip_Id.AsString;
FController.Model.CDSCadastroTip_Codigo.AsString := obj.Model.CDSCadastroTip_Codigo.AsString;
FController.Model.CDSCadastroTip_Nome.AsString := obj.Model.CDSCadastroTip_Nome.AsString;
FreeAndNil(obj);
end;
edtCodTipo.Modified := False;
end;
procedure TfrmVersao.BuscarUsuario(AId, ACodigo: Integer);
var
obj: TUsuarioController;
begin
obj := TUsuarioController.Create;
try
try
obj.Pesquisar(AId, ACodigo);
except
On E: Exception do
begin
ShowMessage(E.Message);
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroVer_Usuario.AsString := obj.Model.CDSCadastroUsu_Id.AsString;
FController.Model.CDSCadastroUsu_Codigo.AsString := obj.Model.CDSCadastroUsu_Codigo.AsString;
FController.Model.CDSCadastroUsu_Nome.AsString := obj.Model.CDSCadastroUsu_Nome.AsString;
FreeAndNil(obj);
end;
edtCodUsuario.Modified := False;
end;
constructor TfrmVersao.create(APesquisar: Boolean);
begin
inherited create(nil);
FController := TVersaoController.Create;
dsPesquisa.DataSet := FController.Model.CDSConsulta;
dsCad.DataSet := FController.Model.CDSCadastro;
TGrade.RetornaCamposGrid(dbDados, cbbCampos);
cbbCampos.ItemIndex := 4;
Localizar('ABCDE'); // para trazer vazio
if APesquisar then
begin
cbbSituacao.ItemIndex := 0;
Pesquisa := APesquisar;
end;
FraUsuario.Inicializar();
FraTipo.Inicializar();
FraStatus.Inicializar();
FraProduto.Inicializar();
end;
procedure TfrmVersao.btnStatusClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmStatus.create(prVersao, True));
if dm.IdSelecionado > 0 then
BuscarStatus(dm.IdSelecionado, 0);
end;
procedure TfrmVersao.btnTipoClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmTipo.create(prVersao, true));
if dm.IdSelecionado > 0 then
BuscarTipo(dm.IdSelecionado, 0);
end;
procedure TfrmVersao.cbbCamposChange(Sender: TObject);
begin
inherited;
lblMensagem.Visible := TFuncoes.MostrarDescricaoPesquisaData(cbbCampos.Text);
end;
procedure TfrmVersao.dbDadosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
dbDadosDblClick(Self);
if edtCodigo.Enabled then
edtCodigo.SetFocus;
end;
end;
procedure TfrmVersao.dbDadosTitleClick(Column: TColumn);
begin
inherited;
TFuncoes.OrdenarCamposGrid(FController.Model.cdsconsulta, Column.FieldName);
end;
procedure TfrmVersao.DBMemo1Enter(Sender: TObject);
begin
inherited;
Self.KeyPreview := False;
end;
procedure TfrmVersao.DBMemo1Exit(Sender: TObject);
begin
inherited;
Self.KeyPreview := True;
end;
procedure TfrmVersao.DBMemo1KeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
inherited;
if Key = VK_F8 then
begin
if btnSalvar.Enabled then
begin
btnSalvar.SetFocus;
btnSalvarClick(Self);
end;
end;
if Key = VK_F9 then
BuscarObservacao();
if Key = VK_ESCAPE then
btnCancelarClick(Self);
end;
procedure TfrmVersao.DocumentospLiberao1Click(Sender: TObject);
begin
inherited;
Impressao(2, FController.Model.CDSConsultaVer_Id.AsInteger);
end;
procedure TfrmVersao.edtCodProdutoExit(Sender: TObject);
begin
inherited;
if edtCodProduto.Modified then
BuscarProduto(0, StrToIntDef(edtCodProduto.Text, 0));
end;
procedure TfrmVersao.edtCodStatusExit(Sender: TObject);
begin
inherited;
if edtCodStatus.Modified then
BuscarStatus(0, StrToIntDef(edtCodStatus.Text,0));
end;
procedure TfrmVersao.edtCodTipoExit(Sender: TObject);
begin
inherited;
if edtCodTipo.Modified then
BuscarTipo(0, StrToIntDef(edtCodTipo.Text, 0));
end;
procedure TfrmVersao.edtCodTipoKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
inherited;
if Key = VK_F9 then
begin
if Sender = edtCodTipo then
btnTipoClick(Self)
else if Sender = edtCodStatus then
btnStatusClick(Self)
else if Sender = edtCodProduto then
btnProdutoClick(Self);
end;
end;
procedure TfrmVersao.edtCodUsuarioExit(Sender: TObject);
begin
inherited;
if edtCodUsuario.Modified then
BuscarUsuario(0, StrToIntDef(edtCodUsuario.Text, 0));
end;
procedure TfrmVersao.edtDescricaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
Localizar(edtDescricao.Text);
end;
procedure TfrmVersao.Estatsticas1Click(Sender: TObject);
begin
inherited;
Impressao(1, FController.Model.CDSConsultaVer_Id.AsInteger);
end;
procedure TfrmVersao.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FController);
end;
procedure TfrmVersao.FormShow(Sender: TObject);
var
Img: TfrmImagens;
Botao: TPosicaoBotao;
begin
inherited;
Img := TfrmImagens.Create(Self);
try
btnTipo.Glyph := Img.btnProcurar.Glyph;
btnStatus.Glyph := Img.btnProcurar.Glyph;
btnProduto.Glyph := Img.btnProcurar.Glyph;
finally
FreeAndNil(Img);
end;
//------------------------------------------------------------------------------
// edicao
Botao := TPosicaoBotao.Create(btnSalvar, 6, 6);
try
Botao.PosicaoBotao(btnCancelar);
finally
FreeAndNil(Botao);
end;
//------------------------------------------------------------------------------
// Pesquisa
Botao := TPosicaoBotao.Create(btnPrimeiro, 6, 6, True);
try
Botao.PosicaoBotaoNavegacao(btnAnterior);
Botao.PosicaoBotaoNavegacao(btnProximo);
Botao.PosicaoBotaoNavegacao(btnUltimo);
Botao.PosicaoBotao(btnNovo);
Botao.PosicaoBotao(btnEditar);
Botao.PosicaoBotao(btnExcluir);
Botao.PosicaoBotao(btnFiltrar);
Botao.PosicaoBotao(btnSair);
finally
FreeAndNil(Botao);
end;
//------------------------------------------------------------------------------
// filtro
Botao := TPosicaoBotao.Create(btnFiltro, 6, 6);
try
Botao.PosicaoBotao(btnImprimir);
Botao.PosicaoBotao(btnFecharFiltro);
finally
FreeAndNil(Botao);
end;
BuscarStatusDesenvolvimento();
end;
procedure TfrmVersao.FraStatusbtnProcClick(Sender: TObject);
begin
inherited;
FraStatus.TipoPrograma := prVersao;
FraStatus.btnProcClick(Sender);
end;
procedure TfrmVersao.FraStatusedtCodigoEnter(Sender: TObject);
begin
inherited;
FraStatus.TipoPrograma := prVersao;
end;
procedure TfrmVersao.FraTipobtnProcClick(Sender: TObject);
begin
inherited;
FraTipo.TipoPrograma := prVersao;
FraTipo.btnProcClick(Sender);
end;
procedure TfrmVersao.FraTipoedtCodigoEnter(Sender: TObject);
begin
inherited;
FraTipo.TipoPrograma := prVersao;
end;
procedure TfrmVersao.Impressao(ATipo, AIdVersao: Integer);
begin
if FController.Model.CDSConsulta.IsEmpty then
raise Exception.Create('Não há Registros!');
case ATipo of
1: ImpressaoVersao(AIdVersao);
2: ImpressaoDocumento(AIdVersao);
end;
end;
procedure TfrmVersao.ImpressaoDocumento(AIdVersao: Integer);
var
obj: TVersaoController;
Filtro: TFiltroVersao;
begin
obj := TVersaoController.Create;
Filtro := TFiltroVersao.Create;
try
Filtro.IdVersao := AIdVersao;
obj.Relatorio02(AIdVersao, Filtro);
finally
FreeAndNil(obj);
FreeAndNil(Filtro);
end;
end;
procedure TfrmVersao.ImpressaoVersao(AIdVersao: Integer);
var
obj: TVersaoController;
begin
obj := TVersaoController.Create;
try
obj.Relatorio01(AIdVersao);
finally
FreeAndNil(obj);
end;
end;
procedure TfrmVersao.Localizar(ATexto: string);
var
sCampo: string;
sSituacao: string;
bContem: Boolean;
Filtro: TFiltroVersao;
begin
Filtro := TFiltroVersao.Create;
try
Filtro.DataInicial := edtDataInicial.Text;
Filtro.DataFinal := edtDataFinal.Text;
Filtro.DataLiberacaoInicial := edtDataLibInicial.Text;
Filtro.DataLiberacaoFinal := edtDataLibFinal.Text;
Filtro.IdTipo := FraTipo.RetornoSelecao();
Filtro.IdStatus := FraStatus.RetornoSelecao();
Filtro.IdUsuario := FraUsuario.RetornoSelecao();
Filtro.IdProduto := FraProduto.RetornoSelecao();
sCampo := TGrade.FiltrarCampo(dbDados, cbbCampos);
sSituacao := Copy(cbbSituacao.Items.Strings[cbbSituacao.ItemIndex], 1, 1);
bContem := (cbbPesquisa.ItemIndex = 1);
FController.FiltrarVersao(Filtro, sCampo, ATexto, bContem);
FController.Model.CDSConsulta.IndexFieldNames := sCampo;
finally
FreeAndNil(Filtro);
end;
end;
procedure TfrmVersao.tsFiltroShow(Sender: TObject);
begin
inherited;
PageControl2.ActivePageIndex := 0;
end;
procedure TfrmVersao.tsGeralShow(Sender: TObject);
begin
cbbPesquisa.SetFocus;
inherited;
end;
end.
|
unit ComboBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, EditableObjects, Editors;
type
TComboBoxEditor =
class(TInPlaceVisualControl)
cbValue: TComboBox;
procedure FormResize(Sender: TObject);
procedure cbValueChange(Sender: TObject);
public
procedure UpdateObject; override;
public
procedure setEditableObject( aEditableObject : TEditableObject; options : integer ); override;
end;
implementation
uses
EditorEvents, Notifications;
{$R *.DFM}
procedure TComboBoxEditor.FormResize(Sender: TObject);
begin
cbValue.SetBounds( 0, 0, ClientWidth, ClientHeight );
end;
procedure TComboBoxEditor.UpdateObject;
begin
fEditableObject.Value := cbValue.Text;
end;
procedure TComboBoxEditor.setEditableObject( aEditableObject : TEditableObject; options : integer );
var
template : TEditableObject;
Data : TGetTemplateData;
begin
inherited;
template := fEditableObject.getProperty( 'comboTemplate' );
if template <> nil
then
begin
Data.Name := template.Value;
Data.Template := cbValue.Items;
DispatchEvent( evGetTemplates, Data );
end;
cbValue.Text := fEditableObject.Value;
end;
procedure TComboBoxEditor.cbValueChange(Sender: TObject);
begin
UpdateObject;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clCryptSignature;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Windows,
{$ELSE}
System.Classes, System.SysUtils, Winapi.Windows,
{$ENDIF}
clUtils, clCryptAPI, clWUtils, clConfig;
type
TclSignature = class(TclConfigObject)
public
procedure Init; virtual; abstract;
procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); virtual; abstract;
procedure Verify(const ASignature: TclByteArray); virtual; abstract;
function Sign: TclByteArray; virtual; abstract;
end;
TclRsaKey = class(TclConfigObject)
private
FKeyLength: Integer;
FKeyType: Integer;
public
procedure Init; virtual; abstract;
procedure GenerateKey; virtual; abstract;
function GetRsaPrivateKey: TclByteArray; virtual; abstract;
function GetRsaPublicKey: TclByteArray; virtual; abstract;
function GetPublicKeyInfo: TclByteArray; virtual; abstract;
procedure SetRsaPrivateKey(const AKey: TclByteArray); virtual; abstract;
procedure SetRsaPublicKey(const AKey: TclByteArray); virtual; abstract;
procedure SetPublicKeyInfo(const AKey: TclByteArray); virtual; abstract;
procedure SetPublicKeyParams(const AModulus, AExponent: TclByteArray); virtual; abstract;
procedure GetPublicKeyParams(var AModulus, AExponent: TclByteArray); virtual; abstract;
property KeyLength: Integer read FKeyLength write FKeyLength;
property KeyType: Integer read FKeyType write FKeyType;
end;
TclSignatureRsa = class(TclSignature)
public
procedure SetPrivateKey(AKey: TclRsaKey); virtual; abstract;
procedure SetPublicKey(AKey: TclRsaKey); virtual; abstract;
end;
TclCryptApiRsaKey = class(TclRsaKey)
private
FContext: HCRYPTPROV;
FKey: HCRYPTKEY;
FCSPPtr: PclChar;
procedure Clear;
function GetCSPPtr: PclChar;
function GetExponent(AE: TclByteArray): DWORD;
protected
procedure LoadKeyInfo;
function GetCSP: string; virtual;
function GetProviderType: Integer; virtual;
public
constructor Create; override;
destructor Destroy; override;
procedure Init; override;
procedure GenerateKey; override;
function GetRsaPrivateKey: TclByteArray; override;
function GetRsaPublicKey: TclByteArray; override;
function GetPublicKeyInfo: TclByteArray; override;
procedure SetRsaPrivateKey(const AKey: TclByteArray); override;
procedure SetRsaPublicKey(const AKey: TclByteArray); override;
procedure SetPublicKeyInfo(const AKey: TclByteArray); override;
procedure SetPublicKeyParams(const AModulus, AExponent: TclByteArray); override;
procedure GetPublicKeyParams(var AModulus, AExponent: TclByteArray); override;
end;
TclCryptApiSignatureRsa = class(TclSignatureRsa)
private
FContext: HCRYPTPROV;
FKey: HCRYPTKEY;
FHash: HCRYPTHASH;
FCSPPtr: PclChar;
FKeyType: Integer;
procedure Clear;
function GetCSPPtr: PclChar;
protected
function GetHashAlgorithm: ALG_ID; virtual; abstract;
function GetCSP: string; virtual; abstract;
function GetProviderType: Integer; virtual; abstract;
public
constructor Create; override;
destructor Destroy; override;
procedure Init; override;
procedure SetPrivateKey(AKey: TclRsaKey); override;
procedure SetPublicKey(AKey: TclRsaKey); override;
procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); override;
procedure Verify(const ASignature: TclByteArray); override;
function Sign: TclByteArray; override;
end;
TclSignatureRsaSha1 = class(TclCryptApiSignatureRsa)
protected
function GetHashAlgorithm: ALG_ID; override;
function GetCSP: string; override;
function GetProviderType: Integer; override;
end;
TclSignatureRsaSha256 = class(TclCryptApiSignatureRsa)
protected
function GetHashAlgorithm: ALG_ID; override;
function GetCSP: string; override;
function GetProviderType: Integer; override;
end;
implementation
uses
clCryptUtils, clEncoder, clTranslator;
{ TclSignatureRsa }
procedure TclCryptApiSignatureRsa.Clear;
begin
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
if (FHash <> nil) then
begin
CryptDestroyHash(FHash);
FHash := nil;
end;
if (FContext <> nil) then
begin
CryptReleaseContext(FContext, 0);
FContext := nil;
end;
FreeMem(FCSPPtr);
FCSPPtr := nil;
end;
constructor TclCryptApiSignatureRsa.Create;
begin
inherited Create();
FContext := nil;
FHash := nil;
FKey := nil;
FKeyType := AT_KEYEXCHANGE;
end;
destructor TclCryptApiSignatureRsa.Destroy;
begin
Clear();
inherited Destroy();
end;
function TclCryptApiSignatureRsa.GetCSPPtr: PclChar;
var
s: TclString;
len: Integer;
begin
Result := FCSPPtr;
if (Result <> nil) then Exit;
if (Trim(GetCSP()) <> '') then
begin
s := GetTclString(GetCSP());
len := Length(s);
GetMem(FCSPPtr, len + SizeOf(TclChar));
system.Move(PclChar(s)^, FCSPPtr^, len);
FCSPPtr[len] := #0;
end;
Result := FCSPPtr;
end;
procedure TclCryptApiSignatureRsa.Init;
begin
Clear();
if not CryptAcquireContext(@FContext, nil, GetCSPPtr(), GetProviderType(), CRYPT_VERIFYCONTEXT) then
begin
RaiseCryptError('CryptAcquireContext');
end;
if not CryptCreateHash(FContext, GetHashAlgorithm(), nil, 0, @FHash) then
begin
RaiseCryptError('CryptCreateHash');
end;
end;
procedure TclCryptApiSignatureRsa.SetPrivateKey(AKey: TclRsaKey);
var
key: TclByteArray;
der, keyBlob: TclCryptData;
size: DWORD;
begin
Assert(FContext <> nil);
FKeyType := AKey.KeyType;
key := AKey.GetRsaPrivateKey();
if (key = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
der := nil;
keyBlob := nil;
try
der := TclCryptData.Create();
der.FromBytes(key);
size := 0;
if not CryptDecodeObjectEx(DefaultEncoding, PKCS_RSA_PRIVATE_KEY, der.Data, der.DataSize, 0, nil, nil, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob := TclCryptData.Create(size);
if not CryptDecodeObjectEx(DefaultEncoding, PKCS_RSA_PRIVATE_KEY, der.Data, der.DataSize, 0, nil, keyBlob.Data, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob.Reduce(size);
if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, 0, @FKey) then
begin
RaiseCryptError('CryptImportKey');
end;
finally
keyBlob.Free();
der.Free();
end;
end;
procedure TclCryptApiSignatureRsa.SetPublicKey(AKey: TclRsaKey);
var
key: TclByteArray;
der, keyBlob: TclCryptData;
size: DWORD;
begin
Assert(FContext <> nil);
FKeyType := AKey.KeyType;
key := AKey.GetRsaPublicKey();
if (key = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
der := nil;
keyBlob := nil;
try
der := TclCryptData.Create();
der.FromBytes(key);
size := 0;
if not CryptDecodeObjectEx(DefaultEncoding, RSA_CSP_PUBLICKEYBLOB, der.Data, der.DataSize, 0, nil, nil, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob := TclCryptData.Create(size);
if not CryptDecodeObjectEx(DefaultEncoding, RSA_CSP_PUBLICKEYBLOB, der.Data, der.DataSize, 0, nil, keyBlob.Data, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob.Reduce(size);
if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, 0, @FKey) then
begin
RaiseCryptError('CryptImportKey');
end;
finally
keyBlob.Free();
der.Free();
end;
end;
function TclCryptApiSignatureRsa.Sign: TclByteArray;
var
sig: TclCryptData;
size: DWORD;
begin
Assert(FHash <> nil);
sig := nil;
try
size := 0;
if (not CryptSignHash(FHash, FKeyType, nil, 0, nil, @size)) then
begin
RaiseCryptError('CryptSignHash');
end;
sig := TclCryptData.Create(size);
if (not CryptSignHash(FHash, FKeyType, nil, 0, sig.Data, @size)) then
begin
RaiseCryptError('CryptSignHash');
end;
sig.Reduce(size);
Result := sig.ToBytes();
Result := ReversedBytes(Result);
finally
sig.Free();
end;
end;
procedure TclCryptApiSignatureRsa.Update(const ABuffer: TclByteArray; AStart, ALen: Integer);
begin
Assert(FHash <> nil);
if not CryptHashData(FHash, Pointer(TclIntPtr(ABuffer) + AStart), ALen, 0) then
begin
RaiseCryptError('CryptHashData');
end;
end;
procedure TclCryptApiSignatureRsa.Verify(const ASignature: TclByteArray);
var
sig: TclCryptData;
sigBytes: TclByteArray;
begin
Assert(FHash <> nil);
if (FKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
sig := TclCryptData.Create();
try
sigBytes := ReversedBytes(ASignature);
sig.FromBytes(sigBytes);
if (not CryptVerifySignature(FHash, sig.Data, sig.DataSize, FKey, nil, 0)) then
begin
RaiseCryptError('CryptVerifySignature');
end;
finally
sig.Free();
end;
end;
{ TclSignatureRsaSha1 }
function TclSignatureRsaSha1.GetHashAlgorithm: ALG_ID;
begin
Result := CALG_SHA1;
end;
function TclSignatureRsaSha1.GetCSP: string;
begin
Result := MS_ENHANCED_PROV;
end;
function TclSignatureRsaSha1.GetProviderType: Integer;
begin
Result := PROV_RSA_FULL;
end;
{ TclSignatureRsaSha256 }
function TclSignatureRsaSha256.GetHashAlgorithm: ALG_ID;
begin
Result := CALG_SHA_256;
end;
function TclSignatureRsaSha256.GetCSP: string;
begin
Result := MS_ENH_RSA_AES_PROV;
end;
function TclSignatureRsaSha256.GetProviderType: Integer;
begin
Result := PROV_RSA_AES;
end;
{ TclRsaKey }
procedure TclCryptApiRsaKey.Clear;
begin
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
if (FContext <> nil) then
begin
CryptReleaseContext(FContext, 0);
FContext := nil;
end;
FreeMem(FCSPPtr);
FCSPPtr := nil;
end;
constructor TclCryptApiRsaKey.Create;
begin
inherited Create();
FContext := nil;
FKey := nil;
FKeyLength := 1024;
FKeyType := AT_KEYEXCHANGE;
end;
destructor TclCryptApiRsaKey.Destroy;
begin
Clear();
inherited Destroy();
end;
procedure TclCryptApiRsaKey.GenerateKey;
var
flags: DWORD;
begin
Assert(FContext <> nil);
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
flags := (KeyLength shl $10) or 1;
if not CryptGenKey(FContext, KeyType, flags, @FKey) then
begin
RaiseCryptError('CryptGenKey');
end;
end;
function TclCryptApiRsaKey.GetCSP: string;
begin
Result := MS_ENHANCED_PROV;
end;
function TclCryptApiRsaKey.GetCSPPtr: PclChar;
var
s: TclString;
len: Integer;
begin
Result := FCSPPtr;
if (Result <> nil) then Exit;
if (Trim(GetCSP()) <> '') then
begin
s := GetTclString(GetCSP());
len := Length(s);
GetMem(FCSPPtr, len + SizeOf(TclChar));
system.Move(PclChar(s)^, FCSPPtr^, len);
FCSPPtr[len] := #0;
end;
Result := FCSPPtr;
end;
function TclCryptApiRsaKey.GetExponent(AE: TclByteArray): DWORD;
var
len, ind: Integer;
begin
Result := 0;
len := Length(AE);
if (len = 1) then
begin
Result := AE[0];
end else
if (len = 2) then
begin
ind := 0;
Result := ByteArrayReadWord(AE, ind);
end else
if (len = 3) then
begin
ind := 0;
Result := AE[ind] shl 16;
Inc(ind);
Result := Result or ByteArrayReadWord(AE, ind);
end else
if (len > 3) then
begin
ind := 0;
Result := ByteArrayReadDWord(AE, ind);
end;
end;
function TclCryptApiRsaKey.GetRsaPrivateKey: TclByteArray;
var
key, der: TclCryptData;
len: DWORD;
begin
if (FKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
len := 0;
if not CryptExportKey(FKey, nil, PRIVATEKEYBLOB, 0, nil, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
key := nil;
der := nil;
try
key := TclCryptData.Create(len);
if not CryptExportKey(FKey, nil, PRIVATEKEYBLOB, 0, key.Data, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
key.Reduce(len);
len := 0;
if not CryptEncodeObjectEx(DefaultEncoding,
PKCS_RSA_PRIVATE_KEY, key.Data, 0, nil, nil, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der := TclCryptData.Create(len);
if not CryptEncodeObjectEx(DefaultEncoding,
PKCS_RSA_PRIVATE_KEY, key.Data, 0, nil, der.Data, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der.Reduce(len);
Result := der.ToBytes();
finally
der.Free();
key.Free();
end;
end;
function TclCryptApiRsaKey.GetProviderType: Integer;
begin
Result := PROV_RSA_FULL;
end;
function TclCryptApiRsaKey.GetRsaPublicKey: TclByteArray;
var
len: DWORD;
key, der: TclCryptData;
begin
if (FKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
len := 0;
if not CryptExportKey(FKey, nil, PUBLICKEYBLOB, 0, nil, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
key := nil;
der := nil;
try
key := TclCryptData.Create(len);
if not CryptExportKey(FKey, nil, PUBLICKEYBLOB, 0, key.Data, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
len := 0;
if not CryptEncodeObjectEx(DefaultEncoding,
RSA_CSP_PUBLICKEYBLOB, key.Data, 0, nil, nil, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der := TclCryptData.Create(len);
if not CryptEncodeObjectEx(DefaultEncoding,
RSA_CSP_PUBLICKEYBLOB, key.Data, 0, nil, der.Data, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der.Reduce(len);
Result := der.ToBytes();
finally
der.Free();
key.Free();
end;
end;
function TclCryptApiRsaKey.GetPublicKeyInfo: TclByteArray;
const
params: array[0..1] of Byte = (5, 0);
var
len: DWORD;
key, keyInfo, der: TclCryptData;
pki: PCERT_PUBLIC_KEY_INFO;
begin
if (FKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
key := nil;
keyInfo := nil;
der := nil;
try
key := TclCryptData.Create();
key.FromBytes(GetRsaPublicKey());
keyInfo := TclCryptData.Create(SizeOf(CERT_PUBLIC_KEY_INFO));
pki := PCERT_PUBLIC_KEY_INFO(keyInfo.Data);
pki.Algorithm.pszObjId := szOID_RSA_RSA;
pki.Algorithm.Parameters.cbData := 2;
pki.Algorithm.Parameters.pbData := @params;
pki.PublicKey.cbData := key.DataSize;
pki.PublicKey.pbData := key.Data;
pki.PublicKey.cUnusedBits := 0;
len := 0;
if not CryptEncodeObjectEx(DefaultEncoding,
X509_PUBLIC_KEY_INFO, keyInfo.Data, 0, nil, nil, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der := TclCryptData.Create(len);
if not CryptEncodeObjectEx(DefaultEncoding,
X509_PUBLIC_KEY_INFO, keyInfo.Data, 0, nil, der.Data, @len) then
begin
RaiseCryptError('CryptEncodeObjectEx');
end;
der.Reduce(len);
Result := der.ToBytes();
finally
der.Free();
keyInfo.Free();
key.Free();
end;
end;
procedure TclCryptApiRsaKey.GetPublicKeyParams(var AModulus, AExponent: TclByteArray);
var
len: DWORD;
ind: Integer;
rsaPubK: PRSAPUBKEY;
keyBlob: TclCryptData;
modulus: PByte;
begin
AModulus := nil;
AExponent := nil;
if (FKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
len := 0;
if not CryptExportKey(FKey, nil, PUBLICKEYBLOB, 0, nil, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
keyBlob := TclCryptData.Create(len);
try
if not CryptExportKey(FKey, nil, PUBLICKEYBLOB, 0, keyBlob.Data, @len) then
begin
RaiseCryptError('CryptExportKey');
end;
rsaPubK := PRSAPUBKEY(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER));
SetLength(AExponent, 4);
ind := 0;
ByteArrayWriteDWord(rsaPubK.pubexp, AExponent, ind);
AExponent := UnfoldBytesWithZero(AExponent);
modulus := PByte(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER) + SizeOf(RSAPUBKEY));
SetLength(AModulus, rsaPubK.bitlen div 8);
System.Move(modulus^, AModulus[0], Length(AModulus));
AModulus := ReversedBytes(AModulus);
finally
keyBlob.Free();
end;
end;
procedure TclCryptApiRsaKey.Init;
begin
Clear();
if not CryptAcquireContext(@FContext, nil, GetCSPPtr(), GetProviderType(), CRYPT_VERIFYCONTEXT) then
begin
RaiseCryptError('CryptAcquireContext');
end;
end;
procedure TclCryptApiRsaKey.LoadKeyInfo;
var
hKey: HCRYPTKEY;
data: TclCryptData;
len: Integer;
begin
hKey := nil;
try
if CryptGetUserKey(FContext, AT_KEYEXCHANGE, @hKey) then
begin
FKeyType := AT_KEYEXCHANGE;
end else
if CryptGetUserKey(FContext, AT_SIGNATURE, @hKey) then
begin
FKeyType := AT_SIGNATURE;
end;
finally
if (hKey <> nil) then
begin
CryptDestroyKey(hKey);
end;
end;
data := TclCryptData.Create(256);
try
len := data.DataSize;
if CryptGetKeyParam(FKey, KP_KEYLEN, data.Data, @len, 0) then
begin
if (len >= 4) then
begin
FKeyLength := DWORD(Pointer(data.Data)^);
end;
end;
finally
data.Free();
end;
end;
procedure TclCryptApiRsaKey.SetPublicKeyInfo(const AKey: TclByteArray);
var
der, keyBlob: TclCryptData;
size: DWORD;
begin
Assert(FContext <> nil);
if (AKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
der := nil;
keyBlob := nil;
try
der := TclCryptData.Create();
der.FromBytes(AKey);
size := 0;
if not CryptDecodeObjectEx(DefaultEncoding, X509_PUBLIC_KEY_INFO, der.Data, der.DataSize, 0, nil, nil, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob := TclCryptData.Create(size);
if not CryptDecodeObjectEx(DefaultEncoding, X509_PUBLIC_KEY_INFO, der.Data, der.DataSize, 0, nil, keyBlob.Data, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob.Reduce(size);
if not CryptImportPublicKeyInfoEx(FContext, DefaultEncoding,
PCERT_PUBLIC_KEY_INFO(keyBlob.Data), 0, 0, nil, @FKey) then
begin
RaiseCryptError('CryptImportPublicKeyInfoEx');
end;
finally
keyBlob.Free();
der.Free();
end;
LoadKeyInfo();
end;
procedure TclCryptApiRsaKey.SetPublicKeyParams(const AModulus, AExponent: TclByteArray);
var
keyBlob: TclCryptData;
keyBlobLen: Integer;
blobHdr: PBLOBHEADER;
rsaPubK: PRSAPUBKEY;
modulus: PByte;
unfoldedModulus: TclByteArray;
begin
unfoldedModulus := UnfoldBytesWithZero(AModulus);
Assert(FContext <> nil);
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
keyBlobLen := SizeOf(BLOBHEADER) + SizeOf(RSAPUBKEY) + Length(unfoldedModulus);
keyBlob := TclCryptData.Create(keyBlobLen);
try
blobHdr := PBLOBHEADER(keyBlob.Data);
blobHdr.bType := PUBLICKEYBLOB;
blobHdr.bVersion := CUR_BLOB_VERSION;
blobHdr.reserved := 0;
blobHdr.aiKeyAlg := CALG_RSA_KEYX;
rsaPubK := PRSAPUBKEY(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER));
rsaPubK.magic := $31415352; //for RSA1
rsaPubK.bitlen := Length(unfoldedModulus) * 8;
rsaPubK.pubexp := GetExponent(AExponent);
modulus := PByte(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER) + SizeOf(RSAPUBKEY));
unfoldedModulus := ReversedBytes(unfoldedModulus);
System.Move(unfoldedModulus[0], modulus^, Length(unfoldedModulus));
if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, 0, @FKey) then
begin
RaiseCryptError('CryptImportKey');
end;
finally
keyBlob.Free();
end;
end;
procedure TclCryptApiRsaKey.SetRsaPrivateKey(const AKey: TclByteArray);
var
der, keyBlob: TclCryptData;
size: DWORD;
begin
Assert(FContext <> nil);
if (AKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
der := nil;
keyBlob := nil;
try
der := TclCryptData.Create();
der.FromBytes(AKey);
size := 0;
if not CryptDecodeObjectEx(DefaultEncoding, PKCS_RSA_PRIVATE_KEY, der.Data, der.DataSize, 0, nil, nil, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob := TclCryptData.Create(size);
if not CryptDecodeObjectEx(DefaultEncoding, PKCS_RSA_PRIVATE_KEY, der.Data, der.DataSize, 0, nil, keyBlob.Data, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob.Reduce(size);
if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, CRYPT_EXPORTABLE, @FKey) then
begin
RaiseCryptError('CryptImportKey');
end;
finally
keyBlob.Free();
der.Free();
end;
LoadKeyInfo();
end;
procedure TclCryptApiRsaKey.SetRsaPublicKey(const AKey: TclByteArray);
var
der, keyBlob: TclCryptData;
size: DWORD;
begin
Assert(FContext <> nil);
if (AKey = nil) then
begin
RaiseCryptError(CryptKeyRequired, CryptKeyRequiredCode);
end;
if (FKey <> nil) then
begin
CryptDestroyKey(FKey);
FKey := nil;
end;
der := nil;
keyBlob := nil;
try
der := TclCryptData.Create();
der.FromBytes(AKey);
size := 0;
if not CryptDecodeObjectEx(DefaultEncoding, RSA_CSP_PUBLICKEYBLOB, der.Data, der.DataSize, 0, nil, nil, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob := TclCryptData.Create(size);
if not CryptDecodeObjectEx(DefaultEncoding, RSA_CSP_PUBLICKEYBLOB, der.Data, der.DataSize, 0, nil, keyBlob.Data, @size) then
begin
RaiseCryptError('CryptDecodeObjectEx');
end;
keyBlob.Reduce(size);
if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, CRYPT_EXPORTABLE, @FKey) then
begin
RaiseCryptError('CryptImportKey');
end;
finally
keyBlob.Free();
der.Free();
end;
LoadKeyInfo();
end;
end.
|
unit DAO.UsuariosBaseEntregador;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Dialogs, Model.UsuariosBaseEntregador;
type
TUsuariosBaseEntregadorDAO = class
private
FConexao : TConexao;
public
constructor Create;
function Inserir(AUsuarios: TUsuariosBaseEntregador): Boolean;
function Alterar(AUsuarios: TUsuariosBaseEntregador): Boolean;
function Excluir(AUsuarios: TUsuariosBaseEntregador): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'tbusuariosagentes';
implementation
{ TUsuariosBaseEntregadorDAO }
function TUsuariosBaseEntregadorDAO.Alterar(AUsuarios: TUsuariosBaseEntregador): Boolean;
var
FDQuery : TFDQuery;
begin
try
REsult := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET '+
'COD_USUARIO = :pCOD_USUARIO, COD_AGENTE = :pCOD_AGENTE, COD_ENTREGADOR = :pCOD_ENTREGADOR ' +
'WHERE ID_USUARIO_AGENTE = :pID_USUARIO_AGENTE;', [aUsuarios.Usuario, aUsuarios.Agente, aUsuarios.Entregador,
aUsuarios.ID]);
Result := True;
finally
FDQuery.Free;
FConexao.Free;
end;
end;
constructor TUsuariosBaseEntregadorDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TUsuariosBaseEntregadorDAO.Excluir(AUsuarios: TUsuariosBaseEntregador): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE ID_USUARIO_AGENTE = :ID_USUARIO_AGENTE', [AUsuarios.ID]);
Result := True;
finally
FDquery.Free;
FConexao.Free;
end;
end;
function TUsuariosBaseEntregadorDAO.Inserir(AUsuarios: TUsuariosBaseEntregador): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' '+
'(COD_USUARIO, COD_AGENTE, COD_ENTREGADOR) ' +
'VALUES ' +
'(:pCOD_USUARIO, :pCOD_AGENTE, :pCOD_ENTREGADOR);' ,
[aUsuarios.Usuario, aUsuarios.Agente, aUsuarios.Entregador]);
Result := True;
finally
FDQuery.Free;
FConexao.Free;
end;
end;
function TUsuariosBaseEntregadorDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('WHERE ID_USUARIO_AGENTE = :ID_USUARIO_AGENTE');
FDQuery.ParamByName('COD_USUARIO_AGENTE').AsInteger := aParam[1];
end;
if aParam[0] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE COD_USUARIO = :COD_USUARIO');
FDQuery.ParamByName('COD_USUARIO').AsInteger := aParam[1];
end;
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE');
FDQuery.ParamByName('COD_AGENTE').Value := aParam[1];
end;
if aParam[0] = 'ENTREGADOR' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR LIKE :COD_ENTREGADOR');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
end.
|
PROGRAM PrintHello(INPUT, OUTPUT);
USES DOS;
VAR
Name: STRING;
BEGIN
WRITELN('Content-Type: text/plain');
WRITELN;
Name := GetEnv('QUERY_STRING');
IF POS('name=', Name) <> 0
THEN
IF POS('&', Name) > 0
THEN
WRITELN('Hello dear ', COPY(Name, 6, POS('&', Name) - 6))
ELSE
WRITELN('Hello dear ', COPY(Name, 6, LENGTH(Name) - 4))
ELSE
WRITELN('Hello anonymous')
END.
|
//
// ABPeoplePickerC.h
// AddressBook Framework
//
// Copyright (c) 2003 Apple Computer. All rights reserved.
//
{ Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, 2004 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit ABPeoplePicker;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,ABAddressBook,CFBase,CFArray,CGGeometry,Drag,HIObjectCore,HIGeometry;
{$ALIGN MAC68K}
type
ABPickerRef = ^SInt32;
{
* Picker creation and manipulation
}
// Creates an ABPickerRef. Release with CFRelease(). The window is created hidden. Call
// ABPickerSetVisibility() to show it.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCreate: ABPickerRef; external name '_ABPickerCreate';
// Change the structural frame of the window.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSetFrame( inPicker: ABPickerRef; const (*var*) inFrame: HIRect ); external name '_ABPickerSetFrame';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerGetFrame( inPicker: ABPickerRef; var outFrame: HIRect ); external name '_ABPickerGetFrame';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSetVisibility( inPicker: ABPickerRef; visible: Boolean ); external name '_ABPickerSetVisibility';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerIsVisible( inPicker: ABPickerRef ): Boolean; external name '_ABPickerIsVisible';
{
* Look and Feel
}
const
// Choose the selection behavior for the value column. If multiple behaviors are selected,
// the most restrictive behavior will be used. Defaults to kABPickerSingleValueSelection set
// to TRUE.
kABPickerSingleValueSelection = 1 shl 0; // Allow user to choose a single value for a person.
kABPickerMultipleValueSelection = 1 shl 1; // Allow user to choose multiple values for a person.
// Allow the user to select entire groups in the group column. If false, at least one
// person in the group will be selected. Defaults to FALSE.
kABPickerAllowGroupSelection = 1 shl 2;
// Allow the user to select more than one group/record at a time. Defaults to TRUE.
kABPickerAllowMultipleSelection = 1 shl 3;
type ABPickerAttributes = OptionBits;
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerGetAttributes( inPicker: ABPickerRef ): ABPickerAttributes; external name '_ABPickerGetAttributes';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerChangeAttributes( inPicker: ABPickerRef; inAttributesToSet: ABPickerAttributes; inAttributesToClear: ABPickerAttributes ); external name '_ABPickerChangeAttributes';
{
* Value column
}
// These methods control what data (if any) is shown in the values column. The column will only
// display if an AB property is added. A popup button in the column header will be used if more
// than one property is added. Titles for built in properties will localized automatically. A
// list of AB properties can be found in <AddressBook/ABGlobals.h>.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerAddProperty( inPicker: ABPickerRef; inProperty: CFStringRef ); external name '_ABPickerAddProperty';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerRemoveProperty( inPicker: ABPickerRef; inProperty: CFStringRef ); external name '_ABPickerRemoveProperty';
// Returns an array of AB Properties as CFStringRefs.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopyProperties( inPicker: ABPickerRef ): CFArrayRef; external name '_ABPickerCopyProperties';
// Localized titles for third party properties should be set with these methods.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSetColumnTitle( inPicker: ABPickerRef; inTitle: CFStringRef; inProperty: CFStringRef ); external name '_ABPickerSetColumnTitle';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopyColumnTitle( inPicker: ABPickerRef; inProperty: CFStringRef ): CFStringRef; external name '_ABPickerCopyColumnTitle';
// Display one of the properties added above in the values column.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSetDisplayedProperty( inPicker: ABPickerRef; inProperty: CFStringRef ); external name '_ABPickerSetDisplayedProperty';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopyDisplayedProperty( inPicker: ABPickerRef ): CFStringRef; external name '_ABPickerCopyDisplayedProperty';
{
* Selection
}
// Returns group column selection as an array of ABGroupRef objects.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopySelectedGroups( inPicker: ABPickerRef ): CFArrayRef; external name '_ABPickerCopySelectedGroups';
// Returns names column selection as an array of ABGroupRef or ABPersonRef objects.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopySelectedRecords( inPicker: ABPickerRef ): CFArrayRef; external name '_ABPickerCopySelectedRecords';
// This method returns an array of selected multi-value identifiers. Returns nil if the displayed
// property is a single value type.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopySelectedIdentifiers( inPicker: ABPickerRef; inPerson: ABPersonRef ): CFArrayRef; external name '_ABPickerCopySelectedIdentifiers';
// Returns an array containing CFStringRefs for each item selected in the values column.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerCopySelectedValues( inPicker: ABPickerRef ): CFArrayRef; external name '_ABPickerCopySelectedValues';
// Select group/name/value programatically.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSelectGroup( inPicker: ABPickerRef; inGroup: ABGroupRef; inExtendSelection: Boolean ); external name '_ABPickerSelectGroup';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSelectRecord( inPicker: ABPickerRef; inRecord: ABRecordRef; inExtendSelection: Boolean ); external name '_ABPickerSelectRecord';
// Individual values contained within an multi-value property can be selected with this method.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSelectIdentifier( inPicker: ABPickerRef; inPerson: ABPersonRef; inIdentifier: CFStringRef; inExtendSelection: Boolean ); external name '_ABPickerSelectIdentifier';
// Remove selection
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerDeselectGroup( inPicker: ABPickerRef; inGroup: ABGroupRef ); external name '_ABPickerDeselectGroup';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerDeselectRecord( inPicker: ABPickerRef; inRecord: ABRecordRef ); external name '_ABPickerDeselectRecord';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerDeselectIdentifier( inPicker: ABPickerRef; inPerson: ABPersonRef; inIdentifier: CFStringRef ); external name '_ABPickerDeselectIdentifier';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerDeselectAll( inPicker: ABPickerRef ); external name '_ABPickerDeselectAll';
{
* Events and Actions
*
* Your delegate will be notified when the user changes the selection or displayed property of the picker.
* Picker events have an event class of kEventClassABPeoplePicker and one of the kinds listed below. Picker
* events contain an event parameter which contains the ABPickerRef. To obtain this:
*
* GetEventParameter(inEvent, kEventParamABPickerRef,
* typeCFTypeRef, NULL, sizeof(ABPickerRef),
* NULL, &outPickerRef);
*
}
const
// Carbon Event class for People Picker
kEventClassABPeoplePicker = FourCharCode('abpp');
const
// Carbon Event kinds for People Picker
kEventABPeoplePickerGroupSelectionChanged = 1;
kEventABPeoplePickerNameSelectionChanged = 2;
kEventABPeoplePickerValueSelectionChanged = 3;
kEventABPeoplePickerDisplayedPropertyChanged = 4;
kEventABPeoplePickerGroupDoubleClicked = 5;
kEventABPeoplePickerNameDoubleClicked = 6;
const
// Carbon Event parameter name
kEventParamABPickerRef = FourCharCode('abpp');
// Set the event handler for People Picker events.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSetDelegate( inPicker: ABPickerRef; inDelegate: HIObjectRef ); external name '_ABPickerSetDelegate';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
function ABPickerGetDelegate( inPicker: ABPickerRef ): HIObjectRef; external name '_ABPickerGetDelegate';
// Clear the search field and reset the list of displayed names.
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerClearSearchField( inPicker: ABPickerRef ); external name '_ABPickerClearSearchField';
// Launch AddressBook and edit the current selection
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerEditInAddressBook( inPicker: ABPickerRef ); external name '_ABPickerEditInAddressBook';
// AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
procedure ABPickerSelectInAddressBook( inPicker: ABPickerRef ); external name '_ABPickerSelectInAddressBook';
end.
|
unit define_data_163;
interface
type
TDealDayDataHeadName_163 = (
headNone,
headDay,
headCode,
headName,
headPrice_Close,
headPrice_High,
headPrice_Low,
headPrice_Open,
headPrice_PrevClose,
headPrice_Change,
headPrice_ChangeRate,
headDeal_VolumeRate,
headDeal_Volume,
headDeal_Amount,
headTotal_Value,
headDeal_Value);
const
Base163DayUrl1 = 'http://quotes.money.163.com/service/chddata.html?';
// 上证指数
// http://quotes.money.163.com/service/chddata.html?
// code=0000001&start=19901219&end=20160219&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER';
// code=1399300 沪深 300
DealDayDataHeadNames_163: array[TDealDayDataHeadName_163] of string = ('',
'日期', '股票代码', '名称',
'收盘价', '最高价', '最低价', '开盘价', '前收盘',
'涨跌额', '涨跌幅', '换手率', '成交量',
'成交金额', '总市值', '流通市值');
implementation
end.
|
unit Model.CadastroPessoas;
interface
uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, Control.Sistema;
type
TCadastroGeral= class
private
FAcao: TAcao;
FNomePai: String;
FDataRG: TDate;
FNaturalidade: String;
FRG: String;
FNascimento: TDate;
FEstadoCivil: String;
FValidadeCNH: TDate;
FUFNaturalidade: String;
FUFRG: String;
FCPF: String;
FRegistroCNH: String;
FID: Integer;
FImagem: String;
FUFCNH: String;
FPrimeiraCNH: TDate;
FDataCadastro: TDateTime;
FNomeMae: String;
FUsuario: Integer;
FSexo: Integer;
FNome: String;
FCategoriaCNH: String;
FNumeroCNH: String;
FCodigoSegurancaCNH: String;
FExpedidor: String;
FDataEmissaoCNH: TDate;
FConexao: TConexao;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
property ID: Integer read FID write FID;
property Nome: String read FNome write FNome;
property CPF: String read FCPF write FCPF;
property RG: String read FRG write FRG;
property Expedidor: String read FExpedidor write FExpedidor;
property DataRG: TDate read FDataRG write FDataRG;
property UFRG: String read FUFRG write FUFRG;
property Nascimento: TDate read FNascimento write FNascimento;
property NomePai: String read FNomePai write FNomePai;
property NomeMae: String read FNomeMae write FNomeMae;
property Naturalidade: String read FNaturalidade write FNaturalidade;
property UFNaturalidade: String read FUFNaturalidade write FNaturalidade;
property CodigoSegurancaCNH: String read FCodigoSegurancaCNH write FCodigoSegurancaCNH;
property NumeroCNH: String read FNumeroCNH write FNumeroCNH;
property RegistroCNH: String read FRegistroCNH write FRegistroCNH;
property ValidadeCNH: TDate read FValidadeCNH write FValidadeCNH;
property CategoriaCNH: String read FCategoriaCNH write FCategoriaCNH;
property PrimeiraCNH: TDate read FPrimeiraCNH write FPrimeiraCNH;
property UFCNH: String read FUFCNH write FUFCNH;
property DataEmissaoCNH: TDate read FDataEmissaoCNH write FDataEmissaoCNH;
property Sexo: Integer read FSexo write FSexo;
property EstadoCivil: String read FEstadoCivil write FEstadoCivil;
property DataCadastro: TDateTime read FDataCadastro write FDataCadastro;
property Usuario: Integer read FUsuario write FUsuario;
property Imagem: String read FImagem write FImagem;
property Acao: TAcao read FAcao write FAcao;
function GetID(): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
const
TABLENAME = 'cadastro_pessoas';
implementation
{ TCadastroGeral }
function TCadastroGeral.Alterar: Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set ' +
'nom_nome = :nom_nome, num_cpf = :num_cpf, num_rg = :num_rg,des_expedidor = :des_expedidor, ' +
'dat_emissao_rg = :dat_emissao_rg, uf_expedidor_rg = :uf_expedidor_rg, ' +
'dat_nascimento = :dat_nascimento, nom_pai = :nom_pai, nom_mae = :nom_mae, ' +
'des_naturalidade = :des_naturalidade, uf_naturalidade = :uf_naturalidade, ' +
'cod_seguranca_cnh = :cod_seguranca_cnh, num_registro_cnh = :num_registro_cnh, ' +
'dat_validade_cnh = :dat_validade_cnh, des_categoria = :des_categoria, ' +
'dat_emissao_cnh = :dat_emissao_cnh, dat_primeira_cnh = :dat_primeira_cnh, uf_cnh = :uf_cnh, ' +
'cod_sexo = :cod_sexo, des_estado_civil = :des_estado_civil, dat_cadastro = :dat_cadastro, ' +
'cod_usuario = :cod_usuario, des_imagem = :des_imagem ' +
'where id_cadastro = :id_cadastro;',
[Self.Nome, Self.CPF, Self.RG, Self.Expedidor, Self.DataRG, Self.UFRG, Self.Nascimento,
Self.NomePai, Self.NomeMae, Self.Naturalidade, Self.UFNaturalidade, Self.CodigoSegurancaCNH,
Self.RegistroCNH, Self.ValidadeCNH, Self.CategoriaCNH, Self.DataEmissaoCNH, Self.PrimeiraCNH,
Self.UFCNH, Self.Sexo, Self.EstadoCivil, Self.DataCadastro, Self.Usuario, Self.Imagem, Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGeral.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_cadastro = :id_cadastro', [Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TCadastroGeral.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_cadastro),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGeral.Gravar: Boolean;
begin
case FAcao of
tacIncluir: Result := Self.Inserir();
tacAlterar: Result := Self.Alterar();
tacExcluir: Result := Self.Excluir();
end;
end;
function TCadastroGeral.Inserir: Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
Self.ID := GetId();
FDQuery.ExecSQL('insert into ' + TABLENAME +
'(id_cadastro, nom_nome, num_cpf, num_rg, des_expedidor, dat_emissao_rg, uf_expedidor_rg, dat_nascimento, ' +
'nom_pai, nom_mae, des_naturalidade, uf_naturalidade, cod_seguranca_cnh, num_registro_cnh, dat_validade_cnh, ' +
'des_categoria, dat_emissao_cnh, dat_primeira_cnh, uf_cnh, cod_sexo, des_estado_civil, dat_cadastro, '+
'cod_usuario, des_imagem) ' +
'values ' +
'(:pid_cadastro, :pnom_nome, :pnum_cpf, :pnum_rg, :pdes_expedidor, :pdat_emissao_rg, :puf_expedidor_rg, :pdat_nascimento, ' +
':pnom_pai, :pnom_mae, :pdes_naturalidade, :puf_naturalidade, :pcod_seguranca_cnh, :pnum_registro_cnh, :pdat_validade_cnh, ' +
':pdes_categoria, :pdat_emissao_cnh, :pdat_primeira_cnh, :puf_cnh, :pcod_sexo, :pdes_estado_civil, :pdat_cadastro, '+
':pcod_usuario, :pdes_imagem) ',
[Self.ID, Self.Nome, Self.CPF, Self.RG, Self.Expedidor, Self.DataRG, Self.UFRG, Self.Nascimento,
Self.NomePai, Self.NomeMae, Self.Naturalidade, Self.UFNaturalidade, Self.CodigoSegurancaCNH,
Self.RegistroCNH, Self.ValidadeCNH, Self.CategoriaCNH, Self.DataEmissaoCNH, Self.PrimeiraCNH, Self.UFCNH,
Self.Sexo, Self.EstadoCivil, Self.DataCadastro, Self.Usuario, Self.Imagem]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGeral.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_cadastro = :id_cadastro');
FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1];
end;
if aParam[0] = 'RG' then
begin
FDQuery.SQL.Add('where um_rg = :um_rg');
FDQuery.ParamByName('um_rg').AsString := aParam[1];
end;
if aParam[0] = 'CPFCNPJ' then
begin
FDQuery.SQL.Add('where num_cpf = :num_cpf');
FDQuery.ParamByName('num_cpf').AsString := aParam[1];
end;
if aParam[0] = 'SEGCNH' then
begin
FDQuery.SQL.Add('where cod_seguranca_cnh = :cod_seguranca_cnh');
FDQuery.ParamByName('cod_seguranca_cnh').AsString := aParam[1];
end;
if aParam[0] = 'REGISTROCNH' then
begin
FDQuery.SQL.Add('where num_registro_cnh = :num_registro_cnh');
FDQuery.ParamByName('num_registro_cnh').AsString := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('where nom_nome_razao LIKE :nom_nome_razao');
FDQuery.ParamByName('nom_nome_razao').AsString := aParam[1];
end;
if aParam[0] = 'ALIAS' then
begin
FDQuery.SQL.Add('where nom_fantasia LIKE :nom_fantasia');
FDQuery.ParamByName('nom_fantasia').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
end.
|
unit fQuickSearch;
{
Copyright 2012 Document Storage Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ORDtTm, ExtCtrls, ComCtrls,
JvExControls, JvButton, JvTransparentButton;
type
TfrmQuickSearch = class(TForm)
Panel1: TPanel;
Image2: TImage;
ordbStartDate: TORDateBox;
Panel2: TPanel;
Image3: TImage;
meSearchTerms: TRichEdit;
laInstructions: TMemo;
laStartDate: TStaticText;
lammddyy: TStaticText;
StaticText3: TStaticText;
ordbEndDate: TORDateBox;
buClear: TJvTransparentButton;
buSearch: TJvTransparentButton;
buClose: TJvTransparentButton;
//procedure buSearchORIGClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
//procedure buClearORIGClick(Sender: TObject);
//procedure buCloseORIGClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure buClearClick(Sender: TObject);
procedure buSearchClick(Sender: TObject);
procedure buCloseClick(Sender: TObject);
private
{ Private declarations }
public
function StripCRLF(thisSearchTermString: TCaption) : string;
end;
const
CRLF = #13#10;
INSTRUCTIONS = ' Quick Search allows you to search all document types from the specified Start Date, until Today.' + CRLF +
' The search term(s) you enter will be applied to All document types.' + CRLF + CRLF +
' Enter all desired search terms in the ''Search Terms'' box below, with each term separated from' + CRLF +
' adjacent terms by one or more spaces.'; // + CRLF +
//' 3) Indicate the search area(s) of interest by checking one or more checkboxes in the ''Apply To'' box.' + CRLF +
//' 4) Click the ''Apply Search Terms'' button.';
DEFAULT_DATE_FORMAT = '(mm/dd/yyyy)';
DATE_FORMAT = 'mm/dd/yyyy';
SEARCH_CANCELLED = 'Search Cancelled.';
NO_SEARCH_TERMS = 'Search terms are missing.';
INVALID_START_DATE = 'The Start Date is invalid.';
var
frmQuickSearch: TfrmQuickSearch;
implementation
uses fSearchCriteria, ORFn;
{$R *.dfm}
var
thisfrmSearchCriteria: fSearchCriteria.TfrmSearchCriteria;
procedure TfrmQuickSearch.buClearClick(Sender: TObject);
begin
meSearchTerms.Clear;
end;
{
procedure TfrmQuickSearch.buClearORIGClick(Sender: TObject);
begin
meSearchTerms.Clear;
end;
}
procedure TfrmQuickSearch.buCloseClick(Sender: TObject);
begin
Close;
Application.ProcessMessages;
end;
{
procedure TfrmQuickSearch.buCloseORIGClick(Sender: TObject);
begin
Close;
Application.ProcessMessages;
end;
}
function TfrmQuickSearch.StripCRLF(thisSearchTermString: TCaption) : string;
var
i: integer;
begin
for i := 0 to Length(thisSearchTermString) do
begin
//replace any carriage returns with space
if thisSearchTermString[i] = #13 then
thisSearchTermString[i] := #32;
//replace any line feeds with space
if thisSearchTermString[i] = #10 then
thisSearchTermString[i] := #32;
end;
result := thisSearchTermString;
end;
function IsValidDate(thisDateString : string; var thisDateTime : TDateTime): boolean;
var
thisFMDateTime: TFMDateTime;
begin
result := true;
try
thisDateTime := StrToDateTime(thisDateString);
thisFMDateTime := DateTimeToFMDateTime(thisDateTime);
if ((not (thisFMDateTime >= 1900101)) and (not (thisFMDateTime <= DateTimeToFMDateTime(Now)))) then
result := false;
except
on EConvertError do
begin
thisDateTime := 0;
result := false;
end;
end;
end;
procedure TfrmQuickSearch.buSearchClick(Sender: TObject);
var
thisDateTime: TDateTime;
begin
//QuickSearch - Standard Tab
if thisfrmSearchCriteria.pcSearch.ActivePageIndex = 0 then
begin
if meSearchTerms.Text = '' then
begin
MessageDlg(SEARCH_CANCELLED + CRLF + NO_SEARCH_TERMS, mtInformation, [mbOk], 0);
meSearchTerms.SetFocus;
Exit;
end;
thisfrmSearchCriteria.SearchType := STANDARD_SEARCH;
thisfrmSearchCriteria.pcSearch.ActivePage := thisfrmSearchCriteria.tsStandardSearch;
//Apply search terms to Standard Search edit boxes
thisfrmSearchCriteria.edTIUSearchTermsStd.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edProblemTextSearchTermsStd.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edConsultsSearchTermsStd.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edOrdersSearchTermsStd.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edReportsSearchTermsStd.Text := self.StripCRLF(meSearchTerms.Text);
end
else
//QuickSearch - Advanced Tab
if thisfrmSearchCriteria.pcSearch.ActivePageIndex = 1 then
begin
if meSearchTerms.Text = '' then
begin
MessageDlg(SEARCH_CANCELLED + CRLF + NO_SEARCH_TERMS, mtInformation, [mbOk], 0);
meSearchTerms.SetFocus;
Exit;
end;
if (not IsValidDate(ordbStartDate.Text, thisDateTime)) then
begin
MessageDlg(SEARCH_CANCELLED + CRLF + INVALID_START_DATE, mtInformation, [mbOk], 0);
meSearchTerms.SetFocus;
Exit;
end;
thisfrmSearchCriteria.SearchType := ADVANCED_SEARCH;
thisfrmSearchCriteria.pcSearch.ActivePage := thisfrmSearchCriteria.tsAdvancedSearch;
if self.ordbStartDate.Text <> '' then
begin
thisfrmSearchCriteria.rgTIUNoteOptionsAdv.ItemIndex := 3; //TIU Signed Notes by Date Range, checked
thisfrmSearchCriteria.rgSortByAdv.ItemIndex := 1; //Descending
thisfrmSearchCriteria.cbIncludeAddendaAdv.Checked := true; //Include Addenda
//Apply Start Dates - Advanced search
thisfrmSearchCriteria.ordbStartDateTIUAdv.Text := self.ordbStartDate.Text;
thisfrmSearchCriteria.ordbStartDateProblemTextAdv.Text := self.ordbStartDate.Text;
thisfrmSearchCriteria.ordbStartDateConsultsAdv.Text := self.ordbStartDate.Text;
thisfrmSearchCriteria.ordbStartDateOrdersAdv.Text := self.ordbStartDate.Text;
thisfrmSearchCriteria.ordbStartDateReportsAdv.Text := self.ordbStartDate.Text;
//Apply End Dates - Advanced search
thisfrmSearchCriteria.ordbEndDateTIUAdv.Text := self.ordbEndDate.Text;
thisfrmSearchCriteria.ordbEndDateProblemTextAdv.Text := self.ordbEndDate.Text;
thisfrmSearchCriteria.ordbEndDateConsultsAdv.Text := self.ordbEndDate.Text;
thisfrmSearchCriteria.ordbEndDateOrdersAdv.Text := self.ordbEndDate.Text;
thisfrmSearchCriteria.ordbEndDateReportsAdv.Text := self.ordbEndDate.Text;
//Apply search terms to Advanced Search edit boxes
thisfrmSearchCriteria.edTIUSearchTermsAdv.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edProblemTextSearchTermsAdv.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edConsultsSearchTermsAdv.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edOrdersSearchTermsAdv.Text := self.StripCRLF(meSearchTerms.Text);
thisfrmSearchCriteria.edReportsSearchTermsAdv.Text := self.StripCRLF(meSearchTerms.Text);
end;
end;
//self.buCloseClick(Sender);
///// Run the search
thisfrmSearchCriteria.sbSearchClick(nil);
end;
procedure TfrmQuickSearch.FormCreate(Sender: TObject);
begin
try
thisfrmSearchCriteria := (self.Owner as TfrmSearchCriteria); //Get a pointer to the main form
except
on E: Exception do
MessageDlg(GENERAL_EXCEPTION_MSG + ' frmQuickSearch.FormCreate()' + CRLF +
E.Message, mtInformation, [mbOk], 0);
end;
//laInstructions.Caption := INSTRUCTIONS;
ordbStartDate.Format := DATE_FORMAT;
ordbEndDate.Format := DATE_FORMAT;
ordbEndDate.Text := DateToStr(Date); //Today's date
end;
procedure TfrmQuickSearch.FormShow(Sender: TObject);
begin
//Enable the date box only if we're on the Advanced tab
if thisfrmSearchCriteria.pcSearch.ActivePageIndex = 1 then
begin
laInstructions.SetFocus; //Jaws
ordbStartDate.Clear;
laStartDate.Visible := true;
laStartDate.Enabled := true;
lammddyy.Visible := true;
lammddyy.Caption := DEFAULT_DATE_FORMAT;
ordbStartDate.Visible := true;
ordbStartDate.Enabled := true;
end
else
begin
laInstructions.SetFocus; //Jaws
laStartDate.Visible := false;
lammddyy.Visible := false;
ordbStartDate.Visible := false;
ordbStartDate.Clear;
ordbStartDate.FMDateTime := DateTimeToFMDateTime(Date);
//ordbStartDate.Enabled := false;
end;
laInstructions.SetFocus;
end;
end.
|
program frasom;
uses crt;
var num1, den1, num2, den2, num3, den3: integer;
{Inizializza le frazioni}
procedure input_dati(var num1, den1, num2, den2 :integer);
begin
write('Inserisci il numeratore del primo numero: ');
readln(num1);
repeat
write('Inserisci il denominatore del primo numero: ');
readln(den1);
until den1 <> 0;
write('Inserisci il numeratore del secondo numero: ');
readln(num2);
repeat
write('Inserisci il denominatore del secondo numero: ');
readln(den2);
until den2 <> 0;
end;
{Calcola l'M.C.D tra due numeri}
procedure mcd(a, b: integer; var c: integer);
var r: integer;
begin
r:= a mod b;
while r <> 0 do
begin;
a:=b;
b:=r;
r:=a mod b;
end;
c:=b;
end;
{Esegue l'McM tra i numeri}
procedure mcm(a, b: integer; var c: integer);
var m: integer;
begin
mcd(a, b, m);
c:=(a * b) div m;
end;
{Esegue la somma tra i numeri}
procedure somma(num1, den1, num2, den2: integer; var num3, den3: integer);
var m: integer;
begin
mcm(den1, den2, m);
den1:=m div den1;
den2:=m div den2;
num1:=den1 * num1;
num2:=den2 * num2;
num3:=num1 + num2;
den3:=m;
end;
{Riduce ai minimi termini numeratore e denominatore}
procedure riduci(var n, d: integer);
var m: integer;
begin
repeat
mcd(n, d, m);
n:=n div m;
d:=d div m;
until m = 1;
end;
{procedura per visualizzare}
procedure visualizza(num1, den1, num2, den2, num3, den3: integer);
begin
writeln('La somma tra ', num1, '/', den1, ' e ', num2, '/', den2, ' è ', num3, '/', den3);
end;
{Main}
begin
writeln('**********Somma Per Frazioni**********');
input_dati(num1, den1, num2, den2);
somma(num1, den1, num2, den2, num3, den3);
riduci(num3, den3);
visualizza(num1, den1, num2, den2, num3, den3);
readln()
end.
|
unit Base;
interface
uses DB, SysUtils, Classes, System.Generics.Collections, Rtti, System.TypInfo;
type
IBaseDados = interface
['{CA9CA227-24D2-414E-8B7D-3F89634EEFF5}']
end;
ITransacao = interface
['{7C2A1CE3-963E-4395-9471-4C615CB72076}']
end;
TTabela = class(TObject)
end;
TRecParams = record
Prop: TRttiProperty;
Campo: string;
Tabela: TTabela;
Qry: TObject;
end;
IDaoBase = interface
['{467A4493-0E3F-442E-9514-FAA8DB07AF31}']
end;
TDaoBase = class(TInterfacedObject, IDaoBase)
private
protected
//geração do sql padrao
function GerarSqlInsert (ATabela: TTabela; TipoRtti: TRttiType): string; virtual;
function GerarSqlUpdate (ATabela: TTabela; TipoRtti: TRttiType): string; virtual;
function GerarSqlDelete (ATabela: TTabela): string; virtual;
function GerarSqlSelect (ATabela: TTabela): string; virtual;
//métodos abstrados para os tipos de campos a serem utilizados nas classes filhas
procedure QryParamInteger(ARecParams: TRecParams); virtual; abstract;
procedure QryParamString(ARecParams: TRecParams); virtual; abstract;
procedure QryParamDate(ARecParams: TRecParams); virtual; abstract;
procedure QryParamCurrency(ARecParams: TRecParams); virtual; abstract;
procedure QryParamVariant(ARecParams: TRecParams); virtual; abstract;
//métodos para setar os variados tipos de campos
procedure SetaCamposInteger(ARecParams: TRecParams); virtual; abstract;
procedure SetaCamposString(ARecParams: TRecParams); virtual; abstract;
procedure SetaCamposDate(ARecParams: TRecParams); virtual; abstract;
procedure SetaCamposCurrency(ARecParams: TRecParams); virtual; abstract;
function ExecutaQuery: Integer; virtual; abstract;
procedure FechaQuery; virtual; abstract;
//configura parâmetros da query
procedure ConfiguraParametro(AProp: TRttiProperty; ACampo: string;
ATabela: TTabela; AQry: TObject; IsPK: Boolean = False); virtual;
//seta os dados da query em TTabela
procedure SetaDadosTabela(AProp: TRttiProperty; ACampo: string;
ATabela: TTabela; AQry: TObject);
public
function Inserir(ATabela: TTabela): Integer; virtual; abstract;
function Salvar(ATabela: TTabela): Integer; virtual; abstract;
function Excluir(ATabela: TTabela): Integer; virtual; abstract;
function Buscar(ATabela:TTabela): Integer; virtual; abstract;
function InTransaction: Boolean; virtual; abstract;
procedure StartTransaction; virtual; abstract;
procedure Commit; virtual; abstract;
procedure RollBack; virtual; abstract;
end;
//DAO genérico
TDaoGenerico<T: IDaoBase> = class
private
FCon: T; //classe de conexao uib, ibx, ...
procedure SetCon(const Value: T);
public
property Con: T read FCon write SetCon;
end;
implementation
uses
Atributos;
{ TDaoGenerico<T> }
procedure TDaoGenerico<T>.SetCon(const Value: T);
begin
FCon := Value;
end;
{ TDaoBase }
procedure TDaoBase.ConfiguraParametro(AProp: TRttiProperty; ACampo: string;
ATabela: TTabela; AQry: TObject ; IsPK: Boolean);
var
Params: TRecParams;
begin
Params.Prop := AProp;
Params.Campo := ACampo;
Params.Tabela := ATabela;
Params.Qry := AQry; // <--- AQUI
case AProp.PropertyType.TypeKind of
tkInt64, tkInteger:
begin
if (IsPK) and (AProp.GetValue(ATabela).AsInteger = 0) then
raise Exception.Create(Format('Campo da Chave [%s] primária não informado!',[ACampo]));
QryParamInteger(Params);
end;
tkChar, tkString, tkUString:
begin
if (IsPK) and (Trim(AProp.GetValue(ATabela).AsString) = '') then
raise Exception.Create(Format('Campo da Chave [%s] primária não informado!',[ACampo]));
QryParamString(Params);
end;
tkFloat:
begin
if (IsPK) and (AProp.GetValue(ATabela).AsVariant = 0) then
raise Exception.Create(Format('Campo da Chave [%s] primária não informado!',[ACampo]));
if CompareText(AProp.PropertyType.Name, 'TDateTime') = 0 then
QryParamDate(Params)
else
QryParamCurrency(Params);
end;
tkVariant:
begin
QryParamVariant(Params);
end;
else
raise Exception.Create('Tipo de campo não conhecido: ' +
AProp.PropertyType.ToString);
end;
end;
function TDaoBase.GerarSqlDelete(ATabela: TTabela): string;
var
Campo, Separador: string;
ASql : TStringList;
begin
ASql := TStringList.Create;
try
with ASql do
begin
Add('Delete from ' + PegaNomeTab(ATabela));
Add('Where');
Separador := '';
for Campo in PegaPks(ATabela) do
begin
Add(Separador + Campo + '= :' + Campo);
Separador := ' and ';
end;
end;
Result := ASql.Text;
finally
ASql.Free;
end;
end;
function TDaoBase.GerarSqlInsert(ATabela: TTabela; TipoRtti: TRttiType): string;
var
Separador: string;
ASql : TStringList;
PropRtti: TRttiProperty;
begin
ASql := TStringList.Create;
try
with ASql do
begin
Add('Insert into ' + PegaNomeTab(ATabela));
Add('(');
//campos da tabela
Separador := '';
for PropRtti in TipoRtti.GetProperties do
begin
Add(Separador + PropRtti.Name);
Separador := ',';
end;
Add(')');
//parâmetros
Add('Values (');
Separador := '';
for PropRtti in TipoRtti.GetProperties do
begin
Add(Separador + ':' + PropRtti.Name);
Separador := ',';
end;
Add(')');
end;
Result := ASql.text;
finally
ASql.Free;
end;
end;
function TDaoBase.GerarSqlSelect(ATabela: TTabela): string;
var
Campo, Separador: string;
ASql : TStringList;
begin
ASql := TStringList.Create;
try
with ASql do
begin
Add('Select * from ' + PegaNomeTab(ATabela));
Add('Where');
Separador := '';
for Campo in PegaPks(ATabela) do
begin
Add(Separador + Campo + '= :' + Campo);
Separador := ' and ';
end;
end;
Result := ASql.Text;
finally
ASql.Free;
end;
end;
function TDaoBase.GerarSqlUpdate(ATabela: TTabela; TipoRtti: TRttiType): string;
var
Campo, Separador: string;
ASql : TStringList;
PropRtti: TRttiProperty;
begin
ASql := TStringList.Create;
try
with ASql do
begin
Add('Update ' + PegaNomeTab(ATabela));
Add('set');
//campos da tabela
Separador := '';
for PropRtti in TipoRtti.GetProperties do
begin
Add(Separador + PropRtti.Name + '=:'+PropRtti.Name);
Separador := ',';
end;
Add('where');
//parâmetros da cláusula where
Separador := '';
for Campo in PegaPks(ATabela) do
begin
Add(Separador+ Campo + '= :' + Campo);
Separador := ' and ';
end;
end;
Result := ASql.text;
finally
ASql.Free;
end;
end;
procedure TDaoBase.SetaDadosTabela(AProp: TRttiProperty; ACampo: string;
ATabela: TTabela; AQry: TObject);
var
Params: TRecParams;
begin
Params.Prop := AProp;
Params.Campo := ACampo;
Params.Tabela := ATabela;
Params.Qry := AQry;
case AProp.PropertyType.TypeKind of
tkInt64, tkInteger:
begin
SetaCamposInteger(Params);
end;
tkChar, tkString, tkUString:
begin
SetaCamposString(Params);
end;
tkFloat:
begin
if CompareText(AProp.PropertyType.Name, 'TDateTime') = 0 then
SetaCamposDate(Params)
else
SetaCamposCurrency(Params);
end;
else
raise Exception.Create('Tipo de campo não conhecido: ' +
AProp.PropertyType.ToString);
end;
end;
end.
|
unit TestMemberSamplesUnit;
interface
uses
TestFramework, Classes, SysUtils, DateUtils,
BaseTestOnlineExamplesUnit;
type
TTestMemberSamples = class(TTestOnlineExamples)
published
procedure AddNewUser;
procedure GetUserDetails;
procedure UpdateUser;
procedure Authentication;
procedure ValidateSession;
procedure UserLicense;
procedure GetUsers;
procedure RegisterWebinar;
procedure RemoveUser;
procedure DeviceLicense;
procedure AddConfigValue;
procedure UpdateConfigValue;
procedure GetConfigValue;
procedure GetAllConfigValues;
procedure DeleteConfigValue;
end;
implementation
{ TTestMemberSamples }
uses UserParametersUnit, UserParameterProviderUnit, UserUnit, EnumsUnit,
NullableBasicTypesUnit, CommonTypesUnit;
var
FMemberId: NullableInteger;
FEMail: String;
FSessionGuid: NullableString;
FSessionId: NullableInteger;
procedure TTestMemberSamples.AddConfigValue;
var
ErrorString: String;
Key: String;
Value: String;
begin
Key := 'destination_icon_width';
Value := '32';
CheckTrue(FRoute4MeManager.User.AddConfigValue(Key, Value, ErrorString));
CheckEquals(EmptyStr, ErrorString);
Key := 'randomString_212';
Value := 'aSD23dSD@sd';
CheckTrue(FRoute4MeManager.User.AddConfigValue(Key, Value, ErrorString));
CheckEquals(EmptyStr, ErrorString);
end;
procedure TTestMemberSamples.AddNewUser;
var
Parameters: TUserParameters;
Provider: IUserParameterProvider;
ErrorString: String;
DoubleMemberId: NullableInteger;
begin
Provider := TUserParameterProvider.Create;
// need real email
FEMail := 'customer.services@store.manutd.com';
Parameters := Provider.GetParameters(FEMail);
try
// Correct adding new user. Must be success.
FMemberId := FRoute4MeManager.User.AddNewUser(Parameters, ErrorString);
CheckEquals(EmptyStr, ErrorString);
CheckTrue(FMemberId.IsNotNull);
// Repeat adding same new user. Must be error.
DoubleMemberId := FRoute4MeManager.User.AddNewUser(Parameters, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
CheckTrue(DoubleMemberId.IsNull);
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestMemberSamples.Authentication;
var
Parameters: TUserParameters;
Provider: IUserParameterProvider;
ErrorString: String;
begin
Provider := TUserParameterProvider.Create;
Parameters := Provider.GetParameters(FEMail);
try
// Authentication the incorrected user. Must be error.
FRoute4MeManager.User.Authentication(FEMail, Parameters.Password + '123',
ErrorString, FSessionId, FSessionGuid);
CheckTrue(FSessionId.IsNull);
CheckTrue(FSessionGuid.IsNull);
CheckNotEquals(EmptyStr, ErrorString);
// Authentication the corrected user. Must be success.
FRoute4MeManager.User.Authentication(FEMail, Parameters.Password,
ErrorString, FSessionId, FSessionGuid);
CheckTrue(FSessionId.IsNotNull);
CheckTrue(FSessionGuid.IsNotNull);
CheckEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestMemberSamples.DeleteConfigValue;
var
ErrorString: String;
Key: String;
begin
Key := 'destination_icon_width';
CheckTrue(FRoute4MeManager.User.DeleteConfigValue(Key, ErrorString));
CheckEquals(EmptyStr, ErrorString);
Key := 'randomString_212';
CheckTrue(FRoute4MeManager.User.DeleteConfigValue(Key, ErrorString));
CheckEquals(EmptyStr, ErrorString);
Key := 'unexisting_key';
CheckFalse(FRoute4MeManager.User.DeleteConfigValue(Key, ErrorString));
CheckNotEquals(EmptyStr, ErrorString);
end;
procedure TTestMemberSamples.DeviceLicense;
var
ErrorString: String;
DeviceId: String;
DeviceType: TDeviceType;
begin
DeviceId := 'random string';
DeviceType := TDeviceType.IPad;
// Undefined DeviceId. Must be error.
CheckFalse(FRoute4MeManager.User.DeviceLicense(DeviceId, DeviceType, ErrorString));
CheckNotEquals(EmptyStr, ErrorString);
{ DONE: For some unknown reason it doesn't work.
// Registered DeviceId. Must be success.
DeviceId := '546546516';
CheckTrue(FRoute4MeManager.User.DeviceLicense(DeviceId, DeviceType, ErrorString));
CheckEquals(EmptyStr, ErrorString);}
end;
procedure TTestMemberSamples.GetAllConfigValues;
var
ErrorString: String;
Values: TListStringPair;
begin
Values := FRoute4MeManager.User.GetAllConfigValues(ErrorString);
CheckEquals(EmptyStr, ErrorString);
CheckNotNull(Values);
CheckTrue(Values.Count > 0);
end;
procedure TTestMemberSamples.GetConfigValue;
var
ErrorString: String;
Key: String;
Value: NullableString;
begin
Key := 'destination_icon_width';
Value := FRoute4MeManager.User.GetConfigValue(Key, ErrorString);
CheckEquals(EmptyStr, ErrorString);
CheckTrue(Value.IsNotNull);
CheckEquals('78', Value.Value);
Key := 'randomString_212';
Value := FRoute4MeManager.User.GetConfigValue(Key, ErrorString);
CheckEquals(EmptyStr, ErrorString);
CheckTrue(Value.IsNotNull);
CheckEquals('aSD23dSD@sd', Value.Value);
Key := 'unexisting_key';
Value := FRoute4MeManager.User.GetConfigValue(Key, ErrorString);
CheckEquals(EmptyStr, ErrorString);
CheckTrue(Value.IsNull);
end;
procedure TTestMemberSamples.GetUserDetails;
var
ErrorString: String;
User: TUser;
begin
CheckTrue(FMemberId.IsNotNull);
// Get details of unexisting user. Must be error.
User := FRoute4MeManager.User.Get(-1, ErrorString);
CheckNull(User);
CheckNotEquals(EmptyStr, ErrorString);
// Get details of correct user. Must be success.
User := FRoute4MeManager.User.Get(FMemberId, ErrorString);
CheckNotNull(User);
CheckTrue(User.MemberId = FMemberId);
CheckEquals(EmptyStr, ErrorString);
end;
procedure TTestMemberSamples.GetUsers;
var
ErrorString: String;
Users: TUserList;
begin
// Must be success.
Users := FRoute4MeManager.User.Get(ErrorString);
try
CheckEquals(EmptyStr, ErrorString);
CheckTrue(Users.Count > 0);
finally
FreeAndNil(Users);
end;
end;
procedure TTestMemberSamples.RegisterWebinar;
var
ErrorString: String;
FirstName, LastName, Phone, Company: String;
StartDate: TDateTime;
begin
FirstName := 'Mmmmm';
LastName := 'Ccccc';
Phone := '454-454544';
Company := 'c_name';
StartDate := IncDay(Now, 1);
// Unexisting MemberId. Must be error.
CheckFalse(FRoute4MeManager.User.RegisterWebinar(FEmail, FirstName, LastName,
Phone, Company, -1, StartDate, ErrorString));
CheckEquals(EmptyStr, ErrorString);
{ DONE: For some unknown reason it doesn't work.
// Must be success.
CheckTrue(FRoute4MeManager.User.RegisterWebinar(FEmail, FirstName, LastName,
Phone, Company, FMemberId, StartDate, ErrorString));
CheckEquals(EmptyStr, ErrorString);}
end;
procedure TTestMemberSamples.RemoveUser;
var
ErrorString: String;
begin
// Removing existing user. Must be success.
CheckTrue(FRoute4MeManager.User.Remove(FMemberId, ErrorString));
CheckEquals(EmptyStr, ErrorString);
// Removing unexisting user. Must be error.
CheckFalse(FRoute4MeManager.User.Remove(FMemberId, ErrorString));
CheckNotEquals(EmptyStr, ErrorString);
end;
procedure TTestMemberSamples.UpdateConfigValue;
var
ErrorString: String;
Key: String;
Value: String;
begin
Key := 'destination_icon_width';
Value := '78';
CheckTrue(FRoute4MeManager.User.UpdateConfigValue(Key, Value, ErrorString));
CheckEquals(EmptyStr, ErrorString);
{ Key := 'unexisting_key';
Value := '123';
// todo 5: возвращает почему-то, что все в порядке, спросил Олега.
// Теперь новое поведение: сервер возвращает, что операция выполнена успешно,
// и при этом добавляет этот ключ со значением в базу. Спросил Олега. Тест закомментировал, чтобы последующие тесты вели себя корректно.
CheckTrue(FRoute4MeManager.User.UpdateConfigValue(Key, Value, ErrorString));
CheckEquals(EmptyStr, ErrorString);}
end;
procedure TTestMemberSamples.UpdateUser;
var
Parameters: TUserParameters;
Provider: IUserParameterProvider;
ErrorString: String;
begin
Provider := TUserParameterProvider.Create;
Parameters := Provider.GetParameters(FEMail);
try
// Correct updating new user. Must be success.
Parameters.FirstName := 'John';
Parameters.MemberId := FMemberId;
FRoute4MeManager.User.Update(Parameters, ErrorString);
CheckEquals(EmptyStr, ErrorString);
Parameters.MemberId := -1;
// Updating unexisting user. Must be error.
FRoute4MeManager.User.Update(Parameters, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
finally
FreeAndNil(Parameters);
end;
end;
procedure TTestMemberSamples.UserLicense;
var
ErrorString: String;
DeviceId: String;
DeviceType: TDeviceType;
Subscription: String;
Token: String;
Payload: String;
begin
DeviceId := 'random string';
DeviceType := TDeviceType.IPad;
Subscription := 'IPAD_MONTHLY';
Token := '4/P7q7W91a-oMsCeLvIaQm6bTrgtp7';
Payload := 'APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx';
// Undefined DeviceId. Must be error.
CheckFalse(FRoute4MeManager.User.UserLicense(FMemberId, FSessionId,
DeviceId, DeviceType, Subscription, Token, Payload, ErrorString));
CheckNotEquals(EmptyStr, ErrorString);
{ DONE: For some unknown reason it doesn't work.
// Registered DeviceId. Must be success.
DeviceId := '546546516';
CheckTrue(FRoute4MeManager.User.UserLicense(FMemberId, FSessionId, DeviceId,
DeviceType, Subscription, Token, Payload, ErrorString));
CheckEquals(EmptyStr, ErrorString);}
end;
procedure TTestMemberSamples.ValidateSession;
var
ErrorString: String;
begin
CheckTrue(FSessionGuid.IsNotNull);
CheckTrue(FMemberId.IsNotNull);
{ DONE: For some unknown reason it doesn't work.
// Validate session of the corrected user. Must be success.
CheckTrue(FRoute4MeManager.User.IsSessionValid(FSessionGuid, FMemberId, ErrorString));
CheckEquals(EmptyStr, ErrorString);}
// Validate session of the incorrected session. Must be error.
CheckFalse(FRoute4MeManager.User.IsSessionValid('1' + FSessionGuid.Value, FMemberId, ErrorString));
CheckEquals(EmptyStr, ErrorString);
// Validate session of the incorrected user. Must be error.
CheckFalse(FRoute4MeManager.User.IsSessionValid(FSessionGuid, -1, ErrorString));
CheckEquals(EmptyStr, ErrorString);
end;
initialization
RegisterTest('Examples\Online\Members\', TTestMemberSamples.Suite);
FMemberId := NullableInteger.Null;
FSessionGuid := NullableString.Null;
FSessionId := NullableInteger.Null;
end.
|
unit Rule_SMA;
interface
uses
BaseRule,
BaseRuleData;
(*//
移动平均
SMA
含义:求移动平均。
用法:SMA(X,N,M),求X的N日移动平均,M为权重。
算法: 若Y=SMA(X,N,M)则 Y=[M*X+(N-M)*Y']/N,其中Y'表示上一周期Y值,N必须大于M。例如:SMA(CLOSE,30,1)表示求30日移动平均价。
SMA(X,N,M),求X的N周期移动平均,M为权重
Y=SMA(X,N,M) 则 Y=(M*X+(N-M)*Y')/N, 其中Y'表示上一周期Y值,N必须大于M
SMA(CLOSE,20,1)
说说常用的DMA,EMA,SMA和MA几个移动平均的区别
dma 动态移动平均--dma(x,a) 若y=dma(x,a) 则 y=a*x+(1-a)*y',
其中y'表示上一周期y值,a必须小于1.它与sma是一家的,看:y=m/n*x+(n-m)/n*y';y=a*x+(1-a)*y';
前者说n必须大于m,后者说a必须小于1.然后两者就一样了:a=m/n.说“a为计算周期”似乎不妥,a要取小数才行.
dma在第一根k线就开始起算,sma要到第二根k线开始起算dma(close,vol/capital)表示求以换手率作平滑因子的平均价。
ema 指数平滑移动平均--ema(x,n) 参数: x为数组,n为计算周期.n可以取到1,不过输出就没有加权的效果了.
算法: 若y=ema(x,n) 则y=[2*x+(n-1)*y']/(n+1), 其中y'表示上一周期y值.
把算法写成这个样子:y=2*x/(n+1)+(n-1)/(n+1)*y',就可以看出,当前周期数组值所占的权重是2/(n+1),
而上一周期y值所占的权重是(n-1)/(n+1).注意,这两个权重相加,结果为1:2/(n+1)+(n-1)/(n+1)=1.
sma 移动平均--sma(x,n,m) 参数:x为数组,n为计算周期,m为权重.若y=sma(x,n,m) 则 y=[m*x+(n-m)*y']/n,
其中y'表示上一周期y值,n必须大于m.把算法写成这个样子:y=m/n*x+(n-m)/n*y',就可以看出,
当前周期数组值所占的权重是m/n,而上一周期y值所占的权重是(n-m)/n.注意,这两个权重相加,
结果为1:m/n+(n-m)/n=1.看出来了吧?sma(x,n+1,2)=ema(x,n);
ma 简单移动平均--ma(x,n) 参数:x为数组,n为计算周期 说明: 求x的n日移动平均值。算法(x1+x2+x3+...+xn)/n
//*)
type
TRule_SMA = class(TBaseRule)
protected
fParamN: Word;
fParamM: Word;
fInt64Ret: PArrayInt64;
fFloatRet: PArrayDouble;
function Get_SMA_ValueF(AIndex: integer): double;
function Get_SMA_ValueI(AIndex: integer): Int64;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
function GetParamM: Word;
procedure SetParamM(const Value: Word);
procedure ComputeInt64;
procedure ComputeFloat;
public
constructor Create(ADataType: TRuleDataType = dtDouble); override;
destructor Destroy; override;
procedure Execute; override;
procedure Clear; override;
property ValueF[AIndex: integer]: double read Get_SMA_ValueF;
property ValueI[AIndex: integer]: int64 read Get_SMA_ValueI;
property ParamN: Word read GetParamN write SetParamN;
property ParamM: Word read GetParamM write SetParamM;
end;
implementation
{ TRule_SMA }
constructor TRule_SMA.Create(ADataType: TRuleDataType = dtDouble);
begin
inherited;
fParamN := 20;
fFloatRet := nil;
fInt64Ret := nil;
end;
destructor TRule_SMA.Destroy;
begin
Clear;
inherited;
end;
procedure TRule_SMA.Execute;
begin
Clear;
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
if fBaseRuleData.DataLength > 0 then
begin
case fBaseRuleData.DataType of
dtInt64: begin
ComputeInt64;
end;
dtDouble: begin
ComputeFloat;
end;
end;
end;
end;
end;
procedure TRule_SMA.Clear;
begin
CheckInArrayInt64(fInt64Ret);
CheckInArrayDouble(fFloatRet);
fBaseRuleData.DataLength := 0;
end;
procedure TRule_SMA.ComputeInt64;
var
tmpInt64_Meta: array of Int64;
i: integer;
tmpCounter: integer;
tmpValue: Int64;
begin
if Assigned(OnGetDataI) then
begin
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
SetArrayInt64Length(fInt64Ret, fBaseRuleData.DataLength);
SetLength(tmpInt64_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpInt64_Meta[i] := OnGetDataI(i);
tmpValue := tmpInt64_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpValue := tmpValue + tmpInt64_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if 1 < fParamN then
begin
if i > fParamN - 1 then
begin
tmpValue := tmpValue div fParamN;
end else
begin
tmpValue := tmpValue div (i + 1);
end;
end;
SetArrayInt64Value(fInt64Ret, i, tmpValue);
end;
end;
end;
procedure TRule_SMA.ComputeFloat;
var
tmpFloat_Meta: array of double;
i: integer;
tmpCounter: integer;
tmpDouble: Double;
begin
if Assigned(OnGetDataF) then
begin
if fFloatRet = nil then
fFloatRet := CheckOutArrayDouble;
SetArrayDoubleLength(fFloatRet, fBaseRuleData.DataLength);
SetLength(tmpFloat_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpFloat_Meta[i] := OnGetDataF(i);
tmpDouble := tmpFloat_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpDouble := tmpDouble + tmpFloat_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if fParamN > 1 then
begin
if i > fParamN - 1 then
begin
tmpDouble := tmpDouble / fParamN;
end else
begin
tmpDouble := tmpDouble / (i + 1);
end;
end;
SetArrayDoubleValue(fFloatRet, i, tmpDouble);
end;
end;
end;
function TRule_SMA.GetParamM: Word;
begin
Result := fParamM;
end;
procedure TRule_SMA.SetParamM(const Value: Word);
begin
if Value > 0 then
fParamM := Value;
end;
function TRule_SMA.GetParamN: Word;
begin
Result := fParamN;
end;
procedure TRule_SMA.SetParamN(const Value: Word);
begin
if Value > 0 then
fParamN := Value;
end;
function TRule_SMA.Get_SMA_ValueF(AIndex: integer): double;
begin
Result := 0;
if fBaseRuleData.DataType = dtDouble then
begin
if fFloatRet <> nil then
begin
Result := GetArrayDoubleValue(fFloatRet, AIndex);
end;
end;
end;
function TRule_SMA.Get_SMA_ValueI(AIndex: integer): Int64;
begin
Result := 0;
if fBaseRuleData.DataType = dtInt64 then
begin
if fInt64Ret <> nil then
begin
Result := GetArrayInt64Value(fInt64Ret, AIndex);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSManagementSetUp.Config;
interface
uses System.Classes;
type
TEMSManagementRegistry = class
public type
TConnectionProperties = record
public
ProfileName: string;
Host: string;
Port: integer;
Protocol: string;
BaseURL: string;
ProxyServer: string;
ProxyPort: integer;
end;
public type
TCredentialsProperties = record
public
ServerPassword: string;
ServerUserName: string;
UseMasterSecret: Boolean;
MasterSecret: string;
AppSecret: string;
ApplicationID: string;
GCMAppID: string;
end;
public const
sRegKeyProfiles = '\Software\Embarcadero\EMS\Profiles';
sEMSConnectionProperties = 'Default';
sLastProfUsed = 'LastProfileUsed';
sConnection = 'Connection';
sCredentials = 'Credentials';
sProfileName = 'ProfileName';
sHost = 'Host';
sPort = 'Port';
sProtocol = 'Protocol';
sBaseURL = 'BaseURL';
sProxyServer = 'ProxyServer';
sProxyPort = 'ProxyPort';
sServerPassword = 'Password';
sServerUserName = 'User';
sUseMasterSecret = 'UseMasterSevret';
sMasterSecret = 'MasterSecret';
sAppSecret = 'AppSecret';
sApplicationID = 'ApplicationID';
sGCMAppID = 'GCMAppID';
private
FFileName: String;
FRegSettingMofified: Boolean;
FConnection: TConnectionProperties;
FCredentials: TCredentialsProperties;
procedure SetConnectionRegistry(const Value: TConnectionProperties);
procedure SetCredentialsRegistry(const Value: TCredentialsProperties);
public
property Filename: String read FFileName write FFileName;
property RegSettingsMofified: Boolean read FRegSettingMofified write FRegSettingMofified;
property Connection: TConnectionProperties read FConnection write SetConnectionRegistry;
property Credentials: TCredentialsProperties read FCredentials write SetCredentialsRegistry;
function SaveProfileToRegistry(const AProfileName: string = ''): Boolean;
function SavedLastProfileUsed(const AProfileName: string): Boolean;
function SaveProfileToRegistryAs(AConnection: TConnectionProperties;
ACredentials: TCredentialsProperties; const AName: string = ''): Boolean;
function ExportProfiles: Boolean;
function SaveProfileFile(const AProfileName, ConnectionIndex: string): Boolean;
function DeleteProfileFromRegistry(const AName: string): Boolean;
function ImportProfiles: Boolean;
function LoadProfileFile(const AIndex: string): Boolean;
function LoadProfileNamesFromRegistry(var AProfilesList: TStringList): Boolean;
function LoadProfileFromRegistry(const AProfileName: string = ''): Boolean;
function GetLastProfile: string;
end;
implementation
uses System.Win.Registry, Winapi.Windows, System.IniFiles,
System.SysUtils, System.NetEncoding;
{ TEMSManagementRegistry }
function TEMSManagementRegistry.GetLastProfile: string;
var
LReg: TRegistryIniFile;
begin
Result := sEMSConnectionProperties;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
begin
Result := LReg.ReadString('', sLastProfUsed, sEMSConnectionProperties);
end
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.LoadProfileFromRegistry(const AProfileName: string = ''): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
begin
SavedLastProfileUsed(AProfileName);
FConnection.ProfileName := LReg.ReadString(LsEMSConnectionProperties, sProfileName, '');
FConnection.Host := LReg.ReadString(LsEMSConnectionProperties, sHost, '');
FConnection.Port := LReg.ReadInteger(LsEMSConnectionProperties, sPort, 0);
FConnection.Protocol := LReg.ReadString(LsEMSConnectionProperties, sProtocol, '');
FConnection.BaseURL := LReg.ReadString(LsEMSConnectionProperties, sBaseURL, '');
FConnection.ProxyServer := LReg.ReadString(LsEMSConnectionProperties, sProxyServer, '');
FConnection.ProxyPort := LReg.ReadInteger(sEMSConnectionProperties, sProxyPort, 0);
FCredentials.ServerPassword := TNetEncoding.Base64.Decode((LReg.ReadString(LsEMSConnectionProperties, sServerPassword, '')));
FCredentials.ServerUserName := LReg.ReadString(LsEMSConnectionProperties, sServerUserName, '');
FCredentials.UseMasterSecret := LReg.ReadBool(LsEMSConnectionProperties, sUseMasterSecret, False);
FCredentials.MasterSecret := LReg.ReadString(LsEMSConnectionProperties, sMasterSecret, '');
FCredentials.AppSecret := LReg.ReadString(LsEMSConnectionProperties, sAppSecret, '');
FCredentials.ApplicationID := LReg.ReadString(LsEMSConnectionProperties, sApplicationID, '');
FCredentials.GCMAppID := LReg.ReadString(LsEMSConnectionProperties, sGCMAppID, '');
Result := True;
end
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.DeleteProfileFromRegistry(const AName: string): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AName <> '' then
LsEMSConnectionProperties := AName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.EraseSection(AName);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.ImportProfiles: Boolean;
var
I, LIndex: integer;
LIndexStr: string;
LProfiles: TStringList;
begin
LProfiles := TStringList.Create;
try
LoadProfileNamesFromRegistry(LProfiles);
I := 0;
while LoadProfileFile(IntToStr(I)) do
begin
LIndex := 0;
LIndexStr := '';
while LProfiles.IndexOf(FConnection.ProfileName + LIndexStr) >= 0 do
begin
Inc(LIndex);
LIndexStr := '.' + IntToStr(LIndex)
end;
SaveProfileToRegistry(FConnection.ProfileName + LIndexStr);
Inc(I);
end;
Result := True;
finally
LProfiles.Free
end;
end;
function TEMSManagementRegistry.LoadProfileFile(const AIndex: string): Boolean;
var
LReg: TIniFile;
begin
Result := False;
LReg := TIniFile.Create(FFileName);
try
FConnection.ProfileName := LReg.ReadString(sConnection + AIndex, sProfileName, '');
FConnection.Host := LReg.ReadString(sConnection + AIndex, sHost, '');
FConnection.Port := LReg.ReadInteger(sConnection + AIndex, sPort, 0);
FConnection.Protocol := LReg.ReadString(sConnection + AIndex, sProtocol, '');
FConnection.BaseURL := LReg.ReadString(sConnection + AIndex, sBaseURL, '');
FConnection.ProxyServer := LReg.ReadString(sConnection + AIndex, sProxyServer, '');
FConnection.ProxyPort := LReg.ReadInteger(sConnection + AIndex, sProxyPort, 0);
FCredentials.ServerPassword := TNetEncoding.Base64.Decode(LReg.ReadString(sCredentials + AIndex, sServerPassword, ''));
FCredentials.ServerUserName := LReg.ReadString(sCredentials + AIndex, sServerUserName, '');
FCredentials.UseMasterSecret := LReg.ReadBool(sCredentials + AIndex, sUseMasterSecret, False);
FCredentials.MasterSecret := LReg.ReadString(sCredentials + AIndex, sMasterSecret, '');
FCredentials.AppSecret := LReg.ReadString(sCredentials + AIndex, sAppSecret, '');
FCredentials.ApplicationID := LReg.ReadString(sCredentials + AIndex, sApplicationID, '');
FCredentials.GCMAppID := LReg.ReadString(sCredentials + AIndex, sGCMAppID, '');
if FConnection.ProfileName <> '' then
Result := True;
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.LoadProfileNamesFromRegistry(var AProfilesList: TStringList): Boolean;
var
LReg: TRegistryIniFile;
begin
Result := False;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
begin
LReg.ReadSections(AProfilesList);
Result := True;
end;
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileToRegistryAs(AConnection: TConnectionProperties;
ACredentials: TCredentialsProperties; const AName: string = ''): Boolean;
begin
SetConnectionRegistry(AConnection);
SetCredentialsRegistry(ACredentials);
Result := SaveProfileToRegistry(AName);
end;
function TEMSManagementRegistry.SavedLastProfileUsed(const AProfileName: string): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.WriteString('', sLastProfUsed, AProfileName);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileToRegistry(const AProfileName: string = ''): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.WriteString('', sLastProfUsed, AProfileName);
LReg.WriteString(LsEMSConnectionProperties, sProfileName, AProfileName);
LReg.WriteString(LsEMSConnectionProperties, sHost, FConnection.Host);
LReg.WriteInteger(LsEMSConnectionProperties, sPort, FConnection.Port);
LReg.WriteString(LsEMSConnectionProperties, sProtocol, FConnection.Protocol);
LReg.WriteString(LsEMSConnectionProperties, sBaseURL, FConnection.BaseURL);
LReg.WriteString(LsEMSConnectionProperties, sProxyServer, FConnection.ProxyServer);
LReg.WriteInteger(LsEMSConnectionProperties, sProxyPort, FConnection.ProxyPort);
LReg.WriteString(LsEMSConnectionProperties, sServerPassword, TNetEncoding.Base64.Encode(FCredentials.ServerPassword));
LReg.WriteString(LsEMSConnectionProperties, sServerUserName, FCredentials.ServerUserName);
LReg.WriteBool(LsEMSConnectionProperties, sUseMasterSecret, FCredentials.UseMasterSecret);
LReg.WriteString(LsEMSConnectionProperties, sMasterSecret, FCredentials.MasterSecret);
LReg.WriteString(LsEMSConnectionProperties, sAppSecret, FCredentials.AppSecret);
LReg.WriteString(LsEMSConnectionProperties, sApplicationID, FCredentials.ApplicationID);
LReg.WriteString(LsEMSConnectionProperties, sGCMAppID, FCredentials.GCMAppID);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.ExportProfiles: Boolean;
var
I: integer;
LProfiles: TStringList;
begin
LProfiles := TStringList.Create;
try
LoadProfileNamesFromRegistry(LProfiles);
for I := 0 to LProfiles.Count - 1 do
begin
LoadProfileFromRegistry(LProfiles[I]);
SaveProfileFile(LProfiles[I], IntToStr(I));
end;
Result := True;
finally
LProfiles.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileFile(const AProfileName, ConnectionIndex: string): Boolean;
var
LReg: TIniFile;
begin
LReg := TIniFile.Create(FFileName);
try
LReg.WriteString(sConnection + ConnectionIndex, sProfileName, AProfileName);
LReg.WriteString(sConnection + ConnectionIndex, sHost, FConnection.Host);
LReg.WriteInteger(sConnection + ConnectionIndex, sPort, FConnection.Port);
LReg.WriteString(sConnection + ConnectionIndex, sProtocol, FConnection.Protocol);
LReg.WriteString(sConnection + ConnectionIndex, sBaseURL, FConnection.BaseURL);
LReg.WriteString(sConnection + ConnectionIndex, sProxyServer, FConnection.ProxyServer);
LReg.WriteInteger(sConnection + ConnectionIndex, sProxyPort, FConnection.ProxyPort);
LReg.WriteString(sCredentials + ConnectionIndex, sServerPassword, TNetEncoding.Base64.Encode(FCredentials.ServerPassword));
LReg.WriteString(sCredentials + ConnectionIndex, sServerUserName, FCredentials.ServerUserName);
LReg.WriteBool(sCredentials + ConnectionIndex, sUseMasterSecret, FCredentials.UseMasterSecret);
LReg.WriteString(sCredentials + ConnectionIndex, sMasterSecret, FCredentials.MasterSecret);
LReg.WriteString(sCredentials + ConnectionIndex, sAppSecret, FCredentials.AppSecret);
LReg.WriteString(sCredentials + ConnectionIndex, sApplicationID, FCredentials.ApplicationID);
LReg.WriteString(sCredentials + ConnectionIndex, sGCMAppID, FCredentials.GCMAppID);
Result := True;
finally
LReg.Free;
end;
end;
procedure TEMSManagementRegistry.SetConnectionRegistry(
const Value: TConnectionProperties);
begin
FConnection := Value;
end;
procedure TEMSManagementRegistry.SetCredentialsRegistry(
const Value: TCredentialsProperties);
begin
FCredentials := Value;
end;
end.
|
unit DAO.ConsumoInsumos;
interface
uses DAO.base, Model.ConsumoInsumos, Generics.Collections, System.Classes;
type TConsumoInsumosDAO = class(TDAO)
public
function Insert(aConsumo: Model.ConsumoInsumos.TConsumoInsumos): Boolean;
function Update(aConsumo: Model.ConsumoInsumos.TConsumoInsumos): Boolean;
function Delete(sFiltro: String): Boolean;
function FindConsumo(sFiltro: String): TObjectList<Model.ConsumoInsumos.TConsumoInsumos>;
end;
const
TABLENAME = 'tbconsumoinsumos';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TConsumoInsumosDAO.Insert(aConsumo: TConsumoInsumos): Boolean;
var
sSQL: String;
begin
Result := False;
aConsumo.ID := GetKeyValue(TABLENAME, 'ID_CONSUMO');
sSQL := 'INSERT INTO ' + TABLENAME + ' ' +
'(ID_CONSUMO, ID_INSUMO, DES_PLACA, DAT_CONSUMO, QTD_KM_CONSUMO, ID_CONTROLE, QTD_CONSUMO, VAL_CONSUMO, ' +
'DOM_ESTOQUE, DES_LOG) ' +
'VALUES ' +
'(:ID, :INSUMO, :PLACA, :DATA, :KM, :CONTROLE, :CONSUMO, :VALOR, :ESTOQUE, :LOG);';
Connection.ExecSQL(sSQL,[aConsumo.ID, aConsumo.Insumo, aConsumo.Placa, aConsumo.Data, aConsumo.KMConsumo, aConsumo.Controle,
aConsumo.Consumo, aConsumo.Valor, aConsumo.Estoque ,aConsumo.Log], [ftInteger, ftInteger, ftString, ftDate,
ftFloat, ftInteger, ftFloat, ftFloat, ftString, ftString]);
Result := True;
end;
function TConsumoInsumosDAO.Update(aConsumo: TConsumoInsumos): Boolean;
var
sSQL: String;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'ID_INSUMO = :INSUMO, DES_PLACA = :PLACA, DAT_CONSUMO = :DATA, QTD_KM_CONSUMO = :KM, ' +
'ID_CONTROLE = :CONTROLE, QTD_CONSUMO = :CONSUMO, VAL_CONSUMO = :VALOR, DOM_ESTOQUE = :ESTOQUE, DES_LOG = :LOG ' +
'WHERE ID_CONSUMO = :ID;';
Connection.ExecSQL(sSQL,[aConsumo.Insumo, aConsumo.Placa, aConsumo.Data, aConsumo.KMConsumo, aConsumo.Controle,
aConsumo.Consumo, aConsumo.Valor, aConsumo.Estoque, aConsumo.Log, aConsumo.ID], [ftInteger, ftString,
ftDate, ftFloat, ftInteger, ftFloat, ftFloat, ftString, ftString, ftInteger]);
Result := True;
end;
function TConsumoInsumosDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Result := True;
end;
function TConsumoInsumosDAO.FindConsumo(sFiltro: string): TObjectList<TConsumoInsumos>;
var
FDQuery: TFDQuery;
Extratos: TObjectList<TConsumoInsumos>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
Extratos := TObjectList<TConsumoInsumos>.Create();
while not FDQuery.Eof do
begin
Extratos.Add(TConsumoInsumos.Create(FDQuery.FieldByName('ID_CONSUMO').AsInteger, FDQuery.FieldByName('ID_INSUMO').AsInteger,
FDQuery.FieldByName('DES_PLACA').AsString, FDQuery.FieldByName('DAT_CONSUMO').AsDateTime,
FDQuery.FieldByName('QTD_KM_CONSUMO').AsFloat, FDQuery.FieldByName('ID_CONTROLE').AsInteger,
FDQuery.FieldByName('QTD_CONSUMO').AsFloat, FDQuery.FieldByName('VAL_CONSUMO').AsFloat,
FDQuery.FieldByName('DOM_ESTOQUE').AsString, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := Extratos;
end;
end.
|
unit ScintStylerInnoSetup;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
TInnoSetupStyler: styler for Inno Setup scripts
}
interface
uses
SysUtils, Classes, Graphics, ScintEdit;
type
{ Internally-used types }
TInnoSetupStylerParamInfo = record
Name: TScintRawString;
end;
TInnoSetupStylerSpanState = (spNone, spBraceComment, spStarComment);
TInnoSetupStylerSection = (
scNone, { Not inside a section (start of file, or last section was closed) }
scUnknown, { Inside an unrecognized section }
scThirdParty, { Inside a '_' section (reserved for third-party tools) }
scCode,
scComponents,
scCustomMessages,
scDirs,
scFiles,
scIcons,
scINI,
scInstallDelete,
scLangOptions,
scLanguages,
scMessages,
scRegistry,
scRun,
scSetup,
scTasks,
scTypes,
scUninstallDelete,
scUninstallRun);
TInnoSetupStylerStyle = (stDefault, stCompilerDirective,
stComment, stSection, stSymbol, stKeyword, stParameterValue,
stEventFunction, stConstant, stMessageArg);
TInnoSetupStyler = class(TScintCustomStyler)
private
FKeywordList: array[TInnoSetupStylerSection] of AnsiString;
procedure ApplyPendingSquigglyFromIndex(const StartIndex: Integer);
procedure ApplySquigglyFromIndex(const StartIndex: Integer);
procedure BuildKeywordListFromEnumType(const Section: TInnoSetupStylerSection;
const EnumTypeInfo: Pointer);
procedure BuildKeywordListFromParameters(const Section: TInnoSetupStylerSection;
const Parameters: array of TInnoSetupStylerParamInfo);
procedure CommitStyleSq(const Style: TInnoSetupStylerStyle;
const Squigglify: Boolean);
procedure CommitStyleSqPending(const Style: TInnoSetupStylerStyle);
function GetKeywordList(Section: TInnoSetupStylerSection): AnsiString;
procedure HandleCodeSection(var SpanState: TInnoSetupStylerSpanState);
procedure HandleKeyValueSection(const Section: TInnoSetupStylerSection);
procedure HandleParameterSection(const ValidParameters: array of TInnoSetupStylerParamInfo);
procedure PreStyleInlineISPPDirectives;
procedure SkipWhitespace;
procedure SquigglifyUntilChars(const Chars: TScintRawCharSet;
const Style: TInnoSetupStylerStyle);
procedure StyleConstsUntilChars(const Chars: TScintRawCharSet;
const NonConstStyle: TInnoSetupStylerStyle; var BraceLevel: Integer);
protected
procedure CommitStyle(const Style: TInnoSetupStylerStyle);
procedure GetStyleAttributes(const Style: Integer;
var Attributes: TScintStyleAttributes); override;
function LineTextSpans(const S: TScintRawString): Boolean; override;
procedure StyleNeeded; override;
public
constructor Create(AOwner: TComponent); override;
class function GetSectionFromLineState(const LineState: TScintLineState): TInnoSetupStylerSection;
class function IsParamSection(const Section: TInnoSetupStylerSection): Boolean;
class function IsSymbolStyle(const Style: TScintStyleNumber): Boolean;
property KeywordList[Section: TInnoSetupStylerSection]: AnsiString read GetKeywordList;
end;
implementation
uses
TypInfo;
type
TInnoSetupStylerLineState = record
Section, NextLineSection: TInnoSetupStylerSection;
SpanState: TInnoSetupStylerSpanState;
Reserved: Byte;
end;
TSetupSectionDirective = (
ssAllowCancelDuringInstall,
ssAllowNetworkDrive,
ssAllowNoIcons,
ssAllowRootDirectory,
ssAllowUNCPath,
ssAlwaysRestart,
ssAlwaysShowComponentsList,
ssAlwaysShowDirOnReadyPage,
ssAlwaysShowGroupOnReadyPage,
ssAlwaysUsePersonalGroup,
ssAppCopyright,
ssAppendDefaultDirName,
ssAppendDefaultGroupName,
ssAppComments,
ssAppContact,
ssAppId,
ssAppModifyPath,
ssAppMutex,
ssAppName,
ssAppPublisher,
ssAppPublisherURL,
ssAppReadmeFile,
ssAppSupportPhone,
ssAppSupportURL,
ssAppUpdatesURL,
ssAppVerName,
ssAppVersion,
ssArchitecturesAllowed,
ssArchitecturesInstallIn64BitMode,
ssBackColor,
ssBackColor2,
ssBackColorDirection,
ssBackSolid,
ssChangesAssociations,
ssChangesEnvironment,
ssCloseApplications,
ssCloseApplicationsFilter,
ssCompression,
ssCompressionThreads,
ssCreateAppDir,
ssCreateUninstallRegKey,
ssDefaultDialogFontName,
ssDefaultDirName,
ssDefaultGroupName,
ssDefaultUserInfoName,
ssDefaultUserInfoOrg,
ssDefaultUserInfoSerial,
ssDirExistsWarning,
ssDisableDirPage,
ssDisableFinishedPage,
ssDisableProgramGroupPage,
ssDisableReadyMemo,
ssDisableReadyPage,
ssDisableStartupPrompt,
ssDisableWelcomePage,
ssDiskClusterSize,
ssDiskSliceSize,
ssDiskSpanning,
ssDontMergeDuplicateFiles,
ssEnableDirDoesntExistWarning,
ssEncryption,
ssExtraDiskSpaceRequired,
ssFlatComponentsList,
ssInfoAfterFile,
ssInfoBeforeFile,
ssInternalCompressLevel,
ssLanguageDetectionMethod,
ssLicenseFile,
ssLZMAAlgorithm,
ssLZMABlockSize,
ssLZMADictionarySize,
ssLZMAMatchFinder,
ssLZMANumBlockThreads,
ssLZMANumFastBytes,
ssLZMAUseSeparateProcess,
ssMergeDuplicateFiles,
ssMessagesFile,
ssMinVersion,
ssOnlyBelowVersion,
ssOutputBaseFilename,
ssOutputDir,
ssOutputManifestFile,
ssPassword,
ssPrivilegesRequired,
ssReserveBytes,
ssRestartApplications,
ssRestartIfNeededByRun,
ssSetupIconFile,
ssSetupLogging,
ssShowComponentSizes,
ssShowLanguageDialog,
ssShowTasksTreeLines,
ssShowUndisplayableLanguages,
ssSignedUninstaller,
ssSignedUninstallerDir,
ssSignTool,
ssSlicesPerDisk,
ssSolidCompression,
ssSourceDir,
ssTerminalServicesAware,
ssTimeStampRounding,
ssTimeStampsInUTC,
ssTouchDate,
ssTouchTime,
ssUpdateUninstallLogAppName,
ssUninstallable,
ssUninstallDisplayIcon,
ssUninstallDisplayName,
ssUninstallDisplaySize,
ssUninstallFilesDir,
ssUninstallIconFile,
ssUninstallLogMode,
ssUninstallRestartComputer,
ssUninstallStyle,
ssUsePreviousAppDir,
ssUsePreviousGroup,
ssUsePreviousLanguage,
ssUsePreviousSetupType,
ssUsePreviousTasks,
ssUsePreviousUserInfo,
ssUseSetupLdr,
ssUserInfoPage,
ssVersionInfoCompany,
ssVersionInfoCopyright,
ssVersionInfoDescription,
ssVersionInfoProductName,
ssVersionInfoProductVersion,
ssVersionInfoProductTextVersion,
ssVersionInfoTextVersion,
ssVersionInfoVersion,
ssWindowResizable,
ssWindowShowCaption,
ssWindowStartMaximized,
ssWindowVisible,
ssWizardImageBackColor,
ssWizardImageFile,
ssWizardImageStretch,
ssWizardSmallImageBackColor,
ssWizardSmallImageFile,
ssWizardStyle);
TLangOptionsSectionDirective = (
lsCopyrightFontName,
lsCopyrightFontSize,
lsDialogFontName,
lsDialogFontSize,
lsDialogFontStandardHeight,
lsLanguageCodePage,
lsLanguageID,
lsLanguageName,
lsRightToLeft,
lsTitleFontName,
lsTitleFontSize,
lsWelcomeFontName,
lsWelcomeFontSize);
const
ComponentsSectionParameters: array[0..8] of TInnoSetupStylerParamInfo = (
(Name: 'Check'),
(Name: 'Description'),
(Name: 'ExtraDiskSpaceRequired'),
(Name: 'Flags'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'),
(Name: 'Types'));
DeleteSectionParameters: array[0..9] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'),
(Name: 'Tasks'),
(Name: 'Type'));
DirsSectionParameters: array[0..11] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'Attribs'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Flags'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'),
(Name: 'Permissions'),
(Name: 'Tasks'));
FilesSectionParameters: array[0..18] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'Attribs'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'CopyMode'),
(Name: 'DestDir'),
(Name: 'DestName'),
(Name: 'Excludes'),
(Name: 'ExternalSize'),
(Name: 'Flags'),
(Name: 'FontInstall'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'OnlyBelowVersion'),
(Name: 'Permissions'),
(Name: 'Source'),
(Name: 'StrongAssemblyName'),
(Name: 'Tasks'));
IconsSectionParameters: array[0..17] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'AppUserModelID'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Comment'),
(Name: 'Components'),
(Name: 'Filename'),
(Name: 'Flags'),
(Name: 'HotKey'),
(Name: 'IconFilename'),
(Name: 'IconIndex'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'),
(Name: 'Parameters'),
(Name: 'Tasks'),
(Name: 'WorkingDir'));
INISectionParameters: array[0..12] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Filename'),
(Name: 'Flags'),
(Name: 'Key'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'OnlyBelowVersion'),
(Name: 'Section'),
(Name: 'String'),
(Name: 'Tasks'));
LanguagesSectionParameters: array[0..4] of TInnoSetupStylerParamInfo = (
(Name: 'InfoAfterFile'),
(Name: 'InfoBeforeFile'),
(Name: 'LicenseFile'),
(Name: 'MessagesFile'),
(Name: 'Name'));
RegistrySectionParameters: array[0..14] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Flags'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'OnlyBelowVersion'),
(Name: 'Permissions'),
(Name: 'Root'),
(Name: 'Subkey'),
(Name: 'Tasks'),
(Name: 'ValueData'),
(Name: 'ValueName'),
(Name: 'ValueType'));
RunSectionParameters: array[0..15] of TInnoSetupStylerParamInfo = (
(Name: 'AfterInstall'),
(Name: 'BeforeInstall'),
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Description'),
(Name: 'Filename'),
(Name: 'Flags'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'OnlyBelowVersion'),
(Name: 'Parameters'),
(Name: 'RunOnceId'),
(Name: 'StatusMsg'),
(Name: 'Tasks'),
(Name: 'Verb'),
(Name: 'WorkingDir'));
TasksSectionParameters: array[0..8] of TInnoSetupStylerParamInfo = (
(Name: 'Check'),
(Name: 'Components'),
(Name: 'Description'),
(Name: 'Flags'),
(Name: 'GroupDescription'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'));
TypesSectionParameters: array[0..6] of TInnoSetupStylerParamInfo = (
(Name: 'Check'),
(Name: 'Description'),
(Name: 'Flags'),
(Name: 'Languages'),
(Name: 'MinVersion'),
(Name: 'Name'),
(Name: 'OnlyBelowVersion'));
const
stPascalNumber = stDefault;
stPascalReservedWord = stKeyword;
stPascalString = stDefault;
inSquiggly = 0;
inPendingSquiggly = 1;
AllChars = [#0..#255];
WhitespaceChars = [#0..' '];
AlphaChars = ['A'..'Z', 'a'..'z'];
DigitChars = ['0'..'9'];
HexDigitChars = DigitChars + ['A'..'F', 'a'..'f'];
AlphaUnderscoreChars = AlphaChars + ['_'];
AlphaDigitChars = AlphaChars + DigitChars;
AlphaDigitUnderscoreChars = AlphaChars + DigitChars + ['_'];
PascalIdentFirstChars = AlphaUnderscoreChars;
PascalIdentChars = AlphaDigitUnderscoreChars;
function SameRawText(const S1, S2: TScintRawString): Boolean;
var
Len, I: Integer;
C1, C2: AnsiChar;
begin
Len := Length(S1);
if Length(S2) <> Len then begin
Result := False;
Exit;
end;
for I := 1 to Len do begin
C1 := S1[I];
C2 := S2[I];
if C1 in ['A'..'Z'] then
Inc(C1, 32);
if C2 in ['A'..'Z'] then
Inc(C2, 32);
if C1 <> C2 then begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function GetASCIISortedInsertPos(const SL: TStringList; const S: String): Integer;
var
L, H, I, C: Integer;
begin
L := 0;
H := SL.Count - 1;
while L <= H do begin
I := (L + H) div 2;
C := CompareText(SL[I], S);
if C = 0 then begin
L := I;
Break;
end;
if C < 0 then
L := I + 1
else
H := I - 1;
end;
Result := L;
end;
function MapSectionNameString(const S: TScintRawString): TInnoSetupStylerSection;
type
TSectionMapEntry = record
Name: TScintRawString;
Value: TInnoSetupStylerSection;
end;
const
SectionMap: array[0..17] of TSectionMapEntry = (
(Name: 'Code'; Value: scCode),
(Name: 'Components'; Value: scComponents),
(Name: 'CustomMessages'; Value: scCustomMessages),
(Name: 'Dirs'; Value: scDirs),
(Name: 'Files'; Value: scFiles),
(Name: 'Icons'; Value: scIcons),
(Name: 'INI'; Value: scINI),
(Name: 'InstallDelete'; Value: scInstallDelete),
(Name: 'LangOptions'; Value: scLangOptions),
(Name: 'Languages'; Value: scLanguages),
(Name: 'Messages'; Value: scMessages),
(Name: 'Registry'; Value: scRegistry),
(Name: 'Run'; Value: scRun),
(Name: 'Setup'; Value: scSetup),
(Name: 'Tasks'; Value: scTasks),
(Name: 'Types'; Value: scTypes),
(Name: 'UninstallDelete'; Value: scUninstallDelete),
(Name: 'UninstallRun'; Value: scUninstallRun));
var
I: Integer;
begin
if (S <> '') and (S[1] = '_') then
Result := scThirdParty
else begin
Result := scUnknown;
for I := Low(SectionMap) to High(SectionMap) do
if SameRawText(S, SectionMap[I].Name) then begin
Result := SectionMap[I].Value;
Break;
end;
end;
end;
{ TInnoSetupStyler }
constructor TInnoSetupStyler.Create(AOwner: TComponent);
begin
inherited;
BuildKeywordListFromParameters(scComponents, ComponentsSectionParameters);
BuildKeywordListFromParameters(scDirs, DirsSectionParameters);
BuildKeywordListFromParameters(scFiles, FilesSectionParameters);
BuildKeywordListFromParameters(scIcons, IconsSectionParameters);
BuildKeywordListFromParameters(scINI, INISectionParameters);
BuildKeywordListFromParameters(scInstallDelete, DeleteSectionParameters);
BuildKeywordListFromEnumType(scLangOptions, TypeInfo(TLangOptionsSectionDirective));
BuildKeywordListFromParameters(scLanguages, LanguagesSectionParameters);
BuildKeywordListFromParameters(scRegistry, RegistrySectionParameters);
BuildKeywordListFromParameters(scRun, RunSectionParameters);
BuildKeywordListFromEnumType(scSetup, TypeInfo(TSetupSectionDirective));
BuildKeywordListFromParameters(scTasks, TasksSectionParameters);
BuildKeywordListFromParameters(scTypes, TypesSectionParameters);
BuildKeywordListFromParameters(scUninstallDelete, DeleteSectionParameters);
BuildKeywordListFromParameters(scUninstallRun, RunSectionParameters);
end;
procedure TInnoSetupStyler.ApplyPendingSquigglyFromIndex(const StartIndex: Integer);
begin
if (CaretIndex >= StartIndex) and (CaretIndex <= CurIndex) then
ApplyIndicators([inPendingSquiggly], StartIndex, CurIndex - 1)
else
ApplyIndicators([inSquiggly], StartIndex, CurIndex - 1);
end;
procedure TInnoSetupStyler.ApplySquigglyFromIndex(const StartIndex: Integer);
begin
ApplyIndicators([inSquiggly], StartIndex, CurIndex - 1);
end;
procedure TInnoSetupStyler.BuildKeywordListFromEnumType(
const Section: TInnoSetupStylerSection; const EnumTypeInfo: Pointer);
var
SL: TStringList;
I: Integer;
S: String;
A, WordList: AnsiString;
begin
SL := TStringList.Create;
try
{ Scintilla uses an ASCII binary search so the list must be in
ASCII sort order (case-insensitive). (TStringList's Sort method is
not suitable as it uses AnsiCompareText.) }
for I := 0 to GetTypeData(EnumTypeInfo).MaxValue do begin
S := Copy(GetEnumName(EnumTypeInfo, I), 3, Maxint);
SL.Insert(GetASCIISortedInsertPos(SL, S), S);
end;
for I := 0 to SL.Count-1 do begin
A := AnsiString(SL[I]);
if I = 0 then
WordList := A
else
WordList := WordList + ' ' + A;
end;
finally
SL.Free;
end;
FKeywordList[Section] := WordList;
end;
procedure TInnoSetupStyler.BuildKeywordListFromParameters(
const Section: TInnoSetupStylerSection;
const Parameters: array of TInnoSetupStylerParamInfo);
var
SL: TStringList;
I: Integer;
S: String;
A, WordList: AnsiString;
begin
SL := TStringList.Create;
try
{ Scintilla uses an ASCII binary search so the list must be in
ASCII sort order (case-insensitive). (TStringList's Sort method is
not suitable as it uses AnsiCompareText.) }
for I := 0 to High(Parameters) do begin
S := String(Parameters[I].Name);
SL.Insert(GetASCIISortedInsertPos(SL, S), S);
end;
for I := 0 to SL.Count-1 do begin
A := AnsiString(SL[I]);
if I = 0 then
WordList := A
else
WordList := WordList + ' ' + A;
end;
finally
SL.Free;
end;
FKeywordList[Section] := WordList;
end;
procedure TInnoSetupStyler.CommitStyle(const Style: TInnoSetupStylerStyle);
begin
inherited CommitStyle(Ord(Style));
end;
procedure TInnoSetupStyler.CommitStyleSq(const Style: TInnoSetupStylerStyle;
const Squigglify: Boolean);
begin
if Squigglify then
ApplySquigglyFromIndex(StyleStartIndex);
CommitStyle(Style);
end;
procedure TInnoSetupStyler.CommitStyleSqPending(const Style: TInnoSetupStylerStyle);
begin
ApplyPendingSquigglyFromIndex(StyleStartIndex);
CommitStyle(Style);
end;
function TInnoSetupStyler.GetKeywordList(Section: TInnoSetupStylerSection): AnsiString;
begin
Result := FKeywordList[Section];
end;
class function TInnoSetupStyler.GetSectionFromLineState(
const LineState: TScintLineState): TInnoSetupStylerSection;
begin
Result := TInnoSetupStylerLineState(LineState).Section;
end;
procedure TInnoSetupStyler.GetStyleAttributes(const Style: Integer;
var Attributes: TScintStyleAttributes);
const
STYLE_BRACELIGHT = 34;
STYLE_IDENTGUIDE = 37;
begin
if (Style >= 0) and (Style <= Ord(High(TInnoSetupStylerStyle))) then begin
case TInnoSetupStylerStyle(Style) of
stCompilerDirective: Attributes.ForeColor := $4040C0;
stComment: Attributes.ForeColor := clGreen;
stSection: Attributes.FontStyle := [fsBold];
stSymbol: Attributes.ForeColor := $707070;
stKeyword: Attributes.ForeColor := clBlue;
//stParameterValue: Attributes.ForeColor := clTeal;
stEventFunction: Attributes.FontStyle := [fsBold];
stConstant: Attributes.ForeColor := $C00080;
stMessageArg: Attributes.ForeColor := $FF8000;
end;
end
else begin
case Style of
STYLE_BRACELIGHT: Attributes.BackColor := $E0E0E0;
STYLE_IDENTGUIDE: Attributes.ForeColor := clSilver;
end;
end;
end;
procedure TInnoSetupStyler.HandleCodeSection(var SpanState: TInnoSetupStylerSpanState);
function FinishConsumingBraceComment: Boolean;
begin
ConsumeCharsNot(['}']);
Result := ConsumeChar('}');
CommitStyle(stComment);
end;
function FinishConsumingStarComment: Boolean;
begin
Result := False;
while True do begin
ConsumeCharsNot(['*']);
if not ConsumeChar('*') then
Break;
if ConsumeChar(')') then begin
Result := True;
Break;
end;
end;
CommitStyle(stComment);
end;
const
PascalReservedWords: array[0..41] of TScintRawString = (
'and', 'array', 'as', 'begin', 'case', 'const', 'div',
'do', 'downto', 'else', 'end', 'except', 'external',
'finally', 'for', 'function', 'goto', 'if', 'in', 'is',
'label', 'mod', 'nil', 'not', 'of', 'or', 'procedure',
'program', 'record', 'repeat', 'set', 'shl', 'shr',
'then', 'to', 'try', 'type', 'until', 'var', 'while',
'with', 'xor');
EventFunctions: array[0..22] of TScintRawString = (
'InitializeSetup', 'DeinitializeSetup', 'CurStepChanged',
'NextButtonClick', 'BackButtonClick', 'ShouldSkipPage',
'CurPageChanged', 'CheckPassword', 'NeedRestart',
'UpdateReadyMemo', 'RegisterPreviousData', 'CheckSerial',
'InitializeWizard', 'GetCustomSetupExitCode',
'InitializeUninstall', 'DeinitializeUninstall',
'CurUninstallStepChanged', 'UninstallNeedRestart',
'CancelButtonClick', 'InitializeUninstallProgressForm',
'PrepareToInstall', 'RegisterExtraCloseApplicationsResources',
'CurInstallProgressChanged');
var
S: TScintRawString;
I: Integer;
C: AnsiChar;
begin
case SpanState of
spBraceComment:
if not FinishConsumingBraceComment then
Exit;
spStarComment:
if not FinishConsumingStarComment then
Exit;
end;
SpanState := spNone;
SkipWhitespace;
while not EndOfLine do begin
if CurChar in PascalIdentFirstChars then begin
S := ConsumeString(PascalIdentChars);
for I := Low(PascalReservedWords) to High(PascalReservedWords) do
if SameRawText(S, PascalReservedWords[I]) then begin
CommitStyle(stPascalReservedWord);
Break;
end;
for I := Low(EventFunctions) to High(EventFunctions) do
if SameRawText(S, EventFunctions[I]) then begin
CommitStyle(stEventFunction);
Break;
end;
CommitStyle(stDefault);
end
else if ConsumeChars(DigitChars) then begin
if not CurCharIs('.') or not NextCharIs('.') then begin
if ConsumeChar('.') then
ConsumeChars(DigitChars);
C := CurChar;
if C in ['E', 'e'] then begin
ConsumeChar(C);
if not ConsumeChar('-') then
ConsumeChar('+');
if not ConsumeChars(DigitChars) then
CommitStyleSqPending(stPascalNumber);
end;
end;
CommitStyle(stPascalNumber);
end
else begin
C := CurChar;
ConsumeChar(C);
case C of
';', ':', '=', '+', '-', '*', '/', '<', '>', ',', '(', ')',
'.', '[', ']', '@', '^':
begin
if (C = '/') and ConsumeChar('/') then begin
ConsumeAllRemaining;
CommitStyle(stComment);
end
else if (C = '(') and ConsumeChar('*') then begin
if not FinishConsumingStarComment then begin
SpanState := spStarComment;
Exit;
end;
end
else
CommitStyle(stSymbol);
end;
'''':
begin
while True do begin
ConsumeCharsNot(['''']);
if not ConsumeChar('''') then begin
CommitStyleSqPending(stPascalString);
Break;
end;
if not ConsumeChar('''') then begin
CommitStyle(stPascalString);
Break;
end;
end;
end;
'{':
begin
if not FinishConsumingBraceComment then begin
SpanState := spBraceComment;
Exit;
end;
end;
'$':
begin
ConsumeChars(HexDigitChars);
CommitStyle(stPascalNumber);
end;
'#':
begin
if ConsumeChar('$') then
ConsumeChars(HexDigitChars)
else
ConsumeChars(DigitChars);
CommitStyle(stPascalString);
end;
else
{ Illegal character }
CommitStyleSq(stSymbol, True);
end;
end;
SkipWhitespace;
end;
end;
procedure TInnoSetupStyler.HandleParameterSection(
const ValidParameters: array of TInnoSetupStylerParamInfo);
var
ParamsSpecified: set of 0..31;
S: TScintRawString;
I, ParamValueIndex, BraceLevel: Integer;
NamePresent, ValidName, DuplicateName, ColonPresent: Boolean;
begin
ParamsSpecified := [];
while not EndOfLine do begin
{ Squigglify any bogus characters before the parameter name }
SquigglifyUntilChars(AlphaChars + [':'], stDefault);
{ Parameter name }
S := ConsumeString(AlphaDigitChars);
NamePresent := (S <> '');
ValidName := False;
DuplicateName := False;
for I := Low(ValidParameters) to High(ValidParameters) do
if SameRawText(S, ValidParameters[I].Name) then begin
ValidName := True;
DuplicateName := (I in ParamsSpecified);
Include(ParamsSpecified, I);
Break;
end;
if DuplicateName then
CommitStyleSqPending(stKeyword)
else if ValidName then
CommitStyle(stKeyword)
else
CommitStyleSqPending(stDefault);
SkipWhitespace;
{ If there's a semicolon with no colon, squigglify the semicolon }
if ConsumeChar(';') then begin
CommitStyleSq(stSymbol, True);
SkipWhitespace;
Continue;
end;
{ Colon }
ColonPresent := ConsumeChar(':');
CommitStyleSq(stSymbol, not NamePresent);
SkipWhitespace;
{ Parameter value. This consumes until a ';' is found or EOL is reached. }
ParamValueIndex := CurIndex;
BraceLevel := 0;
if ConsumeChar('"') then begin
while True do begin
StyleConstsUntilChars(['"'], stParameterValue, BraceLevel);
{ If no closing quote exists, squigglify the whole value and break }
if not ConsumeChar('"') then begin
ApplyPendingSquigglyFromIndex(ParamValueIndex);
Break;
end;
{ Quote found, now break, unless there are two quotes in a row }
if not ConsumeChar('"') then
Break;
end;
end
else begin
while True do begin
StyleConstsUntilChars([';', '"'], stParameterValue, BraceLevel);
{ Squigglify any quote characters inside an unquoted string }
if ConsumeChar('"') then
ApplySquigglyFromIndex(CurIndex - 1)
else
Break;
end;
end;
CommitStyle(stParameterValue);
if not ColonPresent then
ApplySquigglyFromIndex(ParamValueIndex);
{ Squigglify any characters between a quoted string and the next ';' }
SquigglifyUntilChars([';'], stDefault);
{ Semicolon }
ConsumeChar(';');
CommitStyle(stSymbol);
SkipWhitespace;
end;
end;
procedure TInnoSetupStyler.HandleKeyValueSection(const Section: TInnoSetupStylerSection);
procedure StyleMessageArgs;
begin
while True do begin
ConsumeCharsNot(['%']);
CommitStyle(stDefault);
if not ConsumeChar('%') then
Break;
if CurCharIn(['1'..'9', '%', 'n']) then begin
ConsumeChar(CurChar);
CommitStyle(stMessageArg);
end;
end;
end;
var
S: String;
I, BraceLevel: Integer;
begin
{ Squigglify any bogus characters at the start of the line }
SquigglifyUntilChars(AlphaUnderscoreChars, stDefault);
if EndOfLine then
Exit;
S := String(ConsumeString(AlphaDigitUnderscoreChars));
{ Was that a language name? }
if (Section in [scCustomMessages, scLangOptions, scMessages]) and
CurCharIs('.') then begin
CommitStyle(stDefault);
ConsumeChar('.');
CommitStyle(stSymbol);
{ Squigglify any spaces or bogus characters between the '.' and key name }
if ConsumeCharsNot(AlphaUnderscoreChars) then
CommitStyleSq(stDefault, True);
S := String(ConsumeString(AlphaDigitUnderscoreChars));
end;
case Section of
scLangOptions:
I := GetEnumValue(TypeInfo(TLangOptionsSectionDirective), 'ls' + S);
scSetup:
I := GetEnumValue(TypeInfo(TSetupSectionDirective), 'ss' + S);
else
I := -1;
end;
if I <> -1 then
CommitStyle(stKeyword)
else begin
if Section in [scLangOptions, scSetup] then
CommitStyleSqPending(stDefault)
else
CommitStyle(stDefault);
end;
SquigglifyUntilChars(['='], stDefault);
ConsumeChar('=');
CommitStyle(stSymbol);
SkipWhitespace;
if Section in [scCustomMessages, scMessages] then
StyleMessageArgs
else begin
BraceLevel := 0;
StyleConstsUntilChars([], stDefault, BraceLevel);
end;
end;
class function TInnoSetupStyler.IsParamSection(
const Section: TInnoSetupStylerSection): Boolean;
begin
Result := not (Section in [scCustomMessages, scLangOptions, scMessages, scSetup]);
end;
class function TInnoSetupStyler.IsSymbolStyle(const Style: TScintStyleNumber): Boolean;
begin
Result := (Style = Ord(stSymbol));
end;
function TInnoSetupStyler.LineTextSpans(const S: TScintRawString): Boolean;
var
I: Integer;
begin
{ Note: To match ISPP behavior, require length of at least 3 }
I := Length(S);
Result := (I > 2) and (S[I] = '\') and (S[I-1] in WhitespaceChars);
end;
procedure TInnoSetupStyler.PreStyleInlineISPPDirectives;
function IsLineCommented: Boolean;
var
I: Integer;
begin
Result := False;
for I := 1 to TextLength do begin
{ In ISPP, only ';' and '//' inhibit processing of inline directives }
if (Text[I] = ';') or
((I < TextLength) and (Text[I] = '/') and (Text[I+1] = '/')) then begin
Result := True;
Break;
end;
if not(Text[I] in WhitespaceChars) then
Break;
end;
end;
const
LineEndChars = [#10, #13];
var
I, StartIndex: Integer;
Valid: Boolean;
begin
{ Style span symbols, then replace them with spaces to prevent any further
processing }
for I := 3 to TextLength do begin
if ((I = TextLength) or (Text[I+1] in LineEndChars)) and
(Text[I] = '\') and (Text[I-1] in WhitespaceChars) and
not(Text[I-2] in LineEndChars) then begin
ReplaceText(I, I, ' ');
ApplyStyle(Ord(stSymbol), I, I);
end;
end;
{ Style all '{#' ISPP inline directives before anything else }
if not IsLineCommented then begin
I := 1;
while I < TextLength do begin
if (Text[I] = '{') and (Text[I+1] = '#') then begin
StartIndex := I;
Valid := False;
while I <= TextLength do begin
Inc(I);
if Text[I-1] = '}' then begin
Valid := True;
Break;
end;
end;
{ Replace the directive with spaces to prevent any further processing }
ReplaceText(StartIndex, I - 1, ' ');
if Valid then
ApplyStyle(Ord(stCompilerDirective), StartIndex, I - 1)
else begin
if (CaretIndex >= StartIndex) and (CaretIndex <= I) then
ApplyIndicators([inPendingSquiggly], StartIndex, I - 1)
else
ApplyIndicators([inSquiggly], StartIndex, I - 1);
end;
end
else
Inc(I);
end;
end;
end;
procedure TInnoSetupStyler.SkipWhitespace;
begin
ConsumeChars(WhitespaceChars);
CommitStyle(stDefault);
end;
procedure TInnoSetupStyler.SquigglifyUntilChars(const Chars: TScintRawCharSet;
const Style: TInnoSetupStylerStyle);
var
IsWhitespace: Boolean;
begin
{ Consume and squigglify all non-whitespace characters until one of Chars
is encountered }
while not EndOfLine and not CurCharIn(Chars) do begin
IsWhitespace := CurCharIn(WhitespaceChars);
ConsumeChar(CurChar);
if IsWhitespace then
CommitStyle(stDefault)
else
CommitStyleSq(Style, True);
end;
CommitStyle(stDefault);
end;
procedure TInnoSetupStyler.StyleConstsUntilChars(const Chars: TScintRawCharSet;
const NonConstStyle: TInnoSetupStylerStyle; var BraceLevel: Integer);
var
C: AnsiChar;
begin
while not EndOfLine and not CurCharIn(Chars) do begin
if BraceLevel = 0 then
CommitStyle(NonConstStyle);
C := CurChar;
ConsumeChar(C);
if C = '{' then begin
if not ConsumeChar('{') then
Inc(BraceLevel);
end;
if (C = '}') and (BraceLevel > 0) then begin
Dec(BraceLevel);
if BraceLevel = 0 then
CommitStyle(stConstant);
end;
end;
end;
procedure TInnoSetupStyler.StyleNeeded;
var
NewLineState: TInnoSetupStylerLineState;
Section, NewSection: TInnoSetupStylerSection;
SectionEnd: Boolean;
S: TScintRawString;
begin
NewLineState := TInnoSetupStylerLineState(LineState);
if NewLineState.NextLineSection <> scNone then begin
NewLineState.Section := NewLineState.NextLineSection;
NewLineState.NextLineSection := scNone;
end;
Section := NewLineState.Section;
PreStyleInlineISPPDirectives;
SkipWhitespace;
if (Section <> scCode) and ConsumeChar(';') then begin
ConsumeAllRemaining;
CommitStyle(stComment);
end
else if ConsumeChar('[') then begin
SectionEnd := ConsumeChar('/');
S := ConsumeString(AlphaUnderscoreChars);
if ConsumeChar(']') then begin
NewSection := MapSectionNameString(S);
{ Unknown section names and erroneously-placed end tags get squigglified }
CommitStyleSq(stSection, (NewSection = scUnknown) or
(SectionEnd and (NewSection <> Section)));
if not SectionEnd then
NewLineState.NextLineSection := NewSection;
end
else
CommitStyleSqPending(stDefault);
{ Section tags themselves are not associated with any section }
Section := scNone;
SquigglifyUntilChars([], stDefault);
end
else if ConsumeChar('#') then begin
ConsumeAllRemaining;
CommitStyle(stCompilerDirective);
end
else begin
case Section of
scUnknown: ;
scThirdParty: ;
scCode: HandleCodeSection(NewLineState.SpanState);
scComponents: HandleParameterSection(ComponentsSectionParameters);
scCustomMessages: HandleKeyValueSection(Section);
scDirs: HandleParameterSection(DirsSectionParameters);
scFiles: HandleParameterSection(FilesSectionParameters);
scIcons: HandleParameterSection(IconsSectionParameters);
scINI: HandleParameterSection(INISectionParameters);
scInstallDelete: HandleParameterSection(DeleteSectionParameters);
scLangOptions: HandleKeyValueSection(Section);
scLanguages: HandleParameterSection(LanguagesSectionParameters);
scMessages: HandleKeyValueSection(Section);
scRegistry: HandleParameterSection(RegistrySectionParameters);
scRun: HandleParameterSection(RunSectionParameters);
scSetup: HandleKeyValueSection(Section);
scTasks: HandleParameterSection(TasksSectionParameters);
scTypes: HandleParameterSection(TypesSectionParameters);
scUninstallDelete: HandleParameterSection(DeleteSectionParameters);
scUninstallRun: HandleParameterSection(RunSectionParameters);
end;
end;
NewLineState.Section := Section;
LineState := TScintLineState(NewLineState);
end;
end.
|
unit ChangePwdForma;
interface
{$I defines.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OkCancel_frame, PrjConst, FIBQuery, pFIBQuery, Vcl.Buttons,
Vcl.ExtCtrls, CnErrorProvider;
type
TChangePwdForm = class(TForm)
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
edtOLD: TEdit;
edtNEW: TEdit;
edtCONFRM: TEdit;
btnOk: TBitBtn;
btnCancel: TBitBtn;
lblLANG: TLabel;
lblCAPS: TLabel;
Timer1: TTimer;
cnErrors: TCnErrorProvider;
procedure FormShow(Sender: TObject);
procedure frm1bbOkClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure edtNEWKeyPress(Sender: TObject; var Key: Char);
private
procedure UpdateKbdState;
public
{ Public declarations }
end;
implementation
uses
DM, System.StrUtils, AtrCommon;
{$R *.dfm}
procedure TChangePwdForm.edtNEWKeyPress(Sender: TObject; var Key: Char);
begin
if not(Key in ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '!', '@', '#', '$', '%', '&', '*', '_', #8]) then
begin
Key := #0;
cnErrors.SetError((Sender as TEdit), rsEmptyOrIncorrect, iaMiddleLeft, bsNeverBlink);
end
else
cnErrors.Dispose((Sender as TEdit));
end;
procedure TChangePwdForm.FormShow(Sender: TObject);
begin
edtOLD.Text := '';
edtNEW.Text := '';
edtCONFRM.Text := '';
if (dmMain.GetIniValue('KBDSWITCH') = '0')
then SetKeyboardLayout('EN')
else dmMain.SaveKLAndSelectEnglish;
end;
procedure TChangePwdForm.frm1bbOkClick(Sender: TObject);
var
Changed: Boolean;
p: string;
begin
Changed := False;
if pswdPrefix + edtOLD.Text = dmMain.Password
then begin
p := pswdPrefix + edtNEW.Text;
if (Length(edtNEW.Text) <> 0) and (dmMain.User <> 'SYSDBA') and ( p = (pswdPrefix +edtCONFRM.Text)) and ( p <> dmMain.Password)
then begin
try
with TpFIBQuery.Create(Self) do
try
DataBase := dmMain.dbTV;
Transaction := dmMain.trWriteQ;
p := rsQUOTE + ReplaceStr(p, rsQUOTE, rsQUOTE + rsQUOTE) + rsQUOTE;
SQL.Text := Format('ALTER USER %s PASSWORD %s', [dmMain.User, p]);
Transaction.StartTransaction;
ExecQuery;
Transaction.Commit;
SQL.Text := Format('update Sys$User set Pswd_Changed = CURRENT_TIMESTAMP where Ibname = ''%s''', [dmMain.User]);
Transaction.StartTransaction;
ExecQuery;
Transaction.Commit;
Changed := True;
finally Free;
end;
except
end;
end;
end;
if not Changed
then ShowMessage(rsPasswordNotChange)
else begin
if (dmMain.GetIniValue('KBDSWITCH') = '0')
then SetKeyboardLayout(dmMain.GetIniValue('KEYBOARD'))
else dmMain.RestoreKL;
end;
end;
procedure TChangePwdForm.Timer1Timer(Sender: TObject);
begin
UpdateKbdState;
end;
procedure TChangePwdForm.UpdateKbdState;
var
Buf: array [0 .. KL_NAMELENGTH] of char;
Pk: PChar;
C, i: Integer;
begin
GetKeyboardLayoutName(@Buf);
Pk := @Buf;
Val(StrPas(Pk), i, C);
case i of
409:
lblLANG.Caption := 'EN';
419:
lblLANG.Caption := 'RU';
422:
lblLANG.Caption := 'UA';
10437:
lblLANG.Caption := 'ქარ';
42:
lblLANG.Caption := 'HY';
else
lblLANG.Caption := IntToStr(i);
end;
lblCAPS.Width := lblLANG.Width;
lblCAPS.Left := lblLANG.Left;
lblCAPS.Visible := (GetKeyState(VK_CAPITAL) and $01) = 1;
end;
end.
|
{
}
unit mainform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, Buttons, Spin,
// fpchess
chessdrawer, chessgame, chessconfig, chesstcputils,
chessmodules, selectpromotionpiece;
type
{ TFormDrawerDelegate }
TFormDrawerDelegate = class(TChessDrawerDelegate)
public
procedure HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); override;
procedure HandleMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
procedure HandleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
end;
{ TformChess }
TformChess = class(TForm)
btnGameNewGame: TBitBtn;
btnResign: TBitBtn;
btnQuitGame: TBitBtn;
btnQuit: TBitBtn;
btnStartGame: TBitBtn;
btnPlayAgainstAI: TButton;
checkTimer: TCheckBox;
comboGameMode: TComboBox;
comboStartColor: TComboBox;
editLocalIP: TLabeledEdit;
editWebserviceURL: TLabeledEdit;
Label1: TLabel;
labelMode: TLabel;
labelTime: TLabel;
Label2: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
editWebServiceAI: TLabeledEdit;
labelPos: TLabel;
editPlayerName: TLabeledEdit;
memoDebug: TMemo;
pageStart: TPage;
notebookMain: TNotebook;
panelModules: TPanel;
pageGame: TPage;
spinPlayerTime: TSpinEdit;
timerChessTimer: TTimer;
pageWebservice: TPage;
procedure btnGameNewGameClick(Sender: TObject);
procedure btnQuitClick(Sender: TObject);
procedure btnQuitGameClick(Sender: TObject);
procedure btnStartGameClick(Sender: TObject);
procedure comboGameModeSelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure timerChessTimerTimer(Sender: TObject);
private
{ private declarations }
function FormatTime(ATimeInMiliseconds: Integer): string;
procedure UpdateChessModulesUI(ANewIndex: Integer);
function HandlePawnPromotion(APiece: TChessTile): TChessTile;
public
{ public declarations }
procedure UpdateCaptions;
procedure InitializeGameModel;
end;
var
formChess: TformChess;
vFormDrawerDelegate: TFormDrawerDelegate;
procedure HandleOnMove(AFrom, ATo: TPoint);
implementation
{$R *.lfm}
const
INT_PAGE_START = 0;
INT_PAGE_GAME = 1;
INT_PAGE_WEBSERVICE = 2;
{ TformChess }
procedure TformChess.timerChessTimerTimer(Sender: TObject);
begin
vChessGame.UpdateTimes();
UpdateCaptions();
vChessDrawer.HandleOnTimer(Sender);
GetCurrentChessModule().HandleOnTimer();
end;
function TformChess.FormatTime(ATimeInMiliseconds: Integer): string;
var
lTimePart: Integer;
begin
Result := '';
// Hours
lTimePart := ATimeInMiliseconds div (60*60*1000);
if lTimePart > 0 then
Result := IntToStr(lTimePart) + 'h';
// Minutes
lTimePart := (ATimeInMiliseconds div (60*1000)) mod 60;
if (lTimePart > 0) or (Result <> '') then
Result := Result + IntToStr(lTimePart) + 'm';
// Seconds
lTimePart := (ATimeInMiliseconds div (1000)) mod 60;
Result := Result + IntToStr(lTimePart) + 's';
// Miliseconds
lTimePart := ATimeInMiliseconds mod (1000);
Result := Result + IntToStr(lTimePart);
end;
procedure TformChess.UpdateChessModulesUI(ANewIndex: Integer);
var
lModule: TChessModule;
begin
if ANewIndex = gSelectedModuleIndex then Exit;
lModule := GetChessModule(gSelectedModuleIndex);
if lModule <> nil then lModule.HideUserInterface();
GetChessModule(ANewIndex).ShowUserInterface(panelModules);
end;
function TformChess.HandlePawnPromotion(APiece: TChessTile): TChessTile;
var
dlgPromotion: TformPromotion;
begin
dlgPromotion := TformPromotion.Create(vChessGame.IsWhitePlayerTurn);
try
dlgPromotion.ShowModal;
finally
dlgPromotion.Free;
Result := selectPromotionPiece.pieceChosen;
end;
end;
procedure HandleOnMove(AFrom, ATo: TPoint);
var
lStr: String;
begin
lStr := vChessGame.GetCurrentPlayerColor();
lStr := Format('%s executed the move %s-%s', [lStr, vChessGame.BoardPosToChessCoords(AFrom), vChessGame.BoardPosToChessCoords(ATo)]);
formChess.MemoDebug.Lines.Add(lStr);
end;
procedure TformChess.UpdateCaptions;
var
lStr, lStr2: string;
begin
if vChessGame.IsWhitePlayerTurn then lStr := 'White playing'
else lStr := 'Black playing';
lStr2 := vChessGame.BoardPosToChessCoords(vChessGame.MouseMovePos);
lStr := lStr + Format(' X: %d Y: %d = %s',
[vChessGame.MouseMovePos.X, vChessGame.MouseMovePos.Y, lStr2]);
formChess.labelPos.Caption := lStr;
lStr := Format('White time: %s Black time: %s',
[FormatTime(vChessGame.WhitePlayerTime), FormatTime(vChessGame.BlackPlayerTime)]);
formChess.labelTime.Caption := lStr;
lStr := GetChessModule(gSelectedModuleIndex).PlayingDescription;
formChess.labelMode.Caption := lStr;
end;
procedure TformChess.InitializeGameModel;
begin
vChessGame.StartNewGame(comboStartColor.ItemIndex, checkTimer.Checked, spinPlayerTime.Value);
end;
procedure TformChess.FormCreate(Sender: TObject);
begin
// Creation of internal components
vChessDrawer := TChessDrawer.Create(Self);
vChessDrawer.Parent := pageGame;
vChessDrawer.Top := 50;
vChessDrawer.Left := 20;
vChessDrawer.Height := INT_CHESSBOARD_SIZE;
vChessDrawer.Width := INT_CHESSBOARD_SIZE;
vChessDrawer.SetDelegate(vFormDrawerDelegate);
// Loading of resources
vChessDrawer.LoadImages();
// Prepare the modules view
InitializeGameModel();
editLocalIP.Text := ChessGetLocalIP();
PopulateChessModulesList(comboGameMode.Items);
if GetChessModuleCount() >= 1 then
begin
comboGameMode.ItemIndex := 0;
UpdateChessModulesUI(0);
gSelectedModuleIndex := 0;
end;
gChessModulesDebugOutputDestiny := memoDebug;
// Prepare the callbacks
vChessGame.OnBeforeMove := @HandleOnMove;
vChessGame.OnPawnPromotion := @HandlePawnPromotion;
end;
procedure TformChess.btnQuitClick(Sender: TObject);
begin
Close;
end;
procedure TformChess.btnGameNewGameClick(Sender: TObject);
begin
notebookMain.PageIndex := INT_PAGE_START;
timerChessTimer.Enabled := False;
end;
procedure TformChess.btnQuitGameClick(Sender: TObject);
begin
Close;
end;
procedure TformChess.btnStartGameClick(Sender: TObject);
var
lModule: TChessModule;
begin
InitializeGameModel();
vChessGame.Enabled := False;
notebookMain.PageIndex := INT_PAGE_GAME;
gSelectedModuleIndex := comboGameMode.ItemIndex;
lModule := GetChessModule(gSelectedModuleIndex);
vChessGame.PlayerName := editPlayerName.Text;
lModule.PrepareForGame();
// Make sure this is done after lModule.PrepareForGame()
vChessGame.Enabled := True;
timerChessTimer.Enabled := True;
end;
procedure TformChess.comboGameModeSelect(Sender: TObject);
begin
UpdateChessModulesUI(comboGameMode.ItemIndex);
gSelectedModuleIndex := comboGameMode.ItemIndex;
end;
{ TFormDrawerDelegate }
procedure TFormDrawerDelegate.HandleMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
vChessGame.MouseMovePos := vChessGame.ClientToBoardCoords(Point(X, Y));
formChess.UpdateCaptions;
end;
procedure TFormDrawerDelegate.HandleMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
lCoords: TPoint;
lModule: TChessModule;
begin
lModule := GetChessModule(gSelectedModuleIndex);
if not lModule.IsMovingAllowedNow() then Exit;
vChessGame.Dragging := False;
lCoords := vChessGame.ClientToBoardCoords(Point(X, Y));
if not vChessGame.MovePiece(vChessGame.DragStart, lCoords) then Exit;
vChessDrawer.Invalidate;
formChess.UpdateCaptions;
end;
procedure TFormDrawerDelegate.HandleMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
lCoords: TPoint;
lModule: TChessModule;
begin
lModule := GetChessModule(gSelectedModuleIndex);
if not lModule.IsMovingAllowedNow() then Exit;
lCoords := vChessGame.ClientToBoardCoords(Point(X, Y));
if not vChessGame.CheckStartMove(lCoords) then Exit;
vChessGame.Dragging := True;
vChessGame.DragStart := lCoords;
vChessDrawer.Invalidate;
formChess.UpdateCaptions;
end;
initialization
vFormDrawerDelegate := TFormDrawerDelegate.Create;
finalization
vFormDrawerDelegate.Free;
end.
|
unit clAgentesJornal;
interface
uses
clPessoaJ, clConexao;
type
TAgenteJornal = Class(TPessoaJ)
private
function getCodigo: Integer;
procedure setCodigo(const Value: Integer);
function getOperacao: String;
procedure setOperacao(const Value: String);
protected
_codigo: Integer;
_operacao: String;
_conexao: TConexao;
public
constructor Create;
destructor Destroy;
property Codigo: Integer read getCodigo write setCodigo;
property Operacao: String read getOperacao write setOperacao;
function Validar(): Boolean;
function JaExiste(id: String): Boolean;
function Delete(filtro: String): Boolean;
function getObject(id, filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
function getObjects(): Boolean;
function getField(campo, coluna: String): String;
end;
const
TABLENAME = 'JOR_AGENTES';
implementation
{ TAgenteJornal }
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Math;
constructor TAgenteJornal.Create;
begin
_conexao := TConexao.Create;
end;
destructor TAgenteJornal.Destroy;
begin
_conexao.Free;
end;
function TAgenteJornal.getCodigo: Integer;
begin
Result := _codigo;
end;
function TAgenteJornal.getOperacao: String;
begin
Result := _operacao;
end;
function TAgenteJornal.Validar(): Boolean;
begin
Result := False;
if Self.Codigo = 0 then
begin
MessageDlg('Informe o código do Agente!', mtWarning, [mbOK], 0);
Exit
end;
if Self.Operacao = 'I' then
begin
if Self.JaExiste(IntToStr(Self.Codigo)) then
begin
MessageDlg('Código de Agente já Cadastrado', mtWarning, [mbOK], 0);
Exit;
end;
end;
if TUtil.Empty(Self.Razao) then
begin
MessageDlg('Informe o nome do Agente!', mtWarning, [mbNo], 0);
Exit;
end;
Result := True;
end;
function TAgenteJornal.JaExiste(id: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(id) then
begin
Exit;
end;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
dm.qryGetObject.SQL.Add(' WHERE COD_AGENTE = :CODIGO');
dm.qryGetObject.ParamByName('CODIGO').AsInteger := StrToInt(id);
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if (not dm.qryGetObject.IsEmpty) then
begin
dm.qryGetObject.First;
end;
if dm.qryGetObject.RecordCount > 0 then
begin
Result := True;
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.Delete(filtro: String): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
dm.QryCRUD.SQL.Add('WHERE COD_AGENTE = :CODIGO');
dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Codigo;
end;
dm.ZConn.PingServer;
dm.QryCRUD.ExecSQL;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.getObject(id, filtro: String): Boolean;
begin
Try
Result := False;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
if TUtil.Empty(id) then
begin
Exit;
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
dm.qryGetObject.SQL.Add(' WHERE COD_AGENTE = :CODIGO');
dm.qryGetObject.ParamByName('CODIGO').AsInteger := StrToInt(id);
end
else if filtro = 'NOME' then
begin
dm.qryGetObject.SQL.Add(' WHERE NOM_AGENTE = :NOME');
dm.qryGetObject.ParamByName('NOME').AsString := id;
end;
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if (not dm.qryGetObject.IsEmpty) then
begin
dm.qryGetObject.First;
end;
if dm.qryGetObject.RecordCount > 0 then
begin
dm.qryGetObject.First;
Self.Codigo := dm.qryGetObject.FieldByName('COD_AGENTE').AsInteger;
Self.Razao := dm.qryGetObject.FieldByName('NOM_AGENTE').AsString;
Result := True;
end
else
begin
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.Insert(): Boolean;
begin
Try
Result := False;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
dm.QryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_AGENTE, ' +
'NOM_AGENTE) ' + 'VALUES (' + ':CODIGO, ' + ':NOME) ';
dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Codigo;
dm.QryCRUD.ParamByName('NOME').AsString := Self.Razao;
dm.ZConn.PingServer;
dm.QryCRUD.ExecSQL;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.Update(): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
dm.QryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'NOM_AGENTE = :NOME ' + 'WHERE ' + 'COD_AGENTE = :CODIGO';
dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Codigo;
dm.QryCRUD.ParamByName('NOME').AsString := Self.Razao;
dm.ZConn.PingServer;
dm.QryCRUD.ExecSQL;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.getObjects(): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if (not dm.qryGetObject.IsEmpty) then
begin
dm.qryGetObject.First;
end;
if dm.qryGetObject.RecordCount > 0 then
begin
Result := True;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TAgenteJornal.getField(campo, coluna: String): String;
begin
Try
Result := '';
if (not _conexao.VerifyConnZEOS(1)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME;
if coluna = 'CODIGO' then
begin
dm.qryGetObject.SQL.Add(' WHERE COD_AGENTE = :CODIGO ');
dm.qryGetObject.ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if coluna = 'NOME' then
begin
dm.qryGetObject.SQL.Add(' WHERE NOM_AGENTE = :NOME ');
dm.qryGetObject.ParamByName('NOME').AsString := Self.Razao;
end;
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if (not dm.qryGetObject.IsEmpty) then
begin
dm.qryGetObject.First;
end;
if dm.qryGetObject.RecordCount > 0 then
begin
Result := dm.qryGetObject.FieldByName(campo).AsString;
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TAgenteJornal.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
procedure TAgenteJornal.setOperacao(const Value: String);
begin
_operacao := Value;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2015-2021 Kike Pérez
Unit : Quick.Azure
Description : Azure blobs operations
Author : Kike Pérez
Version : 1.4
Created : 27/08/2015
Modified : 21/10/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Azure;
{$i QuickLib.inc}
interface
uses
Classes,
System.SysUtils,
System.Generics.Collections,
IPPeerClient,
IdURI,
Data.Cloud.CloudAPI,
Data.Cloud.AzureAPI,
Quick.Commons;
type
TAzureProtocol = (azHTTP,azHTTPS);
//TAzureBlob = Data.Cloud.AzureAPI.TAzureBlob;
TBlobPublicAccess = Data.Cloud.AzureAPI.TBlobPublicAccess;
TAzureResponseInfo = record
StatusCode : Integer;
StatusMsg : string;
end;
TAzureBlobObject = class
Name : string;
Size : Int64;
IsDir : Boolean;
LastModified : TDateTime;
end;
TBlobList = class (TObjectList<TAzureBlobObject>);
TQuickAzure = class
private
fconAzure : TAzureConnectionInfo;
fAccountName : string;
fAccountKey : string;
fAzureProtocol : TAzureProtocol;
fTimeOut : Integer;
procedure SetAccountName(azAccountName : string);
procedure SetAccountKey(azAccountKey : string);
procedure SetAzureProtocol(azProtocol : TAzureProtocol);
function FileToArray(cFilename : string) : TArray<Byte>;
function StreamToArray(cStream : TStream) : TArray<Byte>;
function ByteContent(DataStream: TStream): TBytes;
function GMT2DateTime(const gmtdate : string):TDateTime;
function CheckContainer(const aContainer : string) : string;
function RemoveFirstSlash(const aValue : string) : string;
public
constructor Create; overload;
constructor Create(azAccountName, azAccountKey : string); overload;
destructor Destroy; override;
property AccountName : string read fAccountName write SetAccountName;
property AccountKey : string read fAccountKey write SetAccountKey;
property AzureProtocol : TAzureProtocol read fAzureProtocol write SetAzureProtocol;
property TimeOut : Integer read fTimeOut write fTimeOut;
function PutBlob(const azContainer, cFilename, azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean; overload;
function PutBlob(const azContainer : string; cStream : TStream; const azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean; overload;
function GetBlob(const azContainer, azBlobName, cFilenameTo : string; out azResponseInfo : TAzureResponseInfo) : Boolean; overload;
function GetBlob(const azContainer, azBlobName : string; out azResponseInfo : TAzureResponseInfo; out Stream : TMemoryStream) : Boolean; overload;
function GetBlob(const azContainer, azBlobName: string; out azResponseInfo: TAzureResponseInfo; var Stream: TStream): Boolean; overload;
function GetBlob(const azContainer, azBlobName : string; out azResponseInfo : TAzureResponseInfo) : TMemoryStream; overload;
function CopyBlob(const azSourceContainer, azSourceBlobName : string; azTargetContainer, azTargetBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
function RenameBlob(const azContainer, azSourceBlobName, azTargetBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
function ExistsObject(const azContainer, azBlobName : string) : Boolean;
function ExistsFolder(const azContainer, azFolderName : string) : Boolean;
function DeleteBlob(const azContainer,azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
function ListBlobs(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TBlobList;
function ListBlobsNames(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TStrings;
function ExistsContainer(const azContainer : string) : Boolean;
function ListContainers(const azContainersStartWith : string; out azResponseInfo : TAzureResponseInfo) : TStrings;
function CreateContainer(const azContainer : string; azPublicAccess : TBlobPublicAccess; out azResponseInfo : TAzureResponseInfo) : Boolean;
function DeleteContainer(const azContainer : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
end;
implementation
constructor TQuickAzure.Create;
begin
inherited;
fconAzure := TAzureConnectionInfo.Create(nil);
fAzureProtocol := azHTTP;
fTimeOut := 30;
end;
constructor TQuickAzure.Create(azAccountName, azAccountKey : string);
begin
Create;
SetAccountName(azAccountName);
SetAccountKey(azAccountKey);
end;
destructor TQuickAzure.Destroy;
begin
if Assigned(fconAzure) then fconAzure.Free;
inherited;
end;
procedure TQuickAzure.SetAccountName(azAccountName : string);
begin
if fAccountName <> azAccountName then
begin
fAccountName := azAccountName;
fconAzure.AccountName := azAccountName;
end;
end;
procedure TQuickAzure.SetAccountKey(azAccountKey : string);
begin
if fAccountKey <> azAccountKey then
begin
fAccountKey := azAccountKey ;
fconAzure.AccountKey := azAccountKey;
end;
end;
procedure TQuickAzure.SetAzureProtocol(azProtocol: TAzureProtocol);
begin
if fAzureProtocol <> azProtocol then
begin
fAzureProtocol := azProtocol;
if azProtocol = azHTTP then fconAzure.Protocol := 'HTTP'
else fconAzure.Protocol := 'HTTPS';
end;
end;
function TQuickAzure.FileToArray(cFilename : string) : TArray<Byte>;
var
fs : TFileStream;
begin
fs := TFileStream.Create(cFilename, fmOpenRead);
try
Result := ByteContent(fs);
finally
fs.Free;
end;
end;
function TQuickAzure.StreamToArray(cStream : TStream) : TArray<Byte>;
var
bs : TBytesStream;
begin
bs := TBytesStream.Create(Result);
try
bs.LoadFromStream(cStream);
Result := bs.Bytes;
finally
bs.Free
end;
end;
function TQuickAzure.ByteContent(DataStream: TStream): TBytes;
var
Buffer: TBytes;
begin
if not Assigned(DataStream) then Exit(nil);
SetLength(Buffer, DataStream.Size);
// the content may have been read
DataStream.Position := 0;
if DataStream.Size > 0 then
DataStream.Read(Buffer[0], DataStream.Size);
Result := Buffer;
end;
function TQuickAzure.GMT2DateTime(const gmtdate : string):TDateTime;
function GetMonthDig(Value : string):Integer;
const
aMonth : array[1..12] of string = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var
idx : Integer;
begin
Result := 0;
for idx := 1 to 12 do
begin
if CompareText(Value,aMonth[idx]) = 0 then
begin
Result := idx;
Break;
end;
end;
end;
var
i : Integer;
Len : Integer;
wDay, wMonth, wYear,
wHour, wMinute, wSec : Word;
begin
//GMT Format: 'Mon, 12 Jan 2014 16:20:35 GMT'
Result := 0;
Len := 0;
if gmtdate = '' then Exit;
try
for i := 0 to Length(gmtdate) do
begin
if gmtdate[i] in ['0'..'9'] then
begin
Len := i;
Break;
end;
end;
//Day
wDay := StrToIntDef(Copy(gmtdate,Len,2),0);
if wDay = 0 then Exit;
Inc(Len,3);
//Month
wMonth := GetMonthDig(Copy(gmtdate,Len,3));
if wMonth = 0 then Exit;
Inc(Len,4);
//Year
wYear := StrToIntDef(Copy(gmtdate,Len,4),0);
if wYear = 0 then Exit;
Inc(Len,5);
//Hour
wHour := StrToIntDef(Copy(gmtdate,Len,2),99);
if wHour = 99 then Exit;
Inc(Len,3);
//Min
wMinute := StrToIntDef(Copy(gmtdate,Len,2),99);
if wMinute = 99 then Exit;
Inc(Len,3);
//Sec
wSec := StrToIntDef(Copy(gmtdate,Len,2),99);
if wSec = 99 then Exit;
Result := EncodeDate(wYear,wMonth,wDay) + EncodeTime(wHour,wMinute,wSec,0);
except
Result := 0;
end;
end;
function GetResponseInfo(ResponseInfo : TCloudResponseInfo) : TAzureResponseInfo;
begin
Result.StatusCode := ResponseInfo.StatusCode;
Result.StatusMsg := ResponseInfo.StatusMessage;
end;
function TQuickAzure.PutBlob(const azContainer, cFilename, azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
Content : TArray<Byte>;
CloudResponseInfo : TCloudResponseInfo;
container : string;
blobname : string;
begin
BlobService := TAzureBlobService.Create(fconAzure);
try
container := CheckContainer(azContainer);
CloudResponseInfo := TCloudResponseInfo.Create;
try
BlobService.Timeout := fTimeout;
Content := FileToArray(cFilename);
if azBlobName = '' then blobname := cFilename
else blobname := azBlobName;
if blobname.StartsWith('/') then blobname := Copy(blobname,2,Length(blobname));
Result := BlobService.PutBlockBlob(container,blobname,Content,EmptyStr,nil,nil,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.PutBlob(const azContainer : string; cStream : TStream; const azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
Content : TBytes;
CloudResponseInfo : TCloudResponseInfo;
container : string;
blobname : string;
begin
Result := False;
azResponseInfo.StatusCode := 500;
if cStream.Size = 0 then
begin
azResponseInfo.StatusMsg := 'Stream is empty';
Exit;
end;
container := CheckContainer(azContainer);
blobname := RemoveFirstSlash(azBlobName);
try
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
CloudResponseInfo := TCloudResponseInfo.Create;
try
Content := ByteContent(cStream);
Result := BlobService.PutBlockBlob(container,blobname,Content,EmptyStr,nil,nil,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
except
on E : Exception do
begin
azResponseInfo.StatusCode := 500;
azResponseInfo.StatusMsg := e.message;
Result := False;
end;
end;
end;
function TQuickAzure.GetBlob(const azContainer, azBlobName, cFilenameTo : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
fs : TFileStream;
CloudResponseInfo : TCloudResponseInfo;
container : string;
blobname : string;
begin
container := CheckContainer(azContainer);
blobname := RemoveFirstSlash(azBlobName);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
fs := TFileStream.Create(cFilenameTo,fmCreate);
try
try
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.GetBlob(container,blobname,fs,EmptyStr,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
except
Result := False;
end;
finally
fs.Free;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.GetBlob(const azContainer, azBlobName : string; out azResponseInfo : TAzureResponseInfo; out Stream : TMemoryStream) : Boolean;
begin
Stream := TMemoryStream.Create;
try
Result := GetBlob(azContainer,azBlobName,azResponseInfo,TStream(Stream));
except
Stream.Free;
end;
end;
function TQuickAzure.GetBlob(const azContainer, azBlobName : string; out azResponseInfo : TAzureResponseInfo) : TMemoryStream;
begin
GetBlob(azContainer,azBlobName,azResponseInfo,Result);
end;
function TQuickAzure.GetBlob(const azContainer, azBlobName: string; out azResponseInfo: TAzureResponseInfo; var Stream: TStream): Boolean;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
container : string;
blobname : string;
begin
container := CheckContainer(azContainer);
blobname := RemoveFirstSlash(azBlobName);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.GetBlob(container,blobname,Stream,EmptyStr,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.CheckContainer(const aContainer: string): string;
begin
if aContainer = '' then Result := '$root'
else Result := aContainer;
end;
function TQuickAzure.CopyBlob(const azSourceContainer, azSourceBlobName : string; azTargetContainer, azTargetBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
sourcecontainer : string;
targetcontainer : string;
sourceblobname : string;
targetblobname : string;
begin
sourcecontainer := CheckContainer(azSourceContainer);
targetcontainer := CheckContainer(azTargetContainer);
sourceblobname := RemoveFirstSlash(azSourceBlobName);
targetblobname := RemoveFirstSlash(azTargetBlobName);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
try
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.CopyBlob(targetcontainer,targetblobname,sourcecontainer,sourceblobname,'',nil,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
except
on E : Exception do
begin
Result := False;
azResponseInfo.StatusCode := 500;
azResponseInfo.StatusMsg := e.message;
end;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.RemoveFirstSlash(const aValue: string): string;
begin
if aValue.StartsWith('/') then Result := Copy(aValue,2,Length(aValue))
else Result := aValue;
end;
function TQuickAzure.RenameBlob(const azContainer, azSourceBlobName, azTargetBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
sourceblobname : string;
begin
Result := False;
if sourceblobname.Contains('%') then sourceblobname := azSourceBlobName
else sourceblobname := TIdURI.PathEncode(azSourceBlobName);
if CopyBlob(azContainer,sourceblobname,azContainer,azTargetBlobName,azResponseInfo) then
begin
Result := DeleteBlob(azContainer,azSourceBlobName,azResponseInfo);
end;
end;
function TQuickAzure.ExistsObject(const azContainer, azBlobName : string) : Boolean;
var
azBlob : string;
azBlobs : TStrings;
ResponseInfo : TAzureResponseInfo;
begin
Result := False;
azBlobs := ListBlobsNames(azContainer,azBlobName,False,ResponseInfo);
try
if (ResponseInfo.StatusCode = 200) and (Assigned(azBlobs)) then
begin
for azBlob in azBlobs do
begin
if azBlob = azBlobName then
begin
Result := True;
Break;
end;
end;
end;
finally
azBlobs.Free;
end;
end;
function TQuickAzure.ExistsFolder(const azContainer, azFolderName : string) : Boolean;
var
BlobService : TAzureBlobService;
azBlob : TAzureBlob;
azBlobList : TList<TAzureBlob>;
CloudResponseInfo : TCloudResponseInfo;
AzParams : TStrings;
cNextMarker : string;
container : string;
foldername : string;
begin
Result := False;
container := CheckContainer(azContainer);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
AzParams := TStringList.Create;
try
if not azFolderName.EndsWith('/') then foldername := azFolderName + '/'
else foldername := azFolderName;
AzParams.Values['prefix'] := foldername;
AzParams.Values['delimiter'] := '/';
AzParams.Values['maxresults'] := '1';
cNextMarker := '';
CloudResponseInfo := TCloudResponseInfo.Create;
try
azBlobList := BlobService.ListBlobs(container,cNextMarker,AzParams,CloudResponseInfo);
try
if (Assigned(azBlobList)) and (azBlobList.Count > 0) and (CloudResponseInfo.StatusCode = 200) then Result := True;
finally
//frees azbloblist objects
for azBlob in azBlobList do azBlob.Free;
azBlobList.Free;
end;
finally
CloudResponseInfo.Free;
end;
finally
AzParams.Free;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.DeleteBlob(const azContainer,azBlobName : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
container : string;
blobname : string;
begin
container := CheckContainer(azContainer);
blobname := RemoveFirstSlash(azBlobName);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.DeleteBlob(container,blobname,False,EmptyStr,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
end;
{$IFDEF DELPHITOKYO_UP}
function TQuickAzure.ListBlobs(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TBlobList;
var
BlobService : TAzureBlobService;
azBlob : TAzureBlobItem;
azBlobList : TArray<TAzureBlobItem>;
Blob : TAzureBlobObject;
CloudResponseInfo : TCloudResponseInfo;
cNextMarker : string;
container : string;
prefix : string;
blobprefix : TArray<string>;
xmlresp : string;
folder : string;
prop : TPair<string,string>;
previousMaker : string;
begin
Result := TBlobList.Create(True);
cNextMarker := '';
container := CheckContainer(azContainer);
BlobService := TAzureBlobService.Create(fconAzure);
try
if Recursive then prefix := ''
else prefix := '/';
BlobService.Timeout := fTimeout;
repeat
CloudResponseInfo := TCloudResponseInfo.Create;
try
previousMaker := cNextMarker;
azBlobList := BlobService.ListBlobs(azContainer,azBlobsStartWith,'/',previousMaker,100,[],cNextMarker,blobprefix,xmlresp,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
if Assigned(azBlobList) then Result.Capacity := High(azBlobList);
//get folders (prefix)
for folder in blobprefix do
begin
Blob := TAzureBlobObject.Create;
if folder.EndsWith('/') then Blob.Name := RemoveLastChar(folder)
else Blob.Name := folder;
Blob.Name := Copy(Blob.Name,Blob.Name.LastDelimiter('/')+2,Blob.Name.Length);
Blob.IsDir := True;
Result.Add(Blob);
end;
//get files (blobs)
if Assigned(azBlobList) then
begin
for azBlob in azBlobList do
begin
Blob := TAzureBlobObject.Create;
Blob.Name := azBlob.Name;
for prop in azBlob.Properties do
begin
if prop.Key = 'Content-Length' then Blob.Size := StrToInt64Def(prop.Value,0)
else if prop.Key = 'Last-Modified' then Blob.LastModified := GMT2DateTime(prop.Value);
end;
Blob.IsDir := False;
Result.Add(Blob);
end;
end;
finally
CloudResponseInfo.Free;
end;
until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200);
finally
BlobService.Free;
end;
end;
{$ELSE}
function TQuickAzure.ListBlobs(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TBlobList;
var
BlobService : TAzureBlobService;
azBlob : TAzureBlob;
azBlobList : TList<TAzureBlob>;
Blob : TAzureBlobObject;
CloudResponseInfo : TCloudResponseInfo;
cNextMarker : string;
AzParams : TStrings;
container : string;
xmlresp : string;
previousMarker : string;
begin
Result := TBlobList.Create(True);
cNextMarker := '';
container := CheckContainer(azContainer);
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
repeat
AzParams := TStringList.Create;
try
AzParams.Values['prefix'] := azBlobsStartWith;
if not Recursive then AzParams.Values['delimiter'] := '/';
if cNextMarker <> '' then AzParams.Values['marker'] := cNextMarker;
CloudResponseInfo := TCloudResponseInfo.Create;
try
azBlobList := BlobService.ListBlobs(container,cNextMarker,AzParams,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
if Assigned(azBlobList) then
begin
Result.Capacity := High(azBlobList);
try
for azBlob in azBlobList do
begin
Blob := TAzureBlobObject.Create;
Blob.Name := azBlob.Name;
Blob.Size := StrToInt64Def(azBlob.Properties.Values['Content-Length'],0);
Blob.LastModified := GMT2DateTime(azBlob.Properties.Values['Last-Modified']);
Result.Add(Blob);
end;
finally
//frees azbloblist objects
for azBlob in azBlobList do azBlob.Free;
azBlobList.Free;
end;
end;
finally
CloudResponseInfo.Free;
end;
finally
FreeAndNil(AzParams);
end;
until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200);
finally
BlobService.Free;
end;
end;
{$ENDIF}
{$IFDEF DELPHITOKYO_UP}
function TQuickAzure.ListBlobsNames(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TStrings;
var
BlobService : TAzureBlobService;
azBlob : TAzureBlobItem;
azBlobList : TArray<TAzureBlobItem>;
Blob : TAzureBlobObject;
CloudResponseInfo : TCloudResponseInfo;
cNextMarker : string;
container : string;
prefix : string;
blobprefix : TArray<string>;
xmlresp : string;
folder : string;
prop : TPair<string,string>;
previousMaker : string;
begin
Result := TStringList.Create;
cNextMarker := '';
container := CheckContainer(azContainer);
BlobService := TAzureBlobService.Create(fconAzure);
try
if Recursive then prefix := ''
else prefix := '/';
BlobService.Timeout := fTimeout;
repeat
CloudResponseInfo := TCloudResponseInfo.Create;
try
previousMaker := cNextMarker;
azBlobList := BlobService.ListBlobs(azContainer,azBlobsStartWith,'/',previousMaker,100,[],cNextMarker,blobprefix,xmlresp,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
if Assigned(azBlobList) then Result.Capacity := High(azBlobList);
//get folders (prefix)
for folder in blobprefix do
begin
Blob := TAzureBlobObject.Create;
if folder.EndsWith('/') then Blob.Name := RemoveLastChar(folder)
else Blob.Name := folder;
Result.Add(Copy(Blob.Name,Blob.Name.LastDelimiter('/')+2,Blob.Name.Length));
end;
//get files (blobs)
if Assigned(azBlobList) then
begin
for azBlob in azBlobList do
begin
Result.Add(azBlob.Name);
end;
end;
finally
CloudResponseInfo.Free;
end;
until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200);
finally
BlobService.Free;
end;
end;
{$ELSE}
function TQuickAzure.ListBlobsNames(const azContainer, azBlobsStartWith : string; Recursive : Boolean; out azResponseInfo : TAzureResponseInfo) : TStrings;
var
BlobService : TAzureBlobService;
azBlob : TAzureBlob;
azBlobList : TList<TAzureBlob>;
CloudResponseInfo : TCloudResponseInfo;
cNextMarker : string;
AzParams : TStrings;
container : string;
begin
Result := TStringList.Create;
cNextMarker := '';
container := CheckContainer(azContainer);
BlobService := TAzureBlobService.Create(fconAzure);
CloudResponseInfo := TCloudResponseInfo.Create;
try
BlobService.Timeout := fTimeout;
repeat
AzParams := TStringList.Create;
try
AzParams.Values['prefix'] := azBlobsStartWith;
if not Recursive then AzParams.Values['delimiter'] := '/';
if cNextMarker <> '' then AzParams.Values['marker'] := cNextMarker;
azBlobList := BlobService.ListBlobs(container,cNextMarker,AzParams,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
if Assigned(azBlobList) then
begin
Result.Capacity := azBlobList.Count;
Result.BeginUpdate;
try
for azBlob in azBlobList do Result.Add(azBlob.Name);
finally
Result.EndUpdate;
//frees bloblist objects
for azBlob in azBlobList do azBlob.Free;
azBlobList.Free;
end;
end;
finally
AzParams.Free;
end;
until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200);
finally
BlobService.Free;
CloudResponseInfo.Free;
end;
end;
{$ENDIF}
function TQuickAzure.ExistsContainer(const azContainer : string) : Boolean;
var
Container : string;
Containers : TStrings;
ResponseInfo : TAzureResponseInfo;
begin
Result := False;
Containers := ListContainers(azContainer,ResponseInfo);
try
if (ResponseInfo.StatusCode = 200) and (Assigned(Containers)) then
begin
for Container in Containers do
begin
if Container = azContainer then
begin
Result := True;
Break;
end;
end;
end;
finally
Containers.Free;
end;
end;
function TQuickAzure.ListContainers(const azContainersStartWith : string; out azResponseInfo : TAzureResponseInfo) : TStrings;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
cNextMarker : string;
AzParams : TStrings;
AzContainer : TAzureContainer;
AzContainers : TList<TAzureContainer>;
begin
Result := TStringList.Create;
cNextMarker := '';
BlobService := TAzureBlobService.Create(fconAzure);
CloudResponseInfo := TCloudResponseInfo.Create;
try
BlobService.Timeout := fTimeout;
repeat
AzParams := TStringList.Create;
try
if azContainersStartWith <> '' then AzParams.Values['prefix'] := azContainersStartWith;
if cNextMarker <> '' then AzParams.Values['marker'] := cNextMarker;
AzContainers := BlobService.ListContainers(cNextMarker,AzParams,CloudResponseInfo);
try
azResponseInfo := GetResponseInfo(CloudResponseInfo);
if (azResponseInfo.StatusCode = 200) and (Assigned(AzContainers)) then
begin
Result.Capacity := AzContainers.Count;
for AzContainer in AzContainers do
begin
Result.Add(AzContainer.Name);
end;
end;
finally
if Assigned(AzContainers) then
begin
//frees ContainerList objects
for AzContainer in AzContainers do AzContainer.Free;
AzContainers.Free;
end;
end;
finally
AzParams.Free;
end;
until (cNextMarker = '') or (azResponseInfo.StatusCode <> 200);
finally
BlobService.Free;
CloudResponseInfo.Free;
end;
end;
function TQuickAzure.CreateContainer(const azContainer : string; azPublicAccess : TBlobPublicAccess; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
begin
Result := False;
if azContainer = '' then Exit;
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.CreateContainer(azContainer,nil,azPublicAccess,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
end;
function TQuickAzure.DeleteContainer(const azContainer : string; out azResponseInfo : TAzureResponseInfo) : Boolean;
var
BlobService : TAzureBlobService;
CloudResponseInfo : TCloudResponseInfo;
begin
Result := False;
if azContainer = '' then Exit;
BlobService := TAzureBlobService.Create(fconAzure);
try
BlobService.Timeout := fTimeout;
CloudResponseInfo := TCloudResponseInfo.Create;
try
Result := BlobService.DeleteContainer(azContainer,CloudResponseInfo);
azResponseInfo := GetResponseInfo(CloudResponseInfo);
finally
CloudResponseInfo.Free;
end;
finally
BlobService.Free;
end;
end;
end.
|
{ C-to-Pas converter command-line utility part of Lazarus Chelper package
Copyright (C) 2010 Dmitry Boyarintsev skalogryz dot lists at gmail.com
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.
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.
}
program cconvert;
{$mode delphi}{$H+}
{.$define leaks}
uses
{$ifdef leaks}
heaptrc,
{$endif}
SysUtils,Classes,
ctopasconvert, cparsertypes, cparserutils, cconvconfig, objcparsing
, cconvlog;
var
ConfigFile : AnsiString = '';
OutputFile : AnsiString = '';
ConfigFileRO : Boolean = false;
ParseAll : Boolean = true;
ShowCodeSize : Boolean = False; // show the size of code processed
isPascalUnit : Boolean = False; // convert to pascal unit
isPrintHelp : Boolean = False;
isVerbose : Boolean = false;
DoIncludes : Boolean = true;
IgnoreDefines : TStringList = nil;
IncludePath : TStringList = nil; // adjustement for include paths
procedure NormalizePath(var pth: string);
var
i : integer;
begin
for i:=1 to length(pth) do
if pth[i] in ['/','\'] then
pth[i]:=DirectorySeparator;
end;
procedure AddStringsFromFile(st: TStrings; const fn: string);
var
add : TstringList;
begin
if not FileExists(fn) then Exit;
try
add := TstringList.Create;
try
add.LoadFromFile(fn);
st.AddStrings(add);
finally
add.Free;
end;
except
end;
end;
function isIncludePath(const include: string; var pth: string; isSystemPath: Boolean): Boolean;
var
i : integer;
p : string;
v : string;
begin
pth:=include;
NormalizePath(pth);
p:=ExtractFileDir(pth);
if (p='') then p:='.'; // special case
i:=IncludePath.IndexOfName(p);
Result:=i>=0;
if not Result then begin
// always include empty path, even if it was not specified
if p ='.' then Result:=not isSystemPath;
Exit;
end;
v:=IncludePath.ValueFromIndex[i];
if p<>'' then p:=IncludeTrailingPathDelimiter(p);
pth:=StringReplace(pth, p, v, [rfIgnoreCase]);
//pth:=StringReplace(include, '\', DirectorySeparator, [rfReplaceAll]);
end;
function StringFromFile(const FileName: AnsiString): AnsiString;
var
fs : TFileStream;
begin
Result:='';
if not FileExists(FileName) then Exit;
try
fs:=TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
SetLength(Result, fs.Size);
fs.Read(Result[1], fs.Size);
finally
fs.Free;
end;
except
end;
end;
function SafeParamStr(i: integer): string;
begin
if (i>=0) and (i<=ParamCount) then Result:=ParamStr(i)
else Result:='';
end;
procedure PrintHelp;
begin
writeln('cconvert 1.1 - c to pascal convert utility by Dmitry Boyarintsev');
writeln('usage:');
writeln(' cconvert [options] %header_filename%');
writeln('possible options:');
writeln(' -first - stops on the first first entity');
writeln(' -o %filename% - specify the output file. if not specified, outputs to stdout');
writeln(' -ro - prevent the configuration file from modifications (adding new types, etc)');
writeln(' -cfg %filename% - specifies the configuration file');
writeln(' -defines %filename%');
writeln(' - macros definition file. should be in C-preprocessor format');
writeln(' -showunparsed - writes out unprased entities by their classname (for debugging only)');
writeln(' -codesize - show two numbers of the code processed (used by Chelper)');
writeln(' -pasunit - generates a pascal unit');
writeln(' -noinclude - prevent processing of #include-ed or @import-ed files');
writeln(' -ip %include_path%[:%phys_path%]');
writeln(' - specify paths to be included (imported) during the conversion');
writeln(' allowing mulitple files to be converted in one call.');
writeln(' physical path is used to specify the actual physical path on the hard drive.');
writeln(' if not specified, the current directory is assumed as a location for the header');
writeln(' -verbose - verbose output');
writeln(' -id %name_of_define%');
writeln(' -id @%filename% ');
writeln(' - the macros name or file name constaining the list of defines to be ignored ');
end;
procedure ConsumeIncludePath(const s: string);
var
k : integer;
ip : string;
pp : string;
begin
if s ='' then Exit;
k:=Pos(':', s);
if k=0 then begin
pp:='';
ip:=s;
end else begin
pp:=Copy(s, k+1, length(s));
ip:=Copy(s, 1, k-1);
end;
if ip='' then ip:='.';
if ip<>'' then begin
NormalizePath(ip);
IncludePath.Values[ip]:=pp;
end;
end;
procedure ReadParams(files: TStrings; cfg: TConvertSettings);
var
i : integer;
s : string;
ss : string;
fn : AnsiString;
k : integer;
begin
if ParamCount=0 then
isPrintHelp:=true
else begin
i:=1;
while i<= ParamCount do begin
ss:=SafeParamStr(i);
s:=LowerCase(ss);
if (s='-h') or (s='-help') or (s='-?') then begin
isPrintHelp:=true;
Break;
end else if s='-showunparsed' then begin
DoDebugEntities:=True;
end else if s='-cfg' then begin
inc(i);
fn:=Trim(SafeParamStr(i));
ConfigFile:=fn;
if FileExists(fn) then cconvconfig.LoadFromFile(fn, cfg);
end else if s='-ro' then
ConfigFileRO:=True
else if s='-defines' then begin
inc(i);
cfg.CustomDefines:=cfg.CustomDefines+' ' + StringFromFile(SafeParamStr(i));
end else if s='-o' then begin
inc(i);
OutputFile:=SafeParamStr(i);
end else if s='-first' then begin
ParseAll:=false
end else if s='-pasunit' then begin
isPascalUnit:=True;
end else if s='-noinclude' then begin
DoIncludes:=false;
end else if s='-verbose' then begin
// do not assign log function now, wait until all params are done
isVerbose:=true;
end else if s='-ip' then begin
inc(i);
ConsumeIncludePath( Trim(SafeParamStr(i)) );
end else if s='-ig' then begin
inc(i);
fn:=Trim(SafeParamStr(i));
if (fn<>'') then begin
if (fn[1]='@')
then AddStringsFromFile(IgnoreDefines, Copy(fn,2,length(fn)))
else IgnoreDefines.Add(fn);
end;
end else
files.Add(ss);
inc(i);
end;
//InputFileName:=SafeParamStr(ParamCount);
end;
if isVerbose then _log:=_stdOutLog;
end;
function GetPascalUnitName(const UnitName: String): String;
begin
Result:=ChangeFileExt(UnitName, '');
end;
procedure AddPascalUnit(outs: TStrings; const UnitName: String);
begin
if not Assigned(outs) then Exit;
outs.Insert(0, 'unit '+UnitName+';');
outs.Insert(1, '');
outs.Insert(2, 'interface');
outs.Add( 'implementation');
outs.Add( 'end.');
end;
function GetIncludeFN(const fn: string): string;
var
i : integer;
begin
i:=length(fn);
while (i>0) and not (fn[i] in ['/','\']) do dec(i);
Result:=Copy(fn, i+1, length(fn));
end;
function SortByUsage(p1, p2: Pointer): integer;
var
f1, f2: THeaderFile;
begin
f1:=THeaderFile(p1);
f2:=THeaderFile(p2);
if (f1.usedBy=f2.usedBy) then begin
if f1.inclOrder=f2.inclOrder then Result:=0
else if f1.inclOrder<f2.inclOrder then Result:=-1
else Result:=1;
end else if (f1.usedBy<>0) then begin
if f1.usedBy<=f2.inclOrder then Result:=-1
else Result:=1;
end else if (f2.usedBy<>0) then begin
if f2.usedBy<=f1.inclOrder then Result:=1
else Result:=-1;
end;
end;
procedure ResortByUsage(files: TStrings);
var
fl : TList;
i : integer;
begin
fl:=TList.Create;
try
for i:=0 to files.Count-1 do
fl.Add(files.Objects[i]);
fl.Sort(SortByUsage);
files.Clear;
for i:=0 to fl.Count-1 do
files.AddObject( THeaderFile(fl[i]).fn, fl[i] );
finally
fl.Free;
end;
end;
(*
procedure NewerMode(files: TStrings; cfg: TConvertSettings);
var
inp : TParseInput;
ot : TParseOutput;
txt : TSTringList;
res : string;
fn : string;
i : integer;
j : integer;
fi : integer;
ic : TCPrepInclude;
hdr : THeaderFile;
hh : THeaderFile;
begin
InitCParserInput(inp, true);
try
LoadDefines(inp, cfg.CustomDefines);
i:=0;
while i<files.Count do begin
fn:=files[i];
hdr:=THeaderFile(files.Objects[i]);
if not Assigned(hdr) then begin
hdr:=THeaderFile.Create;
hdr.fn:=ExtractFileName(fn);
files.Objects[i]:=hdr;
end;
hdr.inclOrder:=i;
txt:=TStringList.Create;
try
txt.LoadFromFile(fn);
ResetText(inp, txt.Text);
finally
txt.Free;
end;
//writeln('parsing entities');
if not ParseCEntities(inp, hdr.ents, ot) then begin
//writeln('error:');
writeln('Parsing error at ', fn,' (',ot.error.ErrorPos.y,':',ot.error.ErrorPos.X,')');
writeln(ot.error.ErrorMsg);
ReleaseList(hdr.Ents);
inc(i);
Continue;
end;
hdr.text:=inp.parser.Buf;
// assing internal comments
//DebugEnList(ents);
AssignIntComments(hdr.ents);
//DebugEnList(ents);
//writeln('c to pas');
//res:=CEntitiesToPas(inp.parser.Buf, hdr.ents, cfg);
//writeln('done!');
//writeln(res);
if DoIncludes then
for j:=0 to hdr.ents.Count-1 do
if TObject(hdr.ents[j]) is TCPrepInclude then begin
ic:=TCPrepInclude(hdr.ents[j]);
if isIncludePath(ic.Included, fn) then begin
//fn:='C:\fpc_laz\chelper\uikit\Headers\'+GetIncludeFN(ic.Included);
fi:=Files.IndexOf(fn);
if fi<0 then
// GetIncludeFN(ic.Included) is a hack not to add UIKit.h twice
fi:=Files.IndexOf( GetIncludeFN(ic.Included) );
if fi<0 then begin
log('adding: ', fn);
hh:=THeaderFile.Create;
hh.fn:=ExtractFileName(fn);
hh.usedBy:=hdr.inclOrder;
fi:=Files.AddObject(fn, hh);
end else begin
hh:=THeaderFile(Files.Objects[fi]);
// fi<>0 is a hack not to add reassing UIKit.h twice
if (hh.usedBy=0) and (fi<>0) then hh.usedBy:=i;
end;
inc(THeaderFile(Files.Objects[fi]).useCount);
end;
end;
inc(i);
end;
if isVerbose then begin
log('files count = ', files.Count);
log('original order');
DebugHeaders(files);
end;
log('files order after usage resolving');
ResortByUsage(files);
if isVerbose then DebugHeaders(files);
for i:=0 to files.Count-1 do begin
hdr:=THeaderFile(files.Objects[i]);
log('// '+files[i]+' ', hdr.ents.Count);
res:=CEntitiesToPas(hdr.text, hdr.ents, cfg);
writeln(res);
end;
{writeln('alphabet!');
TSTringList(files).Sort;
DebugHeaders(files);}
finally
FreeCParserInput(inp);
end;
end;
procedure OldMode(fns: TStrings; cfg: TConvertSettings);
var
inps, outs: TStringList;
err : TErrorInfo;
p : TPoint;
i : Integer;
begin
inps := TStringList.Create;
outs := TStringList.Create;
try
inps.LoadFromFile(ParamStr(ParamCount));
outs.Text:=ConvertCode(inps.Text, p, ParseAll, err, cfg);;
if ShowCodeSize then outs.Insert(0, Format('%d %d', [p.Y,p.X]));
if err.isError then outs.Insert(0, Format('error %d %d %s',[err.ErrorPos.Y, err.ErrorPos. X, err.ErrorMsg]) );
if isPascalUnit then begin
AddPascalUnit(outs, GetPascalUnitName(fns[0]));
end;
if OutputFile<>'' then
outs.SaveToFile(OutputFile)
else
for i:=0 to outs.Count-1 do
writeln(outs[i]);
finally
if not ConfigFileRO and (ConfigFile<>'') then begin
ForceDirectories(ExtractFilePath(ConfigFile));
try
cconvconfig.SaveToFile(ConfigFile, cfg);
except
end;
end;
inps.Free;
outs.Free;
end;
end;
*)
procedure SaveDebugToFile(const buf, filename: string; const comment: string = '');
var
fn : string;
st : text;
begin
fn:='__'+ExtractFileName(filename);
Assign(st, fn); Rewrite(st);
if comment='' then
write(st, buf)
else begin
writeln(st,buf);
writeln(st,'-----');
write(st,comment);
end;
CloseFile(st);
end;
procedure NewestMode(files: TStrings; cfg: TConvertSettings);
var
inp : TParseInput;
ot : TParseOutput;
txt : TStringList;
buf : string;
res : string;
fn : string;
i : integer;
j : integer;
fi : integer;
ic : TCPrepInclude;
hdr : THeaderFile;
hh : THeaderFile;
applied : TList;
begin
applied := TList.Create;
InitCParserInput(inp, true);
try
LoadDefines(inp, cfg.CustomDefines);
i:=0;
while i<files.Count do begin
fn:=files[i];
log(fn);
log('reading');
hdr:=THeaderFile(files.Objects[i]);
if not Assigned(hdr) then begin
hdr:=THeaderFile.Create;
hdr.fn:=ExtractFileName(fn);
files.Objects[i]:=hdr;
end;
hdr.inclOrder:=i;
txt:=TStringList.Create;
try
txt.LoadFromFile(fn);
buf:=txt.Text;
finally
txt.Free;
end;
log('preprocing %s ', [fn]);
buf:=PreprocGlobal(buf, hdr.fileOfs, hdr.cmts);
ParseDirectives(buf, hdr.pres);
applied.Clear;
buf:=PreprocessHeader(buf, hdr.pres, inp.parser.MacroHandler, hdr.fileOfs, IgnoreDefines, applied);
log('preprocing done');
hdr.text:=Buf;
if DoIncludes then begin
Log ('checking included headers');
for j:=0 to applied.Count-1 do
if TObject(applied[j]) is TCPrepInclude then begin
ic:=TCPrepInclude(applied[j]);
if isIncludePath(ic.Included, fn, ic.isSysFile) then begin
Log('adding %s to headers list', [ic.Included]);
fi:=Files.IndexOf(fn);
if not FileExists(fn) then begin
log('warning: incluide file %s not found', [fn]);
Continue;
end;
if fi<0 then
// GetIncludeFN(ic.Included) is a hack not to add UIKit.h twice
fi:=Files.IndexOf( GetIncludeFN(ic.Included) );
if fi<0 then begin
log('adding: ', fn);
hh:=THeaderFile.Create;
hh.fn:=ExtractFileName(fn);
hh.usedBy:=hdr.inclOrder;
fi:=Files.AddObject(fn, hh);
end else begin
log('%s is already in the list ', [ic.Included]);
hh:=THeaderFile(Files.Objects[fi]);
// fi<>0 is a hack not to add reassing UIKit.h twice
if (hh.usedBy=0) and (fi<>0) then hh.usedBy:=i;
end;
inc(THeaderFile(Files.Objects[fi]).useCount);
end else
Log('%s is not suggested for inclusion or a system header', [ic.Included]);
end; {if CPreInclude}
end;
inc(i);
log('');
end;
log('');
if isVerbose then begin
log('total header files count ', files.Count);
log('parsing order:');
DebugHeaders(files);
end;
log('');
log('files order after usage resolving: ');
ResortByUsage(files);
if isVerbose then DebugHeaders(files);
log('macros:');
DebugMacros(inp.mmaker.hnd);
log('');
log('parsing files');
for i:=0 to files.count-1 do begin
hdr := THeaderFile(files.Objects[i]);
Log(files[i]);
Log('parsing, header length %d bytes', [length(hdr.text)]);
ResetText(inp, hdr.text);
//writeln(hdr.text);
if not ParseCEntities(inp, hdr.ents, ot) then begin
writeln('error:');
writeln('Parsing error at ', fn,' (',ot.error.ErrorPos.y,':',ot.error.ErrorPos.X,')');
writeln(ot.error.ErrorMsg);
ReleaseList(hdr.Ents);
SaveDebugToFile(inp.parser.Buf
+LineEnding+'----'+LineEnding+
buf
, fn,
Format('Parsing error at "%s" (%d:%d)'#13#10'%s',
[fn, ot.error.ErrorPos.y, ot.error.ErrorPos.X,ot.error.ErrorMsg]));
end; // else
log('done!');
//AssignIntComments(hdr.ents);
end;
//writeln('cout = ', files.Count);
for i:=0 to files.Count-1 do begin
hdr:=THeaderFile(files.Objects[i]);
log('// '+files[i]+' ', hdr.ents.Count);
res:=CEntitiesToPas(hdr.text, hdr.ents, cfg);
writeln(res);
end;
{writeln('alphabet!');
TSTringList(files).Sort;
DebugHeaders(files);}
finally
FreeCParserInput(inp);
applied.Free;
end;
end;
var
cfg : TConvertSettings;
fns : TStringList;
begin
{$ifdef leaks}
DeleteFile('leaks.txt');
SetHeapTraceOutput('leaks.txt');
{$endif}
cfg:=TConvertSettings.Create;
fns:=TStringList.Create;
IncludePath:=TStringList.Create;
IgnoreDefines:=TStringList.Create;
try
ReadParams(fns, cfg);
if isPrintHelp then begin
PrintHelp;
Exit;
end;
if fns.Count=0 then begin
writeln('no input header files were specified');
Exit;
end;
NewestMode(fns, cfg);
finally
cfg.Free;
fns.Free;
IncludePath.Free;
IgnoreDefines.Free;
end;
end.
|
{******************************************************************************}
{* TFMREG - Programmers registry editor. *}
{* Copyright Toby Allen - Toflidium Software 2001 *}
{* *}
{******************************************************************************}
{* *}
{* 7/02/2002 Toby *}
{* 1. Form no longer created here, must be created when called. *}
{******************************************************************************}
unit SearchValuesDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
tfmRegClasses,
tfmCommonReg;
type
TfrmSearchValuesDlg = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
ckbxHKCR: TCheckBox;
ckbxHKCU: TCheckBox;
ckbxHKLM: TCheckBox;
ckbxHKU: TCheckBox;
ckbxHKCC: TCheckBox;
ckbxSearchKeys: TCheckBox;
ckbxSearchValueNames: TCheckBox;
ckbxSearchValueData: TCheckBox;
ckbxSearchCaseSensitive: TCheckBox;
ckbxMatchWholeKey: TCheckBox;
edSearchValue: TEdit;
btnCancel: TButton;
btnOK: TButton;
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Function ShowAndReturn(Const Search: TRegSearch) : Boolean;
end;
var
frmSearchValuesDlg: TfrmSearchValuesDlg;
implementation
{$R *.DFM}
{ TfrmSearchValuesDlg }
function TfrmSearchValuesDlg.ShowAndReturn(
const Search: TRegSearch): Boolean;
begin
Result := False;
if showmodal = mrOK then
begin
With Search do
begin
SearchValue := edSearchValue.Text;
SearchValueData := ckbxSearchValueData.checked;
SearchValueName := ckbxSearchValueNames.Checked;
SearchKeyNames := ckbxSearchKeys.Checked;
CaseSensitive := ckbxSearchCaseSensitive.Checked;
MatchWholeKey := ckbxMatchWholeKey.Checked;
HKEYS.ShowHive[hkey_CLasses_Root] := ckbxHKCR.Checked;
HKEYS.ShowHive[hkey_Local_Machine] := ckbxHKLM.Checked;
HKEYS.ShowHive[HKEY_CURRENT_USER] := ckbxHKCU.Checked;
HKEYS.ShowHive[HKEY_CURRENT_CONFIG] := ckbxHKCC.Checked ;
HKEYS.SHOWHIVE[HKEY_USERS] := ckbxHKU.Checked ;
end;
Result := True;
end;
end;
procedure TfrmSearchValuesDlg.btnOKClick(Sender: TObject);
begin
if edSearchValue.text = '' then
begin
Showmessage('You must specify text to be searched for.');
ModalResult := mrNone;
end;
end;
end.
|
unit view.main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.TabControl, FMX.Controls.Presentation, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
System.Actions, FMX.ActnList, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, Data.DB,
FireDAC.Comp.Client, FMX.Objects, FMX.Media, FMX.TMSZBarReader,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
Data.Bind.Components, Data.Bind.ObjectScope, REST.Client, IdIOHandler,
IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, FMX.WebBrowser, System.IOUtils, IdSSLOpenSSLHeaders,
DataPak.Android.BarcodeScanner ;
type
TfmMain = class(TForm)
ToolBar1: TToolBar;
btnHome: TSpeedButton;
btnClose: TSpeedButton;
btnQrCode: TSpeedButton;
tabMain: TTabControl;
tabHome: TTabItem;
ListView1: TListView;
tabSale: TTabItem;
lvSale: TListView;
ToolBar5: TToolBar;
Label2: TLabel;
SpeedButton1: TSpeedButton;
ActionList1: TActionList;
ChangeTabAction1: TChangeTabAction;
Image1: TImage;
lbSupermarket: TLabel;
Image2: TImage;
lbDate: TLabel;
Image3: TImage;
lbMoney: TLabel;
Panel1: TPanel;
IdHTTP1: TIdHTTP;
BarcodeScanner1: TBarcodeScanner;
pnlHome: TPanel;
ToolBar3: TToolBar;
Label3: TLabel;
ToolBar2: TToolBar;
Label1: TLabel;
Image4: TImage;
procedure btnHomeClick(Sender: TObject);
procedure btnQrCodeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure TMSFMXZBarReader1GetResult(Sender: TObject; AResult: string);
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure BarcodeScanner1ScanResult(Sender: TObject; AResult: string);
private
{ Private declarations }
FValorQrCode: String;
Procedure PopulaListView;
procedure PopulaDetalhesCompra(AListViewItem: TListViewItem);
procedure PopupaInformacoes(ACfe: String);
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
uses undados, system.json;
{$R *.fmx}
procedure TfmMain.BarcodeScanner1ScanResult(Sender: TObject; AResult: string);
begin
FValorQrCode := Copy(AResult, (Pos('e', AResult)+1), 44);
if FValorQrCode <> EmptyStr then
begin
PopupaInformacoes(FValorQrCode);
PopulaListView;
tabMain.TabIndex := 0;
end;
end;
procedure TfmMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfmMain.btnHomeClick(Sender: TObject);
begin
tabMain.TabIndex := 0;
end;
procedure TfmMain.btnQrCodeClick(Sender: TObject);
begin
BarcodeScanner1.Scan;
end;
procedure TfmMain.FormShow(Sender: TObject);
var
ListViewItem: TListViewItem;
begin
IdOpenSSLSetLibPath(TPath.GetDocumentsPath);
PopulaListView;
tabMain.TabIndex := 0;
end;
procedure TfmMain.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
begin
PopulaDetalhesCompra(AItem);
tabMain.TabIndex := 1;
end;
procedure TfmMain.PopulaDetalhesCompra(AListViewItem: TListViewItem);
var
ListViewItem: TListViewItem;
begin
lvSale.Items.Clear;
dmDados.QSale.Close;
dmDados.QSaleItem.Close;
if ListView1.Items.Count > 0 then
begin
//Populada dados Compra
dmDados.QSale.Open(Concat('SELECT * FROM SALE WHERE CFEKEY = ', QuotedStr(AListViewItem.Text)));
if dmDados.QSale.RecordCount > 0 then
begin
lbSupermarket.Text := dmDados.QSalefantasyname.AsString;
lbDate.Text := dmDados.QSaleemissionDate.AsString;
lbMoney.Text := Concat('R$ ', dmDados.QSalesubTotal.AsString);
//Popula dados Itens da Compra
dmDados.QSaleItem.Open(Concat('SELECT * FROM SALEITEM WHERE CFEKEY = ', QuotedStr(dmDados.QSalecfeKey.AsString)));
if dmDados.QSaleItem.RecordCount > 0 then
begin
dmDados.QSaleItem.First;
while not dmDados.QSaleItem.Eof do
begin
ListViewItem := lvSale.Items.Add;
ListViewItem.Text := dmDados.QSaleItemdescription.AsString;
ListViewItem.Detail := Concat(dmDados.QSaleItemun.AsString, ' ',
dmDados.QSaleItemamount.AsString, ' - Total: ',
dmDados.QSaleItemprice.AsString);
dmDados.QSaleItem.Next;
end;
end;
end;
end;
end;
procedure TfmMain.PopulaListView;
var
ListViewItem: TListViewItem;
begin
ListView1.Items.Clear;
dmDados.QSale.Close;
dmDados.QSale.Open('SELECT * FROM SALE');
if dmDados.QSale.RecordCount > 0 then
begin
dmDados.QSale.First;
while not dmDados.QSale.Eof do
begin
ListViewItem := ListView1.Items.Add;
ListViewItem.Text := dmDados.QSalecfeKey.AsString;
ListViewItem.Detail := Concat(dmDados.QSalefantasyname.AsString, ' - ',
dmDados.QSaleemissionDate.AsString);
dmDados.QSale.Next;
end;
end;
end;
procedure TfmMain.PopupaInformacoes(ACfe: String);
var
Resp: String;
JsonCoupon: TJSONObject;
JsonItems: TJSONArray;
JsonItem: TJSONObject;
I: Integer;
begin
dmDados.QSale.Open(Concat('SELECT * FROM SALE WHERE CFEKEY = ', QuotedStr(FValorQrCode)));
if dmDados.QSale.RecordCount = 0 then
begin
IdHTTP1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
Resp := IdHTTP1.Get(Concat('https://cfe.sefaz.ce.gov.br:8443/portalcfews/mfe/fiscal-coupons/extract/', ACfe));
if IdHTTP1.ResponseCode = 200 then
begin
JsonCoupon := (TJSONObject.ParseJSONValue(Resp) as TJSONObject).GetValue('coupon') as TJSONObject;
{Grava Venda}
dmDados.QSale.Insert;
dmDados.QSalecfeKey.AsString := JsonCoupon.GetValue<string>('cfeKey');
dmDados.QSalefantasyname.AsString := JsonCoupon.GetValue<string>('fantasyName');
dmDados.QSalesubTotal.AsFloat := JsonCoupon.GetValue<Double>('subTotal');
dmDados.QSalediscount.AsFloat := JsonCoupon.GetValue<Double>('discount');
dmDados.QSaletotalTaxes.AsFloat := JsonCoupon.GetValue<Double>('totalTaxes');
dmDados.QSaleemissionDate.AsDateTime := StrToDateTime(copy(JsonCoupon.GetValue<string>('emissionDate'),0,Pos(' ', JsonCoupon.GetValue<string>('emissionDate'))));
dmDados.QSale.Post;
{Grava Items}
JsonItems := JsonCoupon.GetValue<TJSONArray>('items') as TJSONArray;
if JsonItems.Count > 0 then
begin
dmDados.QSaleItem.Close;
dmDados.QSaleItem.Open;
for I := 0 to JsonItems.Count-1 do
begin
JsonItem := JsonItems.Items[I] as TJSONObject;
dmDados.QSaleItem.Insert;
dmDados.QSaleItemamount.AsFloat := JsonItem.GetValue<Double>('amount');
dmDados.QSaleItemprice.AsFloat := JsonItem.GetValue<Double>('price');
dmDados.QSaleItemvalueOfTaxes.AsFloat := JsonItem.GetValue<Double>('valueOfTaxes');
dmDados.QSaleItemcfeKey.AsString := JsonCoupon.GetValue<string>('cfeKey');
dmDados.QSaleItemcode.AsInteger := JsonItem.GetValue<Integer>('code');
dmDados.QSaleItemdescription.AsString := JsonItem.GetValue<string>('description');
dmDados.QSaleItemun.AsString := JsonItem.GetValue<string>('un');
dmDados.QSaleItem.Post;
end;
end;
end;
end
else
begin
ShowMessage('Cupom jŠ cadastrado!');
end;
end;
procedure TfmMain.SpeedButton1Click(Sender: TObject);
begin
PopulaListView;
ChangeTabAction1.ExecuteTarget(Self);
end;
procedure TfmMain.TMSFMXZBarReader1GetResult(Sender: TObject; AResult: string);
begin
FValorQrCode := AResult;
end;
end.
|
unit TestUnmarshalTerritoryListUnit;
interface
uses
TestFramework, SysUtils,
TestBaseJsonUnmarshalUnit,
System.Generics.Collections;
type
TTestUnmarshalTerritoryList = class(TTestBaseJsonUnmarshal)
published
procedure TerritoryListFindResponse;
end;
implementation
{ TTestOptimizationParametersToJson }
uses
Classes, System.JSON, TerritoryUnit, MarshalUnMarshalUnit,
GetTerritoriesResponseUnit;
procedure TTestUnmarshalTerritoryList.TerritoryListFindResponse;
const
Etalon =
'[{"territory_id":"1DC2DCE2F08035B7CC017874451B137C","territory_name":"Circle Territory","territory_color":"ff0000",' +
'"member_id":1,"addresses":[],"territory":{"type":"circle","data":["37.5697528227865,-77.4783325195313","5000"]}},' +
'{"territory_id":"1DF50C0BAD3C66DE13D129698CD63F09","territory_name":"Polygon Territory","territory_color":"ff0000",' +
'"member_id":1,"addresses":[],"territory":{"type":"poly","data":["37.74763966054,-77.69172210693"]}}]';
var
Actual: TGetTerritoriesResponse;
JsonValue: TJSONValue;
begin
JsonValue := TJSONObject.ParseJSONValue(Etalon);
try
Actual := TMarshalUnMarshal.FromJson(TGetTerritoriesResponse, JsonValue) as TGetTerritoriesResponse;
CheckEquals(2, Length(Actual.Territories));
CheckEquals('Circle Territory', Actual.Territories[0].Name);
CheckEquals('Polygon Territory', Actual.Territories[1].Name);
finally
FreeAndNil(JsonValue);
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest('JSON\Unmarshal\', TTestUnmarshalTerritoryList.Suite);
end.
|
unit ConsPago;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ImgList, ActnList, Menus, Db, DBTables, Grids, DBGrids,
ComCtrls, DBCtrls, ToolWin, StdCtrls, DBActns;
type
TFConsPago = class(TForm)
MainMenu1: TMainMenu;
Ventana1: TMenuItem;
Cerrar1: TMenuItem;
ActionList1: TActionList;
Panel1: TPanel;
StatusBar1: TStatusBar;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
Table1: TTable;
CoolBar1: TCoolBar;
ToolBar1: TToolBar;
Cerrar: TAction;
Imprimir: TAction;
Ayuda: TAction;
ToolButton1: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
Registros1: TMenuItem;
Imprimir1: TMenuItem;
Ayuda1: TMenuItem;
Ayuda2: TMenuItem;
Otros1: TMenuItem;
OrCodigo: TAction;
OrNombre: TAction;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
Primero1: TMenuItem;
Anterior1: TMenuItem;
Siguiente1: TMenuItem;
Ultimo1: TMenuItem;
Table1Codigo: TStringField;
Table1Numero: TStringField;
Table1Fecha: TDateTimeField;
Table1Prove: TStringField;
Table1Efectivo: TFloatField;
Table1Cheques: TFloatField;
Table1Documentos: TFloatField;
Table1Otros: TFloatField;
Table2: TTable;
Table1ACREEDOR: TStringField;
Table1TOTAL: TFloatField;
DetalledePago1: TMenuItem;
ToolButton2: TToolButton;
ToolButton5: TToolButton;
procedure CerrarExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Primero1Click(Sender: TObject);
procedure Anterior1Click(Sender: TObject);
procedure Siguiente1Click(Sender: TObject);
procedure Ultimo1Click(Sender: TObject);
procedure AyudaExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Table1CalcFields(DataSet: TDataSet);
procedure DetalledePago1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
procedure EnHint(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
procedure SetRanPro( sCod: string );
end;
var
FConsPago: TFConsPago;
implementation
uses DataMod, DetPago2, Main;
{$R *.DFM}
procedure TFConsPago.CerrarExecute(Sender: TObject);
begin
Close;
end;
procedure TFConsPago.FormCreate(Sender: TObject);
begin
Dm.QConsPago.Open;
Application.OnHint := EnHint;
end;
procedure TFConsPago.Primero1Click(Sender: TObject);
begin
DataSource1.DataSet.First;
end;
procedure TFConsPago.Anterior1Click(Sender: TObject);
begin
DataSource1.DataSet.Prior;
end;
procedure TFConsPago.Siguiente1Click(Sender: TObject);
begin
DataSource1.DataSet.Next;
end;
procedure TFConsPago.Ultimo1Click(Sender: TObject);
begin
DataSource1.DataSet.Last;
end;
procedure TFConsPago.EnHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
procedure TFConsPago.AyudaExecute(Sender: TObject);
begin
Application.HelpCommand( HELP_CONTEXT, 150 );
end;
procedure TFConsPago.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.OnHint := nil;
Action := caFree;
FConsPago := nil;
end;
procedure TFConsPago.Table1CalcFields(DataSet: TDataSet);
begin
Table1TOTAL.value := Table1EFECTIVO.value + Table1CHEQUES.value +
Table1DOCUMENTOS.value + Table1OTROS.value;
end;
procedure TFConsPago.DetalledePago1Click(Sender: TObject);
begin
MostrarDetalleRecibo( Table1CODIGO.value, Table1NUMERO.value );
end;
procedure TFConsPago.FormActivate(Sender: TObject);
begin
Screen.Cursor := crDefault;
end;
procedure TFConsPago.SetRanPro(sCod: string);
begin
Table1.IndexName := 'ProFec';
Table1.SetRange( [ sCod ], [ sCod ] );
end;
end.
|
unit udmRcboRepresentantes;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmRcboRepresentantes = class(TdmPadrao)
qryManutencaoFIL_RECIBO: TStringField;
qryManutencaoNRO_RECIBO: TFloatField;
qryManutencaoEMISSAO: TDateTimeField;
qryManutencaoREFERENCIA_I: TDateTimeField;
qryManutencaoREFERENCIA_F: TDateTimeField;
qryManutencaoAGRUPAMENTO: TIntegerField;
qryManutencaoCONSIDERAR: TIntegerField;
qryManutencaoCOMISSIONAR_POR: TIntegerField;
qryManutencaoUNIDADE: TStringField;
qryManutencaoVLR_COMISSOES: TFloatField;
qryManutencaoVLR_CREDITOS: TFloatField;
qryManutencaoVLR_DESCONTOS: TFloatField;
qryManutencaoVLR_LIQUIDO: TFloatField;
qryManutencaoOBS: TBlobField;
qryManutencaoSTATUS: TStringField;
qryManutencaoFIL_ORIGEM: TStringField;
qryManutencaoAUTORIZACAO: TFloatField;
qryManutencaoPARCELA: TIntegerField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoNM_UNIDADE: TStringField;
qryLocalizacaoFIL_RECIBO: TStringField;
qryLocalizacaoNRO_RECIBO: TFloatField;
qryLocalizacaoEMISSAO: TDateTimeField;
qryLocalizacaoREFERENCIA_I: TDateTimeField;
qryLocalizacaoREFERENCIA_F: TDateTimeField;
qryLocalizacaoAGRUPAMENTO: TIntegerField;
qryLocalizacaoCONSIDERAR: TIntegerField;
qryLocalizacaoCOMISSIONAR_POR: TIntegerField;
qryLocalizacaoUNIDADE: TStringField;
qryLocalizacaoVLR_COMISSOES: TFloatField;
qryLocalizacaoVLR_CREDITOS: TFloatField;
qryLocalizacaoVLR_DESCONTOS: TFloatField;
qryLocalizacaoVLR_LIQUIDO: TFloatField;
qryLocalizacaoOBS: TBlobField;
qryLocalizacaoSTATUS: TStringField;
qryLocalizacaoFIL_ORIGEM: TStringField;
qryLocalizacaoAUTORIZACAO: TFloatField;
qryLocalizacaoPARCELA: TIntegerField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoNM_UNIDADE: TStringField;
protected
procedure MontaSQLBusca(DataSet :TDataSet = Nil); override;
procedure MontaSQLRefresh; override;
private
FRecibo: Real;
FEmissora: String;
function GetSQL_DEFAULT: string;
{ Private declarations }
public
{ Public declarations }
property Emissora :String read FEmissora write FEmissora;
property Recibo :Real read FRecibo write FRecibo;
property SQLPadrao: string read GetSQL_DEFAULT;
end;
const
SQL_DAFAULT =
' SELECT ECR.FIL_RECIBO,' +
' ECR.NRO_RECIBO,' +
' ECR.EMISSAO,' +
' ECR.REFERENCIA_I,' +
' ECR.REFERENCIA_F,' +
' ECR.AGRUPAMENTO,' +
' ECR.CONSIDERAR,' +
' ECR.COMISSIONAR_POR,' +
' ECR.UNIDADE,' +
' ECR.VLR_COMISSOES,' +
' ECR.VLR_CREDITOS,' +
' ECR.VLR_DESCONTOS,' +
' ECR.VLR_LIQUIDO,' +
' ECR.OBS,' +
' ECR.STATUS,' +
' ECR.FIL_ORIGEM,' +
' ECR.AUTORIZACAO,' +
' ECR.PARCELA,' +
' ECR.DT_ALTERACAO,' +
' ECR.OPERADOR,' +
' FIL.NOME NM_UNIDADE' +
' FROM STWACRTRECR ECR' +
' LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = ECR.UNIDADE ';
var
dmRcboRepresentantes: TdmRcboRepresentantes;
implementation
{$R *.dfm}
{ TdmRcboRepresentantes }
function TdmRcboRepresentantes.GetSQL_DEFAULT: string;
begin
Result := SQL_DAFAULT;
end;
procedure TdmRcboRepresentantes.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do begin
SQL.Clear;
SQL.Add(SQL_DAFAULT);
SQL.Add('WHERE ECR.FIL_RECIBO = :FIL_RECIBO AND ECR.NRO_RECIBO = :NRO_RECIBO ');
SQL.Add('ORDER BY FIL_RECIBO, NRO_RECIBO');
Params[0].AsString := FEmissora;
Params[1].AsFloat := FRecibo;
end;
end;
procedure TdmRcboRepresentantes.MontaSQLRefresh;
begin
inherited;
with qryManutencao do begin
SQL.Clear;
SQL.Add(SQL_DAFAULT);
SQL.Add('ORDER BY FIL_RECIBO, NRO_RECIBO');
end;
end;
end.
|
unit libavdevice;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
Uses
ffmpeg_types, libavutil, libavcodec, libavformat;
{$I ffmpeg.inc}
(* *
* @defgroup lavd libavdevice
* Special devices muxing/demuxing library.
*
* Libavdevice is a complementary library to @ref libavf "libavformat". It
* provides various "special" platform-specific muxers and demuxers, e.g. for
* grabbing devices, audio capture and playback etc. As a consequence, the
* (de)muxers in libavdevice are of the AVFMT_NOFILE type (they use their own
* I/O functions). The filename passed to avformat_open_input() often does not
* refer to an actually existing file, but has some special device-specific
* meaning - e.g. for xcbgrab it is the display name.
*
* To use libavdevice, simply call avdevice_register_all() to register all
* compiled muxers and demuxers. They all use standard libavformat API.
*
*)
(* *
* Return the LIBAVDEVICE_VERSION_INT constant.
*)
// unsigned avdevice_version(void);
function avdevice_version(): unsigned; cdecl; external avdevice_dll;
(* *
* Return the libavdevice build-time configuration.
*)
// const char *avdevice_configuration(void);
function avdevice_configuration(): pAnsiChar; cdecl; external avdevice_dll;
(* *
* Return the libavdevice license.
*)
// const char *avdevice_license(void);
function avdevice_license(): pAnsiChar; cdecl; external avdevice_dll;
(* *
* Initialize libavdevice and register all the input and output devices.
*)
// void avdevice_register_all(void);
procedure avdevice_register_all(); cdecl; external avdevice_dll;
(* *
* Audio input devices iterator.
*
* If d is NULL, returns the first registered input audio/video device,
* if d is non-NULL, returns the next registered input audio/video device after d
* or NULL if d is the last one.
*)
// AVInputFormat *av_input_audio_device_next(AVInputFormat *d);
function av_input_audio_device_next(d: pAVInputFormat): pAVInputFormat; cdecl; external avdevice_dll;
(* *
* Video input devices iterator.
*
* If d is NULL, returns the first registered input audio/video device,
* if d is non-NULL, returns the next registered input audio/video device after d
* or NULL if d is the last one.
*)
// AVInputFormat *av_input_video_device_next(AVInputFormat *d);
function av_input_video_device_next(d: pAVInputFormat): pAVInputFormat; cdecl; external avdevice_dll;
(* *
* Audio output devices iterator.
*
* If d is NULL, returns the first registered output audio/video device,
* if d is non-NULL, returns the next registered output audio/video device after d
* or NULL if d is the last one.
*)
// AVOutputFormat *av_output_audio_device_next(AVOutputFormat *d);
function av_output_audio_device_next(d: pAVOutputFormat): pAVOutputFormat; cdecl; external avdevice_dll;
(* *
* Video output devices iterator.
*
* If d is NULL, returns the first registered output audio/video device,
* if d is non-NULL, returns the next registered output audio/video device after d
* or NULL if d is the last one.
*)
// AVOutputFormat *av_output_video_device_next(AVOutputFormat *d);
function av_output_video_device_next(d: pAVOutputFormat): pAVOutputFormat; cdecl; external avdevice_dll;
type
pAVDeviceRect = ^AVDeviceRect;
AVDeviceRect = record
x: int; (* *< x coordinate of top left corner *)
y: int; (* *< y coordinate of top left corner *)
width: int; (* *< width *)
height: int; (* *< height *)
end;
(* *
* Message types used by avdevice_app_to_dev_control_message().
*)
AVAppToDevMessageType = array [0 .. 3] of AnsiChar;
const
(* *
* Dummy message.
*)
AV_APP_TO_DEV_NONE: AVAppToDevMessageType = ('N', 'O', 'N', 'E');
(* *
* Window size change message.
*
* Message is sent to the device every time the application changes the size
* of the window device renders to.
* Message should also be sent right after window is created.
*
* data: AVDeviceRect: new window size.
*)
AV_APP_TO_DEV_WINDOW_SIZE: AVAppToDevMessageType = ('G', 'E', 'O', 'M');
(* *
* Repaint request message.
*
* Message is sent to the device when window has to be repainted.
*
* data: AVDeviceRect: area required to be repainted.
* NULL: whole area is required to be repainted.
*)
AV_APP_TO_DEV_WINDOW_REPAINT: AVAppToDevMessageType = ('R', 'E', 'P', 'A');
(* *
* Request pause/play.
*
* Application requests pause/unpause playback.
* Mostly usable with devices that have internal buffer.
* By default devices are not paused.
*
* data: NULL
*)
AV_APP_TO_DEV_PAUSE: AVAppToDevMessageType = ('P', 'A', 'U', ' ');
AV_APP_TO_DEV_PLAY: AVAppToDevMessageType = ('P', 'L', 'A', 'Y');
AV_APP_TO_DEV_TOGGLE_PAUSE: AVAppToDevMessageType = ('P', 'A', 'U', 'T');
(* *
* Volume control message.
*
* Set volume level. It may be device-dependent if volume
* is changed per stream or system wide. Per stream volume
* change is expected when possible.
*
* data: double: new volume with range of 0.0 - 1.0.
*)
AV_APP_TO_DEV_SET_VOLUME: AVAppToDevMessageType = ('S', 'V', 'O', 'L');
(* *
* Mute control messages.
*
* Change mute state. It may be device-dependent if mute status
* is changed per stream or system wide. Per stream mute status
* change is expected when possible.
*
* data: NULL.
*)
AV_APP_TO_DEV_MUTE: AVAppToDevMessageType = (' ', 'M', 'U', 'T');
AV_APP_TO_DEV_UNMUTE: AVAppToDevMessageType = ('U', 'M', 'U', 'T');
AV_APP_TO_DEV_TOGGLE_MUTE: AVAppToDevMessageType = ('T', 'M', 'U', 'T');
(* *
* Get volume/mute messages.
*
* Force the device to send AV_DEV_TO_APP_VOLUME_LEVEL_CHANGED or
* AV_DEV_TO_APP_MUTE_STATE_CHANGED command respectively.
*
* data: NULL.
*)
AV_APP_TO_DEV_GET_VOLUME: AVAppToDevMessageType = ('G', 'V', 'O', 'L');
AV_APP_TO_DEV_GET_MUTE: AVAppToDevMessageType = ('G', 'M', 'U', 'T');
type
AVDevToAppMessageType = array [0 .. 3] of AnsiChar;
const
(* *
* Message types used by avdevice_dev_to_app_control_message().
*)
(* *
* Dummy message.
*)
AV_DEV_TO_APP_NONE: AVDevToAppMessageType = ('N', 'O', 'N', 'E');
(* *
* Create window buffer message.
*
* Device requests to create a window buffer. Exact meaning is device-
* and application-dependent. Message is sent before rendering first
* frame and all one-shot initializations should be done here.
* Application is allowed to ignore preferred window buffer size.
*
* @note: Application is obligated to inform about window buffer size
* with AV_APP_TO_DEV_WINDOW_SIZE message.
*
* data: AVDeviceRect: preferred size of the window buffer.
* NULL: no preferred size of the window buffer.
*)
AV_DEV_TO_APP_CREATE_WINDOW_BUFFER: AVDevToAppMessageType = ('B', 'C', 'R', 'E');
(* *
* Prepare window buffer message.
*
* Device requests to prepare a window buffer for rendering.
* Exact meaning is device- and application-dependent.
* Message is sent before rendering of each frame.
*
* data: NULL.
*)
AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER: AVDevToAppMessageType = ('B', 'P', 'R', 'E');
(* *
* Display window buffer message.
*
* Device requests to display a window buffer.
* Message is sent when new frame is ready to be displayed.
* Usually buffers need to be swapped in handler of this message.
*
* data: NULL.
*)
AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER: AVDevToAppMessageType = ('B', 'D', 'I', 'S');
(* *
* Destroy window buffer message.
*
* Device requests to destroy a window buffer.
* Message is sent when device is about to be destroyed and window
* buffer is not required anymore.
*
* data: NULL.
*)
AV_DEV_TO_APP_DESTROY_WINDOW_BUFFER: AVDevToAppMessageType = ('B', 'D', 'E', 'S');
(* *
* Buffer fullness status messages.
*
* Device signals buffer overflow/underflow.
*
* data: NULL.
*)
AV_DEV_TO_APP_BUFFER_OVERFLOW: AVDevToAppMessageType = ('B', 'O', 'F', 'L');
AV_DEV_TO_APP_BUFFER_UNDERFLOW: AVDevToAppMessageType = ('B', 'U', 'F', 'L');
(* *
* Buffer readable/writable.
*
* Device informs that buffer is readable/writable.
* When possible, device informs how many bytes can be read/write.
*
* @warning Device may not inform when number of bytes than can be read/write changes.
*
* data: int64_t: amount of bytes available to read/write.
* NULL: amount of bytes available to read/write is not known.
*)
AV_DEV_TO_APP_BUFFER_READABLE: AVDevToAppMessageType = ('B', 'R', 'D', ' ');
AV_DEV_TO_APP_BUFFER_WRITABLE: AVDevToAppMessageType = ('B', 'W', 'R', ' ');
(* *
* Mute state change message.
*
* Device informs that mute state has changed.
*
* data: int: 0 for not muted state, non-zero for muted state.
*)
AV_DEV_TO_APP_MUTE_STATE_CHANGED: AVDevToAppMessageType = ('C', 'M', 'U', 'T');
(* *
* Volume level change message.
*
* Device informs that volume level has changed.
*
* data: double: new volume with range of 0.0 - 1.0.
*)
AV_DEV_TO_APP_VOLUME_LEVEL_CHANGED: AVDevToAppMessageType = ('C', 'V', 'O', 'L');
(* *
* Send control message from application to device.
*
* @param s device context.
* @param type message type.
* @param data message data. Exact type depends on message type.
* @param data_size size of message data.
* @return >= 0 on success, negative on error.
* AVERROR(ENOSYS) when device doesn't implement handler of the message.
*)
// int avdevice_app_to_dev_control_message(struct AVFormatContext *s,
// enum AVAppToDevMessageType type,
// void *data, size_t data_size);
function avdevice_app_to_dev_control_message(s: pAVFormatContext; _type: AVAppToDevMessageType; data: Pointer; data_size: size_t): int;
cdecl; external avdevice_dll;
(* *
* Send control message from device to application.
*
* @param s device context.
* @param type message type.
* @param data message data. Can be NULL.
* @param data_size size of message data.
* @return >= 0 on success, negative on error.
* AVERROR(ENOSYS) when application doesn't implement handler of the message.
*)
// int avdevice_dev_to_app_control_message(struct AVFormatContext *s,
// enum AVDevToAppMessageType type,
// void *data, size_t data_size);
function avdevice_dev_to_app_control_message(s: pAVFormatContext; _type: AVDevToAppMessageType; data: Pointer; data_size: size_t): int;
cdecl; external avdevice_dll;
(* *
* Following API allows user to probe device capabilities (supported codecs,
* pixel formats, sample formats, resolutions, channel counts, etc).
* It is build on top op AVOption API.
* Queried capabilities make it possible to set up converters of video or audio
* parameters that fit to the device.
*
* List of capabilities that can be queried:
* - Capabilities valid for both audio and video devices:
* - codec: supported audio/video codecs.
* type: AV_OPT_TYPE_INT (AVCodecID value)
* - Capabilities valid for audio devices:
* - sample_format: supported sample formats.
* type: AV_OPT_TYPE_INT (AVSampleFormat value)
* - sample_rate: supported sample rates.
* type: AV_OPT_TYPE_INT
* - channels: supported number of channels.
* type: AV_OPT_TYPE_INT
* - channel_layout: supported channel layouts.
* type: AV_OPT_TYPE_INT64
* - Capabilities valid for video devices:
* - pixel_format: supported pixel formats.
* type: AV_OPT_TYPE_INT (AVPixelFormat value)
* - window_size: supported window sizes (describes size of the window size presented to the user).
* type: AV_OPT_TYPE_IMAGE_SIZE
* - frame_size: supported frame sizes (describes size of provided video frames).
* type: AV_OPT_TYPE_IMAGE_SIZE
* - fps: supported fps values
* type: AV_OPT_TYPE_RATIONAL
*
* Value of the capability may be set by user using av_opt_set() function
* and AVDeviceCapabilitiesQuery object. Following queries will
* limit results to the values matching already set capabilities.
* For example, setting a codec may impact number of formats or fps values
* returned during next query. Setting invalid value may limit results to zero.
*
* Example of the usage basing on opengl output device:
*
* @code
* AVFormatContext *oc = NULL;
* AVDeviceCapabilitiesQuery *caps = NULL;
* AVOptionRanges *ranges;
* int ret;
*
* if ((ret = avformat_alloc_output_context2(&oc, NULL, "opengl", NULL)) < 0)
* goto fail;
* if (avdevice_capabilities_create(&caps, oc, NULL) < 0)
* goto fail;
*
* //query codecs
* if (av_opt_query_ranges(&ranges, caps, "codec", AV_OPT_MULTI_COMPONENT_RANGE)) < 0)
* goto fail;
* //pick codec here and set it
* av_opt_set(caps, "codec", AV_CODEC_ID_RAWVIDEO, 0);
*
* //query format
* if (av_opt_query_ranges(&ranges, caps, "pixel_format", AV_OPT_MULTI_COMPONENT_RANGE)) < 0)
* goto fail;
* //pick format here and set it
* av_opt_set(caps, "pixel_format", AV_PIX_FMT_YUV420P, 0);
*
* //query and set more capabilities
*
* fail:
* //clean up code
* avdevice_capabilities_free(&query, oc);
* avformat_free_context(oc);
* @endcode
*)
type
(* *
* Structure describes device capabilities.
*
* It is used by devices in conjunction with av_device_capabilities AVOption table
* to implement capabilities probing API based on AVOption API. Should not be used directly.
*)
pAVDeviceCapabilitiesQuery = ^AVDeviceCapabilitiesQuery;
AVDeviceCapabilitiesQuery = record
av_class: pAVClass;
device_context: pAVFormatContext;
codec: AVCodecID;
sample_format: AVSampleFormat;
pixel_format: AVPixelFormat;
sample_rate: int;
channels: int;
channel_layout: int64_t;
window_width: int;
window_height: int;
frame_width: int;
frame_height: int;
fps: AVRational;
end;
(* *
* AVOption table used by devices to implement device capabilities API. Should not be used by a user.
*)
// extern const AVOption av_device_capabilities[];
(* *
* Initialize capabilities probing API based on AVOption API.
*
* avdevice_capabilities_free() must be called when query capabilities API is
* not used anymore.
*
* @param[out] caps Device capabilities data. Pointer to a NULL pointer must be passed.
* @param s Context of the device.
* @param device_options An AVDictionary filled with device-private options.
* On return this parameter will be destroyed and replaced with a dict
* containing options that were not found. May be NULL.
* The same options must be passed later to avformat_write_header() for output
* devices or avformat_open_input() for input devices, or at any other place
* that affects device-private options.
*
* @return >= 0 on success, negative otherwise.
*)
// int avdevice_capabilities_create(AVDeviceCapabilitiesQuery **caps, AVFormatContext *s,
// AVDictionary **device_options);
function avdevice_capabilities_create(var caps: pAVDeviceCapabilitiesQuery; s: pAVFormatContext; var device_options: pAVDictionary): int;
cdecl; external avdevice_dll;
(* *
* Free resources created by avdevice_capabilities_create()
*
* @param caps Device capabilities data to be freed.
* @param s Context of the device.
*)
// void avdevice_capabilities_free(AVDeviceCapabilitiesQuery **caps, AVFormatContext *s);
procedure avdevice_capabilities_free(var caps: pAVDeviceCapabilitiesQuery; s: pAVFormatContext); cdecl; external avdevice_dll;
type
(* *
* Structure describes basic parameters of the device.
*)
pAVDeviceInfo = ^AVDeviceInfo;
ppAVDeviceInfo = ^pAVDeviceInfo;
AVDeviceInfo = record
device_name: pAnsiChar; (* *< device name, format depends on device *)
device_description: pAnsiChar; (* *< human friendly name *)
end;
(* *
* List of devices.
*)
pAVDeviceInfoList = ^AVDeviceInfoList;
AVDeviceInfoList = record
devices: ppAVDeviceInfo; (* *< list of autodetected devices *)
nb_devices: int; (* *< number of autodetected devices *)
default_device: int; (* *< index of default device or -1 if no default *)
end;
(* *
* List devices.
*
* Returns available device names and their parameters.
*
* @note: Some devices may accept system-dependent device names that cannot be
* autodetected. The list returned by this function cannot be assumed to
* be always completed.
*
* @param s device context.
* @param[out] device_list list of autodetected devices.
* @return count of autodetected devices, negative on error.
*)
// int avdevice_list_devices(struct AVFormatContext *s, AVDeviceInfoList **device_list);
function avdevice_list_devices(s: pAVFormatContext; var device_list: pAVDeviceInfoList): int; cdecl; external avdevice_dll;
(* *
* Convenient function to free result of avdevice_list_devices().
*
* @param devices device list to be freed.
*)
// void avdevice_free_list_devices(AVDeviceInfoList **device_list);
procedure avdevice_free_list_devices(var device_list: pAVDeviceInfoList); cdecl; external avdevice_dll;
(* *
* List devices.
*
* Returns available device names and their parameters.
* These are convinient wrappers for avdevice_list_devices().
* Device context is allocated and deallocated internally.
*
* @param device device format. May be NULL if device name is set.
* @param device_name device name. May be NULL if device format is set.
* @param device_options An AVDictionary filled with device-private options. May be NULL.
* The same options must be passed later to avformat_write_header() for output
* devices or avformat_open_input() for input devices, or at any other place
* that affects device-private options.
* @param[out] device_list list of autodetected devices
* @return count of autodetected devices, negative on error.
* @note device argument takes precedence over device_name when both are set.
*)
// int avdevice_list_input_sources(struct AVInputFormat *device, const char *device_name,
// AVDictionary *device_options, AVDeviceInfoList **device_list);
function avdevice_list_input_sources(device: pAVInputFormat; const device_name: pAnsiChar; device_options: pAVDictionary;
var device_list: pAVDeviceInfoList): int; cdecl; external avdevice_dll;
// int avdevice_list_output_sinks(struct AVOutputFormat *device, const char *device_name,
// AVDictionary *device_options, AVDeviceInfoList **device_list);
function avdevice_list_output_sinks(device: pAVOutputFormat; const device_name: pAnsiChar; device_options: pAVDictionary;
var device_list: pAVDeviceInfoList): int; cdecl; external avdevice_dll;
implementation
end.
|
unit LUX.GPU.Vulkan.Buffer;
interface //#################################################################### ■
uses vulkan_core,
LUX.GPU.Vulkan.root,
LUX.GPU.Vulkan.Memory;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TVkBuffers<TVkDevice_:class> = class;
TVkBuffer<TVkDevice_,TVkParent_:class> = class;
TVkBufMem<TVkDevice_,TVkParent_:class> = class;
TVkBuffer<TVkDevice_:class> = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBufMem<TVkDevice_,TVkParent_>
TVkBufMem<TVkDevice_,TVkParent_:class> = class( TVkMemory<TVkDevice_,TVkBuffer<TVkDevice_,TVkParent_>> )
private
type TVkBuffer_ = TVkBuffer<TVkDevice_,TVkParent_>;
protected
///// アクセス
function GetDevice :TVkDevice_; override;
function GetSize :VkDeviceSize; override;
function GetTypeI :UInt32; override;
///// メソッド
procedure CreateHandle; override;
public
///// プロパティ
property Buffer :TVkBuffer_ read GetParent;
property Size :VkDeviceSize read GetSize ;
property TypeI :UInt32 read GetTypeI ;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_,TVkParent_>
TVkBuffer<TVkDevice_,TVkParent_:class> = class( TVkDeviceObject<TVkDevice_,TVkParent_> )
private
type TVkBufMem_ = TVkBufMem <TVkDevice_,TVkParent_>;
protected
_Inform :VkBufferCreateInfo;
_Handle :VkBuffer;
_Memory :TVkBufMem_;
///// アクセス
function GetSize :VkDeviceSize; virtual;
procedure SetSize( const Size_:VkDeviceSize ); virtual;
function GetUsage :VkBufferUsageFlags; virtual;
procedure SetUsage( const Usage_:VkBufferUsageFlags ); virtual;
function GetSharingMode :VkSharingMode; virtual;
procedure SetSharingMode( const SharingMode_:VkSharingMode ); virtual;
function GetHandle :VkBuffer; virtual;
procedure SetHandle( const Handle_:VkBuffer ); virtual;
function GetDescri :VkDescriptorBufferInfo; virtual;
function GetRequir :VkMemoryRequirements; virtual;
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; override;
destructor Destroy; override;
///// プロパティ
property Inform :VkBufferCreateInfo read _Inform ;
property Size :VkDeviceSize read GetSize write SetSize ;
property Usage :VkBufferUsageFlags read GetUsage write SetUsage ;
property SharingMode :VkSharingMode read GetSharingMode write SetSharingMode;
property Handle :VkBuffer read GetHandle write SetHandle ;
property Descri :VkDescriptorBufferInfo read GetDescri ;
property Requir :VkMemoryRequirements read GetRequir ;
property Memory :TVkBufMem_ read _Memory ;
///// メソッド
function Bind( const Memory_:TVkBufMem_ ) :Boolean;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_>
TVkBuffer<TVkDevice_:class> = class( TVkBuffer<TVkDevice_,TVkBuffers<TVkDevice_>> )
private
type TVkBuffers_ = TVkBuffers<TVkDevice_>;
protected
///// アクセス
function GetDevice :TVkDevice_; override;
public
constructor Create( const Buffers_:TVkBuffers_ ); override;
constructor Create( const Device_:TVkDevice_ ); overload; virtual;
///// プロパティ
property Buffers :TVkBuffers_ read GetParent;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffers<TVkDevice_>
TVkBuffers<TVkDevice_:class> = class( TVkDeviceLister<TVkDevice_,TVkBuffer<TVkDevice_>> )
private
type TVkBuffer_ = TVkBuffer<TVkDevice_>;
protected
public
///// メソッド
function Add :TVkBuffer_; overload;
procedure FreeHandles;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses LUX.GPU.Vulkan;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBufMem<TVkDevice_,TVkParent_>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkBufMem<TVkDevice_,TVkParent_>.GetDevice :TVkDevice_;
begin
Result := Buffer.Device;
end;
//------------------------------------------------------------------------------
function TVkBufMem<TVkDevice_,TVkParent_>.GetSize :VkDeviceSize;
begin
Result := Buffer.Requir.size;
end;
//------------------------------------------------------------------------------
function TVkBufMem<TVkDevice_,TVkParent_>.GetTypeI :UInt32;
begin
Assert( TVkDevice( Device ).memory_type_from_properties(
Buffer.Requir.memoryTypeBits,
Ord( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ) or Ord( VK_MEMORY_PROPERTY_HOST_COHERENT_BIT ),
Result ),
'No mappable, coherent memory' );
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkBufMem<TVkDevice_,TVkParent_>.CreateHandle;
begin
inherited;
Buffer.Bind( Self );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_,TVkParent_>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkBuffer<TVkDevice_,TVkParent_>.GetSize :VkDeviceSize;
begin
Result := _Inform.size;
end;
procedure TVkBuffer<TVkDevice_,TVkParent_>.SetSize( const Size_:VkDeviceSize );
begin
_Inform.size := Size_;
Handle := VK_NULL_HANDLE;
end;
//------------------------------------------------------------------------------
function TVkBuffer<TVkDevice_,TVkParent_>.GetUsage :VkBufferUsageFlags;
begin
Result := _Inform.usage;
end;
procedure TVkBuffer<TVkDevice_,TVkParent_>.SetUsage( const Usage_:VkBufferUsageFlags );
begin
_Inform.usage := Usage_;
Handle := VK_NULL_HANDLE;
end;
//------------------------------------------------------------------------------
function TVkBuffer<TVkDevice_,TVkParent_>.GetSharingMode :VkSharingMode;
begin
Result := _Inform.sharingMode;
end;
procedure TVkBuffer<TVkDevice_,TVkParent_>.SetSharingMode( const SharingMode_:VkSharingMode );
begin
_Inform.sharingMode := SharingMode_;
Handle := VK_NULL_HANDLE;
end;
//------------------------------------------------------------------------------
function TVkBuffer<TVkDevice_,TVkParent_>.GetHandle :VkBuffer;
begin
if _Handle = VK_NULL_HANDLE then CreateHandle;
Result := _Handle;
end;
procedure TVkBuffer<TVkDevice_,TVkParent_>.SetHandle( const Handle_:VkBuffer );
begin
if _Handle <> VK_NULL_HANDLE then DestroHandle;
_Handle := Handle_;
end;
//------------------------------------------------------------------------------
function TVkBuffer<TVkDevice_,TVkParent_>.GetDescri :VkDescriptorBufferInfo;
begin
with Result do
begin
buffer := Handle;
offset := 0;
range := Size;
end;
end;
//------------------------------------------------------------------------------
function TVkBuffer<TVkDevice_,TVkParent_>.GetRequir :VkMemoryRequirements;
begin
vkGetBufferMemoryRequirements( TVkDevice( Device ).Handle, Handle, @Result );
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkBuffer<TVkDevice_,TVkParent_>.CreateHandle;
begin
Assert( vkCreateBuffer( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
Assert( Bind( _Memory ) );
end;
procedure TVkBuffer<TVkDevice_,TVkParent_>.DestroHandle;
begin
_Memory.Handle := VK_NULL_HANDLE;
vkDestroyBuffer( TVkDevice( Device ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkBuffer<TVkDevice_,TVkParent_>.Create;
begin
inherited;
_Handle := VK_NULL_HANDLE;
_Memory := TVkBufMem_.Create( Self );
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
pNext := nil;
flags := 0;
// size = Size
// usage = Usage
// sharingMode = SharingMode
queueFamilyIndexCount := 0;
pQueueFamilyIndices := nil;
end;
Size := 0;
Usage := 0;
SharingMode := VK_SHARING_MODE_EXCLUSIVE;
end;
destructor TVkBuffer<TVkDevice_,TVkParent_>.Destroy;
begin
_Memory.Free;
Handle := VK_NULL_HANDLE;
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
function TVkBuffer<TVkDevice_,TVkParent_>.Bind( const Memory_:TVkBufMem_ ) :Boolean;
begin
Result := vkBindBufferMemory( TVkDevice( Device ).Handle, Handle, Memory_.Handle, 0 ) = VK_SUCCESS;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkBuffer<TVkDevice_>.GetDevice :TVkDevice_;
begin
Result := Buffers.Device;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkBuffer<TVkDevice_>.Create( const Buffers_:TVkBuffers_ );
begin
inherited;
Buffers.Add( Self );
end;
constructor TVkBuffer<TVkDevice_>.Create( const Device_:TVkDevice_ );
begin
Create( TVkBuffers_( TVkDevice( Device_ ).Buffers ) );
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffers<TVkDevice_>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
/////////////////////////////////////////////////////////////////////// メソッド
function TVkBuffers<TVkDevice_>.Add :TVkBuffer_;
begin
Result := TVkBuffer_.Create( Self );
end;
//------------------------------------------------------------------------------
procedure TVkBuffers<TVkDevice_>.FreeHandles;
var
B :TVkBuffer_;
begin
for B in Self do B.Handle := VK_NULL_HANDLE;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
end. //######################################################################### ■ |
unit Expressions;
interface
uses
Classes, SysUtils;
function ExtractFEN(const aCommand: string; var aFEN: string): boolean;
function ExtractMoves(const aCommand: string): boolean;
var
list: TStringList;
implementation
uses
RegExpr, Log;
const
PATTERN_PIECES = '[1-8BKNPQRbknpqr]+';
PATTERN_ACTIVECOLOR = '[wb]';
PATTERN_CASTLING = '([KQkq]+|-)';
PATTERN_ENPASSANT = '([a-h][1-8]|-)';
PATTERN_NUMBER = '\d+';
PATTERN_MOVE = '[a-h][1-8][a-h][1-8][nbrq]?';
var
fenPattern: string;
efen, emove: TRegExpr;
function ExtractFEN(const aCommand: string; var aFEN: string): boolean;
begin
result := efen.Exec(aCommand);
if result then
aFEN := efen.Match[0];
end;
function ExtractMoves(const aCommand: string): boolean;
begin
TLog.Append(Format('%s %s', [{$I %FILE%}, {$I %LINE%}]));
list.Clear;
result := emove.Exec(aCommand);
if result then
repeat
list.Append(emove.Match[0]);
until not emove.ExecNext;
end;
initialization
fenPattern := Format('%s %s %s %s %s %s', [
ReplaceRegExpr('x', 'x/x/x/x/x/x/x/x', PATTERN_PIECES, false),
PATTERN_ACTIVECOLOR,
PATTERN_CASTLING,
PATTERN_ENPASSANT,
PATTERN_NUMBER,
PATTERN_NUMBER
]);
list := TStringList.Create;
efen := TRegExpr.Create(fenPattern);
emove := TRegExpr.Create(PATTERN_MOVE);
finalization
list.Free;
efen.Free;
emove.Free;
end.
|
{
"name": "Everyone gets a planet",
"planets": [
{
"name": "Cyan",
"mass": 50000,
"position_x": 54000.0078125,
"position_y": -1099.986328125,
"velocity_x": 1.959501028060913,
"velocity_y": 96.19510650634766,
"required_thrust_to_move": 0,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1368851200,
"radius": 1000,
"heightRange": 79,
"waterHeight": 48,
"waterDepth": 62,
"temperature": 4.999998569488525,
"metalDensity": 0,
"metalClusters": 0,
"metalSpotLimit": -1,
"biomeScale": 100.00000013739177,
"biome": "gas",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Grey",
"mass": 5000,
"position_x": 68600,
"position_y": -200.00286865234375,
"velocity_x": 10.002917289733887,
"velocity_y": -34.289207458496094,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1916249856,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Red",
"mass": 5000,
"position_x": 65800,
"position_y": -400.000244140625,
"velocity_x": -6.652280807495117,
"velocity_y": 241.36782836914062,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1716123264,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "lava",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Dark",
"mass": 5000,
"position_x": 64300,
"position_y": -500.00146484375,
"velocity_x": -7.092652320861816,
"velocity_y": 251.5941162109375,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 869659456,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "tropical",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Dune",
"mass": 5000,
"position_x": 62800,
"position_y": -600.0017700195312,
"velocity_x": -7.593805313110352,
"velocity_y": 264.3382263183594,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1172806784,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "dessert",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "White",
"mass": 5000,
"position_x": 61300,
"position_y": -700.0001220703125,
"velocity_x": -8.157583236694336,
"velocity_y": 280.8379211425781,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 916496960,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "ice",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Rock",
"mass": 5000,
"position_x": 59900,
"position_y": -800.0001831054688,
"velocity_x": -8.486580848693848,
"velocity_y": 301.6437683105469,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1120065152,
"radius": 100,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "asteroid",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Dark Timmy",
"mass": 5000,
"position_x": 67300,
"position_y": -300.0018310546875,
"velocity_x": -6.2647905349731445,
"velocity_y": 232.92642211914062,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 295816064,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "AngryKrogania",
"mass": 5000,
"position_x": 69900,
"position_y": -100,
"velocity_x": -5.903406143188477,
"velocity_y": 221.21690368652344,
"required_thrust_to_move": 3,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 130990368,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Thuxophide",
"mass": 5000,
"position_x": 58400,
"position_y": -900.0007934570312,
"velocity_x": -8.857800483703613,
"velocity_y": 334.1922912597656,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 578684480,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Perron",
"mass": 5000,
"position_x": 56900,
"position_y": -999.9999389648438,
"velocity_x": 12.073647499084473,
"velocity_y": -197.1539306640625,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1104989440,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 25,
"metalClusters": 25,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
}
]
} |
unit Daemons;
interface
uses
DirServerSession, SyncObjs, IniFiles, RDOInterfaces, RDOObjectProxy;
type
IDaemon =
interface
procedure InitDaemon(const DSAddr : string; DSPort : integer);
function GetName : string;
function GetDescription : string;
function IsRunning : boolean;
procedure Run;
procedure SynchronizedRun;
function GetPeriod : integer;
procedure SetPeriod(period : integer);
function LastRun : integer;
function ShowPropertiesUI : boolean;
end;
type
TDaemonCreatorRoutine = function(const DSAddr : string; const DSPort : integer) : IDaemon;
const
cDaemonCreatorRoutineName = 'CreateDaemon';
type
TBasicDaemon =
class(TInterfacedObject, IDaemon)
public
constructor Create(const DSAddr : string; DSPort : integer);
destructor Destroy; override;
protected // IDaemon
procedure InitDaemon(const DSAddr : string; DSPort : integer); virtual;
function GetName : string; virtual;
function GetDescription : string; virtual;
function IsRunning : boolean;
procedure Run;
procedure SynchronizedRun;
function GetPeriod : integer;
procedure SetPeriod(period : integer);
function LastRun : integer;
function ShowPropertiesUI : boolean; virtual;
private
fDSAddr : string;
fDSPort : integer;
fDSConnection : IRDOConnectionInit;
fDSProxy : variant;
fConnected : boolean;
fConnTimeOut : integer;
fCallTimeOut : integer;
fServerTruceLen : integer;
fLock : TCriticalSection;
fPeriod : integer;
fRunning : boolean;
fLastRun : integer;
protected
fSession : IDirServerSession;
private
function InitDSConnection(const DSAddr : string; DSPort : integer) : boolean;
function InitSession : boolean;
procedure FreeDSConnectionObjs;
procedure ReadConfigData;
procedure OnDisconnectFromDS(const ClientConnection : IRDOConnection);
protected
procedure Execute; virtual;
procedure SynchronizedExecute; virtual;
procedure ReadConfiguration(IniFile : TIniFile); virtual;
function GetLogId : string; virtual;
end;
implementation
uses
Windows, SysUtils, WinsockRDOConnection, Logs;
const
cDefaultPeriod = 60*1000; //1*1000;
const
cDefConnTimeOut = 20000;
cDefCallTimeOut = 120000;
cDefServerTruceLen = 5*60*1000;//60*1000;
const
cDSObjectName = 'DirectoryServer';
// TBasicDaemon
constructor TBasicDaemon.Create(const DSAddr : string; DSPort : integer);
begin
inherited Create;
fDSAddr := DSAddr;
fDSPort := DSPort;
fConnTimeOut := cDefConnTimeOut;
fCallTimeOut := cDefCallTimeOut;
fServerTruceLen := cDefServerTruceLen;
fLock := TCriticalSection.Create;
fPeriod := cDefaultPeriod;
ReadConfigData;
end;
destructor TBasicDaemon.Destroy;
begin
fLock.Free;
FreeDSConnectionObjs;
inherited;
end;
procedure TBasicDaemon.InitDaemon(const DSAddr : string; DSPort : integer);
begin
fDSAddr := DSAddr;
fDSPort := DSPort;
end;
function TBasicDaemon.GetName : string;
begin
Result := 'Basic daemon';
end;
function TBasicDaemon.GetDescription : string;
begin
Result := 'Basic daemon implementation';
end;
function TBasicDaemon.IsRunning : boolean;
begin
fLock.Enter;
try
Result := fRunning;
finally
fLock.Leave;
end;
end;
procedure TBasicDaemon.Run;
var
executed : boolean;
initickcount : integer;
const
DebugCntLost : longint = 0;
begin
fLock.Enter;
try
fRunning := true;
finally
fLock.Leave;
end;
initickcount := GetTickCount;
if fConnected
then
if InitSession
then
try
try
Execute;
executed := true;
except
executed := false;
end;
finally
fSession := nil;
end
else executed := false
else
begin
FreeDSConnectionObjs;
Inc(DebugCntLost);
if InitDSConnection(fDSAddr, fDSPort) and InitSession
then
try
try
Execute;
executed := true;
except
executed := false;
end;
finally
fSession := nil;
end
else executed := false;
end;
fLock.Enter;
try
if executed
then fLastRun := GetTickCount
else
if fPeriod < fServerTruceLen
then inc(fLastRun, (longint(GetTickCount) - initickcount) + 2*fPeriod)
else inc(fLastRun, (longint(GetTickCount) - initickcount) + fServerTruceLen);
fRunning := false;
finally
fLock.Leave;
end;
end;
procedure TBasicDaemon.SynchronizedRun;
begin
SynchronizedExecute;
end;
function TBasicDaemon.GetPeriod : integer;
begin
Result := fPeriod;
end;
procedure TBasicDaemon.SetPeriod(period : integer);
begin
fPeriod := period;
end;
function TBasicDaemon.LastRun : integer;
begin
fLock.Enter;
try
Result := fLastRun;
finally
fLock.Leave;
end;
end;
function TBasicDaemon.ShowPropertiesUI : boolean;
begin
Result := false;
end;
function TBasicDaemon.InitDSConnection(const DSAddr : string; DSPort : integer) : boolean;
begin
try
fDSConnection := TWinsockRDOConnection.Create('DS');
fDSConnection.Server := DSAddr;
fDSConnection.Port := DSPort;
(fDSConnection as IRDOConnection).OnDisconnect := OnDisconnectFromDS;
Log(GetLogId, 'Trying to connect to Directory Server at IP=' + DSAddr + ' and Port=' + IntToStr(DSPort));
if fDSConnection.Connect(fConnTimeOut)
then
begin
Log(GetLogId, 'Sucessfully connected to Directory Server at IP=' + DSAddr + ' and Port=' + IntToStr(DSPort));
fConnected := true;
fDSProxy := IDispatch(TRDOObjectProxy.Create);// as IDispatch;
fDSProxy.SetConnection(fDSConnection);
fDSProxy.WaitForAnswer := true;
fDSProxy.TimeOut := fCallTimeOut;
if fDSProxy.BindTo(cDSObjectName)
then
begin
Log(GetLogId, 'Successfully bound to ' + cDSObjectName + ' object');
Result := true;
end
else
begin
Log(GetLogId, 'Couldn''t bind to ' + cDSObjectName + ' object');
Result := false;
end;
end
else
begin
Log(GetLogId, 'Couldn''t connect to the Directory Server');
Result := false;
end;
except
Result := false;
Log(GetLogId, 'Exception generated while trying to connect to Directory Server');
end;
end;
function TBasicDaemon.InitSession : boolean;
var
sessionid : integer;
SessionProxy : variant;
begin
try
sessionid := fDSProxy.RDOOpenSession;
if sessionid <> 0
then
begin
SessionProxy := IDispatch(TRDOObjectProxy.Create);// as IDispatch;
SessionProxy.SetConnection(fDSConnection);
SessionProxy.WaitForAnswer := true;
SessionProxy.TimeOut := fCallTimeOut;
if SessionProxy.BindTo(sessionid)
then
begin
fSession := TDirServerSession.Create(SessionProxy);
Result := true;
end
else
begin
Log(GetLogId, 'Couldn''t bind to session object');
Result := false;
end;
end
else
begin
Log(GetLogId, 'Couldn''t get session from Directory Server');
Result := false;
end;
except
Log(GetLogId, 'Couldn''t get session from Directory Server');
Result := false;
end;
end;
procedure TBasicDaemon.FreeDSConnectionObjs;
begin
fDSProxy := unassigned;
fDSConnection := nil;
end;
procedure TBasicDaemon.ReadConfigData;
const
cMaxNameLength = 300;
var
IniFile : TIniFile;
modulename : string;
fnamelen : integer;
function GenerateIniName(const modulename : string) : string;
var
inifilename : string;
i : integer;
begin
inifilename := modulename;
i := length(inifilename);
while inifilename[i] <> '.' do
begin
dec(i);
setlength(inifilename, i);
end;
inifilename := inifilename + 'ini';
Result := inifilename;
end;
begin
setlength(modulename, cMaxNameLength);
fnamelen := GetModuleFileName(HInstance, pchar(modulename), cMaxNameLength);
if fnamelen > 0
then
begin
setlength(modulename, fnamelen);
try
IniFile := TIniFile.Create(GenerateIniName(modulename));
try
fPeriod := IniFile.ReadInteger('General', 'Period', fPeriod);
ReadConfiguration(IniFile);
finally
IniFile.Free;
end;
except
end;
end;
end;
procedure TBasicDaemon.OnDisconnectFromDS(const ClientConnection : IRDOConnection);
begin
fConnected := false;
Log(GetLogId, 'Disconnected from Directory Server');
end;
procedure TBasicDaemon.Execute;
begin
end;
procedure TBasicDaemon.SynchronizedExecute;
begin
end;
procedure TBasicDaemon.ReadConfiguration(IniFile : TIniFile);
begin
fPeriod := IniFile.ReadInteger('General', 'Period', fPeriod);
fConnTimeOut := IniFile.ReadInteger('General', 'ConnTimeOut', fConnTimeOut);
fCallTimeOut := IniFile.ReadInteger('General', 'CallTimeOut', fCallTimeOut);
fServerTruceLen := IniFile.ReadInteger('General', 'ServerTruceLen', fServerTruceLen);
end;
function TBasicDaemon.GetLogId : string;
begin
Result := 'Basic Daemon';
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.StrUtils, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
// function CalcMyNumberCheckDigit(MyNumber: string): Integer;
// function IsValudMyNumber(MyNumber: string): boolean;
private
{ Private 宣言 }
public
{ Public 宣言 }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function CalcMyNumberCheckDigit(MyNumber: string): Integer;
var
MyNumberUnique: String;
CheckDigitCalc, Pn, N: Integer;
MyNumber_num: UInt64;
begin
// チェックデジット計算前のマイナンバーは11桁なので11桁以外の場合は -1 を返す。
if Length(MyNumber) <> 11 then
begin
Result := -1; Exit;
end;
// 入力文字列が数字かどうかを検証し、数字ではない場合は -1 を返す。
MyNumber_num := StrToUInt64Def(MyNumber,0);
if MyNumber_num = 0 then
begin
Result := -1; Exit;
end;
// https://www.j-lis.go.jp/data/open/cnt/3/1282/1/H2707_qa.pdf
// ①11桁の番号の末尾から1桁ずつ順に重みを2、3、4、5、6、7、2、3、4、5、6と乗じて総和を求める。
// ②総和を11で割りその余りを求める。
// ③11より余りを引いた値がチェックデジットとなる。
//
// <例>
// 11桁 の 番 号 がabcdefghijkの場合(a~kは任意の1桁の数字、X~Zは計算により求められた数字を表す)
// ①(k×2)+(j×3)+(i×4)+(h×5)+(g×6)+(f×7)+(e×2)+(d×3)+(c×4)+(b×5)+(a×6)=X
// ②X÷11=Y余りZ
// ③11-Zがチェックデジット
// ※Z(余り)が0または1の場合はチェックデジットを「0」とする。
// 文字列処理の都合上、反転した文字列を扱う
MyNumberUnique := ReverseString(MyNumber);
CheckDigitCalc := 0;
for N := 1 to 11 do
begin
Pn := StrToInt(MyNumberUnique[N]);
// 1~6文字目までと 7~11文字目向けの演算を行う。
if N < 7 then
CheckDigitCalc := CheckDigitCalc + Pn * (N + 1)
else
CheckDigitCalc := CheckDigitCalc + Pn * (N - 5);
end;
CheckDigitCalc := CheckDigitCalc mod 11;
// 11 から、計算された数値を引いた値がチェックデジット。
// ただし 0 または 1 の場合は常に 0 とする。
if CheckDigitCalc <= 1 then
CheckDigitCalc := 0
else
CheckDigitCalc := 11 - CheckDigitCalc;
Result := CheckDigitCalc;
end;
function IsValudMyNumber(MyNumber: string): boolean;
var
CheckDigit: String;
CheckDigitCalc: Integer;
MyNumber_num: UInt64;
begin
// マイナンバーは12桁なので12桁以外の場合は False を返す。
if Length(MyNumber) <> 12 then
begin
Result := False; Exit;
end;
// 入力文字列が数字かどうかを検証し、数字ではない場合は False を返す。
MyNumber_num := StrToUInt64Def(MyNumber,0);
if MyNumber_num = 0 then
begin
Result := False; Exit;
end;
// 番号 123456789018 は、末尾の 8 がチェックデジット、12345678901 が番号部分。
CheckDigit := Copy(MyNumber, 12, 1);
// 先頭1文字目から11文字からチェックデジットを計算する
CheckDigitCalc := CalcMyNumberCheckDigit(Copy(MyNumber, 1, 11));
if CheckDigitCalc.ToString = CheckDigit then
Result := true
else
Result := false;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
IsMyNumber: Boolean;
begin
IsMyNumber := IsValudMyNumber( Edit1.Text );
if IsMyNumber then
Memo1.Lines.Add( Edit1.Text + ' is valid MyNumber' )
else
Memo1.Lines.Add( Edit1.Text + ' is invalid' );
end;
end.
|
unit better_collections;
{$MESSAGE '*******************COMPILING Better_Collections.pas'}
{$INCLUDE DelphiDefs.inc}
{$IFDEF MSWINDOWS}
{$DEFINE USE_FAST_LIST}
{$ENDIF}
{$DEFINE DEBUG_ITEMS}
{$D-}
interface
uses
debug, generics.collections.fixed, systemx, sharedobject, typex, betterobject, classes,
{$IFDEF USE_FAST_LIST}
fastlist,
{$ENDIF}
sysutils;
type
{$IFDEF USE_FAST_LIST}
TBetterList<T: class> = class(TFastList<T>)
{$ELSE}
TBetterList<T: class> = class(TList<T>)
{$ENDIF}
private
function GetLast: T;
public
constructor Create;
function Has(obj: T): boolean;
procedure ClearandFree;
procedure Replace(old, nu: T);
procedure BetterRemove(obj: T);
procedure AddList(list: TBetterList<T>);
property Last: T read GetLast;
end;
TBetterStack<T: class> = class(TStack<T>)
private
function GetTop: T;
public
property Top: T read GetTop;
end;
TSharedList<T: class> = class(TSharedObject)
private
FOwnsObjects: boolean;
function GEtItem(idx: nativeint): T;
procedure SetItem(idx: nativeint; const Value: T);
protected
FList: TBetterList<T>;
FVolatileCount: ni;
function GetCount: nativeint;virtual;
public
RestrictedtoThreadID: int64;
constructor Create;override;
destructor Destroy;override;
function Add(obj: T): nativeint;virtual;
procedure AddList(l: TSharedList<T>);virtual;
procedure Delete(idx: nativeint);virtual;
procedure Remove(obj: T);virtual;
procedure BetterRemove(obj: T);
procedure Insert(idx: ni; obj: T);virtual;
property Count: nativeint read GetCount;
function IndexOf(obj: T): nativeint;virtual;
function Has(obj: T): boolean;virtual;
property Items[idx: nativeint]: T read GEtItem write SetItem;default;
procedure Clear;
procedure FreeAndClear;
property VOlatileCount: ni read FVolatileCount;
property OwnsObjects: boolean read FOwnsObjects write FOwnsObjects;
end;
TSharedStringList = class(TSharedObject)
strict private
FList: TStringList;
private
function GetItem(idx: ni): string;
procedure Setitem(idx: ni; const Value: string);
function GetText: string;
procedure SetText(const Value: string);
public
property Text: string read GetText write SetText;
procedure Add(s: string);
procedure Remove(s: string);
property Items[idx: ni]: string read GetItem write Setitem;default;
procedure Delete(i: ni);
function IndexOf(s: string): ni;
end;
TStringObjectList<T_OBJECTTYPE: class> = class(TBetterObject)
strict private
FItems: TStringlist;
private
FTakeOwnership: boolean;
FDuplicates: TDuplicates;
function GetItem(sKey: string): T_OBJECTTYPE;
procedure SetItem(sKey: string; const Value: T_OBJECTTYPE);
function GetKey(idx: ni): string;
function GetItemByIndex(idx: ni): T_ObjectType;
public
enable_debug: boolean;
procedure Add(sKey: string; obj: T_OBJECTTYPE);
procedure Clear;
procedure Delete(i: ni);
procedure Remove(o: T_OBJECTTYPE);
function IndexOfKey(sKey: string): ni;
function IndexOfObject(o: T_OBJECTTYPE): ni;
function Count: ni;
procedure Init; override;
constructor Create; override;
destructor Destroy; override;
property Items[sKey: string]: T_OBJECTTYPE read GetItem write SetItem;default;
property ItemsByIndex[idx: ni]: T_ObjectType read GetItemByIndex;
property Keys[idx: ni]: string read GetKey;
property TakeOwnership: boolean read FTakeOwnership write FTakeOwnership;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
procedure DebugItems;
end;
implementation
{$IFDEF DEBUG_ITEMS}
uses
JSONHelpers;
{$ENDIF}
{ TBetterList<T> }
procedure TBetterList<T>.AddList(list: TBetterList<T>);
var
t: ni;
begin
for t := 0 to list.count-1 do begin
self.Add(list[t]);
end;
end;
procedure TBetterList<T>.BetterRemove(obj: T);
var
t: ni;
begin
for t:= count-1 downto 0 do begin
if items[t] = obj then
delete(t);
end;
end;
procedure TBetterList<T>.ClearandFree;
var
o: T;
begin
while count > 0 do begin
o := items[0];
remove(items[0]);
o.free;
o := nil;
end;
end;
constructor TBetterList<T>.Create;
begin
inherited;
end;
function TBetterList<T>.GetLast: T;
begin
result := self[self.count-1];
end;
function TBetterList<T>.Has(obj: T): boolean;
begin
result := IndexOf(obj) >= 0;
end;
procedure TBetterList<T>.Replace(old, nu: T);
var
t: ni;
begin
for t:= 0 to count-1 do begin
if Self.Items[t] = old then
self.items[t] := nu;
end;
end;
{ TSharedList<T> }
{$MESSAGE '*******************1 COMPILING Better_Collections.pas'}
function TSharedList<T>.Add(obj: T): nativeint;
begin
if (RestrictedtoThreadID <> 0) and (TThread.CurrentThread.ThreadID <> RestrictedToThreadID) then
{$IFDEF STRICT_THREAD_ENFORCEMENT}
raise Ecritical.create(self.ClassName+' is restricted to thread #'+RestrictedToThreadID.ToString+' but you are accessing it from #'+TThread.CurrentThread.ThreadID.tostring);
{$ELSE}
Debug.Log(CLR_ERR+self.ClassName+' is restricted to thread #'+RestrictedToThreadID.ToString+' but you are accessing it from #'+TThread.CurrentThread.ThreadID.tostring);
{$ENDIF}
Lock;
try
result := FList.add(obj);
FVolatileCount := FList.count;
finally
Unlock;
end;
end;
{$MESSAGE '*******************2 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.AddList(l: TSharedList<T>);
var
x: nativeint;
begin
if (RestrictedtoThreadID <> 0) and (TThread.CurrentThread.ThreadID <> RestrictedToThreadID) then
raise Ecritical.create(self.ClassName+' is restricted to thread #'+RestrictedToThreadID.ToString+' but you are accessing it from #'+TThread.CurrentThread.ThreadID.tostring);
l.Lock;
try
Lock;
try
for x := 0 to l.count-1 do begin
self.Add(l[x]);
end;
finally
Unlock;
end;
finally
l.Unlock;
end;
end;
{$MESSAGE '*******************3 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.BetterRemove(obj: T);
begin
Remove(obj);
end;
{$MESSAGE '*******************4 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.Clear;
begin
Lock;
try
FList.Clear;
FVolatileCount := FList.count;
finally
Unlock;
end;
end;
{$MESSAGE '*******************5 COMPILING Better_Collections.pas'}
constructor TSharedList<T>.Create;
{$MESSAGE '*******************5.1 COMPILING Better_Collections.pas'}
begin
{$MESSAGE '*******************5.2 COMPILING Better_Collections.pas'}
inherited;
{$MESSAGE '*******************5.3 COMPILING Better_Collections.pas'}
FList := TBetterList<T>.create();
{$MESSAGE '*******************5.4 COMPILING Better_Collections.pas'}
end;
{$MESSAGE '*******************5 COMPILING Better_Collections.pas'}
{$MESSAGE '*******************6 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.Delete(idx: nativeint);
begin
Lock;
try
FList.Delete(idx);
FVolatileCount := FList.count;
finally
Unlock;
end;
end;
{$MESSAGE '*******************7 COMPILING Better_Collections.pas'}
destructor TSharedList<T>.Destroy;
begin
if OwnsObjects then begin
while FList.count > 0 do begin
FList[FList.count].free;
FList.delete(FList.count);
end;
end;
FList.free;
FList := nil;
inherited;
end;
procedure TSharedList<T>.FreeAndClear;
begin
while count > 0 do begin
items[count-1].free;
delete(count-1);
end;
end;
{$MESSAGE '*******************8 COMPILING Better_Collections.pas'}
function TSharedList<T>.GetCount: nativeint;
begin
Lock;
try
result := FList.count;
finally
Unlock;
end;
end;
{$MESSAGE '*******************9 COMPILING Better_Collections.pas'}
function TSharedList<T>.GEtItem(idx: nativeint): T;
begin
lock;
try
result := FList[idx];
finally
Unlock;
end;
end;
function TSharedList<T>.Has(obj: T): boolean;
begin
result := IndexOf(obj) >=0;
end;
{$MESSAGE '*******************10 COMPILING Better_Collections.pas'}
function TSharedList<T>.IndexOf(obj: T): nativeint;
begin
Lock;
try
result := FList.IndexOf(obj);
finally
Unlock;
end;
end;
{$MESSAGE '*******************11 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.Insert(idx: ni; obj: T);
begin
Lock;
try
FList.Insert(idx, obj);
FVolatileCount := FList.count;
finally
unlock;
end;
end;
{$MESSAGE '*******************12 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.Remove(obj: T);
begin
Lock;
try
FList.BetterRemove(obj);
FVolatileCount := FList.count;
finally
Unlock;
end;
end;
{$MESSAGE '*******************13 COMPILING Better_Collections.pas'}
procedure TSharedList<T>.SetItem(idx: nativeint; const Value: T);
begin
lock;
try
FLIst[idx] := value;
finally
Unlock;
end;
end;
{ TBetterStack<T> }
function TBetterStack<T>.GetTop: T;
begin
result := Peek;
end;
{ TStringObjectList<T_OBJECTTYPE> }
procedure TStringObjectList<T_OBJECTTYPE>.Add(sKey: string; obj: T_OBJECTTYPE);
begin
case duplicates of
Tduplicates.dupIgnore: begin
if FItems.IndexOf(sKey) >=0 then begin
self[sKey] := obj;
exit;
end;
end;
Tduplicates.dupError: begin
raise ECritical.create(classname+' already has item with key '+sKey);
end;
end;
FItems.AddObject(sKey, obj);
DebugItems();
end;
procedure TStringObjectList<T_OBJECTTYPE>.Clear;
begin
if takeownership then begin
while count > 0 do begin
delete(count-1);
end;
end;
FItems.Clear;
end;
function TStringObjectList<T_OBJECTTYPE>.Count: ni;
begin
result := FItems.count;
end;
constructor TStringObjectList<T_OBJECTTYPE>.Create;
begin
inherited;
FItems := TStringList.create;
Fitems.CaseSensitive := true;
end;
procedure TStringObjectList<T_OBJECTTYPE>.DebugItems;
var
t: ni;
begin
{$IFDEF DEBUG_ITEMS}
if not enable_debug then
exit;
Debug.Log('----------------');
for t:= 0 to FItems.count-1 do begin
if FItems.Objects[t] is TJSON then begin
Debug.Log(FItems[t]+' = '+TJSON(FItems.Objects[t]).tojson);
end;
end;
{$ENDIF}
end;
procedure TStringObjectList<T_OBJECTTYPE>.Delete(i: ni);
begin
if takeownership then
FItems.objects[i].free;
FItems.Delete(i);
end;
destructor TStringObjectList<T_OBJECTTYPE>.Destroy;
begin
Clear;
FItems.free;
FItems := nil;
inherited;
end;
function TStringObjectList<T_OBJECTTYPE>.GetItem(sKey: string): T_OBJECTTYPE;
var
i: ni;
begin
i := IndexofKey(sKey);
result := nil;
if i >=0 then
result := T_OBJECTTYPE(FItems.Objects[i])
else
raise ECritical.create('no object named '+sKey+' was found in '+self.ClassName);
end;
function TStringObjectList<T_OBJECTTYPE>.GetItemByIndex(idx: ni): T_ObjectType;
begin
result := T_OBJECTTYPE(FItems.Objects[idx]);
end;
function TStringObjectList<T_OBJECTTYPE>.GetKey(idx: ni): string;
begin
result := FItems[idx];
end;
function TStringObjectList<T_OBJECTTYPE>.IndexOfKey(sKey: string): ni;
begin
result := FItems.IndexOf(sKey);
end;
function TStringObjectList<T_OBJECTTYPE>.IndexOfObject(o: T_OBJECTTYPE): ni;
begin
result := FItems.IndexOfObject(o);
end;
procedure TStringObjectList<T_OBJECTTYPE>.Init;
begin
inherited;
end;
procedure TStringObjectList<T_OBJECTTYPE>.Remove(o: T_OBJECTTYPE);
var
i: ni;
begin
i := FItems.IndexOfObject(o);
if i >=0 then begin
Delete(i);
end;
end;
procedure TStringObjectList<T_OBJECTTYPE>.SetItem(sKey: string;
const Value: T_OBJECTTYPE);
var
i: ni;
begin
i := Fitems.IndexOf(sKey);
if i >= 0 then
FItems.Objects[i] := value;
end;
{ TSharedStringList }
procedure TSharedStringList.Add(s: string);
var
l : ILock;
begin
l := self.LockI;
FList.add(s);
end;
procedure TSharedStringList.Delete(i: ni);
var
l: ILock;
begin
l := self.LockI;
FList.delete(i);
end;
function TSharedStringList.GetItem(idx: ni): string;
var
l: ILock;
begin
l := self.LockI;
result := FList[idx];
end;
function TSharedStringList.GetText: string;
var
l: ILock;
begin
l := self.LockI;
result := Flist.Text;
end;
function TSharedStringList.IndexOf(s: string): ni;
var
l: ILock;
begin
l := self.LockI;
result := Flist.IndexOf(s);
end;
procedure TSharedStringList.Remove(s: string);
var
l: ILock;
i: ni;
begin
l := self.LockI;
i := FList.IndexOf(s);
if i>=0 then
FList.delete(i);
end;
procedure TSharedStringList.Setitem(idx: ni; const Value: string);
var
l: ILock;
begin
l := self.LockI;
Flist[idx] := value;
end;
procedure TSharedStringList.SetText(const Value: string);
var
l: ILock;
begin
l := self.LockI;
Flist.Text := value;
end;
end.
|
unit ExtAIActions;
interface
uses
Classes, SysUtils,
ExtAIMsgActions, ExtAINetClient, ExtAISharedInterface;
// Actions of the ExtAI
type
TExtAIActions = class
private
fActions: TExtAIMsgActions;
fClient: TExtAINetClient;
// Triggers
fOnGroupOrderAttackUnit: TGroupOrderAttackUnit;
fOnGroupOrderWalk: TGroupOrderWalk;
fOnLog: TLog;
// Send action via client
procedure SendAction(aData: Pointer; aLength: Cardinal);
public
constructor Create(aClient: TExtAINetClient);
destructor Destroy(); override;
// Connect Msg directly with creator of ExtAI so he can type Actions.XY instead of Actions.Msg.XY
property Msg: TExtAIMsgActions read fActions;
property GroupOrderAttackUnit: TGroupOrderAttackUnit read fOnGroupOrderAttackUnit;
property GroupOrderWalk: TGroupOrderWalk read fOnGroupOrderWalk;
property Log: TLog read fOnLog;
end;
implementation
{ TExtAIActions }
constructor TExtAIActions.Create(aClient: TExtAINetClient);
begin
Inherited Create;
fClient := aClient;
fActions := TExtAIMsgActions.Create();
// Connect callbacks
fActions.OnSendAction := SendAction;
// Connect properties
fOnGroupOrderAttackUnit := fActions.GroupOrderAttackUnitW;
fOnGroupOrderWalk := fActions.GroupOrderWalkW;
fOnLog := fActions.LogW;
end;
destructor TExtAIActions.Destroy();
begin
fOnGroupOrderAttackUnit := nil;
fOnGroupOrderWalk := nil;
fOnLog := nil;
fActions.Free;
fClient := nil;
Inherited;
end;
procedure TExtAIActions.SendAction(aData: Pointer; aLength: Cardinal);
begin
Assert(fClient <> nil, 'Action cannot be send because client = nil');
fClient.SendMessage(aData, aLength);
end;
end.
|
unit ts2pas.Declarations;
interface
const
CRLF = #13#10;
type
TVisibility = (vPublic, vProtected, vPrivate);
TAccessibilityModifier = (
amPublic,
amPrivate,
amProtected
);
IDeclarationOwner = interface
end;
TCustomDeclaration = class
private
FOwner: IDeclarationOwner;
class var FIndentionLevel: Integer;
class var FNamespaces: array of String;
protected
function GetAsCode: String; virtual; abstract;
class function GetIndentionString: String;
class function GetNamespaceString: String;
public
constructor Create(Owner: IDeclarationOwner); virtual;
class procedure BeginIndention;
class procedure EndIndention;
class procedure BeginNamespace(Value: String);
class procedure EndNamespace;
property AsCode: String read GetAsCode;
property NamespaceString: String read GetNamespaceString;
end;
TNamedDeclaration = class(TCustomDeclaration)
public
property Name: String;
end;
TCustomType = class(TCustomDeclaration)
public
function GetPromiseType: TCustomType; virtual;
function IsPromise: Boolean; virtual;
end;
TTypeParameter = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property Name: String;
property ExtendsType: TCustomType;
end;
TArrayType = class(TCustomType)
protected
function GetAsCode: String; override;
public
property &Type: TCustomType;
end;
TUnionType = class(TCustomType)
protected
function GetAsCode: String; override;
public
property &Types: array of TCustomType;
end;
TCustomNamedType = class(TCustomType)
protected
function GetName: String; virtual; abstract;
function GetAsCode: String; override;
public
property Name: String read GetName;
end;
TTypeOfType = class(TCustomNamedType)
protected
function GetAsCode: String; override;
function GetName: String; override;
public
property &Type: TCustomType;
end;
TPredefinedType = class(TCustomNamedType)
protected
function GetAsCode: String; override;
end;
TVariantType = class(TPredefinedType)
protected
function GetName: String; override;
end;
TFloatType = class(TPredefinedType)
protected
function GetName: String; override;
end;
TStringType = class(TPredefinedType)
protected
function GetName: String; override;
end;
TBooleanType = class(TPredefinedType)
protected
function GetName: String; override;
end;
TJSObject = class(TPredefinedType)
protected
function GetName: String; override;
end;
TFunctionParameter = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
function GetAsCodeOmitType(OmitType: Boolean): String;
public
property &Type: TCustomType;
property IsOptional: Boolean;
property AsCode[OmitType: Boolean]: String read GetAsCodeOmitType;
end;
TFunctionType = class(TCustomNamedType)
protected
function GetName: String; override;
function GetAsCode: String; override;
function GetAsCodeWithOptionalLevel(OptionalLevel: Integer): String; overload;
public
property Name: String read GetName;
property ResultType: TCustomType;
property ParameterList: array of TFunctionParameter;
property TypeParameters: array of TTypeParameter;
property AsCode[OptionalLevel: Integer]: String read GetAsCodeWithOptionalLevel;
end;
TConstructorType = class(TCustomNamedType)
protected
function GetName: String; override;
function GetAsCode: String; override;
public
property Name: String read GetName;
property ResultType: TCustomType;
property ParameterList: array of TFunctionParameter;
end;
TTypeArgument = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property &Type: TCustomType;
end;
TNamedType = class(TCustomNamedType)
private
FName: String;
protected
function GetName: String; override;
function GetAsCode: String; override;
public
constructor Create(Owner: IDeclarationOwner; AName: String); reintroduce;
function GetPromiseType: TCustomType; override;
function IsPromise: Boolean; override;
property Name: String read GetName;
property Arguments: array of TTypeArgument;
end;
TExportDeclaration = class(TNamedDeclaration)
private
FDefault: Boolean;
protected
function GetAsCode: String; override;
public
property Default: Boolean read FDefault write FDefault;
end;
TDefinitionDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
end;
TEnumerationItem = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property Name: String;
property Value: String;
end;
TTupleType = class(TCustomType)
protected
function GetAsCode: String; override;
public
property Types: array of TCustomType;
end;
TNullType = class(TCustomType)
protected
function GetAsCode: String; override;
end;
TCustomTypeMember = class(TNamedDeclaration)
public
constructor Create(Owner: IDeclarationOwner); override;
property Visibility: TVisibility;
property IsStatic: Boolean;
property TypeArguments: array of TTypeArgument;
property TypeParameters: array of TTypeParameter;
end;
TObjectType = class(TCustomType)
protected
function GetAsCode: String; override;
public
property Members: array of TCustomTypeMember;
end;
TParameter = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
function GetAsCodeOmitType(OmitType: Boolean): String;
public
property AccessibilityModifier: TAccessibilityModifier;
property &Type: TCustomType;
property IsOptional: Boolean;
property IsRest: Boolean;
property DefaultValue: string;
property AsCode[OmitType: Boolean]: String read GetAsCodeOmitType;
end;
TIndexSignature = class(TCustomTypeMember)
protected
function GetAsCode: String; override;
public
property IsStringIndex: Boolean;
property &Type: TCustomType;
end;
TClassTypeMember = class(TCustomTypeMember)
public
property Visibility: TVisibility;
property IsStatic: Boolean;
end;
TIndexMemberDeclaration = class(TClassTypeMember)
protected
function GetAsCode: String; override;
public
property IndexSignature: TIndexSignature;
end;
TPropertyMemberDeclaration = class(TClassTypeMember)
protected
function GetAsCode: String; override;
public
property Nullable: Boolean;
property &Type: TCustomType;
end;
TConstructorDeclaration = class(TClassTypeMember)
protected
function GetAsCode: String; override;
public
property ParameterList: array of TParameter;
property &Type: TCustomType;
end;
TCallSignature = class(TCustomTypeMember)
protected
function GetAsCode: String; override;
function GetAsCodeWithOptionalLevel(OptionalLevel: Integer): String; overload;
public
property ParameterList: array of TParameter;
property &Type: TCustomType;
property TypeParameters: array of TTypeParameter;
property AsCode[OptionalLevel: Integer]: String read GetAsCodeWithOptionalLevel;
end;
TMethodDeclaration = class(TClassTypeMember)
protected
function GetAsCode: String; override;
public
property CallSignature: TCallSignature;
end;
TTypeReference = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property Name: String;
property Arguments: array of TTypeArgument;
end;
TInterfaceDeclaration = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
function GetDeclaration: String; virtual;
public
function GetForwardDeclaration: String;
property Name: String;
property Extends: array of TTypeReference;
property IsExport: Boolean;
property &Type: TObjectType;
property TypeParameters: array of TTypeParameter;
end;
TEnumerationDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Items: array of TEnumerationItem;
end;
TFunctionDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property &Type: TFunctionType;
end;
TClassDeclaration = class(TInterfaceDeclaration)
protected
function GetAsCode: String; override;
function GetDeclaration: String; override;
public
property Implements: array of TTypeReference;
property IsAbstract: Boolean;
property Members: array of TCustomTypeMember;
end;
TImportDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Value: String;
end;
TTypeAlias = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
function GetDeclaration(BreakLine: Boolean): String;
public
function GetForwardDeclaration: String;
property &Type: TCustomType;
property &TypeParameters: array of TTypeParameter;
end;
TNamespaceDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Enums: array of TEnumerationDeclaration;
property TypeAliases: array of TTypeAlias;
property Functions: array of TFunctionDeclaration;
property Classes: array of TClassDeclaration;
property Interfaces: array of TInterfaceDeclaration;
property Namespaces: array of TNamespaceDeclaration;
end;
TAmbientBinding = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property &Type: TCustomType;
end;
TAmbientVariableDeclaration = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property IsConst: Boolean;
property AmbientBindingList: array of TAmbientBinding;
end;
TAmbientFunctionDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property CallSignature: TCallSignature;
end;
TAmbientBodyElement = class(TCustomDeclaration);
TAmbientClassDeclaration = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property Name: String;
property Extends: array of TTypeReference;
property Implements: array of String;
property Members: array of TAmbientBodyElement;
property TypeParameters: array of TTypeParameter;
end;
TAmbientPropertyMemberDeclaration = class(TAmbientBodyElement)
public
property Visibility: TVisibility;
property IsStatic: Boolean;
property Name: string;
end;
TAmbientPropertyMemberDeclarationProperty = class(TAmbientPropertyMemberDeclaration)
protected
function GetAsCode: String; override;
public
property &Type: TCustomType;
end;
TAmbientPropertyMemberDeclarationMethod = class(TAmbientPropertyMemberDeclaration)
protected
function GetAsCode: String; override;
public
property CallSignature: TCallSignature;
end;
TAmbientEnumerationDeclaration = class(TEnumerationDeclaration);
TAmbientNamespaceDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Enums: array of TAmbientEnumerationDeclaration;
property Functions: array of TAmbientFunctionDeclaration;
property Classes: array of TAmbientClassDeclaration;
property Interfaces: array of TInterfaceDeclaration;
property Variables: array of TAmbientVariableDeclaration;
property Namespaces: array of TAmbientNamespaceDeclaration;
property TypeAliases: array of TTypeAlias;
end;
TAmbientConstructorDeclaration = class(TAmbientBodyElement)
protected
function GetAsCode: String; override;
public
property ParameterList: array of TFunctionParameter;
end;
TAmbientModuleDeclaration = class(TCustomDeclaration)
protected
function GetAsCode: String; override;
public
property IdentifierPath: String;
property Enums: array of TEnumerationDeclaration;
property Variables: array of TAmbientVariableDeclaration;
property TypeAliases: array of TTypeAlias;
property Functions: array of TAmbientFunctionDeclaration;
property Classes: array of TClassDeclaration;
property Modules: array of TAmbientModuleDeclaration;
property Namespaces: array of TNamespaceDeclaration;
property Interfaces: array of TInterfaceDeclaration;
end;
TVariableDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property &Type: TCustomType;
end;
TModuleDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Classes: array of TClassDeclaration;
property Interfaces: array of TInterfaceDeclaration;
property Functions: array of TFunctionDeclaration;
property Exports: array of TExportDeclaration;
property Variables: array of TVariableDeclaration;
property Modules: array of TModuleDeclaration;
end;
TAmbientDeclaration = class(TNamedDeclaration)
protected
function GetAsCode: String; override;
public
property Classes: array of TAmbientClassDeclaration;
property Functions: array of TAmbientFunctionDeclaration;
property Enums: array of TEnumerationDeclaration;
property Modules: array of TAmbientModuleDeclaration;
property Namespaces: array of TAmbientNamespaceDeclaration;
property Variables: array of TAmbientVariableDeclaration;
end;
implementation
uses
NodeJS.Core, System.Dictionaries;
function Escape(Name: String): String;
begin
Result := Name.Replace('$', '');
if LowerCase(Name) in ['as', 'abstract', 'array', 'begin', 'class', 'const',
'constructor', 'default', 'div', 'end', 'exit', 'export', 'external',
'function', 'inline', 'interface', 'label', 'method', 'object', 'private',
'property', 'protected', 'public', 'record', 'repeat', 'set',
'then', 'type', 'unit', 'uses'] then
Result := '&' + Result;
if LowerCase(Name) in ['length', 'include', 'exclude', 'string'] then
Result := '_' + Result;
end;
{ TCustomDeclaration }
constructor TCustomDeclaration.Create(Owner: IDeclarationOwner);
begin
FOwner := Owner;
end;
class procedure TCustomDeclaration.BeginIndention;
begin
Inc(FIndentionLevel);
end;
class procedure TCustomDeclaration.BeginNameSpace(Value: String);
begin
FNamespaces.Push(Value);
end;
class procedure TCustomDeclaration.EndIndention;
begin
Dec(FIndentionLevel);
end;
class procedure TCustomDeclaration.EndNamespace;
begin
FNamespaces.Pop;
end;
class function TCustomDeclaration.GetIndentionString: String;
begin
Result := DupeString(' ', FIndentionLevel);
end;
class function TCustomDeclaration.GetNamespaceString: String;
begin
Result := '';
if FNamespaces.Count > 0 then
begin
Result += FNamespaces[0];
for var Index := Low(FNamespaces) + 1 to High(FNamespaces) do
Result += '.' + FNamespaces[Index];
end;
end;
{ TArrayType }
function TArrayType.GetAsCode: String;
begin
Result := 'array of ' + &Type.AsCode;
end;
{ TUnionType }
function TUnionType.GetAsCode: String;
begin
Result := 'JSValue {';
for var Index := Low(Types) to High(Types) - 1 do
begin
Result += if Assigned(Types[Index]) then Types[Index].AsCode else 'void';
Result += ' or ';
end;
var LastType := Types[High(Types)];
Result += if Assigned(LastType) then LastType.AsCode else 'void';
Result += '}';
end;
{ TCustomNamedType }
function TCustomNamedType.GetAsCode: String;
begin
(*
case LowerCase(Name) of
'date':
Result := 'JDate';
else
Result := Escape(Name);
end;
*)
Result := 'T' + Name;
end;
{ TTypeOfType }
function TTypeOfType.GetName: String;
begin
Result := 'type of';
end;
function TTypeOfType.GetAsCode: String;
begin
if &Type is TCustomNamedType then
Result := 'T' + TCustomNamedType(&Type).Name + 'Class';
end;
{ TPredefinedType }
function TPredefinedType.GetAsCode: String;
begin
Result := Name;
end;
{ TVariantType }
function TVariantType.GetName: String;
begin
Result := 'JSValue';
end;
{ TFloatType }
function TFloatType.GetName: String;
begin
Result := 'Double';
end;
{ TBooleanType }
function TBooleanType.GetName: String;
begin
Result := 'Boolean';
end;
{ TStringType }
function TStringType.GetName: String;
begin
Result := 'String';
end;
{ TFunctionType }
function TFunctionType.GetName: String;
begin
Result := 'function';
end;
function TFunctionType.GetAsCode: String;
begin
if ParameterList.Count > 0 then
begin
Result := '(' + ParameterList[0].AsCode[False];
for var Index := Low(ParameterList) + 1 to High(ParameterList) do
Result += '; ' + ParameterList[Index].AsCode[False];
Result += ')';
end;
if Assigned(ResultType) then
Result += ': ' + ResultType.AsCode;
end;
function IsIdenticalFunctionParameterType(A, B: TFunctionParameter): Boolean;
begin
Result := Assigned(A.&Type) xor Assigned(A.&Type);
if Result and Assigned(A.&Type) then
Result := A.&Type.AsCode = B.&Type.AsCode;
end;
function TFunctionType.GetAsCodeWithOptionalLevel(OptionalLevel: Integer): String;
var
CanOmitType: Boolean;
begin
var CurrentOptionalLevel := 0;
if ParameterList.Count > 0 then
begin
// check if the first parameter isn't optional and there is no budget
if not (ParameterList[0].IsOptional and (OptionalLevel = 0)) then
begin
CurrentOptionalLevel += Integer(ParameterList[0].IsOptional);
// ensure at least two parameter are available
CanOmitType := (ParameterList.Count >= 2)
// ensure that both have a type
and IsIdenticalFunctionParameterType(ParameterList[0], ParameterList[1])
// ensure that the current type is optional and that there is still some budget
and (not ParameterList[0].IsOptional or (CurrentOptionalLevel < OptionalLevel));
Result := '(' + ParameterList[0].AsCode[CanOmitType];
for var Index := Low(ParameterList) + 1 to High(ParameterList) do
begin
// check if optional level is reached
if ParameterList[Index].IsOptional and (CurrentOptionalLevel >= OptionalLevel) then
break;
// increase optional level
CurrentOptionalLevel += Integer(ParameterList[Index].IsOptional);
// add separator
Result += if CanOmitType then ', ' else '; ';
// check if current type is needed
CanOmitType := (Index + 1 < ParameterList.Count) and
IsIdenticalFunctionParameterType(ParameterList[0], ParameterList[1])
and (not ParameterList[Index].IsOptional or (CurrentOptionalLevel < OptionalLevel));
Result += ParameterList[Index].AsCode[CanOmitType];
end;
Result += ')';
end;
end;
if Assigned(ResultType) then
Result += ': ' + ResultType.AsCode;
end;
{ TConstructorType }
function TConstructorType.GetName: String;
begin
Result := 'constructor';
end;
function TConstructorType.GetAsCode: String;
begin
if ParameterList.Count > 0 then
begin
Result := '(' + ParameterList[0].AsCode[False];
for var Index := Low(ParameterList) + 1 to High(ParameterList) do
Result += '; ' + ParameterList[Index].AsCode[False];
Result += ')';
end;
if Assigned(ResultType) then
Result += ': ' + ResultType.AsCode;
end;
{ TNamedType }
constructor TNamedType.Create(Owner: IDeclarationOwner; AName: String);
begin
inherited Create(Owner);
FName := AName
end;
function TNamedType.GetName: String;
begin
Result := FName;
end;
function TNamedType.GetAsCode: String;
begin
if Name = 'Partial' then
Result := Arguments[0].AsCode
else if IsPromise then
Result := GetPromiseType.AsCode
else
begin
var ArgumentsValue := '';
Result := inherited GetAsCode;
for var Argument in Arguments do
begin
if ArgumentsValue <> '' then
ArgumentsValue += ', ';
ArgumentsValue += Argument.AsCode;
end;
if ArgumentsValue <> '' then
Result += '<' + ArgumentsValue + '>';
end;
end;
function TNamedType.IsPromise: Boolean;
begin
Result := Name = 'Promise';
end;
function TNamedType.GetPromiseType: TCustomType;
begin
var &Type := Arguments[0].&Type;
if (&Type is TNamedType) and (TNamedType(&Type).Name = 'void') then
Result := nil
else
Result := &Type;
end;
{ TExportDeclaration }
function TExportDeclaration.GetAsCode: String;
begin
Result := '';
end;
{ TAmbientDeclaration }
function TAmbientDeclaration.GetAsCode: String;
begin
for var &Function in Functions do
Result += &Function.AsCode;
for var Module in Modules do
Result += Module.AsCode;
if Classes.Count > 0 then
begin
Result += 'type' + CRLF;
BeginIndention;
for var &Class in Classes do
Result += &Class.AsCode;
EndIndention;
end;
if Variables.Count > 0 then
for var Variable in Variables do
Result += Variable.AsCode;
for var Namespace in Namespaces do
Result += Namespace.AsCode;
end;
{ TDefinitionDeclaration }
function TDefinitionDeclaration.GetAsCode: String;
begin
Console.Log('not implemented: TDefinitionDeclaration.GetAsCode');
end;
{ TEnumerationItem }
function TEnumerationItem.GetAsCode: String;
begin
Result := Name;
end;
{ TEnumerationDeclaration }
function TEnumerationDeclaration.GetAsCode: String;
begin
Result += GetIndentionString + 'T' + Name + ' = JSValue;' + CRLF;
Result += GetIndentionString + 'T' + Name + 'Helper = strict helper for T' + Name + CRLF;
BeginIndention;
for var Item in Items do
begin
Result += GetIndentionString + 'const ' + Escape(Item.AsCode);
if Item.Value <> '' then
begin
try
Result += ' = ' + IntToStr(Item.Value.ToInteger) + ';' + CRLF;
except
Result += ' = ''' + Item.Value + ''';' + CRLF;
end;
end
else
Result += ' = ''' + Item.Name + ''';' + CRLF
end;
(*
for var Index := Low(Items) to High(Items) - 1 do
Result += Items[Index].AsCode + ', ' + CRLF;
Result += Items[High(Items)].AsCode + CRLF;
*)
EndIndention;
Result += GetIndentionString + 'end;' + CRLF;
Result += CRLF;
end;
{ TFunctionDeclaration }
function TFunctionDeclaration.GetAsCode: String;
var
Head: string;
Foot: string;
begin
var OptionalParameterCount := 0;
for var Parameter in &Type.ParameterList do
if Parameter.IsOptional then
Inc(OptionalParameterCount);
Head := GetIndentionString;
Head += if Assigned(&Type.ResultType) then 'function' else 'procedure';
Head += ' ' + Escape(Name);
Foot := ';' + if OptionalParameterCount > 0 then ' overload;';
(*
if NamespaceString <> '' then
Foot += ' external ''' + NamespaceString + Escape(Name) + '''';
*)
Foot += CRLF;
Result := '';
for var i := 0 to OptionalParameterCount do
Result += Head + &Type.AsCode[i] + Foot;
end;
{ TConstructorDeclaration }
function TConstructorDeclaration.GetAsCode: String;
begin
Result := GetIndentionString;
if IsStatic then
Result += 'class ';
Result += 'constructor Create';
if Assigned(&Type) then
Result += &Type.AsCode;
// line break
Result += ';' + CRLF;
end;
{ TPropertyMemberDeclaration }
function TPropertyMemberDeclaration.GetAsCode: String;
begin
Result := GetIndentionString;
if IsStatic then
Result += 'class var ';
Result += Escape(Name);
if TypeArguments.Count > 0 then
begin
Result += '{<';
for var Argument in TypeArguments do
Result += Argument.AsCode;
Result += '>}';
end;
Result += ': ';
if Assigned(&Type) then
begin
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode;
end
else
Result += 'JSValue';
Result += ';';
if Nullable then
Result += ' // nullable';
// line break
Result += CRLF;
end;
{ TIndexMemberDeclaration }
function TIndexMemberDeclaration.GetAsCode: String;
begin
Result := IndexSignature.GetAsCode + ';' + CRLF;
end;
{ TIndexSignature }
function TIndexSignature.GetAsCode: String;
begin
Result := GetIndentionString + '// ';
Result += 'property Item[' + Name + ': ';
Result += if IsStringIndex then 'String' else 'Integer';
Result += ']: ' + &Type.AsCode + ';' + CRLF;
end;
{ TMethodDeclaration }
function TMethodDeclaration.GetAsCode: String;
var
Head: string;
Foot: string;
begin
var IsPromise := Assigned(CallSignature.&Type) and CallSignature.&Type.IsPromise;
var OptionalParameterCount := 0;
var ReturnType := CallSignature.&Type;
if IsPromise then
ReturnType := CallSignature.&Type.GetPromiseType;
for var Parameter in CallSignature.ParameterList do
if Parameter.IsOptional then
Inc(OptionalParameterCount);
Head := GetIndentionString;
if IsStatic then
Head += 'class ';
Head += if Assigned(ReturnType) then 'function' else 'procedure';
Head += ' ' + Escape(Name);
Foot := ';';
Foot += if OptionalParameterCount > 0 then ' overload;';
if IsPromise then
Foot += ' async;';
Foot += CRLF;
Result := '';
for var i := 0 to OptionalParameterCount do
Result += Head + CallSignature.AsCode[i] + Foot;
end;
{ TFunctionParameter }
function TFunctionParameter.GetAsCode: String;
begin
Result := Escape(Name) + ': ';
if Assigned(&Type) then
begin
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode
end
else
Result += 'JSValue';
end;
function TFunctionParameter.GetAsCodeOmitType(OmitType: Boolean): String;
begin
Result := Escape(Name);
if not OmitType then
begin
Result += ': ';
if Assigned(&Type) then
begin
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode
end
else
Result += 'JSValue';
end;
end;
{ TCustomTypeMember }
constructor TCustomTypeMember.Create(Owner: IDeclarationOwner);
begin
inherited Create(Owner);
Visibility := vPublic;
end;
{ TObjectType }
function TObjectType.GetAsCode: String;
begin
(*
Result +=
for var Extend in Extends do
Result += ' // extends ' + Extend;
*)
BeginIndention;
for var Member in Members do
if Member is TCallSignature then
begin
Result += GetIndentionString;
var ResType := TCallSignature(Member).&Type;
Result += if Assigned(ResType) then 'function' else 'procedure';
Result += Member.AsCode + ';' + CRLF
end
else
Result += Member.AsCode;
EndIndention;
Result += GetIndentionString + 'end';
end;
{ TTupleType }
function TTupleType.GetAsCode: String;
begin
Result := 'TupletType';
end;
{ TImportDeclaration }
function TImportDeclaration.GetAsCode: String;
begin
Console.Log('not implemented: TImportDeclaration.GetAsCode');
end;
{ TVariableDeclaration }
function TVariableDeclaration.GetAsCode: String;
begin
Console.Log('not implemented: TVariableDeclaration.GetAsCode');
end;
{ TModuleDeclaration }
function TModuleDeclaration.GetAsCode: String;
begin
Result := '';
// classes and interfaces
if Classes.Count + Interfaces.Count > 0 then
begin
Result += 'type' + CRLF;
BeginIndention;
for var &Class in Classes do
Result := Result + &Class.AsCode;
for var &Interface in Interfaces do
Result := Result + &Interface.AsCode;
EndIndention;
end;
if Variables.Count > 0 then
begin
Result += 'var' + CRLF;
BeginIndention;
for var Variable in Variables do
Result := Result + Variable.AsCode;
EndIndention;
end;
end;
{ TParameter }
function TParameter.GetAsCode: String;
begin
Result := Name + ': ';
if Assigned(&Type) then
begin
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode
end
else
Result += 'JSValue';
if DefaultValue <> '' then
Result += ' = ' + DefaultValue;
if IsRest then
Result += ' {...}';
end;
function TParameter.GetAsCodeOmitType(OmitType: Boolean): String;
begin
Result := Escape(Name);
if not OmitType then
begin
Result += ': ';
if Assigned(&Type) then
begin
if &Type is TObjectType then
Result += 'record' + CRLF;
if &Type is TFunctionType then
begin
var ResType := TFunctionType(&Type).ResultType;
Result += if Assigned(ResType) then 'function' else 'procedure';
end;
Result += &Type.AsCode
end
else
Result += 'JSValue';
end;
end;
{ TCallSignature }
function TCallSignature.GetAsCode: String;
begin
Result := '';
if TypeParameters.Length > 0 then
begin
Result += '{<';
for var TypeParameter in TypeParameters do
Result += TypeParameter.AsCode;
Result += '>}';
end;
if ParameterList.Length > 0 then
begin
Result += '(';
for var Index := Low(ParameterList) to High(ParameterList) - 1 do
Result += ParameterList[Index].AsCode[False] + '; ';
Result += ParameterList[High(ParameterList)].AsCode[False] + ')';
end;
if Assigned(&Type) then
begin
Result += ': ';
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode;
end;
Result += ';';
end;
function IsIdenticalParameterType(A, B: TParameter): Boolean;
begin
Result := Assigned(A.&Type) xor Assigned(A.&Type);
if Result and Assigned(A.&Type) then
Result := A.&Type.AsCode = B.&Type.AsCode;
end;
function TCallSignature.GetAsCodeWithOptionalLevel(OptionalLevel: Integer): String;
var
CanOmitType: Boolean;
begin
var CurrentOptionalLevel := 0;
if ParameterList.Count > 0 then
begin
// check if the first parameter isn't optional and there is no budget
if not (ParameterList[0].IsOptional and (OptionalLevel = 0)) then
begin
CurrentOptionalLevel += Integer(ParameterList[0].IsOptional);
// ensure at least two parameter are available
CanOmitType := (ParameterList.Count >= 2)
// ensure that both have a type
and IsIdenticalParameterType(ParameterList[0], ParameterList[1])
// ensure that the current type is optional and that there is still some budget
and (not ParameterList[0].IsOptional or (CurrentOptionalLevel < OptionalLevel));
Result := '(' + ParameterList[0].AsCode[CanOmitType];
for var Index := Low(ParameterList) + 1 to High(ParameterList) do
begin
// check if optional level is reached
if ParameterList[Index].IsOptional and (CurrentOptionalLevel >= OptionalLevel) then
break;
// increase optional level
CurrentOptionalLevel += Integer(ParameterList[Index].IsOptional);
// add separator
Result += if CanOmitType then ', ' else '; ';
// check if current type is needed
CanOmitType := (Index + 1 < ParameterList.Count) and
IsIdenticalParameterType(ParameterList[Index], ParameterList[Index + 1])
and (not ParameterList[Index].IsOptional or (CurrentOptionalLevel < OptionalLevel));
Result += ParameterList[Index].AsCode[CanOmitType];
end;
Result += ')';
end;
end;
if Assigned(&Type) then
begin
Result += ': ';
if &Type is TObjectType then
Result += 'record' + CRLF;
Result += &Type.AsCode;
end;
end;
{ TAmbientBinding }
function TAmbientBinding.GetAsCode: String;
begin
Result := Name + ': ' + &Type.AsCode;
end;
{ TAmbientVariableDeclaration }
function TAmbientVariableDeclaration.GetAsCode: String;
begin
for var AmbientBinding in AmbientBindingList do
Result += GetIndentionString + AmbientBinding.AsCode;
Result += ';' + CRLF;
end;
{ TAmbientFunctionDeclaration }
function TAmbientFunctionDeclaration.GetAsCode: String;
var
Head: string;
Foot: string;
begin
var OptionalParameterCount := 0;
for var Parameter in CallSignature.ParameterList do
if Parameter.IsOptional then
Inc(OptionalParameterCount);
Head := GetIndentionString;
Head += if Assigned(CallSignature.&Type) then 'function' else 'procedure';
Head += ' ' + Escape(Name);
Foot := ';' + if OptionalParameterCount > 0 then ' overload;';
if NamespaceString <> '' then
Foot += ' external ''' + NamespaceString + '.' + Name + '''';
Foot += CRLF;
Result := '';
for var i := 0 to OptionalParameterCount do
Result += Head + CallSignature.AsCode[i] + Foot;
end;
{ TAmbientFunctionDeclaration }
function TAmbientModuleDeclaration.GetAsCode: String;
var
ProcessedClasses: TW3ObjDictionary;
procedure ProcessClass(ClassName: String);
begin
if ProcessedClasses.Contains(ClassName) then
begin
var &Class := TClassDeclaration(ProcessedClasses[ClassName]);
ProcessedClasses.Delete(ClassName);
for var TypeReference in &Class.Extends do
ProcessClass(TypeReference.Name);
Result += &Class.AsCode;
end;
end;
begin
ProcessedClasses := TW3ObjDictionary.Create;
Result := '//' + IdentifierPath + CRLF + CRLF;
var Constants := 0;
for var Variable in Variables do
if Variable.IsConst then
Inc(Constants);
if Constants > 0 then
begin
Result += 'const' + CRLF;
BeginIndention;
for var Variable in Variables do
if Variable.IsConst then
Result := Result + Variable.AsCode;
EndIndention;
Result += CRLF;
end;
if Enums.Count + Classes.Count + Interfaces.Count > 0 then
begin
Result += 'type' + CRLF;
BeginIndention;
for var Enum in Enums do
Result += Enum.AsCode;
for var &Type in TypeAliases do
if &Type.&Type is TObjectType then
Result += &Type.GetForwardDeclaration;
for var &Interface in Interfaces do
Result += &Interface.GetForwardDeclaration;
for var &Class in Classes do
begin
ProcessedClasses[&Class.Name] := &Class;
Result += &Class.GetForwardDeclaration;
end;
for var &Interface in Interfaces do
Result += &Interface.AsCode;
for var &Class in Classes do
ProcessClass(&Class.Name);
for var TypeAlias in TypeAliases do
Result += TypeAlias.AsCode;
EndIndention;
end;
for var Module in Modules do
Result += Module.AsCode;
if Functions.Count > 0 then
begin
for var &Function in Functions do
Result += &Function.AsCode;
Result += CRLF;
end;
if Variables.Count - Constants > 0 then
begin
Result += 'var' + CRLF;
BeginIndention;
for var Variable in Variables do
if not Variable.IsConst then
Result := Result + Variable.AsCode;
EndIndention;
Result += CRLF;
end;
for var Namespace in Namespaces do
Result += Namespace.AsCode;
Result += CRLF;
end;
{ TClassDeclaration }
function TClassDeclaration.GetAsCode: String;
begin
{$IFDEF DEBUG} Console.Log('Write external class: ' + Name); {$ENDIF}
Result := GetDeclaration + ' external name ''' + Name + '''';
if Extends.Count > 0 then
begin
Result += '(';
Result += Extends[0].AsCode;
for var Index := Low(Extends) + 1 to High(Extends) do
Result += ', ' + Extends[Index].AsCode;
Result += ')';
end;
Result += CRLF;
BeginIndention;
for var Member in Members do
Result += Member.AsCode;
EndIndention;
Result += GetIndentionString + 'end;' + CRLF + CRLF;
end;
function TClassDeclaration.GetDeclaration: String;
begin
Result := GetIndentionString + 'T' + Name + ' = class';
end;
{ TInterfaceDeclaration }
function TInterfaceDeclaration.GetAsCode: String;
begin
{$IFDEF DEBUG} Console.Log('Write interface: ' + Name); {$ENDIF}
Result += GetDeclaration;
if TypeParameters.Length > 0 then
begin
Result += '{<';
for var TypeParameter in TypeParameters do
Result += TypeParameter.AsCode;
Result += '>}';
end;
Result += ' = class external';
if Extends.Count > 0 then
begin
Result += '(';
Result += Extends[0].AsCode;
for var Index := Low(Extends) + 1 to High(Extends) do
Result += ', ' + Extends[Index].AsCode;
Result += ')';
end;
Result += CRLF;
Result += &Type.AsCode;
// line breaks
Result += ';' + CRLF + CRLF;
end;
function TInterfaceDeclaration.GetForwardDeclaration: String;
begin
Result := GetDeclaration + ';' + CRLF;
end;
function TInterfaceDeclaration.GetDeclaration: String;
begin
Result := GetIndentionString + 'T' + Name;
end;
{ TTypeParameter }
function TTypeParameter.GetAsCode: String;
begin
Result := Name;
if Assigned(ExtendsType) then
Result += ' extends ' + ExtendsType.AsCode;
end;
{ TTypeArgument }
function TTypeArgument.GetAsCode: String;
begin
if Assigned(&Type) then
Result := &Type.AsCode
else
Result := 'JSValue';
end;
{ TTypeReference }
function TTypeReference.GetAsCode: String;
begin
Result := 'T' + Name;
if Arguments.Length > 0 then
begin
Result += ' <' + Arguments[0].AsCode;
for var Index := Low(Arguments) + 1 to High(Arguments) do
Result += ', ' + Arguments[Index].AsCode;
Result += '> ';
end;
end;
{ TTypeAlias }
function TTypeAlias.GetAsCode: String;
begin
{$IFDEF DEBUG} Console.Log('Write type: ' + Name); {$ENDIF}
Result := GetDeclaration(True) + &Type.AsCode + ';' + CRLF + CRLF
end;
function TTypeAlias.GetForwardDeclaration: String;
begin
Result := GetDeclaration(False) + ';' + CRLF;
end;
function TTypeAlias.GetDeclaration(BreakLine: Boolean): String;
begin
var IsObject := &Type is TObjectType;
Result := GetIndentionString;
if IsObject then
Result += 'T';
Result += Name + ' = ';
if IsObject then
Result += 'class';
if BreakLine then
Result += CRLF;
end;
{ TAmbientConstructorDeclaration }
function TAmbientConstructorDeclaration.GetAsCode: String;
begin
Result := GetIndentionString + 'constructor Create';
if ParameterList.Length > 0 then
begin
Result += '(';
for var Index := Low(ParameterList) to High(ParameterList) - 1 do
Result += ParameterList[Index].AsCode[False] + '; ';
Result += ParameterList[High(ParameterList)].AsCode[False] + ')';
Result += ')';
end;
Result += ';' + CRLF;
end;
{ TAmbientClassDeclaration }
function TAmbientClassDeclaration.GetAsCode: String;
begin
{$IFDEF DEBUG} Console.Log('Write class: ' + Name); {$ENDIF}
Result += GetIndentionString + 'T' + Name + ' = class external name ''' + Name + '''';
if Extends.Count > 0 then
begin
Result += '(';
Result += Extends[0].AsCode;
for var Index := Low(Extends) + 1 to High(Extends) do
Result += ', ' + Extends[Index].AsCode;
Result += ')';
end;
Result += CRLF;
var LastVisibility := vPublic;
BeginIndention;
for var Member in Members do
begin
var CurrentVisibility := if Member is TAmbientPropertyMemberDeclaration then
TAmbientPropertyMemberDeclaration(Member).Visibility else vPublic;
if LastVisibility <> CurrentVisibility then
begin
EndIndention;
Result += GetIndentionString;
case CurrentVisibility of
vPublic:
Result += 'public' + CRLF;
vProtected:
Result += 'protected' + CRLF;
vPrivate:
Result += 'private' + CRLF;
end;
BeginIndention;
LastVisibility := CurrentVisibility;
end;
Result += Member.AsCode;
end;
EndIndention;
Result += GetIndentionString + 'end;' + CRLF + CRLF;
end;
{ TAmbientPropertyMemberDeclarationProperty }
function TAmbientPropertyMemberDeclarationProperty.GetAsCode: String;
begin
Result := GetIndentionString;
if IsStatic then
Result += 'class var ';
Result += Escape(Name);
Result += ': ' + if Assigned(&Type) then &Type.AsCode else 'JSValue';
// line break
Result += ';' + CRLF;
end;
{ TAmbientPropertyMemberDeclarationMethod }
function TAmbientPropertyMemberDeclarationMethod.GetAsCode: String;
var
Head: string;
Foot: string;
begin
var OptionalParameterCount := 0;
for var Parameter in CallSignature.ParameterList do
if Parameter.IsOptional then
Inc(OptionalParameterCount);
Head := GetIndentionString;
Head += if Assigned(CallSignature.&Type) then 'function' else 'procedure';
Head += ' ' + Escape(Name);
Foot := if OptionalParameterCount > 0 then ' overload;';
Foot += ';' + CRLF;
Result := '';
for var i := 0 to OptionalParameterCount do
Result += Head + CallSignature.AsCode[i] + Foot;
end;
{ TNamespaceDeclaration }
function TNamespaceDeclaration.GetAsCode: String;
begin
BeginNamespace(Name);
if Enums.Count + Classes.Count + Interfaces.Count > 0 then
begin
Result += 'type' + CRLF;
BeginIndention;
for var Enum in Enums do
Result += Enum.AsCode;
for var &Class in Classes do
Result += &Class.AsCode;
for var &Interface in Interfaces do
Result += &Interface.AsCode;
EndIndention;
end;
if Functions.Count > 0 then
begin
for var &Function in Functions do
Result += &Function.AsCode;
Result += CRLF;
end;
for var Namespace in Namespaces do
Result += Namespace.AsCode;
Result += CRLF;
EndNamespace;
end;
{ TAmbientNamespaceDeclaration }
function TAmbientNamespaceDeclaration.GetAsCode: String;
begin
BeginNameSpace(Name);
var Constants := 0;
for var Variable in Variables do
if Variable.IsConst then
Inc(Constants);
if Constants > 0 then
begin
Result += 'const' + CRLF;
BeginIndention;
for var Variable in Variables do
if Variable.IsConst then
Result := Result + Variable.AsCode;
EndIndention;
Result += CRLF;
end;
if Enums.Count + Classes.Count + Interfaces.Count + TypeAliases.Count > 0 then
begin
Result += 'type' + CRLF;
BeginIndention;
for var Enum in Enums do
Result += Enum.AsCode;
for var &Class in Classes do
Result += &Class.AsCode;
for var &Interface in Interfaces do
Result += &Interface.AsCode;
for var TypeAlias in TypeAliases do
Result += TypeAlias.AsCode;
EndIndention;
end;
if Functions.Count > 0 then
begin
for var &Function in Functions do
Result += &Function.AsCode;
Result += CRLF;
end;
if Variables.Count - Constants > 0 then
begin
Result += 'var' + CRLF;
BeginIndention;
for var Variable in Variables do
if not Variable.IsConst then
Result := Result + Variable.AsCode;
EndIndention;
Result += CRLF;
end;
for var Namespace in Namespaces do
Result += Namespace.AsCode;
Result += CRLF;
EndNameSpace;
end;
{ TJSObject }
function TJSObject.GetName: String;
begin
Result := 'TJSObject';
end;
{ TNullType }
function TNullType.GetAsCode: String;
begin
Result := '';
end;
{ TCustomType }
function TCustomType.IsPromise: Boolean;
begin
Result := False;
end;
function TCustomType.GetPromiseType: TCustomType;
begin
Result := nil;
end;
end.
|
unit uBase;
{$mode objfpc}{$H+}
interface
uses Classes, sqlite3ds, variants, Db;
type
{ TDatabaseConnect }
TStringsFillEvent = procedure (D:TDataset) of object;
TDatabaseConnect = class(TComponent)
private
BaseFileName:string;
function GetOption(const OptId: string): string;
procedure SetOption(const OptId: string; const AValue: string);
public
constructor Create;reintroduce;
destructor Destroy;override;
procedure ConnectToBase(D:TSqlite3Dataset);
function DatasetCreate(const SQL:string; OpenDataset:boolean=true):TSqlite3Dataset;overload;
function DatasetCreate(const Table, PKField:string; OpenDataset:boolean=true):TSqlite3Dataset;overload;
//заполнение списка по шаблону
//имена полей задаются через %FIELDNAME%
//пока что поле может входить в шаблое только один раз
procedure StringsFill(const SQL:string; const Template:string; List:TStrings; OnFill:TStringsFillEvent = nil; ClearList:boolean=true);
function DLookup(const SQL, Column:string):Variant;overload;
function DLookup(const SQL:string; Params:array of const; const Column:string):Variant;overload;
procedure SQLExec(const S:String);overload;
procedure SQLExec(const S:String; Args:array of const);overload;
property OptionUser[const OptId:string]:string read GetOption write SetOption;
end;
function BaseConnect:TDatabaseConnect;
implementation
uses SysUtils, uConfig, uDebug;
var BaseObj:TDatabaseConnect=nil;
function BaseConnect:TDatabaseConnect;
begin
if BaseObj = nil then
begin
BaseObj:=TDatabaseConnect.Create;
end;
Result:=BaseObj;
end;
{ TDatabaseConnect }
function TDatabaseConnect.GetOption(const OptId: string): string;
begin
Result:=VarToStr(DLookup(Format('select OptValue from Options where Name=''%s''', [OptId]), 'OptValue'));
end;
procedure TDatabaseConnect.SetOption(const OptId: string; const AValue: string);
begin
SQLExec('DELETE FROM Options WHERE Name=''%s''',[OptId]);
SQLExec('INSERT INTO Options (Name, OptValue) VALUES(''%s'', ''%s'')', [OptId, AValue]);
end;
constructor TDatabaseConnect.Create;
begin
inherited Create(nil);
BaseFileName:=GlobalConfig.BaseFile;
end;
destructor TDatabaseConnect.Destroy;
begin
inherited Destroy;
end;
procedure TDatabaseConnect.ConnectToBase(D: TSqlite3Dataset);
begin
if D.Active then D.Close;
D.FileName:=BaseFileName;
end;
function TDatabaseConnect.DatasetCreate(const SQL: string; OpenDataset:boolean): TSqlite3Dataset;
begin
Result:=TSqlite3Dataset.Create(Self);
Result.FileName:=BaseFileName;
Result.SQL:=SQL;
try
if OpenDataset then Result.Open;
except
Result.Free;
raise;
end;
end;
function TDatabaseConnect.DatasetCreate(const Table, PKField: string;
OpenDataset: boolean): TSqlite3Dataset;
begin
Result:=TSqlite3Dataset.Create(Self);
Result.FileName:=BaseFileName;
Result.TableName:=Table;
Result.AutoIncrementKey:=true;
Result.PrimaryKey:=PKField;
try
if OpenDataset then Result.Open;
except
Result.Free;
raise;
end;
end;
procedure TDatabaseConnect.StringsFill(const SQL: string; const Template: string; List: TStrings;
OnFill:TStringsFillEvent; ClearList:boolean);
var D:TSqlite3Dataset;
Strpos, WStrPos:array of integer;
i, j:integer;
FS, TemplatePrepared, S:String;
begin
D:=DatasetCreate(SQL);
List.BeginUpdate;
try
SetLength(Strpos, D.FieldCount);
TemplatePrepared:=Template;
for i:=0 to D.FieldCount-1 do
begin
FS:='%'+ D.Fields.Fields[i].FieldName + '%';
StrPos[i]:=Pos(FS, TemplatePrepared);
if StrPos[i]<>0 then
begin
Delete(TemplatePrepared, StrPos[i], Length(FS));
//цикл коррекции предыдущих найденных позиций
for j:=0 to i-1 do
if StrPos[j] > StrPos[i] then Dec(StrPos[j], Length(FS));
end;
end;
SetLength(WStrPos, Length(Strpos));
if ClearList then List.Clear;
while not D.EOF do
begin
//инициализация массива текущих позиций
Move(Strpos[0], WStrPos[0], Length(StrPos)*SizeOf(StrPos[0]));
S:=TemplatePrepared;
for i:=0 to D.FieldCount-1 do
if WStrPos[i] > 0 then
begin
FS:=D.Fields.Fields[i].AsString;
Insert(FS, S, WStrPos[i]);
//цикл коррекции
for j:=i+1 to High(WStrPos) do
if WStrPos[j] > WStrPos[i] then Inc(WStrPos[j], Length(FS));
end;
if OnFill <> nil then
OnFill(D);
List.Add(S);
D.Next;
end;
finally
D.Free;
List.EndUpdate;
end;
end;
function TDatabaseConnect.DLookup(const SQL, Column: string): Variant;
begin
Result:=null;
with DatasetCreate(SQL) do
try
First;
if not EOF then
Result:=FieldByName(Column).AsVariant;
finally
Free;
end;
end;
function TDatabaseConnect.DLookup(const SQL: string; Params: array of const;
const Column: string): Variant;
begin
Result:=DLookup(Format(SQL, Params), Column);
end;
procedure TDatabaseConnect.SQLExec(const S: String);
var PostDS:TSqlite3Dataset;
begin
PostDS:=TSqlite3Dataset.Create(nil);
try
PostDS.FileName:=BaseFileName;
//PostDS.ExecuteDirect(S);
PostDS.ExecSQL(S);
finally
PostDS.Free;
end;
end;
procedure TDatabaseConnect.SQLExec(const S: String; Args: array of const);
begin
SQLExec(Format(S, Args));
end;
finalization
BaseObj.Free;
end.
|
unit K293279996;
{* [Requestlink:293279996] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K293279996.pas"
// Стереотип: "TestCase"
// Элемент модели: "K293279996" MUID: (519CBF11000F)
// Имя типа: "TK293279996"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoRTFWriterTest
;
type
TK293279996 = class(TEVDtoRTFWriterTest)
{* [Requestlink:293279996] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK293279996
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *519CBF11000Fimpl_uses*
//#UC END# *519CBF11000Fimpl_uses*
;
function TK293279996.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.8';
end;//TK293279996.GetFolder
function TK293279996.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '519CBF11000F';
end;//TK293279996.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK293279996.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit RESTRequest4D.Request.Authentication;
interface
uses RESTRequest4D.Request.Authentication.Intf, REST.Client, REST.Authenticator.Basic;
type
TRequestAuthentication = class(TInterfacedObject, IRequestAuthentication)
private
FRESTClient: TRESTClient;
FHTTPBasicAuthenticator: THTTPBasicAuthenticator;
function Clear: IRequestAuthentication;
function SetPassword(const APassword: string): IRequestAuthentication;
function SetUsername(const AUser: string): IRequestAuthentication;
function GetPassword: string;
function GetUsername: string;
public
constructor Create(const ARESTClient: TRESTClient);
destructor Destroy; override;
end;
implementation
uses System.SysUtils;
{ TRequestAuthentication }
function TRequestAuthentication.Clear: IRequestAuthentication;
begin
FRESTClient.Authenticator := nil;
FHTTPBasicAuthenticator.Password := EmptyStr;
FHTTPBasicAuthenticator.Username := EmptyStr;
end;
constructor TRequestAuthentication.Create(const ARESTClient: TRESTClient);
begin
FHTTPBasicAuthenticator := THTTPBasicAuthenticator.Create(nil);
FRESTClient := ARESTClient;
end;
destructor TRequestAuthentication.Destroy;
begin
FreeAndNil(FHTTPBasicAuthenticator);
inherited;
end;
function TRequestAuthentication.GetPassword: string;
begin
Result := FHTTPBasicAuthenticator.Password;
end;
function TRequestAuthentication.SetPassword(const APassword: string): IRequestAuthentication;
begin
Result := Self;
if not Assigned(FRESTClient.Authenticator) then
FRESTClient.Authenticator := FHTTPBasicAuthenticator;
FHTTPBasicAuthenticator.Password := APassword;
end;
function TRequestAuthentication.SetUsername(const AUser: string): IRequestAuthentication;
begin
Result := Self;
if not Assigned(FRESTClient.Authenticator) then
FRESTClient.Authenticator := FHTTPBasicAuthenticator;
FHTTPBasicAuthenticator.Username := AUser;
end;
function TRequestAuthentication.GetUsername: string;
begin
Result := FHTTPBasicAuthenticator.Username;
end;
end.
|
unit RDOChannelCodec;
interface
type
TRDOChannelCodec =
class
private
fAliases : TStringList;
function AliasOf( aStr : string ) : string;
function StringOf( aAlias : string ) : string;
public
constructor Create;
destructor Destroy; override;
public
function EncodeQuery( Query : string ) : string;
function DecodeQuery( EncodedQuery : string ) : string;
end;
implementation
uses
RDOProtocol, RDOUtils;
type
TAliasData =
class
private
fRepeatCount : integer;
public
property RepeatCount : integer read fRepeatCount write fRepeatCount;
end;
// TAliasData
// TRDOChannelCodec
constructor TRDOChannelCodec.Create;
begin
inherited;
fAliases := TStringList.Create
end;
destructor TRDOChannelCodec.Destroy;
begin
fAliases.Free;
inherited
end;
function TRDOChannelCodec.AliasOf( aStr : string ) : string;
begin
end;
function TRDOChannelCodec.EncodeQuery( Query : string ) : string;
var
begin
end;
function TRDOChannelCodec.DecodeQuery( EncodedQuery : string ) : string;
var
AliasIdPos : integer;
DecodedQuery : string;
begin
AliasIdPos := Pos( Query, AliasId );
while AliasIdPos <> 0 do
begin
end
end;
end.
|
uses math;
const fi ='TBIKE.inp';
fo ='TBIKE.out';
maxn =2000;
var a :array[1..maxn] of longint;
count,n :longint;
Procedure Docfile;
var i:longint;
begin
assign(input,fi); reset(input);
readln(n);
for i:= 1 to n do read(a[i]);
close(input);
end;
Function GCD(a,b:longint):longint;
var r:longint;
begin
r:=b mod a;
while r<>0 do
begin
r:=a mod b;
a:=b;
b:=r;
end;
exit(a);
end;
Function Check(i,j:longint):boolean;
var Amax,Amin,ucln,t,k:longint;
begin
Amax:=a[j];
Amin:=a[j];
Ucln:=abs(a[i]-a[i+1]);
for k:= i to j-1 do
begin
if a[k]>Amax then Amax:=a[k];
if a[k]<Amin then Amin:=a[k];
ucln:=GCD(ucln,abs(a[k]-a[k+1]));
end;
t:=int64(ucln*(j-i));
if t=Amax-Amin then exit(true);
exit(false);
end;
Procedure Thuchien1;
var i,j,vt:longint;
begin
j:=1;
count:=0;
while j<=n do
begin
for i:= j+1 to n do
if check(j,i) then vt:=i;
j:=vt+1;
inc(count);
end;
writeln(count);
end;
BEGIN
Docfile;
Thuchien1;
END.
|
unit CommentAndScrollTest;
{* Тест для добавления и удаления комментария и последующего скроллирования. }
// Модуль: "w:\common\components\gui\Garant\Daily\CommentAndScrollTest.pas"
// Стереотип: "TestCase"
// Элемент модели: "TCommentAndScrollTest" MUID: (4C9CA365006C)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3IntfUses
, TextEditorVisitor
, nevTools
, PrimTextLoad_Form
;
type
TCommentAndScrollTest = {abstract} class(TTextEditorVisitor)
{* Тест для добавления и удаления комментария и последующего скроллирования. }
protected
procedure MoveCursor4Insert(aForm: TPrimTextLoadForm); virtual;
{* Переместить курсор перед вставкой комментария. }
function GetUserComment(const aPoint: InevBasePoint): InevBasePoint; virtual;
{* Получить пользовательский комментарий }
procedure DoScroll(aForm: TPrimTextLoadForm); virtual;
{* Прокрутка текста в редакторе (если нужна). }
procedure DoVisit(aForm: TPrimTextLoadForm); override;
{* Обработать текст }
procedure CheckTopAnchor(const aView: InevInputView); override;
{* проверить якорь начала отрисовки после окончания прокрутки }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function F1Like: Boolean; override;
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TCommentAndScrollTest
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3ImplUses
{$If Defined(k2ForEditor)}
, evCursorTools
{$IfEnd} // Defined(k2ForEditor)
, evOp
, evTypes
, l3Base
, CommentPara_Const
, eeEditorExport
, TestFrameWork
, vcmBase
, SysUtils
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *4C9CA365006Cimpl_uses*
//#UC END# *4C9CA365006Cimpl_uses*
;
procedure TCommentAndScrollTest.MoveCursor4Insert(aForm: TPrimTextLoadForm);
{* Переместить курсор перед вставкой комментария. }
//#UC START# *4CA2F33F01E5_4C9CA365006C_var*
var
i : Integer;
//#UC END# *4CA2F33F01E5_4C9CA365006C_var*
begin
//#UC START# *4CA2F33F01E5_4C9CA365006C_impl*
for i := 0 to 5 do
aForm.Text.Selection.Cursor.Move(aForm.Text.View, ev_ocParaDown);
//#UC END# *4CA2F33F01E5_4C9CA365006C_impl*
end;//TCommentAndScrollTest.MoveCursor4Insert
function TCommentAndScrollTest.GetUserComment(const aPoint: InevBasePoint): InevBasePoint;
{* Получить пользовательский комментарий }
//#UC START# *4CA982110056_4C9CA365006C_var*
//#UC END# *4CA982110056_4C9CA365006C_var*
begin
//#UC START# *4CA982110056_4C9CA365006C_impl*
Result := aPoint;
while not Result.AsObject.IsKindOf(k2_typCommentPara) do
Result := Result.Inner;
//#UC END# *4CA982110056_4C9CA365006C_impl*
end;//TCommentAndScrollTest.GetUserComment
procedure TCommentAndScrollTest.DoScroll(aForm: TPrimTextLoadForm);
{* Прокрутка текста в редакторе (если нужна). }
//#UC START# *4CA982800281_4C9CA365006C_var*
//#UC END# *4CA982800281_4C9CA365006C_var*
begin
//#UC START# *4CA982800281_4C9CA365006C_impl*
//#UC END# *4CA982800281_4C9CA365006C_impl*
end;//TCommentAndScrollTest.DoScroll
procedure TCommentAndScrollTest.DoVisit(aForm: TPrimTextLoadForm);
{* Обработать текст }
//#UC START# *4BE419AF0217_4C9CA365006C_var*
var
l_UserComment : InevBasePoint;
l_PID : Integer;
i : Integer;
//#UC END# *4BE419AF0217_4C9CA365006C_var*
begin
//#UC START# *4BE419AF0217_4C9CA365006C_impl*
aForm.Text.Select(ev_stDocument);
aForm.Text.Copy;
MoveCursor4Insert(aForm);
(aForm.Text as TeeEditorExport).InsertUserComment;
aForm.Text.Paste;
l3System.ClearClipboard;
l_UserComment := GetUserComment(aForm.Text.Selection.Cursor);
DoScroll(aForm);
l_PID := l_UserComment.Obj^.PID;
l_UserComment.Obj^.OwnerObj.SubRange(aForm.Text.View, l_PID + 1, l_PID + 1).Modify.Delete(aForm.Text.View);
ScrollByLine(aForm, 1, True, False);
CheckTopAnchor(aForm.Text.View);
//#UC END# *4BE419AF0217_4C9CA365006C_impl*
end;//TCommentAndScrollTest.DoVisit
procedure TCommentAndScrollTest.CheckTopAnchor(const aView: InevInputView);
{* проверить якорь начала отрисовки после окончания прокрутки }
//#UC START# *4C1F0A260192_4C9CA365006C_var*
//#UC END# *4C1F0A260192_4C9CA365006C_var*
begin
//#UC START# *4C1F0A260192_4C9CA365006C_impl*
CheckFalse(aView.TopAnchor.Inner.AsObject.IsKindOf(k2_typCommentPara), 'Комментарий мы уже удалили! А TopAnchor его еще держит!');
//#UC END# *4C1F0A260192_4C9CA365006C_impl*
end;//TCommentAndScrollTest.CheckTopAnchor
function TCommentAndScrollTest.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Everest';
end;//TCommentAndScrollTest.GetFolder
function TCommentAndScrollTest.F1Like: Boolean;
//#UC START# *4C9B31F6015E_4C9CA365006C_var*
//#UC END# *4C9B31F6015E_4C9CA365006C_var*
begin
//#UC START# *4C9B31F6015E_4C9CA365006C_impl*
Result := True;
//#UC END# *4C9B31F6015E_4C9CA365006C_impl*
end;//TCommentAndScrollTest.F1Like
function TCommentAndScrollTest.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4C9CA365006C';
end;//TCommentAndScrollTest.GetModelElementGUID
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Compression.LZO
Description : LZO Compressor
Author : Kike Pérez
Version : 1.8
Created : 15/09/2019
Modified : 22/09/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Compression.LZO;
{$i QuickLib.inc}
interface
uses
SysUtils;
const
{$IFDEF MSWINDOWS}
LIBPATH = '.\lzo.dll';
{$ELSE}
LIBPATH = './lzo.so';
{$ENDIF}
type
TLZOCompressor = class
private
fWorkMemory : Pointer;
public
constructor Create;
destructor Destroy; override;
function Version : string;
function VersionDate : string;
function Compress(const aUncompressed : string) : string;
function Decompress(const aCompressed : string) : string;
end;
ELZOCompressor = class(Exception);
implementation
function __lzo_init3 : Integer; stdcall; external LIBPATH;
function lzo_version_string : PChar; stdcall; external LIBPATH;
function lzo_version_date : PChar; stdcall; external LIBPATH;
function lzo1x_1_compress(src : Pointer; src_len : LongWord; dest : Pointer; var dest_len : LongWord; wrkmem : Pointer) : Integer; stdcall; external LIBPATH;
function lzo1x_decompress(src : Pointer; src_len : LongWord; dest : Pointer; var dest_len : LongWord; wrkmem : Pointer) : Integer; stdcall; external LIBPATH;
{ TLZOCompressor }
function TLZOCompressor.Compress(const aUncompressed: string): string;
var
srclen : Integer;
outlen : LongWord;
uncompressed : TBytes;
compressed : TBytes;
byteslen : array[1.. sizeof(integer)] of byte;
begin
outlen := 0;
try
SetLength(compressed, Round(aUncompressed.Length + aUncompressed.Length / 64 + 16 + 3 + 4));
uncompressed := TEncoding.UTF8.GetBytes(aUncompressed);
lzo1x_1_compress(uncompressed, High(uncompressed)+1, compressed, outlen, fWorkMemory);
Finalize(uncompressed);
srclen := aUncompressed.Length;
Move(srclen,byteslen[1], SizeOf(Integer));
SetLength(compressed,outlen + 4);
Move(byteslen,compressed[outlen],4);
Result := TEncoding.ANSI.GetString(compressed,0,outlen + 4);
except
on E : Exception do raise ELZOCompressor.CreateFmt('LZO Compression error: %s',[e.Message]);
end;
end;
constructor TLZOCompressor.Create;
begin
if __lzo_init3 <> 0 then raise Exception.Create('Initialization LZO-Compressor failed');
GetMem(fWorkMemory,16384 * 4);
end;
function TLZOCompressor.Decompress(const aCompressed: string): string;
var
srclen : LongWord;
dstlen : LongWord;
uncompressed : TBytes;
compressed : TBytes;
i : Integer;
begin
try
compressed := TEncoding.ANSI.GetBytes(aCompressed);
//get src length
srclen := PLongInt(@compressed[High(compressed)-3])^;
SetLength(uncompressed,srclen);
dstlen := 0;
lzo1x_decompress(compressed, High(compressed) - 4, uncompressed, dstlen, fWorkMemory);
Result := TEncoding.UTF8.GetString(uncompressed,0,dstlen);
except
on E : Exception do raise ELZOCompressor.CreateFmt('LZO Descompression error: %s',[e.Message]);
end;
end;
destructor TLZOCompressor.Destroy;
begin
FreeMem(fWorkMemory);
inherited;
end;
function TLZOCompressor.Version: string;
begin
Result := string(lzo_version_string);
end;
function TLZOCompressor.VersionDate: string;
begin
Result := string(lzo_version_date^);
end;
end.
|
unit BuildClasses;
interface
uses
MapTypes;
type
TFastIndex = array[idBuilding] of word;
TClassArray = array[word] of TBuildingClass;
type
TBuildingClasses =
class(TInterfacedObject, IBuildingClassBag)
public
destructor Destroy; override;
private // IBuildingClassBag
procedure Add(const which : TBuildingClass);
function Get(id : idBuilding) : PBuildingClass;
function GetByName(var startidx : integer; const classname : string) : PBuildingClass;
function GetMaxId : idBuilding;
procedure Clear;
private
fIndexes : integer;
fCount : integer;
fLimit : integer;
fMaxId : integer;
fIndex : ^TFastIndex;
fItems : ^TClassArray;
end;
implementation
// TBuildingClasses
destructor TBuildingClasses.Destroy;
begin
assert(RefCount = 0);
Clear;
inherited;
end;
procedure TBuildingClasses.Add(const which : TBuildingClass);
const
cIndexDelta = 8;
cClassDelta = 32;
begin
if which.id >= fIndexes
then
begin
reallocmem(fIndex, (which.id + cIndexDelta)*sizeof(fIndex[0]));
fillchar(fIndex[fIndexes], (which.id + cIndexDelta - fIndexes)*sizeof(fIndex[0]), $FF);
fIndexes := which.id + cIndexDelta;
end;
if which.id > fMaxId
then fMaxId := which.id;
if fIndex[which.id] <> $FFFF
then
begin
assert(fIndex[which.id] < fCount);
fItems[fIndex[which.id]] := which;
end
else
begin
if fCount = fLimit
then
begin
reallocmem(fItems, (fLimit + cClassDelta)*sizeof(fItems[0]));
initialize(fItems[fLimit], cClassDelta);
inc(fLimit, cClassDelta);
end;
fIndex[which.id] := fCount;
fItems[fCount] := which;
inc(fCount);
end;
end;
function TBuildingClasses.Get(id : idBuilding) : PBuildingClass;
begin
if (id < fIndexes) and (fIndex[id] <> $FFFF)
then Result := @fItems[fIndex[id]]
else Result := nil;
end;
function TBuildingClasses.GetByName(var startidx : integer; const classname : string) : PBuildingClass;
begin
while (startidx < fCount) and (classname <> fItems[startidx].Name) do
inc(startidx);
if startidx < fCount
then Result := @fItems[startidx]
else Result := nil;
end;
function TBuildingClasses.GetMaxId : idBuilding;
begin
Result := fMaxId;
end;
procedure TBuildingClasses.Clear;
var
i : integer;
begin
if fIndexes > 0
then
begin
freemem(fIndex);
fIndexes := 0;
fIndex := nil;
end;
if fCount > 0
then
begin
for i := 0 to pred(fCount) do
begin
with fItems[i].SoundData do
if (Kind <> ssNone) and (Sounds <> nil)
then
begin
finalize(Sounds^, Count);
freemem(Sounds);
end;
with fItems[i].EfxData do
if Efxs <> nil
then freemem(Efxs);
end;
try
finalize(fItems[0], fCount); // why the fuck this sometimes generates an exception!!!!!?????
except
end;
freemem(fItems);
fCount := 0;
fLimit := 0;
fItems := nil;
end;
end;
end.
|
unit WinSockRDOConnectionsServer;
interface
uses
Windows, Classes, SyncObjs, SmartThreads, SocketComp, RDOInterfaces,
RDOQueries;
type
TWinSockRDOConnectionsServer =
class(TInterfacedObject, IRDOServerConnection, IRDOConnectionsServer)
private
fQueryServer : IRDOQueryServer;
fSocketComponent : TServerSocket;
fMsgLoopThread : TSmartThread;
fEventSink : IRDOConnectionServerEvents;
fQueryQueue : TList;
fQueryWaiting : THandle;
fQueryQueueLock : TCriticalSection;
fMaxQueryThreads : integer;
fQueryThreads : TList;
fTerminateEvent : THandle;
public
constructor Create(Prt : integer);
destructor Destroy; override;
protected
procedure SetQueryServer(const QueryServer : IRDOQueryServer);
function GetMaxQueryThreads : integer;
procedure SetMaxQueryThreads(MaxQueryThreads : integer);
protected
procedure StartListening;
procedure StopListening;
function GetClientConnection(const ClientAddress : string; ClientPort : integer) : IRDOConnection;
function GetClientConnectionById(Id : integer) : IRDOConnection;
procedure InitEvents(const EventSink : IRDOConnectionServerEvents);
private
procedure ClientConnected(Sender : TObject; Socket : TCustomWinSocket);
procedure ClientDisconnected(Sender : TObject; Socket : TCustomWinSocket);
procedure DoClientRead(Sender : TObject; Socket : TCustomWinSocket);
procedure HandleError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer);
procedure RemoveQuery(Socket : TCustomWinSocket);
function GetStuckQueries : string;
end;
const
MaxDebugServers = 5;
var
DebugServers : array[0..MaxDebugServers] of TWinSockRDOConnectionsServer;
ServerCount : integer = 0;
implementation
uses
SysUtils,
WinSock,
RDOProtocol,
RDOUtils,
{$IFDEF LogsEnabled}
LogFile,
{$ENDIF}
ErrorCodes,
RDOQueryServer,
WinSockRDOServerClientConnection;
const
QUERY_COUNT_ENQUIRE = 'GetQueryCount';
type
PQueryToService = ^TQueryToService;
TQueryToService =
record
Valid : boolean;
Query : TRDOQuery;
Socket : TCustomWinSocket;
end;
type
PSocketData = ^TSocketData;
TSocketData =
record
RDOConnection : IRDOConnection;
Stream : TQueryStream;
end;
procedure ReleaseQueryToService(QueryToService : PQueryToService);
begin
if QueryToService <> nil
then
begin
QueryToService.Query.Free;
dispose(QueryToService);
end;
end;
type
TServicingQueryThread =
class(TSmartThread)
private
fConnectionsServer : TWinSockRDOConnectionsServer;
fLock : TCriticalSection;
fQueryToService : PQueryToService;
fStatus : integer;
fQueryStatus : integer;
public
constructor Create(theConnServer : TWinSockRDOConnectionsServer);
destructor Destroy; override;
procedure Execute; override;
public
procedure Lock;
procedure Unlock;
procedure CheckQuery(Socket : TCustomWinSocket);
public
property TheLock : TCriticalSection read fLock;
end;
type
TMsgLoopThread =
class(TSmartThread)
private
fRDOConnServ : TWinSockRDOConnectionsServer;
public
constructor Create(RDOConnServ : TWinSockRDOConnectionsServer);
procedure Execute; override;
end;
// TServicingQueryThread
constructor TServicingQueryThread.Create(theConnServer : TWinSockRDOConnectionsServer);
begin
inherited Create(true);
fConnectionsServer := theConnServer;
fLock := TCriticalSection.Create;
Resume;
end;
destructor TServicingQueryThread.Destroy;
begin
Terminate;
WaitFor;
fLock.Free;
inherited;
end;
procedure TServicingQueryThread.Execute;
var
Query : TRDOQuery;
QueryResult : TRDOQuery;
Sckt : integer;
QueryThreadEvents : array [1 .. 2] of THandle;
WaitRes : integer;
begin
with fConnectionsServer do
begin
QueryThreadEvents[1] := fQueryWaiting;
QueryThreadEvents[2] := fTerminateEvent;
while not Terminated do
try
fStatus := 1; {1}
WaitRes := WaitForMultipleObjects(2, @QueryThreadEvents[1], false, INFINITE);
fStatus := 2; {2}
if not Terminated and (WaitRes = WAIT_OBJECT_0)
then
begin
fQueryQueueLock.Acquire;
fStatus := 3; {3}
try
if fQueryQueue.Count <> 0
then
begin
fQueryToService := fQueryQueue[0];
fQueryQueue.Delete(0);
end
else
begin
fQueryToService := nil;
ResetEvent(fQueryWaiting);
end
finally
fQueryQueueLock.Release
end;
// Catch the query
fStatus := 4; {4}
Lock;
fStatus := 5; {5}
try
if fQueryToService <> nil
then
begin
// remove the query from the record
Query := fQueryToService.Query;
fQueryToService.Query := nil;
if fQueryToService.Valid
then Sckt := integer(fQueryToService.Socket)
else
begin
Query.Free;
Query := nil;
Sckt := 0;
end;
end
else
begin
Query := nil;
Sckt := 0;
end;
finally
Unlock;
end;
fStatus := 6; {6}
// Check if there is something to excecute
if Query <> nil
then
begin
// Execute and release the query
try
try
QueryResult := fQueryServer.ExecQuery(Query, Sckt, fQueryStatus);
finally
Query.Free;
end;
except
QueryResult := nil;
end;
// Check result
if QueryResult = nil
then
begin
{$IFDEF LogsEnabled}
LogThis('No result');
{$ENDIF}
end
else
begin
// Check if can send result back
fStatus := 7; {7}
Lock;
try
fStatus := 8; {8}
if (fQueryToService <> nil) and fQueryToService.Valid and fQueryToService.Socket.Connected
then
try
RDOUtils.SendQuery(QueryResult, fQueryToService.Socket);
{$IFDEF LogsEnabled}
LogThis('Result : ' + QueryResult.ToStr);
{$ENDIF}
except
{$IFDEF LogsEnabled}
LogThis('Error sending query result')
{$ENDIF}
end;
finally
Unlock;
QueryResult.Free;
end;
end;
// Free the Query
fStatus := 9; {9}
Lock;
fStatus := 10; {10}
try
if fQueryToService <> nil
then
begin
ReleaseQueryToService(fQueryToService);
fQueryToService := nil;
end
finally
Unlock;
end;
end;
end;
except
{$IFDEF LogsEnabled}
LogThis('Un handled exception in the Servicing Query Thread loop!')
{$ENDIF}
end;
end
end;
procedure TServicingQueryThread.Lock;
begin
fLock.Enter;
end;
procedure TServicingQueryThread.Unlock;
begin
fLock.Leave;
end;
procedure TServicingQueryThread.CheckQuery(Socket : TCustomWinSocket);
begin
Lock;
try
if (fQueryToService <> nil) and (fQueryToService.Socket = Socket)
then fQueryToService.Valid := false;
finally
Unlock;
end;
end;
// TMsgLoopThread
constructor TMsgLoopThread.Create(RDOConnServ : TWinSockRDOConnectionsServer);
begin
inherited Create(true);
fRDOConnServ := RDOConnServ;
Priority := tpHigher;
Resume;
end;
procedure TMsgLoopThread.Execute;
var
Msg : TMsg;
begin
with fRDOConnServ do
begin
try
with fSocketComponent do
if not Active
then Active := true
except
{$IFDEF LogsEnabled}
LogThis('Error establishing connection')
{$ENDIF}
end;
while not Terminated do
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE)
then
try
DispatchMessage(Msg)
except
{$IFDEF LogsEnabled}
on E : Exception do
LogThis('Loop thread error: ' + E.Message);
{$ENDIF}
end
else MsgWaitForMultipleObjects(1, fTerminateEvent, false, INFINITE, QS_ALLINPUT);
with fSocketComponent do
Active := false
end
end;
// TWinSockRDOConnectionsServer
constructor TWinSockRDOConnectionsServer.Create(Prt : integer);
begin
inherited Create;
fSocketComponent := TServerSocket.Create(nil);
with fSocketComponent do
begin
Active := false;
Port := Prt;
OnClientConnect := ClientConnected;
OnClientDisconnect := ClientDisconnected;
OnClientRead := DoClientRead;
OnClientError := HandleError
end;
fQueryQueue := TList.Create;
fQueryThreads := TList.Create;
fQueryWaiting := CreateEvent(nil, true, false, nil);
fQueryQueueLock := TCriticalSection.Create;
fTerminateEvent := CreateEvent(nil, true, false, nil);
// Temporary debug patch..
DebugServers[ServerCount] := self;
inc(ServerCount);
end;
destructor TWinSockRDOConnectionsServer.Destroy;
procedure FreeQueryQueue;
var
QueryIdx : integer;
Query : PQueryToService;
begin
for QueryIdx := 0 to fQueryQueue.Count - 1 do
begin
Query := PQueryToService(fQueryQueue[QueryIdx]);
dispose(Query);
end;
fQueryQueue.Free
end;
begin
StopListening;
fSocketComponent.Free;
FreeQueryQueue;
CloseHandle(fQueryWaiting);
CloseHandle(fTerminateEvent);
fQueryQueueLock.Free;
inherited Destroy
end;
procedure TWinSockRDOConnectionsServer.SetQueryServer(const QueryServer : IRDOQueryServer);
begin
fQueryServer := QueryServer
end;
function TWinSockRDOConnectionsServer.GetMaxQueryThreads : integer;
begin
Result := fMaxQueryThreads
end;
procedure TWinSockRDOConnectionsServer.SetMaxQueryThreads(MaxQueryThreads : integer);
begin
fMaxQueryThreads := MaxQueryThreads
end;
procedure TWinSockRDOConnectionsServer.StartListening;
var
ThreadIdx : integer;
begin
ResetEvent(fTerminateEvent);
fMsgLoopThread := TMsgLoopThread.Create(Self);
for ThreadIdx := 1 to fMaxQueryThreads do
fQueryThreads.Add(TServicingQueryThread.Create(Self))
end;
procedure TWinSockRDOConnectionsServer.StopListening;
procedure FreeQueryThreads;
var
ThreadIdx : integer;
aQueryThread : TSmartThread;
begin
for ThreadIdx := 0 to fQueryThreads.Count - 1 do
begin
aQueryThread := TSmartThread(fQueryThreads[ThreadIdx]);
aQueryThread.Free
end;
fQueryThreads.Free;
fQueryThreads := nil
end;
begin
SetEvent(fTerminateEvent);
if fMsgLoopThread <> nil
then
begin
fMsgLoopThread.Free;
fMsgLoopThread := nil
end;
if fQueryThreads <> nil
then
FreeQueryThreads
end;
function TWinSockRDOConnectionsServer.GetClientConnection(const ClientAddress : string; ClientPort : integer) : IRDOConnection;
var
ConnIdx : integer;
ConnCount : integer;
FoundConn : IRDOConnection;
UseIPAddr : boolean;
CurrConn : TCustomWinSocket;
CurConnRmtAddr : string;
begin
ConnIdx := 0;
with fSocketComponent do
begin
Socket.Lock;
try
ConnCount := Socket.ActiveConnections;
FoundConn := nil;
if inet_addr(PChar(ClientAddress)) = u_long(INADDR_NONE)
then
UseIPAddr := false
else
UseIPAddr := true;
while (ConnIdx < ConnCount) and (FoundConn = nil) do
begin
CurrConn := Socket.Connections[ConnIdx];
if UseIPAddr
then
CurConnRmtAddr := CurrConn.RemoteAddress
else
CurConnRmtAddr := CurrConn.RemoteHost;
if (CurConnRmtAddr = ClientAddress) and (CurrConn.RemotePort = ClientPort)
then
FoundConn := PSocketData(CurrConn.Data).RDOConnection;
inc(ConnIdx)
end
finally
Socket.Unlock;
end;
end;
Result := FoundConn
end;
function TWinSockRDOConnectionsServer.GetClientConnectionById(Id : integer) : IRDOConnection;
var
ConnIdx : integer;
ConnCount : integer;
FoundConn : IRDOConnection;
CurrConn : TCustomWinSocket;
begin
ConnIdx := 0;
with fSocketComponent do
begin
Socket.Lock;
try
ConnCount := Socket.ActiveConnections;
FoundConn := nil;
while (ConnIdx < ConnCount) and (FoundConn = nil) do
begin
CurrConn := Socket.Connections[ConnIdx];
if integer(CurrConn) = Id
then FoundConn := PSocketData(CurrConn.Data).RDOConnection
else inc(ConnIdx);
end;
finally
Socket.Unlock;
end;
end;
Result := FoundConn
end;
procedure TWinSockRDOConnectionsServer.InitEvents(const EventSink : IRDOConnectionServerEvents);
begin
fEventSink := EventSink
end;
procedure TWinSockRDOConnectionsServer.ClientConnected(Sender : TObject; Socket : TCustomWinSocket);
var
SocketData : PSocketData;
begin
New(SocketData);
SocketData.RDOConnection := TWinSockRDOServerClientConnection.Create(Socket);
SocketData.Stream := TQueryStream.Create;
Socket.Data := SocketData;
if fEventSink <> nil
then
fEventSink.OnClientConnect(SocketData.RDOConnection)
end;
procedure TWinSockRDOConnectionsServer.ClientDisconnected(Sender : TObject; Socket : TCustomWinSocket);
var
SocketData : PSocketData;
begin
SocketData := PSocketData(Socket.Data);
if fEventSink <> nil
then fEventSink.OnClientDisconnect(SocketData.RDOConnection);
if Assigned(SocketData.RDOConnection.OnDisconnect)
then SocketData.RDOConnection.OnDisconnect(SocketData.RDOConnection);
{$IFDEF LogsEnabled}
LogThis('RemoveQuery start..');
{$ENDIF}
RemoveQuery(Socket);
{$IFDEF LogsEnabled}
LogThis('RemoveQuery end');
{$ENDIF}
SocketData.Stream.Free;
SocketData.RDOConnection := nil;
dispose(SocketData);
end;
procedure TWinSockRDOConnectionsServer.DoClientRead(Sender : TObject; Socket : TCustomWinSocket);
var
QueryToService : PQueryToService;
ReadError : boolean;
SocketData : PSocketData;
ServClienConn : IRDOServerClientConnection;
Query : TRDOQuery;
QueryReady : boolean;
begin
SocketData := PSocketData(Socket.Data);
try
QueryReady := SocketData.Stream.Receive(Socket);
ReadError := false;
except
QueryReady := false;
ReadError := true;
Socket.Close; // >> ???
end;
if not ReadError and (fQueryServer <> nil)
then
begin
if QueryReady
then
begin
SocketData.Stream.Position := 0;
Query := TRDOQuery.Read(SocketData.Stream);
SocketData.Stream.Clear;
if (Query.QKind <> qkAnswer) and (Query.QKind <> qkError)
then
begin
new(QueryToService);
QueryToService.Query := Query;
QueryToService.Socket := Socket;
QueryToService.Valid := true;
fQueryQueueLock.Enter;
try
if Query.Name <> QUERY_COUNT_ENQUIRE
then
begin
if not fQueryServer.Busy
then
begin
fQueryQueue.Add(QueryToService);
if fQueryQueue.Count > 0
then SetEvent(fQueryWaiting);
end
else
begin
Query := TRDOQuery.Create(qkError, Query.Id);
Query.PushParam(integer(errServerBusy));
ReleaseQueryToService(QueryToService);
try
RDOUtils.SendQuery(Query, Socket);
finally
Query.Free;
end;
end;
end
else
begin
ReleaseQueryToService(QueryToService);
Query := TRDOQuery.Create(qkAnswer, Query.Id);
Query.PushParam(GetStuckQueries);
try
RDOUtils.SendQuery(Query, Socket);
finally
Query.Free;
end;
end;
finally
fQueryQueueLock.Release
end
end
else
begin
ServClienConn := SocketData.RDOConnection as IRDOServerClientConnection;
ServClienConn.OnQueryResultArrival(Query);
end;
end;
end
else
{$IFDEF LogsEnabled}
LogThis('Error while reading from socket');
{$ENDIF}
end;
procedure TWinSockRDOConnectionsServer.HandleError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : Integer);
begin
ErrorCode := 0;
{$IFDEF LogsEnabled}
case ErrorEvent of
eeGeneral:
LogThis('General socket error');
eeSend:
LogThis('Error writing to socket');
eeReceive:
LogThis('Error reading from socket');
eeConnect:
LogThis('Error establishing connection');
eeDisconnect:
LogThis('Error closing connection');
eeAccept:
LogThis('Error accepting connection')
end
{$ENDIF}
end;
procedure TWinSockRDOConnectionsServer.RemoveQuery(Socket : TCustomWinSocket);
var
i : integer;
Query : PQueryToService;
begin
try
fQueryQueueLock.Enter;
try
i := 0;
while i < fQueryQueue.Count do
begin
Query := PQueryToService(fQueryQueue[i]);
if Query.Socket = Socket
then
begin
ReleaseQueryToService(Query);
fQueryQueue.Delete(i);
end
else inc(i);
end;
finally
fQueryQueueLock.Leave;
end;
// Check Query Threads
for i := 0 to pred(fQueryThreads.Count) do
TServicingQueryThread(fQueryThreads[i]).CheckQuery(Socket);
except
end;
end;
function TWinSockRDOConnectionsServer.GetStuckQueries : string;
var
i : integer;
Q : PQueryToService;
Thread : TServicingQueryThread;
status : string;
begin
result := '';
for i := 0 to pred(fQueryThreads.Count) do
try
Thread := TServicingQueryThread(fQueryThreads[i]);
status := IntToStr(Thread.fStatus) + ',' + IntToStr(Thread.fQueryStatus);
Q := Thread.fQueryToService;
if (Q <> nil) and (Q.Query <> nil)
then result := result + IntToStr(i) + '(' + status + '):' + Q.Query.ToStr + ' '
else result := result + IntToStr(i) + '(' + status + '): None ';
except
end;
end;
initialization
FillChar(DebugServers, sizeof(DebugServers), 0);
end.
|
unit uimpl;
interface
uses Types, Windows, Messages, SysUtils;
const
{ MessageBox() Flags }
{$EXTERNALSYM MB_OK}
MB_OK = $00000000;
{$EXTERNALSYM MB_OKCANCEL}
MB_OKCANCEL = $00000001;
{$EXTERNALSYM MB_ABORTRETRYIGNORE}
MB_ABORTRETRYIGNORE = $00000002;
{$EXTERNALSYM MB_YESNOCANCEL}
MB_YESNOCANCEL = $00000003;
{$EXTERNALSYM MB_YESNO}
MB_YESNO = $00000004;
{$EXTERNALSYM MB_RETRYCANCEL}
MB_RETRYCANCEL = $00000005;
{$EXTERNALSYM MB_ICONHAND}
MB_ICONHAND = $00000010;
{$EXTERNALSYM MB_ICONQUESTION}
MB_ICONQUESTION = $00000020;
{$EXTERNALSYM MB_ICONEXCLAMATION}
MB_ICONEXCLAMATION = $00000030;
{$EXTERNALSYM MB_ICONASTERISK}
MB_ICONASTERISK = $00000040;
{$EXTERNALSYM MB_USERICON}
MB_USERICON = $00000080;
{$EXTERNALSYM MB_ICONWARNING}
MB_ICONWARNING = MB_ICONEXCLAMATION;
{$EXTERNALSYM MB_ICONERROR}
MB_ICONERROR = MB_ICONHAND;
{$EXTERNALSYM MB_ICONINFORMATION}
MB_ICONINFORMATION = MB_ICONASTERISK;
{$EXTERNALSYM MB_ICONSTOP}
MB_ICONSTOP = MB_ICONHAND;
WS_EX_CONTROLPARENT = $10000;
WS_CHILD = $40000000;
WS_VISIBLE = $10000000;
WM_XBUTTONDOWN = $020B;
WM_XBUTTONUP = $020C;
WM_XBUTTONDBLCLK = $020D;
SW_SHOWNORMAL = 1;
SW_SHOWMINIMIZED = 2;
SW_SHOWMAXIMIZED = 3;
CUSTOM_WIN = 'CustomWindow';
CUSTOM_COMP = 'CustomComponent';
DC_BRUSH = 18;
DC_PEN = 19;
MR_NONE = 0; // no close
MR_OK = 1; // ok close
MR_CANCEL = 2; // cancel close
MR_CLOSE = 3; // just close
clWhite=$ffffff;
clBlack=$000000;
clGray95=$f2f2f2;
// $c8d0d4
clGray98=$fafafa;
// $e2e1e1
clGray25=$404040;
clButton=$7dba5f;
clDkGray=$808080;
clWebRoyalBlue=$E16941;
clWebSlateGray=$908070;
clWebLightBlue=$E6D8AD;
clWebLightCyan=$FFFFE0;
clWebSkyBlue=$EBCE87;
clFaceBook1=$98593B;
clFaceBook2=$c39d8b;
clFaceBook3=$eee3df;
clFaceBook4=$f7f7f7;
clPanelBackground1=$eeeeee;
clPanelBackground2=$c8d0d4;
clButtonInactiveBackground=$e1e1e1;
clButtonInactiveBorder=$adadad;
DT_TOP = 0;
DT_LEFT = 0;
DT_CENTER = 1;
DT_RIGHT = 2;
DT_VCENTER = 4;
DT_BOTTOM = 8;
DT_WORDBREAK = $10;
DT_SINGLELINE = $20;
DT_EXPANDTABS = $40;
DT_TABSTOP = $80;
DT_NOCLIP = $100;
DT_EXTERNALLEADING = $200;
DT_CALCRECT = $400;
DT_NOPREFIX = $800;
DT_INTERNAL = $1000;
DT_HIDEPREFIX = $00100000;
DT_PREFIXONLY = $00200000;
type
TPoint = Types.TPoint;
TRect = Types.TRect;
TMouseButton = (mbLeft, mbMiddle, mbRight, mbX1, mbX2);
HWND = type LongWord;
HFONT = type LongWord;
HBITMAP = type LongWord;
HDC = type LongWord;
UINT = type LongWord;
COLORREF=longword;
TWinHandleImpl=class
private
protected
hWindow:HWnd;
wParent:TWinHandleImpl;
wStyle,wExStyle:cardinal;
wText:string;
hLeft, hTop, hWidth, hHeight : integer;
wBitmap, wMask : HBITMAP;
wCursor:cardinal;
KeyCursorX, KeyCursorY : integer;
hTrackMouseEvent:TTrackMouseEvent;
wTrackingMouse:boolean;
wEnabled:boolean;
wModalResult:integer;
dc : hdc;
ps : paintstruct;
procedure CreateFormStyle;
procedure CreateFormWindow;
procedure CreateModalStyle;
procedure CreateModalWindow;
procedure CreateCompStyle;
procedure CreateCompWindow;
procedure CreatePopupStyle;
procedure RegisterMouseLeave;
public
procedure Show(nCmdShow:integer = SW_SHOWNORMAL);virtual;
procedure Hide;virtual;
procedure RedrawPerform;
procedure SetPosPerform;
procedure SetFocusPerform;virtual;
procedure CustomPaint;virtual;
function SetCapture(hWnd: HWND): HWND;
function ReleaseCapture: BOOL;
function GetCursorPos(var lpPoint: TPoint): BOOL;
function GetClientRect:TRect;
procedure BeginPaint;
procedure EndPaint;
procedure DrawText(var r:TRect; const text:string; font:HFONT; color, bkcolor:cardinal; mode:integer; style:cardinal);
procedure Polygon(color, bkcolor:cardinal; Left, Top, Right, Bottom:integer);
procedure Polyline(color:cardinal; start, count:integer; Left, Top, Right, Bottom:integer);
function ShowModalWindow:integer;
procedure CloseModalWindow;
procedure EnableWindow;
procedure CloseModalPerform;
procedure SetFocus;
procedure HideKeyCursor;
procedure ShowKeyCursor;
procedure CreateImagePerform;
procedure CustomImagePaint;
procedure SetCursor;
procedure EventPerform(AMessage: UINT; WParam : WPARAM; LParam: LPARAM);virtual;
procedure SizePerform;virtual;
procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);virtual;
procedure MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);virtual;
procedure MouseLeavePerform;virtual;
procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual;
procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual;
procedure MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual;
procedure KillFocusPerform(handle:HWND);virtual;
procedure ClosePerform;virtual;
procedure KeyCharPerform(keychar:cardinal);virtual;
procedure CapturePerform(AWindow:HWND);virtual;
procedure CalcTextSize(const AText:string; var AWidth, AHeight:integer);
property Cursor:cardinal read wCursor write wCursor;
end;
var
crArrow, crHand, crIBeam, crHourGlass, crSizeNS, crSizeWE : cardinal; // will be initialalized
fntRegular,fntBold:HFONT; // will be initialalized
var MainWinForm:TWinHandleImpl;
function MessageBox(hWnd: HWND; lpText, lpCaption: PChar; uType: UINT): Integer; stdcall;
function SetDCBrushColor(DC: HDC; Color: COLORREF): COLORREF; stdcall;
function SetDCPenColor(DC: HDC; Color: COLORREF): COLORREF; stdcall;
function GetWindowLongPtr(hWnd: HWND; nIndex: Integer): pointer; stdcall;
function SetWindowLongPtr(hWnd: HWND; nIndex: Integer; dwNewLong: pointer): pointer; stdcall;
procedure InitUI;
procedure ProcessMessages;
procedure FreeUI;
function CreateBitmapMask(hbmColour:HBITMAP; crTransparent:COLORREF):HBITMAP;
implementation
{$IFDEF CPU64}
function GetWindowLongPtr; external user32 name 'GetWindowLongPtrA';
function SetWindowLongPtr; external user32 name 'SetWindowLongPtrA';
{$ELSE}
function GetWindowLongPtr; external user32 name 'GetWindowLongA';
function SetWindowLongPtr; external user32 name 'SetWindowLongA';
{$ENDIF}
function SetDCBrushColor; external gdi32 name 'SetDCBrushColor';
function SetDCPenColor; external gdi32 name 'SetDCPenColor';
function MessageBox; external user32 name 'MessageBoxA';
function MouseCustomProc(comp:TWinHandleImpl;AMessage: UINT; WParam : WPARAM; LParam: LPARAM):boolean;
var
x,y,deltawheel:integer;
mb:TMouseButton;
p:TPoint;
hWndUnder:HWND;
begin
result:=false;
x:=lparam and $ffff;
y:=(lparam shr 16) and $ffff;
case AMessage of
WM_LBUTTONDOWN,WM_LBUTTONUP,WM_LBUTTONDBLCLK,
WM_RBUTTONDOWN,WM_RBUTTONUP,WM_RBUTTONDBLCLK,
WM_MBUTTONDOWN,WM_MBUTTONUP,WM_MBUTTONDBLCLK,
WM_XBUTTONUP,WM_XBUTTONDOWN,WM_XBUTTONDBLCLK:begin
mb:=mbLeft;
case AMessage of
WM_LBUTTONDOWN,WM_LBUTTONUP,WM_LBUTTONDBLCLK:mb:=mbLeft;
WM_RBUTTONDOWN,WM_RBUTTONUP,WM_RBUTTONDBLCLK:mb:=mbRight;
WM_MBUTTONDOWN,WM_MBUTTONUP,WM_MBUTTONDBLCLK:mb:=mbMiddle;
WM_XBUTTONUP,WM_XBUTTONDOWN,WM_XBUTTONDBLCLK:begin
if (wparam shr 16) and $ffff = 1 then mb:=mbX1;
if (wparam shr 16) and $ffff = 2 then mb:=mbX2;
end;
end;
case AMessage of
WM_LBUTTONDOWN,WM_RBUTTONDOWN,WM_MBUTTONDOWN,WM_XBUTTONDOWN:begin
comp.MouseButtonDownPerform(mb, wparam, x, y);
end;
WM_LBUTTONUP,WM_RBUTTONUP,WM_MBUTTONUP,WM_XBUTTONUP:begin
comp.MouseButtonUpPerform(mb, wparam, x, y);
end;
WM_LBUTTONDBLCLK,WM_RBUTTONDBLCLK,WM_MBUTTONDBLCLK,WM_XBUTTONDBLCLK:begin
comp.MouseButtonDblDownPerform(mb, wparam, x, y);
end;
end;
result:=true;
end;
WM_MOUSEMOVE:begin
comp.MouseMovePerform(wparam, x, y);
result:=true;
end;
WM_MOUSELEAVE:begin
comp.MouseLeavePerform;
result:=true;
end;
WM_MOUSEWHEEL:begin
GetCursorPos(p);
hWndUnder:=WindowFromPoint(p);
if(hWndUnder=0)or(comp.hWindow=hWndUnder)
then begin
(*
deltawheel:=wparam;
asm
lea eax, deltawheel
sar DWORD PTR [eax], 16
end;
*)
if wparam and $80000000 = $80000000
then deltawheel := -1
else deltawheel := 1;
comp.MouseWheelPerform(wparam and $ffff, deltawheel, x, y);
end
else PostMessage(hWndUnder, WM_MOUSEWHEEL, WParam, LParam);
result:=true;
end;
WM_MOUSEHOVER:begin
//comp.WinClass.Text:=comp.WinClass.Text+'H';
//comp.WinClass.RedrawPerform;
//result:=0;
//Exit;
end;
end;
end;
function WindowProc(hWindow: HWnd; AMessage: UINT; WParam : WPARAM; LParam: LPARAM): LRESULT; stdcall;
var r:TRect;
frm:TWinHandleImpl;
begin
WindowProc := 0;
frm:=GetWindowLongPtr(hWindow, GWL_USERDATA);
if frm<>nil
then begin
frm.EventPerform(AMessage, WParam, LParam);
if MouseCustomProc(frm, AMessage, WParam, LParam)
then exit;
case AMessage of
WM_KILLFOCUS:begin
frm.KillFocusPerform(WParam);
WindowProc:=0;
exit;
end;
WM_CLOSE:begin
frm.ClosePerform;
if MainWinForm.hWindow <> hWindow
then begin
frm.Hide;
WindowProc:=0;
exit
end;
end;
(* WM_MOUSEACTIVATE:Begin
if not frm.Enabled
then begin
WindowProc:=MA_NOACTIVATEANDEAT;
exit;
end;
end;*)
wm_char:begin
frm.KeyCharPerform(wparam);
WindowProc:=0;
Exit;
end;
wm_keydown:begin
// get focused comp
// if wparam=65
// then begin
// MessageBox(0, pchar('keyup '+inttostr(wparam)+' '+inttostr(lparam)), nil, mb_Ok);
WindowProc:=0;
Exit;
// end;
end;
// wm_keyup
// WM_SYSKEYDOWN
WM_SYSCHAR:begin
// get focused comp
if wparam<>18
then begin
MessageBox(0, pchar('keyup '+inttostr(wparam)+' '+inttostr(lparam)), nil, mb_Ok);
WindowProc:=0;
Exit;
end;
end;
// wm_create:begin
// end;
// wm_sizing:begin
// WindowProc:=0;
// end;
wm_size:begin
if (wParam = SIZE_MAXIMIZED) or(wParam = SIZE_RESTORED)
then begin
frm.SizePerform;
GetWindowRect(hWindow, r);
//todo if r.Bottom-r.Top<500
// then begin
// SetWindowPos(hWindow, 0, r.Left, r.Top, r.Right-r.Left, 500, SWP_NOZORDER);
// end;
end
end;
WM_EraseBkgnd:begin
// WindowProc:=1;
// Exit;
end;
wm_Destroy: begin
if MainWinForm.hWindow = hWindow
then PostQuitMessage(0);
Exit;
end;
end;
end;
WindowProc := DefWindowProc(hWindow, AMessage, WParam, LParam);
end;
function CustomProc(hWindow: HWnd; AMessage: UINT; WParam : WPARAM;
LParam: LPARAM): LRESULT; stdcall;
var
comp:TWinHandleImpl;
begin
comp:=GetWindowLongPtr(hWindow, GWL_USERDATA);
if comp<>nil
then begin
if MouseCustomProc(comp, AMessage, WParam, LParam)
then begin
result:=0;
exit;
end;
case AMessage of
WM_CAPTURECHANGED:begin
comp.CapturePerform(lparam);
result:=0;
exit;
end;
WM_KILLFOCUS:begin
comp.KillFocusPerform(wparam);
result:=0;
exit;
end;
WM_INPUTLANGCHANGE:begin
//MessageBox(0, pchar('WM_INPUTLANGCHANGE '+inttostr(wparam)+' '+inttostr(lparam)), nil, mb_Ok);
end;
wm_char:begin
comp.KeyCharPerform(wparam);
result:=0;
Exit;
end;
wm_paint:begin
comp.CustomPaint;
Result:=0;
exit
end;
end;
end;
CustomProc := DefWindowProc(hWindow, AMessage, WParam, LParam);
end;
procedure CustomRegister;
var
wc: WndClass;
begin
wc.style := CS_GLOBALCLASS or CS_HREDRAW or CS_VREDRAW or CS_DBLCLKS;
wc.lpfnWndProc := @CustomProc;
wc.cbClsExtra := 0;
wc.cbWndExtra := 0;
wc.hInstance := 0;
wc.hIcon := 0;
wc.hCursor := 0; //crArrow;
wc.hbrBackground := 0; //COLOR_BACKGROUND;
wc.lpszMenuName := nil;
wc.lpszClassName := CUSTOM_COMP;
RegisterClass(wc);
end;
procedure CustomUnregister;
begin
UnregisterClass(CUSTOM_COMP, 0);
end;
function WinRegister: Boolean;
var
WindowClass: WndClass;
begin
WindowClass.Style := cs_hRedraw or cs_vRedraw;
WindowClass.lpfnWndProc := @WindowProc;
WindowClass.cbClsExtra := 0;
WindowClass.cbWndExtra := 0;
WindowClass.hInstance := system.MainInstance;
WindowClass.hIcon := LoadIcon(system.MainInstance, 'APP');
// WindowClass.hIcon := LoadIcon(0, IDI_INFORMATION);
WindowClass.hCursor := crArrow;
WindowClass.hbrBackground := COLOR_BTNFACE + 1;
WindowClass.lpszMenuName := nil;
WindowClass.lpszClassName := CUSTOM_WIN;
Result := RegisterClass(WindowClass) <> 0;
end;
function CreateBitmapMask(hbmColour:HBITMAP; crTransparent:COLORREF):HBITMAP;
var
hdcMem, hdcMem2:HDC;
hbmMask:HBITMAP;
bm:BITMAP;
begin
// Create monochrome (1 bit) mask bitmap.
GetObject(hbmColour, sizeof(BITMAP), @bm);
hbmMask := CreateBitmap(bm.bmWidth, bm.bmHeight, 1, 1, nil);
// Get some HDCs that are compatible with the display driver
hdcMem := CreateCompatibleDC(0);
hdcMem2 := CreateCompatibleDC(0);
SelectObject(hdcMem, hbmColour);
SelectObject(hdcMem2, hbmMask);
crTransparent:=GetPixel(hdcMem,0,0);
// Set the background colour of the colour image to the colour
// you want to be transparent.
SetBkColor(hdcMem, crTransparent);
// Copy the bits from the colour image to the B+W mask... everything
// with the background colour ends up white while everythig else ends up
// black...Just what we wanted.
BitBlt(hdcMem2, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
// Take our new mask and use it to turn the transparent colour in our
// original colour image to black so the transparency effect will
// work right.
BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem2, 0, 0, SRCINVERT);
// Clean up.
DeleteDC(hdcMem);
DeleteDC(hdcMem2);
result:=hbmMask;
end;
procedure ProcessMessages;
var AMessage: Msg;
ret:longbool;
begin
repeat
ret:=GetMessage(AMessage, 0, 0, 0);
if integer(ret) = -1 then break;
TranslateMessage(AMessage);
DispatchMessage(AMessage)
until not ret
end;
procedure LoadCursors;
begin
crArrow:=LoadCursor(0, IDC_ARROW);
crHand:=LoadCursor(0, IDC_HAND);
crIBeam:=LoadCursor(0, IDC_IBEAM);
crHourGlass:=LoadCursor(0, IDC_WAIT);
crSizeNS:=LoadCursor(0, IDC_SIZENS);
crSizeWE:=LoadCursor(0, IDC_SIZEWE);
end;
procedure CreateFonts;
begin
fntRegular:=CreateFont(-muldiv(12,96,72),0,0,0,FW_REGULAR,0,0,0,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,NONANTIALIASED_QUALITY,DEFAULT_PITCH,'Courier New');
fntBold:=CreateFont(-muldiv(12,96,72),0,0,0,FW_BOLD,0,0,0,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,NONANTIALIASED_QUALITY,DEFAULT_PITCH,'Courier New');
end;
procedure DeleteFonts;
begin
DeleteObject(fntRegular);
DeleteObject(fntBold);
end;
procedure InitUI;
begin
LoadCursors;
CreateFonts;
CustomRegister;
if not WinRegister then begin
MessageBox(0, 'WinRegister failed', nil, mb_Ok);
halt(0);
end;
end;
procedure FreeUI;
begin
CustomUnregister;
DeleteFonts;
end;
procedure TWinHandleImpl.CreateFormStyle;
begin
wExStyle:=WS_EX_COMPOSITED or WS_EX_LAYERED or WS_EX_NOINHERITLAYOUT;
wStyle:=WS_OVERLAPPEDWINDOW;
end;
procedure TWinHandleImpl.CreateModalStyle;
begin
wExStyle:=WS_EX_COMPOSITED or WS_EX_LAYERED or WS_EX_DLGMODALFRAME;
wStyle:=WS_BORDER or WS_POPUP or WS_SYSMENU or WS_DLGFRAME
or WS_SIZEBOX or WS_MINIMIZEBOX or WS_MAXIMIZEBOX;
end;
procedure TWinHandleImpl.CreateFormWindow;
begin
hWindow := CreateWindowEx(wExStyle, CUSTOM_WIN, pchar(wText), wStyle,
hLeft, hTop, hWidth, hHeight,
0, 0, system.MainInstance, nil);
SetWindowLongPtr(hWindow, GWL_USERDATA, self);
end;
procedure TWinHandleImpl.CreateModalWindow;
begin
hWindow := CreateWindowEx(wExStyle, CUSTOM_WIN, pchar(wText), wStyle,
hLeft, hTop, hWidth, hHeight,
wParent.hWindow, 0, system.MainInstance, nil);
SetWindowLongPtr(hWindow, GWL_USERDATA, self);
end;
procedure TWinHandleImpl.CreateCompStyle;
begin
wExStyle:=WS_EX_CONTROLPARENT;
wStyle:=WS_CHILD or WS_VISIBLE;
end;
procedure TWinHandleImpl.CreatePopupStyle;
begin
wExStyle:=WS_EX_COMPOSITED or WS_EX_LAYERED;
wStyle:=WS_POPUP;
end;
procedure TWinHandleImpl.CreateCompWindow;
begin
hWindow := CreateWindowEx(wExStyle, CUSTOM_COMP, nil, wStyle,
hLeft, hTop, hWidth, hHeight,
wParent.hWindow, 0, 0, nil);
SetWindowLongPtr(hWindow, GWL_USERDATA, self);
end;
procedure TWinHandleImpl.Show(nCmdShow:integer=SW_SHOWNORMAL);
begin
ShowWindow(hWindow, nCmdShow);
end;
procedure TWinHandleImpl.Hide;
begin
Show(SW_HIDE)
end;
procedure TWinHandleImpl.RedrawPerform;
begin
InvalidateRect(hWindow, nil, TRUE);
end;
procedure TWinHandleImpl.SetPosPerform;
begin
SetWindowPos(hWindow, 0, hLeft, hTop, hWidth, hHeight, SWP_NOZORDER);
end;
procedure TWinHandleImpl.RegisterMouseLeave;
begin
if not wTrackingMouse
then begin
wTrackingMouse:=true;
hTrackMouseEvent.cbSize:=SizeOf(hTrackMouseEvent);
hTrackMouseEvent.dwFlags:=TME_LEAVE or TME_HOVER;
hTrackMouseEvent.hwndTrack:=hWindow;
hTrackMouseEvent.dwHoverTime:=HOVER_DEFAULT;
if not TrackMouseEvent(hTrackMouseEvent)
then wTrackingMouse:=false
end;
end;
// custompaint support
function TWinHandleImpl.GetClientRect:TRect;
begin
windows.GetClientRect(hWindow, result)
end;
procedure TWinHandleImpl.BeginPaint;
begin
dc:=windows.BeginPaint(hWindow, ps)
end;
procedure TWinHandleImpl.EndPaint;
begin
windows.EndPaint(hWindow, ps)
end;
procedure TWinHandleImpl.DrawText(var r:TRect; const text:string; font:HFONT; color, bkcolor:cardinal; mode:integer; style:cardinal);
begin
SelectObject(dc, font);
SetTextColor(dc, color);
SetBkColor(dc, bkcolor);
SetBkMode(dc, mode);
windows.DrawText(dc, pchar(text), -1, r, style);
end;
procedure TWinHandleImpl.Polygon(color, bkcolor:cardinal; Left, Top, Right, Bottom:integer);
var p : array[0..3] of tpoint;
begin
SelectObject(dc, GetStockObject(DC_PEN));
SetDCPenColor(dc, color);
SelectObject(dc, GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, bkcolor);
p[0].X:=Left; p[0].Y:=Top;
p[1].X:=Right; p[1].Y:=Top;
p[2].X:=Right; p[2].Y:=Bottom;
p[3].X:=Left; p[3].Y:=Bottom;
windows.Polygon(dc, p, 4);
end;
procedure TWinHandleImpl.Polyline(color:cardinal; start, count:integer; Left, Top, Right, Bottom:integer);
var p : array[-1..4] of tpoint;
begin
SelectObject(dc, GetStockObject(DC_PEN));
SetDCPenColor(dc, color);
p[-1].X:=Left; p[-1].Y:=Bottom;
p[0].X:=Left; p[0].Y:=Top;
p[1].X:=Right; p[1].Y:=Top;
p[2].X:=Right; p[2].Y:=Bottom;
p[3].X:=Left; p[3].Y:=Bottom;
p[4].X:=Left; p[4].Y:=Top;
windows.Polyline(dc, p[start], count);
end;
function TWinHandleImpl.GetCursorPos(var lpPoint: TPoint): BOOL;
begin
result:=windows.GetCursorPos(lpPoint);
end;
function TWinHandleImpl.SetCapture(hWnd: HWND): HWND;
begin
result:=windows.SetCapture(hWnd);
end;
function TWinHandleImpl.ReleaseCapture: BOOL;
begin
result:=windows.ReleaseCapture;
end;
function TWinHandleImpl.ShowModalWindow:integer;
var AMessage: Msg;
ret:longbool;
begin
// result:=inherited ShowModal;
wParent.wEnabled:=false;
windows.EnableWindow(wParent.hWindow, FALSE);
Show;
// ProcessMessages;
wModalResult:=MR_NONE;
repeat
ret:=GetMessage(AMessage, 0, 0, 0);
if integer(ret) = -1 then break;
TranslateMessage(AMessage);
DispatchMessage(AMessage)
until not ret and (wModalResult<>MR_NONE);
result:=wModalResult
end;
procedure TWinHandleImpl.CloseModalWindow;
begin
PostMessage(hWindow, wm_close, 0, 0);
end;
procedure TWinHandleImpl.EnableWindow;
begin
windows.EnableWindow(hWindow, TRUE);
end;
procedure TWinHandleImpl.CloseModalPerform;
begin
if wModalResult=MR_NONE
then wModalResult:=MR_CLOSE;
PostMessage(hWindow, WM_QUIT, 0, 0);
wParent.wEnabled:=true;
windows.EnableWindow(wParent.hWindow, TRUE);
end;
procedure TWinHandleImpl.SetFocus;
var h:HWND;
begin
h:=GetFocus;
if h<>0
then SendMessage(h, WM_KILLFOCUS, 0, 0);
windows.SetFocus(hWindow);
SetFocusPerform;
end;
procedure TWinHandleImpl.SetFocusPerform;
begin
end;
procedure TWinHandleImpl.HideKeyCursor;
begin
HideCaret(hWindow);
end;
procedure TWinHandleImpl.ShowKeyCursor;
begin
HideCaret(hWindow);
CreateCaret(hWindow, 0, 2, 17);
SetCaretPos(KeyCursorX, KeyCursorY);
ShowCaret(hWindow);
end;
procedure TWinHandleImpl.CreateImagePerform;
begin
wBitmap:=LoadBitmap(system.MainInstance, 'BAD'); //todo deleteobject
wMask:=CreateBitmapMask(wBitmap, $ffffff{clWhite});
end;
procedure TWinHandleImpl.CustomImagePaint;
var
img : hdc;
begin
BeginPaint;
img:=CreateCompatibleDC(dc);
SelectObject(img, wMask);
BitBlt(dc,0,0,50,50,img,0,0,SRCAND);
SelectObject(img, wBitmap);
BitBlt(dc,0,0,50,50,img,0,0,SRCPAINT);
DeleteDC(img);
EndPaint;
end;
procedure TWinHandleImpl.SetCursor;
begin
windows.SetCursor(wCursor);
end;
procedure TWinHandleImpl.CustomPaint;
begin
end;
procedure TWinHandleImpl.SizePerform;
begin
end;
procedure TWinHandleImpl.MouseMovePerform(AButtonControl:cardinal; x,y:integer);
begin
end;
procedure TWinHandleImpl.MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);
begin
end;
procedure TWinHandleImpl.MouseLeavePerform;
begin
end;
procedure TWinHandleImpl.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
end;
procedure TWinHandleImpl.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
end;
procedure TWinHandleImpl.MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
end;
procedure TWinHandleImpl.KillFocusPerform(handle:HWND);
begin
end;
procedure TWinHandleImpl.ClosePerform;
begin
end;
procedure TWinHandleImpl.KeyCharPerform(keychar:cardinal);
begin
end;
procedure TWinHandleImpl.CapturePerform(AWindow:HWND);
begin
end;
procedure TWinHandleImpl.CalcTextSize(const AText:string; var AWidth, AHeight:integer);
var r:trect;
begin
r.Left:=0;
r.Top:=0;
BeginPaint;
DrawText(r, AText, 0, 0, 0, TRANSPARENT, DT_SINGLELINE or DT_LEFT or DT_TOP or DT_CALCRECT);
EndPaint;
AWidth:=r.Right;
AHeight:=r.Bottom;
end;
procedure TWinHandleImpl.EventPerform;
begin
end;
end.
|
unit cavemanninja_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine,
oki6295,sound_engine,hu6280,deco_16ic,deco_common,deco_104,deco_146,
misc_functions;
function iniciar_cninja:boolean;
implementation
const
//Caveman Ninja
cninja_rom:array[0..5] of tipo_roms=(
(n:'gn-02-3.1k';l:$20000;p:0;crc:$39aea12a),(n:'gn-05-2.3k';l:$20000;p:$1;crc:$0f4360ef),
(n:'gn-01-2.1j';l:$20000;p:$40000;crc:$f740ef7e),(n:'gn-04-2.3j';l:$20000;p:$40001;crc:$c98fcb62),
(n:'gn-00.rom';l:$20000;p:$80000;crc:$0b110b16),(n:'gn-03.rom';l:$20000;p:$80001;crc:$1e28e697));
cninja_sound:tipo_roms=(n:'gl-07.rom';l:$10000;p:$0;crc:$ca8bef96);
cninja_chars:array[0..1] of tipo_roms=(
(n:'gl-09.rom';l:$10000;p:$0;crc:$5a2d4752),(n:'gl-08.rom';l:$10000;p:1;crc:$33a2b400));
cninja_tiles1:tipo_roms=(n:'mag-02.rom';l:$80000;p:$0;crc:$de89c69a);
cninja_tiles2:array[0..1] of tipo_roms=(
(n:'mag-00.rom';l:$80000;p:$0;crc:$a8f05d33),(n:'mag-01.rom';l:$80000;p:$80000;crc:$5b399eed));
cninja_oki2:tipo_roms=(n:'mag-07.rom';l:$80000;p:0;crc:$08eb5264);
cninja_oki1:tipo_roms=(n:'gl-06.rom';l:$20000;p:0;crc:$d92e519d);
cninja_sprites:array[0..3] of tipo_roms=(
(n:'mag-03.rom';l:$80000;p:0;crc:$2220eb9f),(n:'mag-05.rom';l:$80000;p:$1;crc:$56a53254),
(n:'mag-04.rom';l:$80000;p:$100000;crc:$144b94cc),(n:'mag-06.rom';l:$80000;p:$100001;crc:$82d44749));
cninja_dip:array [0..7] of def_dip=(
(mask:$0007;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(dip_val:$2;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$0038;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(dip_val:$10;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$0040;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$0300;name:'Lives';number:4;dip:((dip_val:$100;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$300;dip_name:'3'),(dip_val:$200;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$0c00;name:'Difficulty';number:4;dip:((dip_val:$800;dip_name:'Easy'),(dip_val:$c00;dip_name:'Normal'),(dip_val:$400;dip_name:'Hard'),(dip_val:$000;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Restore Live Meter';number:2;dip:((dip_val:$1000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Demo Sounds';number:2;dip:((dip_val:$8000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
//Robocop 2
robocop2_rom:array[0..7] of tipo_roms=(
(n:'gq-03.k1';l:$20000;p:0;crc:$a7e90c28),(n:'gq-07.k3';l:$20000;p:$1;crc:$d2287ec1),
(n:'gq-02.j1';l:$20000;p:$40000;crc:$6777b8a0),(n:'gq-06.j3';l:$20000;p:$40001;crc:$e11e27b5),
(n:'go-01-1.h1';l:$20000;p:$80000;crc:$ab5356c0),(n:'go-05-1.h3';l:$20000;p:$80001;crc:$ce21bda5),
(n:'go-00.f1';l:$20000;p:$c0000;crc:$a93369ea),(n:'go-04.f3';l:$20000;p:$c0001;crc:$ee2f6ad9));
robocop2_char:array[0..1] of tipo_roms=(
(n:'gp10-1.y6';l:$10000;p:1;crc:$d25d719c),(n:'gp11-1.z6';l:$10000;p:0;crc:$030ded47));
robocop2_sound:tipo_roms=(n:'gp-09.k13';l:$10000;p:$0;crc:$4a4e0f8d);
robocop2_oki1:tipo_roms=(n:'gp-08.j13';l:$20000;p:0;crc:$365183b1);
robocop2_oki2:tipo_roms=(n:'mah-11.f13';l:$80000;p:0;crc:$642bc692);
robocop2_tiles1:array[0..1] of tipo_roms=(
(n:'mah-04.z4';l:$80000;p:$0;crc:$9b6ca18c),(n:'mah-03.y4';l:$80000;p:$80000;crc:$37894ddc));
robocop2_tiles2:array[0..2] of tipo_roms=(
(n:'mah-01.z1';l:$80000;p:0;crc:$26e0dfff),(n:'mah-00.y1';l:$80000;p:$80000;crc:$7bd69e41),
(n:'mah-02.a1';l:$80000;p:$100000;crc:$328a247d));
robocop2_sprites:array[0..5] of tipo_roms=(
(n:'mah-05.y9';l:$80000;p:$000000;crc:$6773e613),(n:'mah-08.y12';l:$80000;p:$000001;crc:$88d310a5),
(n:'mah-06.z9';l:$80000;p:$100000;crc:$27a8808a),(n:'mah-09.z12';l:$80000;p:$100001;crc:$a58c43a7),
(n:'mah-07.a9';l:$80000;p:$200000;crc:$526f4190),(n:'mah-10.a12';l:$80000;p:$200001;crc:$14b770da));
robocop2_dip_a:array [0..8] of def_dip=(
(mask:$0007;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(dip_val:$2;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$0038;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(dip_val:$10;dip_name:'1C 6C'),(),(),(),(),(),(),(),())),
(mask:$0040;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$0300;name:'Lives';number:4;dip:((dip_val:$100;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$300;dip_name:'3'),(dip_val:$200;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$0c00;name:'Time';number:4;dip:((dip_val:$800;dip_name:'400 Seconds'),(dip_val:$c00;dip_name:'300 Seconds'),(dip_val:$400;dip_name:'200 Seconds'),(dip_val:$000;dip_name:'100 Seconds'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$3000;name:'Health';number:4;dip:((dip_val:$000;dip_name:'17'),(dip_val:$1000;dip_name:'24'),(dip_val:$3000;dip_name:'33'),(dip_val:$2000;dip_name:'40'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4000;name:'Continues';number:2;dip:((dip_val:$000;dip_name:'Off'),(dip_val:$4000;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Demo Sounds';number:2;dip:((dip_val:$8000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
robocop2_dip_b:array [0..5] of def_dip=(
(mask:$3;name:'Bullets';number:4;dip:((dip_val:$0;dip_name:'Least'),(dip_val:$1;dip_name:'Less'),(dip_val:$3;dip_name:'Normal'),(dip_val:$2;dip_name:'More'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Enemy Movement';number:4;dip:((dip_val:$8;dip_name:'Slow'),(dip_val:$c;dip_name:'Normal'),(dip_val:$4;dip_name:'Fast'),(dip_val:$0;dip_name:'Fastest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Enemy Strength';number:4;dip:((dip_val:$20;dip_name:'Less'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'More'),(dip_val:$0;dip_name:'Most'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Enemy Weapon Speed';number:2;dip:((dip_val:$40;dip_name:'Normal'),(dip_val:$0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Game Over Message';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
rom:array[0..$7ffff] of word;
ram:array[0..$1fff] of word;
screen_line,irq_mask,irq_line:byte;
prioridad:word;
raster_irq:boolean;
proc_update_video:procedure;
procedure update_video_cninja;
begin
deco16ic_1.update_pf_2(5,false);
deco_sprites_0.draw_sprites($80);
deco16ic_1.update_pf_1(5,true);
deco_sprites_0.draw_sprites($40);
deco16ic_0.update_pf_2(5,true);
deco_sprites_0.draw_sprites($00);
deco16ic_0.update_pf_1(5,true);
actualiza_trozo_final(0,8,256,240,5);
end;
procedure update_video_robocop2;
begin
if (prioridad and 4)=0 then deco16ic_1.update_pf_2(5,false)
else begin
deco_sprites_0.draw_sprites($c0);
fill_full_screen(5,$200);
end;
deco_sprites_0.draw_sprites($80);
if (prioridad and $8)<>0 then begin
deco16ic_0.update_pf_2(5,true);
deco_sprites_0.draw_sprites($40);
deco16ic_1.update_pf_1(5,true);
end else begin
deco16ic_1.update_pf_1(5,(prioridad and 4)=0);
deco_sprites_0.draw_sprites($40);
deco16ic_0.update_pf_2(5,true);
end;
deco_sprites_0.draw_sprites($00);
deco16ic_0.update_pf_1(5,true);
actualiza_trozo_final(0,8,320,240,5);
end;
procedure eventos_cninja;
begin
if event.arcade then begin
//P1
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or 4);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or 8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80);
//P2
if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100);
if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400);
if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800);
if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $bfff) else marcade.in0:=(marcade.in0 or $4000);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $7fff) else marcade.in0:=(marcade.in0 or $8000);
//SYSTEM
if arcade_input.coin[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
end;
end;
procedure cninja_principal;
var
frame_m,frame_s:single;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=h6280_0.tframes;
while EmuStatus=EsRuning do begin
for screen_line:=0 to $ff do begin
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
h6280_0.run(trunc(frame_s));
frame_s:=frame_s+h6280_0.tframes-h6280_0.contador;
case screen_line of
1..239:if raster_irq then begin
if irq_line=screen_line then begin
if (irq_mask and $10)<>0 then m68000_0.irq[3]:=ASSERT_LINE
else m68000_0.irq[4]:=ASSERT_LINE;
raster_irq:=false;
end;
end;
247:begin
m68000_0.irq[5]:=HOLD_LINE;
proc_update_video;
marcade.in1:=marcade.in1 or $8;
end;
255:marcade.in1:=marcade.in1 and $f7;
end;
end;
eventos_cninja;
video_sync;
end;
end;
function cninja_protection_deco_104_r(real_address:word):word;
var
data,deco104_addr:word;
cs:byte;
begin
//int real_address = 0 + (offset *2);
deco104_addr:=BITSWAP32(real_address,31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11,17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) and $7fff;
cs:=0;
data:=main_deco104.read_data(deco104_addr,cs);
cninja_protection_deco_104_r:=data;
end;
function cninja_getword(direccion:dword):word;
begin
case direccion of
$0..$bffff:cninja_getword:=rom[direccion shr 1];
$144000..$144fff:cninja_getword:=deco16ic_0.pf1.data[(direccion and $fff) shr 1];
$146000..$146fff:cninja_getword:=deco16ic_0.pf2.data[(direccion and $fff) shr 1];
$14c000..$14c7ff:cninja_getword:=deco16ic_0.pf1.rowscroll[(direccion and $7ff) shr 1];
$14e000..$14e7ff:cninja_getword:=deco16ic_0.pf2.rowscroll[(direccion and $7ff) shr 1];
$154000..$154fff:cninja_getword:=deco16ic_1.pf1.data[(direccion and $fff) shr 1];
$156000..$156fff:cninja_getword:=deco16ic_1.pf2.data[(direccion and $fff) shr 1];
$15c000..$15c7ff:cninja_getword:=deco16ic_1.pf1.rowscroll[(direccion and $7ff) shr 1];
$15e000..$15e7ff:cninja_getword:=deco16ic_1.pf2.rowscroll[(direccion and $7ff) shr 1];
$184000..$187fff:cninja_getword:=ram[(direccion and $3fff) shr 1];
$190000..$190007:case ((direccion shr 1) and $7) of
1:cninja_getword:=screen_line; // Raster IRQ scanline position
2:begin // Raster IRQ ACK
m68000_0.irq[3]:=CLEAR_LINE;
m68000_0.irq[4]:=CLEAR_LINE;
cninja_getword:=0;
end;
else cninja_getword:=0;
end;
$19c000..$19dfff:cninja_getword:=buffer_paleta[(direccion and $1fff) shr 1];
$1a4000..$1a47ff:cninja_getword:=buffer_sprites_w[(direccion and $7ff) shr 1];
$1bc000..$1bffff:cninja_getword:=cninja_protection_deco_104_r(direccion-$1bc000);
end;
end;
procedure cambiar_color(numero:word);
var
color:tcolor;
begin
color.b:=buffer_paleta[numero shl 1] and $ff;
color.g:=buffer_paleta[(numero shl 1)+1] shr 8;
color.r:=buffer_paleta[(numero shl 1)+1] and $ff;
set_pal_color(color,numero);
case numero of
$000..$0ff:deco16ic_0.pf1.buffer_color[(numero shr 4) and $f]:=true;
$100..$1ff:deco16ic_0.pf2.buffer_color[(numero shr 4) and $f]:=true;
$200..$2ff:deco16ic_1.pf1.buffer_color[(numero shr 4) and $f]:=true;
$500..$5ff:deco16ic_1.pf2.buffer_color[(numero shr 4) and deco16ic_1.color_mask[2]]:=true;
end;
end;
procedure cninja_protection_deco_104_w(real_address,data:word);
var
deco104_addr:word;
cs:byte;
begin
//int real_address = 0 + (offset *2);
deco104_addr:=BITSWAP32(real_address,31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11,17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) and $7fff;
cs:=0;
main_deco104.write_data(deco104_addr, data,cs);
end;
procedure cninja_putword(direccion:dword;valor:word);
begin
case direccion of
0..$bffff:; //ROM
$140000..$14000f:deco16ic_0.control_w((direccion and $f) shr 1,valor);
$144000..$144fff:if deco16ic_0.pf1.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_0.pf1.data[(direccion and $fff) shr 1]:=valor;
deco16ic_0.pf1.buffer[(direccion and $fff) shr 1]:=true
end;
$146000..$146fff:if deco16ic_0.pf2.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_0.pf2.data[(direccion and $fff) shr 1]:=valor;
deco16ic_0.pf2.buffer[(direccion and $fff) shr 1]:=true
end;
$14c000..$14c7ff:deco16ic_0.pf1.rowscroll[(direccion and $7ff) shr 1]:=valor;
$14e000..$14e7ff:deco16ic_0.pf2.rowscroll[(direccion and $7ff) shr 1]:=valor;
$150000..$15000f:begin
deco16ic_1.control_w((direccion and $f) shr 1,valor);
if ((direccion and $f)=0) then main_screen.flip_main_screen:=(valor and $0080)<>0
end;
$154000..$154fff:if deco16ic_1.pf1.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_1.pf1.data[(direccion and $fff) shr 1]:=valor;
deco16ic_1.pf1.buffer[(direccion and $fff) shr 1]:=true
end;
$156000..$156fff:if deco16ic_1.pf2.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_1.pf2.data[(direccion and $fff) shr 1]:=valor;
deco16ic_1.pf2.buffer[(direccion and $fff) shr 1]:=true
end;
$15c000..$15c7ff:deco16ic_1.pf1.rowscroll[(direccion and $7ff) shr 1]:=valor;
$15e000..$15e7ff:deco16ic_1.pf2.rowscroll[(direccion and $7ff) shr 1]:=valor;
$184000..$187fff:ram[(direccion and $3fff) shr 1]:=valor;
$190000..$190007:case ((direccion shr 1) and 7) of
0:irq_mask:=valor and $ff; // IRQ enable:
1:begin // Raster IRQ scanline position, only valid for values between 1 & 239 (0 and 240-256 do NOT generate IRQ's)
irq_line:=valor and $ff;
raster_irq:=(irq_line>0) and (irq_line<240) and ((irq_mask and $2)=0);
end;
end;
$19c000..$19dfff:if (buffer_paleta[(direccion and $1fff) shr 1]<>valor) then begin
buffer_paleta[(direccion and $1fff) shr 1]:=valor;
cambiar_color((direccion and $1fff) shr 2);
end;
$1a4000..$1a47ff:buffer_sprites_w[(direccion and $7ff) shr 1]:=valor;
$1b4000..$1b4001:copymemory(@deco_sprites_0.ram[0],@buffer_sprites_w[0],$400*2);
$1b0002..$1b000f:;
$1bc000..$1bffff:cninja_protection_deco_104_w(direccion-$1bc000,valor);
end;
end;
//Roboop 2
function robocop2_protection_deco_146_r(real_address:word):word;
var
deco146_addr,data:word;
cs:byte;
begin
//int real_address = 0 + (offset *2);
deco146_addr:=BITSWAP32(real_address,31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11, 17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) and $7fff;
cs:=0;
data:=main_deco146.read_data(deco146_addr,cs);
robocop2_protection_deco_146_r:=data;
end;
function robocop2_getword(direccion:dword):word;
begin
case direccion of
$0..$fffff:robocop2_getword:=rom[direccion shr 1];
$144000..$144fff:robocop2_getword:=deco16ic_0.pf1.data[(direccion and $fff) shr 1];
$146000..$146fff:robocop2_getword:=deco16ic_0.pf2.data[(direccion and $fff) shr 1];
$14c000..$14c7ff:robocop2_getword:=deco16ic_0.pf1.rowscroll[(direccion and $7ff) shr 1];
$14e000..$14e7ff:robocop2_getword:=deco16ic_0.pf2.rowscroll[(direccion and $7ff) shr 1];
$154000..$154fff:robocop2_getword:=deco16ic_1.pf1.data[(direccion and $fff) shr 1];
$156000..$156fff:robocop2_getword:=deco16ic_1.pf2.data[(direccion and $fff) shr 1];
$15c000..$15c7ff:robocop2_getword:=deco16ic_1.pf1.rowscroll[(direccion and $7ff) shr 1];
$15e000..$15e7ff:robocop2_getword:=deco16ic_1.pf2.rowscroll[(direccion and $7ff) shr 1];
$180000..$1807ff:robocop2_getword:=buffer_sprites_w[(direccion and $7ff) shr 1];
$18c000..$18ffff:robocop2_getword:=robocop2_protection_deco_146_r(direccion-$18c000);
$1a8000..$1a9fff:robocop2_getword:=buffer_paleta[(direccion and $1fff) shr 1];
$1b0000..$1b0007:case ((direccion shr 1) and $7) of
1:robocop2_getword:=screen_line; // Raster IRQ scanline position
2:begin // Raster IRQ ACK
m68000_0.irq[3]:=CLEAR_LINE;
m68000_0.irq[4]:=CLEAR_LINE;
robocop2_getword:=0;
end;
else robocop2_getword:=0;
end;
$1b8000..$1bbfff:robocop2_getword:=ram[(direccion and $3fff) shr 1];
$1f8000..$1f8001:robocop2_getword:=marcade.dswb;
end;
end;
procedure robocop2_protection_deco_146_w(real_address,data:word);
var
deco146_addr:word;
cs:byte;
begin
//int real_address = 0 + (offset *2);
deco146_addr:=BITSWAP32(real_address, 31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11, 17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) and $7fff;
cs:=0;
main_deco146.write_data(deco146_addr,data,cs);
end;
procedure robocop2_putword(direccion:dword;valor:word);
begin
case direccion of
0..$fffff:; //ROM
$140000..$14000f:deco16ic_0.control_w((direccion and $f) shr 1,valor);
$144000..$144fff:if deco16ic_0.pf1.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_0.pf1.data[(direccion and $fff) shr 1]:=valor;
deco16ic_0.pf1.buffer[(direccion and $fff) shr 1]:=true
end;
$146000..$146fff:if deco16ic_0.pf2.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_0.pf2.data[(direccion and $fff) shr 1]:=valor;
deco16ic_0.pf2.buffer[(direccion and $fff) shr 1]:=true
end;
$14c000..$14c7ff:deco16ic_0.pf1.rowscroll[(direccion and $7ff) shr 1]:=valor;
$14e000..$14e7ff:deco16ic_0.pf2.rowscroll[(direccion and $7ff) shr 1]:=valor;
$150000..$15000f:begin
deco16ic_1.control_w((direccion and $f) shr 1,valor);
if ((direccion and $f)=0) then main_screen.flip_main_screen:=(valor and $0080)<>0
end;
$154000..$154fff:if deco16ic_1.pf1.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_1.pf1.data[(direccion and $fff) shr 1]:=valor;
deco16ic_1.pf1.buffer[(direccion and $fff) shr 1]:=true
end;
$156000..$156fff:if deco16ic_1.pf2.data[(direccion and $fff) shr 1]<>valor then begin
deco16ic_1.pf2.data[(direccion and $fff) shr 1]:=valor;
deco16ic_1.pf2.buffer[(direccion and $fff) shr 1]:=true
end;
$15c000..$15c7ff:deco16ic_1.pf1.rowscroll[(direccion and $7ff) shr 1]:=valor;
$15e000..$15e7ff:deco16ic_1.pf2.rowscroll[(direccion and $7ff) shr 1]:=valor;
$180000..$1807ff:buffer_sprites_w[(direccion and $7ff) shr 1]:=valor;
$18c000..$18ffff:robocop2_protection_deco_146_w(direccion-$18c000,valor);
$198000..$198001:copymemory(@deco_sprites_0.ram[0],@buffer_sprites_w[0],$400*2);
$1a0002..$1a00ff:;
$1a8000..$1a9fff:if buffer_paleta[(direccion and $1fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $1fff) shr 1]:=valor;
cambiar_color((direccion and $1fff) shr 2);
end;
$1b0000..$1b0007:case ((direccion shr 1) and 7) of
0:irq_mask:=valor and $ff; // IRQ enable:
1:begin // Raster IRQ scanline position, only valid for values between 1 & 239 (0 and 240-256 do NOT generate IRQ's)
irq_line:=valor and $ff;
raster_irq:=(irq_line>0) and (irq_line<240) and ((irq_mask and $2)=0);
end;
end;
$1b8000..$1bbfff:ram[(direccion and $3fff) shr 1]:=valor;
$1f0000..$1f0001:if prioridad<>valor then begin
prioridad:=valor;
if (prioridad and 4)<>0 then begin
deco16ic_1.gfx_plane[2]:=4;
deco16ic_1.color_mask[2]:=0;
end else begin
deco16ic_1.gfx_plane[2]:=2;
deco16ic_1.color_mask[2]:=$f;
end;
fillchar(deco16ic_1.pf1.buffer[0],$800,1);
fillchar(deco16ic_1.pf2.buffer[0],$800,1);
end;
end;
end;
procedure sound_bank_rom(valor:byte);
begin
copymemory(oki_6295_1.get_rom_addr,@oki_rom[valor and 1],$40000);
end;
function cninja_video_bank(bank:word):word;
begin
if ((bank shr 4) and $f)<>0 then cninja_video_bank:=$0 //Only 2 banks
else cninja_video_bank:=$1000;
end;
function robocop2_video_bank(bank:word):word;
begin
robocop2_video_bank:=(bank and $30) shl 8;
end;
//Main
procedure reset_cninja;
begin
m68000_0.reset;
deco16ic_0.reset;
deco16ic_1.reset;
deco_sprites_0.reset;
case main_vars.tipo_maquina of
162:main_deco104.reset;
163:main_deco146.reset;
end;
deco16_snd_double_reset;
copymemory(oki_6295_1.get_rom_addr,@oki_rom[0],$40000);
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$f7;
irq_mask:=0;
raster_irq:=false;
end;
function iniciar_cninja:boolean;
const
pt_x:array[0..15] of dword=(32*8+0, 32*8+1, 32*8+2, 32*8+3, 32*8+4, 32*8+5, 32*8+6, 32*8+7,
0, 1, 2, 3, 4, 5, 6, 7);
pt_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16);
ps_x:array[0..15] of dword=(64*8+0, 64*8+1, 64*8+2, 64*8+3, 64*8+4, 64*8+5, 64*8+6, 64*8+7,
0, 1, 2, 3, 4, 5, 6, 7);
ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32);
var
memoria_temp,memoria_temp2,ptemp,ptemp2:pbyte;
tempw:word;
procedure cninja_convert_chars(num:word);
begin
init_gfx(0,8,8,num);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,16*8,num*16*8+8,num*16*8+0,8,0);
convert_gfx(0,0,memoria_temp,@pt_x[8],@pt_y,false,false);
end;
procedure cninja_convert_tiles(ngfx:byte;num:word);
begin
init_gfx(ngfx,16,16,num);
gfx[ngfx].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,num*64*8+8,num*64*8+0,8,0);
convert_gfx(ngfx,0,memoria_temp2,@pt_x,@pt_y,false,false);
end;
procedure cninja_convert_sprites(num:dword);
begin
init_gfx(3,16,16,num);
gfx[3].trans[0]:=true;
gfx_set_desc_data(4,0,128*8,16,0,24,8);
convert_gfx(3,0,memoria_temp,@ps_x,@ps_y,false,false);
end;
begin
llamadas_maquina.bucle_general:=cninja_principal;
llamadas_maquina.reset:=reset_cninja;
llamadas_maquina.fps_max:=58;
iniciar_cninja:=false;
iniciar_audio(false);
case main_vars.tipo_maquina of
162:begin
tempw:=256;
deco16ic_0:=chip_16ic.create(1,2,$000,$000,$f,$f,0,1,0,16,nil,nil);
deco16ic_1:=chip_16ic.create(3,4,$000,$200,$f,$f,0,2,0,48,cninja_video_bank,cninja_video_bank);
deco_sprites_0:=tdeco16_sprite.create(3,5,240,$300,$3fff);
end;
163:begin
tempw:=320;
deco16ic_0:=chip_16ic.create(1,2,$000,$000,$f,$f,0,1,0,16,nil,robocop2_video_bank);
deco16ic_1:=chip_16ic.create(3,4,$000,$200,$f,$f,0,2,0,48,robocop2_video_bank,robocop2_video_bank);
deco_sprites_0:=tdeco16_sprite.create(3,5,304,$300,$7fff);
end;
end;
screen_init(5,512,512,false,true);
iniciar_video(tempw,240);
//Sound CPU
deco16_snd_double_init(32220000 div 8,32220000,sound_bank_rom);
getmem(memoria_temp,$300000);
case main_vars.tipo_maquina of
162:begin //Caveman Ninja
//Main CPU
m68000_0:=cpu_m68000.create(12000000,$100);
m68000_0.change_ram16_calls(cninja_getword,cninja_putword);
proc_update_video:=update_video_cninja;
//cargar roms
if not(roms_load16w(@rom,cninja_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,cninja_sound)) then exit;
//OKIs rom
if not(roms_load(oki_6295_0.get_rom_addr,cninja_oki1)) then exit;
if not(roms_load(memoria_temp,cninja_oki2)) then exit;
ptemp:=memoria_temp;
copymemory(@oki_rom[0],ptemp,$40000);
inc(ptemp,$40000);
copymemory(@oki_rom[1],ptemp,$40000);
//convertir chars
if not(roms_load16b(memoria_temp,cninja_chars)) then exit;
cninja_convert_chars($1000);
//Tiles
getmem(memoria_temp2,$100000);
if not(roms_load(memoria_temp2,cninja_tiles1)) then exit;
cninja_convert_tiles(1,$1000);
if not(roms_load(memoria_temp,cninja_tiles2)) then exit;
//ordenar
ptemp:=memoria_temp2;
ptemp2:=memoria_temp;
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$80000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
ptemp:=memoria_temp2;
inc(ptemp,$40000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$80000);
copymemory(ptemp,ptemp2,$40000);
cninja_convert_tiles(2,$2000);
freemem(memoria_temp2);
//Sprites
if not(roms_load16b(memoria_temp,cninja_sprites)) then exit;
cninja_convert_sprites($4000);
//Proteccion deco104
main_deco104:=cpu_deco_104.create;
main_deco104.SET_USE_MAGIC_ADDRESS_XOR;
//Dip
marcade.dswa:=$7fff;
marcade.dswa_val:=@cninja_dip;
end;
163:begin //Robocop 2
//Main CPU
m68000_0:=cpu_m68000.create(14000000,$100);
m68000_0.change_ram16_calls(robocop2_getword,robocop2_putword);
proc_update_video:=update_video_robocop2;
//cargar roms
if not(roms_load16w(@rom,robocop2_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,robocop2_sound)) then exit;
//OKIs rom
if not(roms_load(oki_6295_0.get_rom_addr,robocop2_oki1)) then exit;
if not(roms_load(memoria_temp,robocop2_oki2)) then exit;
ptemp:=memoria_temp;
copymemory(@oki_rom[0],ptemp,$40000);
inc(ptemp,$40000);
copymemory(@oki_rom[1],ptemp,$40000);
//convertir chars
if not(roms_load16b(memoria_temp,robocop2_char)) then exit;
cninja_convert_chars($1000);
//Tiles
if not(roms_load(memoria_temp,robocop2_tiles1)) then exit;
getmem(memoria_temp2,$180000);
ptemp:=memoria_temp2;
ptemp2:=memoria_temp;
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$80000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
ptemp:=memoria_temp2;
inc(ptemp,$40000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$80000);
copymemory(ptemp,ptemp2,$40000);
cninja_convert_tiles(1,$2000);
//Tiles 2
if not(roms_load(memoria_temp,robocop2_tiles2)) then exit;
ptemp:=memoria_temp2;
ptemp2:=memoria_temp;
copymemory(ptemp,ptemp2,$40000);
inc(ptemp,$c0000);
inc(ptemp2,$40000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
ptemp:=memoria_temp2;
inc(ptemp,$40000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$c0000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
ptemp:=memoria_temp2;
inc(ptemp,$80000);
copymemory(ptemp,ptemp2,$40000);
inc(ptemp2,$40000);
inc(ptemp,$c0000);
copymemory(ptemp,ptemp2,$40000);
cninja_convert_tiles(2,$3000);
//Tiles 8bbp
init_gfx(4,16,16,$1000);
gfx[4].trans[0]:=true;
gfx_set_desc_data(8,0,64*8,$100000*8+8,$100000*8,$40000*8+8,$40000*8,$c0000*8+8,$c0000*8,8,0);
convert_gfx(4,0,memoria_temp2,@pt_x,@pt_y,false,false);
freemem(memoria_temp2);
//Sprites
if not(roms_load16b(memoria_temp,robocop2_sprites)) then exit;
cninja_convert_sprites($6000);
//Proteccion deco146
main_deco146:=cpu_deco_146.create;
main_deco146.SET_USE_MAGIC_ADDRESS_XOR;
//Dip
marcade.dswa:=$7fbf;
marcade.dswa_val:=@robocop2_dip_a;
marcade.dswb:=$ff;
marcade.dswb_val:=@robocop2_dip_b;
end;
end;
//final
freemem(memoria_temp);
reset_cninja;
iniciar_cninja:=true;
end;
end.
|
unit UAccountPreviousBlockInfo;
interface
uses
Classes, UAccountPreviousBlockInfoData;
type
{ TAccountPreviousBlockInfo }
TAccountPreviousBlockInfo = Class
private
FList : TList;
Function FindAccount(const account: Cardinal; var Index: Integer): Boolean;
function GetData(index : Integer): TAccountPreviousBlockInfoData;
public
Constructor Create;
Destructor Destroy; override;
Procedure UpdateIfLower(account, previous_updated_block : Cardinal);
Function Add(account, previous_updated_block : Cardinal) : Integer;
Procedure Remove(account : Cardinal);
Procedure Clear;
Procedure CopyFrom(Sender : TAccountPreviousBlockInfo);
Function IndexOfAccount(account : Cardinal) : Integer;
Property Data[index : Integer] : TAccountPreviousBlockInfoData read GetData;
Function GetPreviousUpdatedBlock(account : Cardinal; defaultValue : Cardinal) : Cardinal;
Function Count : Integer;
procedure SaveToStream(stream : TStream);
function LoadFromStream(stream : TStream) : Boolean;
end;
implementation
uses
SysUtils, UConst;
{ TAccountPreviousBlockInfo }
Type PAccountPreviousBlockInfoData = ^TAccountPreviousBlockInfoData;
function TAccountPreviousBlockInfo.FindAccount(const account: Cardinal; var Index: Integer): Boolean;
var L, H, I: Integer;
C : Int64;
P : PAccountPreviousBlockInfoData;
begin
Result := False;
L := 0;
H := FList.Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
P := FList[i];
C := Int64(P^.Account) - Int64(account);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
L := I;
end;
end;
end;
Index := L;
end;
function TAccountPreviousBlockInfo.GetData(index : Integer): TAccountPreviousBlockInfoData;
begin
Result := PAccountPreviousBlockInfoData(FList[index])^;
end;
constructor TAccountPreviousBlockInfo.Create;
begin
FList := TList.Create;
end;
destructor TAccountPreviousBlockInfo.Destroy;
begin
Clear;
FreeAndNil(FList);
inherited Destroy;
end;
procedure TAccountPreviousBlockInfo.UpdateIfLower(account, previous_updated_block: Cardinal);
Var P : PAccountPreviousBlockInfoData;
i : Integer;
begin
if (account>=CT_AccountsPerBlock) And (previous_updated_block=0) then Exit; // Only accounts 0..4 allow update on block 0
if Not FindAccount(account,i) then begin
New(P);
P^.Account:=account;
P^.Previous_updated_block:=previous_updated_block;
FList.Insert(i,P);
end else begin
P := FList[i];
If (P^.Previous_updated_block>previous_updated_block) then begin
P^.Previous_updated_block:=previous_updated_block;
end;
end
end;
function TAccountPreviousBlockInfo.Add(account, previous_updated_block: Cardinal): Integer;
Var P : PAccountPreviousBlockInfoData;
begin
if Not FindAccount(account,Result) then begin
New(P);
P^.Account:=account;
P^.Previous_updated_block:=previous_updated_block;
FList.Insert(Result,P);
end else begin
P := FList[Result];
P^.Previous_updated_block:=previous_updated_block;
end
end;
procedure TAccountPreviousBlockInfo.Remove(account: Cardinal);
Var i : Integer;
P : PAccountPreviousBlockInfoData;
begin
If FindAccount(account,i) then begin
P := FList[i];
FList.Delete(i);
Dispose(P);
end;
end;
procedure TAccountPreviousBlockInfo.Clear;
var P : PAccountPreviousBlockInfoData;
i : Integer;
begin
For i:=0 to FList.Count-1 do begin
P := FList[i];
Dispose(P);
end;
FList.Clear;
end;
procedure TAccountPreviousBlockInfo.CopyFrom(Sender: TAccountPreviousBlockInfo);
Var P : PAccountPreviousBlockInfoData;
i : Integer;
begin
if (Sender = Self) then Raise Exception.Create('ERROR DEV 20180312-4 Myself');
Clear;
For i:=0 to Sender.Count-1 do begin
New(P);
P^ := Sender.GetData(i);
FList.Add(P);
end;
end;
function TAccountPreviousBlockInfo.IndexOfAccount(account: Cardinal): Integer;
begin
If Not FindAccount(account,Result) then Result := -1;
end;
function TAccountPreviousBlockInfo.GetPreviousUpdatedBlock(account: Cardinal; defaultValue : Cardinal): Cardinal;
var i : Integer;
begin
i := IndexOfAccount(account);
If i>=0 then Result := GetData(i).Previous_updated_block
else Result := defaultValue;
end;
function TAccountPreviousBlockInfo.Count: Integer;
begin
Result := FList.Count;
end;
procedure TAccountPreviousBlockInfo.SaveToStream(stream: TStream);
var i : Integer;
c : Cardinal;
apbi : TAccountPreviousBlockInfoData;
begin
c := Count;
stream.Write(c,SizeOf(c)); // Save 4 bytes for count
for i:=0 to Count-1 do begin
apbi := GetData(i);
stream.Write(apbi.Account,SizeOf(apbi.Account)); // 4 bytes for account
stream.Write(apbi.Previous_updated_block,SizeOf(apbi.Previous_updated_block)); // 4 bytes for block number
end;
end;
function TAccountPreviousBlockInfo.LoadFromStream(stream: TStream): Boolean;
Var lastAcc,nposStreamStart : Int64;
c : Cardinal;
i : Integer;
apbi : TAccountPreviousBlockInfoData;
begin
Result := False;
clear;
nposStreamStart:=stream.Position;
Try
lastAcc := -1;
if (stream.Read(c,SizeOf(c))<SizeOf(c)) then Exit;
for i:=1 to c do begin
if stream.Read(apbi.Account,SizeOf(apbi.Account)) < SizeOf(apbi.Account) then Exit; // 4 bytes for account
if stream.Read(apbi.Previous_updated_block,SizeOf(apbi.Previous_updated_block)) < SizeOf(apbi.Previous_updated_block) then Exit; // 4 bytes for block number
if (lastAcc >= apbi.Account) then Exit;
Add(apbi.Account,apbi.Previous_updated_block);
lastAcc := apbi.Account;
end;
Result := True;
finally
if Not Result then stream.Position:=nposStreamStart;
end;
end;
end.
|
unit UIWrapper_StageUnit;
interface
uses
SearchOption_Intf, FMX.Controls, UIWrapper_SchOptPartUnit,
UIWrapper_StageEditorUnit, StageOptionPart, UIWrapper_LogSearchUnit;
type
TUIWrapper_SchOpt_Stage = class(TUIWrapper_AbsSearchOptionPart)
private
FChkAutoDetect: TCheckBox;
FStageEditor: TUIWrapper_StageEditor;
FLogSearch: TUIWrapper_LogSearch;
protected
procedure ChkAutoDetectCheckedChange(Sender: TObject);
public
constructor Create(owner: TExpander; autoDetect: TCheckBox;
stageEditor: TUIWrapper_StageEditor; logSearch: TUIWrapper_LogSearch);
function GetSearchOptionPart: ISearchOptionPart; override;
procedure SetAutoStageDetectionByDBMS(dbmsName: String);
function GetStageOptionList: TStageOptionList;
end;
implementation
{ TUIWrapper_SchOpt_Stage }
procedure TUIWrapper_SchOpt_Stage.ChkAutoDetectCheckedChange(Sender: TObject);
begin
FStageEditor.SetEnabled( not FChkAutoDetect.IsChecked );
FLogSearch.SetEnabled( not FChkAutoDetect.IsChecked );
end;
constructor TUIWrapper_SchOpt_Stage.Create(owner: TExpander; autoDetect: TCheckBox;
stageEditor: TUIWrapper_StageEditor; logSearch: TUIWrapper_LogSearch);
begin
Init( owner );
FChkAutoDetect := autoDetect;
FStageEditor := stageEditor;
FLogSearch := logSearch;
FChkAutoDetect.OnChange := ChkAutoDetectCheckedChange;
end;
function TUIWrapper_SchOpt_Stage.GetSearchOptionPart: ISearchOptionPart;
begin
result := FStageEditor.GetStageOption( 0 );
end;
function TUIWrapper_SchOpt_Stage.GetStageOptionList: TStageOptionList;
begin
result := FStageEditor.GetStageOptionList;
end;
procedure TUIWrapper_SchOpt_Stage.SetAutoStageDetectionByDBMS(dbmsName: String);
begin
if dbmsName = 'firebird' then
begin
FChkAutoDetect.Enabled := true;
FChkAutoDetect.IsChecked := true;
end
else
begin
FChkAutoDetect.Enabled := false;
FChkAutoDetect.IsChecked := false;
end;
end;
end.
|
{
Copyright (C) Alexey Torgashin, uvviewsoft.com
License: MPL 2.0 or LGPL
}
unit ATCanvasPrimitives;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics,
Types,
Math;
procedure CanvasInvertRect(C: TCanvas; const R: TRect; AColor: TColor);
implementation
var
_Pen: TPen = nil;
procedure CanvasInvertRect(C: TCanvas; const R: TRect; AColor: TColor);
var
X: integer;
AM: TAntialiasingMode;
begin
AM:= C.AntialiasingMode;
_Pen.Assign(C.Pen);
X:= (R.Left+R.Right) div 2;
//C.Pen.Mode:= {$ifdef darwin} pmNot {$else} pmNotXor {$endif};
C.Pen.Mode:= pmNotXor;
C.Pen.Style:= psSolid;
C.Pen.Color:= AColor;
C.AntialiasingMode:= amOff;
C.Pen.EndCap:= pecFlat;
C.Pen.Width:= R.Width;
C.MoveTo(X, R.Top);
C.LineTo(X, R.Bottom);
C.Pen.Assign(_Pen);
C.AntialiasingMode:= AM;
C.Rectangle(0, 0, 0, 0); //apply pen
end;
initialization
_Pen:= TPen.Create;
finalization
if Assigned(_Pen) then
FreeAndNil(_Pen);
end.
|
unit RenderReports;
interface
procedure ResetImgCount;
procedure ImgRendered(width, height : integer);
function GetImgCount : integer;
procedure EnableReports;
procedure DisableReports;
implementation
uses
Classes, SysUtils;
var
imgcount : integer = 0;
repsenabled : boolean = false;
minimgcount : integer = high(integer);
maximgcount : integer = 0;
totalimgcount : integer = 0;
widthssum : integer = 0;
heightssum : integer = 0;
runs : integer = 0;
procedure ResetImgCount;
begin
inc(totalimgcount, imgcount);
inc(runs);
if imgcount > 0
then
if imgcount < minimgcount
then minimgcount := imgcount
else
if imgcount > maximgcount
then maximgcount := imgcount;
imgcount := 0;
end;
procedure ImgRendered(width, height : integer);
begin
if repsenabled
then
begin
inc(imgcount);
inc(widthssum, width);
inc(heightssum, height);
end;
end;
function GetImgCount : integer;
begin
Result := imgcount;
end;
procedure EnableReports;
begin
repsenabled := true;
end;
procedure DisableReports;
begin
repsenabled := false;
end;
{$IFDEF RENDERREPORTS}
var
log : TStringList;
{$ENDIF}
initialization
finalization
{$IFDEF RENDERREPORTS}
log := TStringList.Create;
try
log.Add('Average rendered sprite size is (' + IntToStr(round(widthssum/totalimgcount)) + 'X' + IntToStr(round(heightssum/totalimgcount)) + ')');
log.Add('Average sprites rendered: ' + IntToStr(round(totalimgcount/runs)));
log.Add('Minimum sprites rendered: ' + IntToStr(minimgcount));
log.Add('Maximum sprites rendered: ' + IntToStr(maximgcount));
log.SaveToFile('RenderReport.log');
finally
log.Free;
end;
{$ENDIF}
end.
|
unit k2LogFont;
{ Библиотека "K-2" }
{ Автор: Люлин А.В. © }
{ Модуль: k2LogFont - }
{ Начат: 16.01.2006 19:19 }
{ $Id: k2LogFont.pas,v 1.5 2008/02/21 13:48:21 lulin Exp $ }
// $Log: k2LogFont.pas,v $
// Revision 1.5 2008/02/21 13:48:21 lulin
// - cleanup.
//
// Revision 1.4 2007/12/05 12:35:08 lulin
// - вычищен условный код, составлявший разницу ветки и Head'а.
//
// Revision 1.3 2006/11/03 11:00:44 lulin
// - объединил с веткой 6.4.
//
// Revision 1.2.14.1 2006/10/26 09:10:21 lulin
// - используем "родную" директиву.
//
// Revision 1.2 2006/01/18 10:51:18 lulin
// - bug fix: не компилировалось.
//
// Revision 1.1 2006/01/16 16:41:44 lulin
// - сделана возможность работать со строками без теговых оберток (почему-то на производительность не повлияло).
//
{$Include k2Define.inc }
interface
uses
l3Types,
l3Base,
l3Font,
k2Interfaces,
k2Base
;
type
_Parent_ = Tl3LogFont;
{.$Define k2TagIsList}
{$Define k2TagIsString}
{$Include k2Tag.int}
Tk2LogFont = class(_Tag_)
public
// public methods
constructor Create(aTagType: Tk2Type);
reintroduce;
{-}
procedure AssignString(aStr: Tl3CustomString);
override;
{-}
end;//Tk2LogFont
implementation
uses
TypInfo,
Classes,
SysUtils,
l3String,
l3Stream,
k2Const,
k2Except,
k2Tags
;
{$Include k2Tag.int}
constructor Tk2LogFont.Create(aTagType: Tk2Type);
//reintroduce;
{-}
begin
f_TagType := aTagType;
inherited Create;
end;
procedure Tk2LogFont.AssignString(aStr: Tl3CustomString);
//override;
{-}
begin
inherited;
if (f_TagType = nil) AND (aStr Is Tk2LogFont) then
f_TagType := Tk2LogFont(aStr).TagType;
end;
end.
|
unit InfGastos;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ppCtrls, ppPrnabl, ppClass, ppBands, ppProd, ppReport, ppComm, ppCache,
ppDB, ppDBBDE, Db, DBTables;
type
TFInfGastos = class(TForm)
Query1: TQuery;
DataSource1: TDataSource;
ppBDEPipeline1: TppBDEPipeline;
ppR: TppReport;
ppRHeaderBand1: TppHeaderBand;
ppRDetailBand1: TppDetailBand;
ppRFooterBand1: TppFooterBand;
Empresa: TppLabel;
ppRDBText1: TppDBText;
ppRDBText2: TppDBText;
ppRDBText3: TppDBText;
ppRLabel1: TppLabel;
ppRLabel2: TppLabel;
ppRLabel3: TppLabel;
ppRLabel4: TppLabel;
ppRDBCalc1: TppDBCalc;
TDatos: TTable;
ppRCalc1: TppCalc;
ppRSummaryBand1: TppSummaryBand;
ppRLabel5: TppLabel;
ppRShape1: TppShape;
ppRCalc2: TppCalc;
Fechas: TppLabel;
procedure FormCreate(Sender: TObject);
procedure EmpresaPrint(Sender: TObject);
procedure FechasPrint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FInfGastos: TFInfGastos;
implementation
{$R *.DFM}
procedure TFInfGastos.FormCreate(Sender: TObject);
begin
TDatos.Open;
end;
procedure TFInfGastos.EmpresaPrint(Sender: TObject);
begin
Empresa.Caption := TDatos.FieldByName( 'DENOMINA' ).AsString;
end;
procedure TFInfGastos.FechasPrint(Sender: TObject);
begin
Fechas.Caption := 'Entre el: ' + DateToStr( Query1.ParamByName( 'FecIni' ).AsDateTime ) +
' y el ' + DateToStr( Query1.ParamByName( 'FecFin' ).AsDateTime );
end;
end.
|
unit TestFftw3_80;
interface
uses
{$IFNDEF FPC}
TestFramework,
{$ELSE}
FPCUnit, TestUtils, TestRegistry,
{$ENDIF}
Fftw3_Common, Classes, SysUtils, Fftw3_80;
const
CFFTSize = 8192;
type
TestTFftw80Dft = class(TTestCase)
strict private
FFftw80Dft: TFftw80Dft;
FInput, FOutput: PFftw80Complex;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecuteSplit;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80DftReal2Complex = class(TTestCase)
strict private
FFftw80DftReal2Complex: TFftw80DftReal2Complex;
FInput: PFftw80Real;
FOutput: PFftw80Complex;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecuteSplit;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80DftComplex2Real = class(TTestCase)
strict private
FFftw80DftComplex2Real: TFftw80DftComplex2Real;
FInput: PFftw80Complex;
FOutput: PFftw80Real;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecuteSplit;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80Real2Real = class(TTestCase)
strict private
FFftw80Real2Real: TFftw80Real2Real;
FInput, FOutput: PFftw80Real;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80Guru = class(TTestCase)
strict private
FFftw80Guru: TFftw80Guru;
FInput, FOutput: PFftw80Complex;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecuteSplit;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80Guru64 = class(TTestCase)
strict private
FFftw80Guru64: TFftw80Guru64;
FInput, FOutput: PFftw80Complex;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecuteSplit;
procedure TestGetFlops;
procedure TestGetCost;
end;
TestTFftw80Wisdom = class(TTestCase)
private
FDataStream: TMemoryStream;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestForgetWisdom;
procedure TestImportExportToFilename;
procedure TestImportExportToString;
procedure TestImportExport;
procedure TestImportSystem;
end;
implementation
{ TestTFftw80Dft }
procedure TestTFftw80Dft.SetUp;
begin
// allocate memory
FInput := Fftw80AllocComplex(CFFTSize);
FOutput := Fftw80AllocComplex(CFFTSize);
// create plan
FFftw80Dft := TFftw80Dft.Create(CFFTSize, FInput, FOutput, fsForward, [ffEstimate]);
end;
procedure TestTFftw80Dft.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
// destroy FFT
FFftw80Dft.Free;
FFftw80Dft := nil;
end;
procedure TestTFftw80Dft.TestExecute;
begin
// perform FFT
FFftw80Dft.Execute(FInput, FOutput);
// perform FFT (again)
FFftw80Dft.Execute(FInput, FOutput);
end;
procedure TestTFftw80Dft.TestExecuteSplit;
var
Ii, Ri, Io, Ro: PFftw80Real;
begin
Ri := PFftw80Real(FInput);
Ii := PFftw80Real(FInput);
Ro := PFftw80Real(FOutput);
Io := PFftw80Real(FOutput);
// perform FFT
FFftw80Dft.Execute(Ri, Ii, Ro, Io);
// perform FFT (again)
FFftw80Dft.Execute(Ri, Ii, Ro, Io);
end;
procedure TestTFftw80Dft.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80Dft.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80Dft.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80Dft.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80DftReal2Complex }
procedure TestTFftw80DftReal2Complex.SetUp;
begin
// allocate memory
FInput := Fftw80AllocReal(CFFTSize);
FOutput := Fftw80AllocComplex(CFFTSize);
// create plan
FFftw80DftReal2Complex := TFftw80DftReal2Complex.Create(CFFTSize, FInput,
FOutput, [ffEstimate]);
end;
procedure TestTFftw80DftReal2Complex.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
// destroy FFT
FFftw80DftReal2Complex.Free;
FFftw80DftReal2Complex := nil;
end;
procedure TestTFftw80DftReal2Complex.TestExecute;
begin
// perform FFT
FFftw80DftReal2Complex.Execute(FInput, FOutput);
// repeat FFT
FFftw80DftReal2Complex.Execute(FInput, FOutput);
end;
procedure TestTFftw80DftReal2Complex.TestExecuteSplit;
var
&In, Ro, Io: PFftw80Real;
begin
&In := PFftw80Real(FInput);
Ro := PFftw80Real(FOutput);
Io := PFftw80Real(FOutput);
// perform FFT
FFftw80DftReal2Complex.Execute(&In, Ro, Io);
// perform FFT (again)
FFftw80DftReal2Complex.Execute(&In, Ro, Io);
end;
procedure TestTFftw80DftReal2Complex.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80DftReal2Complex.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80DftReal2Complex.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80DftReal2Complex.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80DftComplex2Real }
procedure TestTFftw80DftComplex2Real.SetUp;
begin
// allocate memory
FInput := Fftw80AllocComplex(CFFTSize);
FOutput := Fftw80AllocReal(CFFTSize);
// create plan
FFftw80DftComplex2Real := TFftw80DftComplex2Real.Create(CFFTSize, FInput,
FOutput, [ffEstimate]);
end;
procedure TestTFftw80DftComplex2Real.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
// destroy FFT
FFftw80DftComplex2Real.Free;
FFftw80DftComplex2Real := nil;
end;
procedure TestTFftw80DftComplex2Real.TestExecute;
begin
// perform FFT
FFftw80DftComplex2Real.Execute(FInput, FOutput);
// repeat FFT
FFftw80DftComplex2Real.Execute(FInput, FOutput);
end;
procedure TestTFftw80DftComplex2Real.TestExecuteSplit;
var
Ri, Ii, &Out: PFftw80Real;
begin
Ri := PFftw80Real(FInput);
Ii := PFftw80Real(FInput);
&Out := PFftw80Real(FOutput);
// perform FFT
FFftw80DftComplex2Real.Execute(Ri, Ii, &Out);
// perform FFT (again)
FFftw80DftComplex2Real.Execute(Ri, Ii, &Out);
end;
procedure TestTFftw80DftComplex2Real.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80DftComplex2Real.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80DftComplex2Real.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80DftComplex2Real.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80Real2Real }
procedure TestTFftw80Real2Real.SetUp;
begin
// allocate memory
FInput := Fftw80AllocReal(CFFTSize);
FOutput := Fftw80AllocReal(CFFTSize);
// create plan
FFftw80Real2Real := TFftw80Real2Real.Create(CFFTSize, FInput, FOutput,
fkDiscreteHartleyTransform, [ffEstimate]);
end;
procedure TestTFftw80Real2Real.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
FFftw80Real2Real.Free;
FFftw80Real2Real := nil;
end;
procedure TestTFftw80Real2Real.TestExecute;
begin
// perform FFT
FFftw80Real2Real.Execute(FInput, FOutput);
// repeat FFT
FFftw80Real2Real.Execute(FInput, FOutput);
end;
procedure TestTFftw80Real2Real.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80Real2Real.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80Real2Real.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80Real2Real.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80Guru }
procedure TestTFftw80Guru.SetUp;
var
Dim: TFftwIoDim;
begin
// allocate memory
FInput := Fftw80AllocComplex(CFFTSize);
FOutput := Fftw80AllocComplex(CFFTSize);
// create plan
FFftw80Guru := TFftw80Guru.Create(CFFTSize, @Dim, 1, @Dim, FInput,
FOutput, fsForward, [ffEstimate]);
end;
procedure TestTFftw80Guru.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
// destroy FFT
FFftw80Guru.Free;
FFftw80Guru := nil;
end;
procedure TestTFftw80Guru.TestExecute;
begin
// perform FFT
FFftw80Guru.Execute(FInput, FOutput);
// perform FFT (again)
FFftw80Guru.Execute(FInput, FOutput);
end;
procedure TestTFftw80Guru.TestExecuteSplit;
var
Ii, Ri, Io, Ro: PFftw80Real;
begin
Ri := PFftw80Real(FInput);
Ii := PFftw80Real(FInput);
Ro := PFftw80Real(FOutput);
Io := PFftw80Real(FOutput);
// perform FFT
FFftw80Guru.Execute(Ri, Ii, Ro, Io);
// perform FFT (again)
FFftw80Guru.Execute(Ri, Ii, Ro, Io);
end;
procedure TestTFftw80Guru.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80Guru.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80Guru.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80Guru.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80Guru64 }
procedure TestTFftw80Guru64.SetUp;
var
Dim: TFftwIoDim;
begin
// allocate memory
FInput := Fftw80AllocComplex(CFFTSize);
FOutput := Fftw80AllocComplex(CFFTSize);
// create plan
FFftw80Guru64 := TFftw80Guru64.Create(CFFTSize, @Dim, 1, @Dim, FInput,
FOutput, fsForward, [ffEstimate]);
end;
procedure TestTFftw80Guru64.TearDown;
begin
// free memory
Fftw80Free(FOutput);
FOutput := nil;
Fftw80Free(FInput);
FInput := nil;
// destroy FFT
FFftw80Guru64.Free;
FFftw80Guru64 := nil;
end;
procedure TestTFftw80Guru64.TestExecute;
begin
// perform FFT
FFftw80Guru64.Execute(FInput, FOutput);
// perform FFT (again)
FFftw80Guru64.Execute(FInput, FOutput);
end;
procedure TestTFftw80Guru64.TestExecuteSplit;
var
Ii, Ri, Io, Ro: PFftw80Real;
begin
Ri := PFftw80Real(FInput);
Ii := PFftw80Real(FInput);
Ro := PFftw80Real(FOutput);
Io := PFftw80Real(FOutput);
// perform FFT
FFftw80Guru64.Execute(Ri, Ii, Ro, Io);
// perform FFT (again)
FFftw80Guru64.Execute(Ri, Ii, Ro, Io);
end;
procedure TestTFftw80Guru64.TestGetFlops;
var
Add, Mul, FMA: Double;
begin
FFftw80Guru64.GetFlops(Add, Mul, FMA);
CheckTrue(Add > 0);
CheckTrue(Mul > 0);
CheckTrue(FMA > 0);
end;
procedure TestTFftw80Guru64.TestGetCost;
var
Cost: Double;
begin
Cost := FFftw80Guru64.GetCost;
CheckTrue(Cost >= 0);
end;
{ TestTFftw80Wisdom }
procedure TestTFftw80Wisdom.SetUp;
begin
end;
procedure TestTFftw80Wisdom.TearDown;
begin
end;
procedure TestTFftw80Wisdom.TestForgetWisdom;
begin
TFftw80Wisdom.ForgetWisdom;
end;
procedure TestTFftw80Wisdom.TestImportExportToFilename;
var
ReturnValue: Boolean;
begin
ReturnValue := TFftw80Wisdom.ExportToFilename('Wisdom.wsd');
CheckTrue(ReturnValue);
ReturnValue := TFftw80Wisdom.ImportFromFilename('Wisdom.wsd');
CheckTrue(ReturnValue);
end;
procedure TestTFftw80Wisdom.TestImportExportToString;
var
Wisdom: AnsiString;
ReturnValue: Boolean;
begin
Wisdom := TFftw80Wisdom.ExportToString;
CheckTrue(Wisdom <> '');
ReturnValue := TFftw80Wisdom.ImportFromString(Wisdom);
CheckTrue(ReturnValue);
end;
procedure FftwWriteCharFunc(c: AnsiChar; Ptr: Pointer); cdecl;
begin
Assert(TObject(Ptr) is TestTFftw80Wisdom);
TestTFftw80Wisdom(Ptr).FDataStream.Write(C, 1);
end;
function FftwReadCharFunc(Ptr: Pointer): PAnsiChar; cdecl;
begin
Assert(TObject(Ptr) is TestTFftw80Wisdom);
Result := TestTFftw80Wisdom(Ptr).FDataStream.Memory;
end;
procedure TestTFftw80Wisdom.TestImportExport;
var
ReturnValue: Integer;
begin
FDataStream := TMemoryStream.Create;
try
TFftw80Wisdom.Export(FftwWriteCharFunc, Self);
CheckTrue(FDataStream.Size > 0);
FDataStream.Position := 0;
ReturnValue := TFftw80Wisdom.Import(FftwReadCharFunc, Self);
CheckEquals(0, ReturnValue);
finally
FDataStream.Free;
end;
end;
procedure TestTFftw80Wisdom.TestImportSystem;
var
ReturnValue: Integer;
begin
ReturnValue := TFftw80Wisdom.ImportSystem;
CheckEquals(0, ReturnValue);
end;
initialization
RegisterTest('Fftw80', TestTFftw80Dft.Suite);
RegisterTest('Fftw80', TestTFftw80DftReal2Complex.Suite);
RegisterTest('Fftw80', TestTFftw80DftComplex2Real.Suite);
RegisterTest('Fftw80', TestTFftw80Real2Real.Suite);
(*
RegisterTest('Fftw80', TestTFftw80Guru.Suite);
RegisterTest('Fftw80', TestTFftw80Guru64.Suite);
*)
RegisterTest('Fftw80', TestTFftw80Wisdom.Suite);
end.
|
unit GetConfigValueResponseUnit;
interface
uses
REST.Json.Types, SysUtils,
NullableBasicTypesUnit, GenericParametersUnit, JSONNullableAttributeUnit, CommonTypesUnit;
type
TConfigValue = class
private
[JSONName('member_id')]
[Nullable]
FMemberId: NullableInteger;
[JSONName('config_key')]
FConfigKey: String;
[JSONName('config_value')]
FConfigValue: String;
public
constructor Create;
property MemberId: NullableInteger read FMemberId;
property Key: String read FConfigKey;
property Value: String read FConfigValue;
function AsStringPair: TStringPair;
end;
TConfigValueArray = TArray<TConfigValue>;
TGetConfigValueResponse = class(TGenericParameters)
private
[JSONName('result')]
[Nullable]
FResult: NullableString;
[JSONName('data')]
[NullableArray(TConfigValue)]
FConfigValues: TConfigValueArray;
public
constructor Create;
destructor Destroy; override;
property Result: NullableString read FResult;
property ConfigValues: TConfigValueArray read FConfigValues;
end;
implementation
{ TGetConfigValueResponse }
constructor TGetConfigValueResponse.Create;
begin
FResult := NullableString.Null;
SetLength(FConfigValues, 0);
end;
destructor TGetConfigValueResponse.Destroy;
var
i: integer;
begin
for i := Length(FConfigValues) - 1 downto 0 do
FreeAndNil(FConfigValues[i]);
inherited;
end;
{ TConfigValue }
function TConfigValue.AsStringPair: TStringPair;
begin
Result := TStringPair.Create(FConfigKey, FConfigValue);
end;
constructor TConfigValue.Create;
begin
FMemberId := NullableInteger.Null;
end;
end.
|
{
*****************************************************************************
* *
* See the file COPYING.modifiedLGPL, included in this distribution, *
* for details about the copyright. *
* *
* 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. *
* *
*****************************************************************************
}
unit registermultilog;
{$Mode ObjFpc}
{$H+}
interface
uses
Classes, SysUtils, LResources, LazarusPackageIntf, logtreeview;
procedure Register;
implementation
procedure RegisterUnitLogTreeView;
begin
RegisterComponents('MultiLog',[TLogTreeView]);
end;
procedure Register;
begin
RegisterUnit('logtreeview',@RegisterUnitLogTreeView);
end;
initialization
{$i icons.lrs}
end.
|
program simplechrono;
uses
SysUtils,
DateUtils,
Quick.Commons,
Quick.Console,
Quick.Chrono;
var
crono : TChronometer;
starttime : TDateTime;
ms : Int64;
begin
try
Console.LogVerbose := LOG_ALL;
cout('Chrono Test',etInfo);
crono := TChronometer.Create;
crono.Start;
starttime := Now();
repeat
ms := MillisecondsBetween(Now(),StartTime);
until ms >= 4000;
crono.Stop;
cout('crono stopped!',etInfo);
cout('Loop: %d Elapsed: %s',[ms,crono.ElapsedTime],etInfo);
Readln;
except
on e : Exception do WriteLn(e.message);
end;
end.
|
// --------------------------------------------------------------------------
// Archivo del Proyecto Ventas
// Página del proyecto: http://sourceforge.net/projects/ventas
// --------------------------------------------------------------------------
// Este archivo puede ser distribuido y/o modificado bajo lo terminos de la
// Licencia Pública General versión 2 como es publicada por la Free Software
// Fundation, Inc.
// --------------------------------------------------------------------------
unit ReportesArticulos;
interface
uses
SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QButtons, QExtCtrls, IniFiles, rpcompobase, rpclxreport,
QcurrEdit;
type
TfrmReportesArticulos = class(TForm)
rgpOrden: TRadioGroup;
grpDeptos: TGroupBox;
lblDesde: TLabel;
lblHasta: TLabel;
pnlCateg: TPanel;
cmbCategIni: TComboBox;
cmbCategFin: TComboBox;
pnlCodigo: TPanel;
txtCodigoIni: TEdit;
txtCodigoFin: TEdit;
pnlProveedor1: TPanel;
txtProvIni1: TEdit;
txtProvFin1: TEdit;
pnlDescrip: TPanel;
txtDescripIni: TEdit;
txtDescripFin: TEdit;
pnlDepto: TPanel;
cmbDeptoIni: TComboBox;
cmbDeptoFin: TComboBox;
rdoTodo: TRadioButton;
rdoRango: TRadioButton;
btnImprimir: TBitBtn;
rptReportes: TCLXReport;
btnCancelar: TBitBtn;
chkPreliminar: TCheckBox;
Label4: TLabel;
pnlProveedor2: TPanel;
txtProvIni2: TEdit;
txtProvFin2: TEdit;
chkDesglozar: TCheckBox;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rgpOrdenClick(Sender: TObject);
procedure rdoTodoClick(Sender: TObject);
procedure cmbDeptoIniSelect(Sender: TObject);
procedure Numero (Sender: TObject; var Key: Char);
procedure btnCancelarClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure chkPreliminarClick(Sender: TObject);
procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
private
procedure RecuperaConfig;
procedure CargaCombos;
function VerificaDatos : boolean;
function VerificaRangos : boolean;
procedure ImprimeArtiCateg;
procedure ImprimeArtiCodigo;
procedure ImprimeArtiDepto;
procedure ImprimeArtiDescrip;
procedure ImprimeArtiProv1;
procedure ImprimeArtiProv2;
public
end;
var
frmReportesArticulos: TfrmReportesArticulos;
implementation
uses dm;
{$R *.xfm}
procedure TfrmReportesArticulos.FormShow(Sender: TObject);
begin
CargaCombos;
rgpOrdenClick(Sender);
rdoTodoClick(Sender);
end;
procedure TfrmReportesArticulos.CargaCombos;
begin
cmbCategIni.Clear;
cmbCategFin.Clear;
cmbDeptoIni.Clear;
cmbDeptoFin.Clear;
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT nombre FROM categorias WHERE tipo =''A'' ORDER BY nombre');
Open;
while(not EOF) do begin
cmbCategIni.Items.Add(FieldByName('nombre').AsString);
cmbCategFin.Items.Add(FieldByName('nombre').AsString);
Next;
end;
Close;
SQL.Clear;
SQL.Add('SELECT nombre FROM departamentos ORDER BY nombre');
Open;
while(not EOF) do begin
cmbDeptoIni.Items.Add(FieldByName('nombre').AsString);
cmbDeptoFin.Items.Add(FieldByName('nombre').AsString);
Next;
end;
Close;
end;
cmbCategIni.ItemIndex := 0;
cmbCategFin.ItemIndex := 0;
cmbDeptoIni.ItemIndex := 0;
cmbDeptoFin.ItemIndex := 0;
end;
procedure TfrmReportesArticulos.RecuperaConfig;
var
iniArchivo : TIniFile;
sIzq, sArriba, sValor : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
//Recupera la posición Y de la ventana
sArriba := ReadString('RepArticulos', 'Posy', '');
//Recupera la posición X de la ventana
sIzq := ReadString('RepArticulos', 'Posx', '');
if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin
Left := StrToInt(sIzq);
Top := StrToInt(sArriba);
end;
//Recupera la posición de los botones de radio
sValor := ReadString('RepArticulos', 'Tipo', '');
if (Length(sValor) > 0) then
rgpOrden.ItemIndex := StrToInt(sValor);
Free;
end;
end;
procedure TfrmReportesArticulos.FormClose(Sender: TObject; var Action: TCloseAction);
var iniArchivo : TIniFile;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
// Registra la posición y de la ventana
WriteString('RepArticulos', 'Posy', IntToStr(Top));
// Registra la posición X de la ventana
WriteString('RepArticulos', 'Posx', IntToStr(Left));
// Registra la posición de los botones de radio
WriteString('RepArticulos', 'Tipo', IntToStr(rgpOrden.ItemIndex));
Free;
end;
end;
procedure TfrmReportesArticulos.rgpOrdenClick(Sender: TObject);
begin
pnlCateg.Visible := false;
pnlCodigo.Visible := false;
pnlDepto.Visible := false;
pnlDescrip.Visible := false;
pnlProveedor1.Visible := false;
pnlProveedor2.Visible := false;
case rgpOrden.ItemIndex of
0: pnlCateg.Visible := true;
1: pnlCodigo.Visible := true;
2: pnlDepto.Visible := true;
3: pnlDescrip.Visible := true;
4: pnlProveedor1.Visible := true;
5: pnlProveedor2.Visible := true;
end;
end;
procedure TfrmReportesArticulos.rdoTodoClick(Sender: TObject);
begin
if(rdoTodo.Checked) then begin
lblDesde.Enabled := false;
lblHasta.Enabled := false;
txtCodigoIni.Enabled := false;
txtCodigoFin.Enabled := false;
cmbCategIni.Enabled := false;
cmbCategFin.Enabled := false;
cmbDeptoIni.Enabled := false;
cmbDeptoFin.Enabled := false;
txtDescripIni.Enabled := false;
txtDescripFin.Enabled := false;
txtProvIni1.Enabled := false;
txtProvFin1.Enabled := false;
txtProvIni2.Enabled := false;
txtProvFin2.Enabled := false;
end
else begin
lblDesde.Enabled := true;
lblHasta.Enabled := true;
txtCodigoIni.Enabled := true;
txtCodigoFin.Enabled := true;
cmbCategIni.Enabled := true;
cmbCategFin.Enabled := true;
cmbDeptoIni.Enabled := true;
cmbDeptoFin.Enabled := true;
txtDescripIni.Enabled := true;
txtDescripFin.Enabled := true;
txtProvIni1.Enabled := true;
txtProvFin1.Enabled := true;
txtProvIni2.Enabled := true;
txtProvFin2.Enabled := true;
end;
end;
procedure TfrmReportesArticulos.cmbDeptoIniSelect(Sender: TObject);
begin
if(cmbDeptoFin.ItemIndex < cmbDeptoIni.ItemIndex) then
cmbDeptoFin.ItemIndex := cmbDeptoIni.ItemIndex;
end;
procedure TfrmReportesArticulos.Numero(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9',#8]) then
Key := #0;
end;
procedure TfrmReportesArticulos.btnCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TfrmReportesArticulos.chkPreliminarClick(Sender: TObject);
begin
rptReportes.Preview := chkPreliminar.Checked;
end;
procedure TfrmReportesArticulos.btnImprimirClick(Sender: TObject);
begin
if VerificaDatos then
case rgpOrden.ItemIndex of
0: ImprimeArtiCateg;
1: ImprimeArtiCodigo;
2: ImprimeArtiDepto;
3: ImprimeArtiDescrip;
4: ImprimeArtiProv1;
5: ImprimeArtiProv2;
end;
end;
function TfrmReportesArticulos.VerificaDatos : boolean;
var
bResult : boolean;
begin
bResult:= true;
if not VerificaRangos then
bResult := false;
Result := bResult;
end;
function TfrmReportesArticulos.VerificaRangos : boolean;
var
bResult : boolean;
begin
bResult:= true;
if rdoRango.Checked then
case rgpOrden.ItemIndex of
0 : if (Length(cmbCategIni.Text)=0) or (Length(cmbCategFin.Text)=0) then
bResult := false;
1 : if (Length(txtCodigoIni.Text)=0) or (Length(txtCodigoFin.Text)=0) then
bResult := false;
2 : if (Length(cmbDeptoIni.Text)=0) or (Length(cmbDeptoFin.Text)=0) then
bResult := false;
3 : if (Length(txtDescripIni.Text)=0) or (Length(txtDescripFin.Text)=0) then
bResult := false;
4 : if (Length(txtProvIni1.Text)=0) or (Length(txtProvFin1.Text)=0) then
bResult := false;
5 : if (Length(txtProvIni2.Text)=0) or (Length(txtProvFin2.Text)=0) then
bResult := false;
end;
if not bResult then
Application.MessageBox('Introduce un rango válido','Error',[smbOK],smsCritical);
Result := bResult
end;
procedure TfrmReportesArticulos.ImprimeArtiCateg;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosCategoria', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('CATEGINI').AsString := '';
rptReportes.Report.Params.ParamByName('CATEGFIN').AsString := 'ZZZZZZZZZZZZZZZ';
end
else begin
rptReportes.Report.Params.ParamByName('CATEGINI').AsString := cmbCategIni.Text;
rptReportes.Report.Params.ParamByName('CATEGFIN').AsString := cmbCategFin.Text;
end;
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.ImprimeArtiCodigo;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosCodigo', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('CODIGOINI').AsString := '';
rptReportes.Report.Params.ParamByName('CODIGOFIN').AsString := 'ZZZZZZZZZZZZZ';
end
else begin
rptReportes.Report.Params.ParamByName('CODIGOINI').AsString := txtCodigoIni.Text;
rptReportes.Report.Params.ParamByName('CODIGOFIN').AsString := txtCodigoFin.Text;
end;
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.ImprimeArtiDepto;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosDepartamento', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('DEPTOINI').AsString := '';
rptReportes.Report.Params.ParamByName('DEPTOFIN').AsString := 'ZZZZZZZZZZZZZ';
end
else begin
rptReportes.Report.Params.ParamByName('DEPTOINI').AsString := cmbDeptoIni.Text;
rptReportes.Report.Params.ParamByName('DEPTOFIN').AsString := cmbDeptoFin.Text;
end;
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.ImprimeArtiDescrip;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosDescripcion', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('DESCRIPINI').AsString := '';
rptReportes.Report.Params.ParamByName('DESCRIPFIN').AsString := 'ZZZZZZZZZZZZZ';
end
else begin
rptReportes.Report.Params.ParamByName('DESCRIPINI').AsString := txtDescripIni.Text;
rptReportes.Report.Params.ParamByName('DESCRIPFIN').AsString := txtDescripFin.Text;
end;
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.ImprimeArtiProv1;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosProveedor1', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('PROVINI').AsString := '1';
rptReportes.Report.Params.ParamByName('PROVFIN').AsString := '9999';
end
else begin
rptReportes.Report.Params.ParamByName('PROVINI').AsString := txtProvIni1.Text;
rptReportes.Report.Params.ParamByName('PROVFIN').AsString := txtProvFin1.Text;
end;
if(chkDesglozar.Checked) then
rptReportes.Report.Params.ParamByName('DESGLOCEJUEGO').AsString := 'S'
else
rptReportes.Report.Params.ParamByName('DESGLOCEJUEGO').AsString := 'N';
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.ImprimeArtiProv2;
var
iniArchivo : TIniFile;
sArchivo : String;
sDirReportes : String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', '');
if not (Length(sDirReportes) > 0) then
sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\';
sArchivo := iniArchivo.ReadString('Reportes', 'ArticulosProveedor2', '');
if (Length(sArchivo) > 0) then begin
rptReportes.FileName := sDirReportes + sArchivo;
rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection;
if(rdoTodo.Checked) then begin
rptReportes.Report.Params.ParamByName('PROVINI').AsString := '1';
rptReportes.Report.Params.ParamByName('PROVFIN').AsString := '9999';
end
else begin
rptReportes.Report.Params.ParamByName('PROVINI').AsString := txtProvIni2.Text;
rptReportes.Report.Params.ParamByName('PROVFIN').AsString := txtProvFin2.Text;
end;
rptReportes.Execute;
end
else
Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical);
end;
procedure TfrmReportesArticulos.Salta(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)}
if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then
if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then
SelectNext(Sender as TWidgetControl, true, true);
end;
procedure TfrmReportesArticulos.FormCreate(Sender: TObject);
begin
RecuperaConfig;
end;
end.
|
{$mode objfpc} { Directive for defining classes }
{$m+} { Directive for using constructor }
program PascalProgram37;
uses crt, math; { e.g. crt enables `readkey`; math - `power`, `abs` etc }
{ class Vector }
type
array_of_double_type = array of double;
type
VectorClass = class
private
_size : integer;
_elements : array_of_double_type;
procedure create_elements(size : integer);
public
constructor create(size : integer);
function get_size() : integer;
procedure set_element(element : double; index : integer);
function get_element(index : integer) : double;
function get_elements() : array_of_double_type;
end;
constructor VectorClass.create(size : integer);
begin
_size := size;
create_elements(size);
end;
procedure VectorClass.create_elements(size : integer);
begin
setlength(_elements, size); { std procedure to set length of dynamic array }
end;
function VectorClass.get_size() : integer;
begin
get_size := _size;
end;
procedure VectorClass.set_element(element : double; index : integer);
begin
_elements[index] := element;
end;
function VectorClass.get_element(index : integer) : double;
begin
get_element := _elements[index];
end;
function VectorClass.get_elements() : array_of_double_type;
begin
get_elements := _elements;
end;
{ ---------------------------------------------------------------------------- }
{ class SquareMatrix }
type
array_of_vectors_type = array of VectorClass;
type
SquareMatrixClass = class
private
_size : integer;
_rows : array_of_vectors_type;
procedure create_rows(size : integer);
public
constructor create(size : integer);
function get_size() : integer;
procedure set_row(row : VectorClass; index : integer);
function get_row(index : integer) : VectorClass;
function get_rows() : array_of_vectors_type;
procedure set_element(
element : double;
row_index : integer;
column_index : integer
);
function get_element(
row_index : integer;
column_index : integer
) : double;
function construct_transposed_martix() : SquareMatrixClass;
end;
constructor SquareMatrixClass.create(size : integer);
begin
_size := size;
create_rows(size);
end;
procedure SquareMatrixClass.create_rows(size : integer);
var
i : integer;
begin
setlength(_rows, size); { std procedure to set length of dynamic array }
for i := 0 to size - 1 do
begin
_rows[i] := VectorClass.create(size);
end;
end;
function SquareMatrixClass.get_size() : integer;
begin
get_size := _size;
end;
procedure SquareMatrixClass.set_row(row : VectorClass; index : integer);
begin
_rows[index] := row;
end;
function SquareMatrixClass.get_row(index : integer) : VectorClass;
begin
get_row := _rows[index];
end;
function SquareMatrixClass.get_rows() : array_of_vectors_type;
begin
get_rows := _rows;
end;
procedure SquareMatrixClass.set_element(
element : double;
row_index : integer;
column_index : integer
);
begin
_rows[row_index].set_element(element, column_index);
end;
function SquareMatrixClass.get_element(
row_index : integer;
column_index : integer
) : double;
begin
get_element := _rows[row_index].get_element(column_index);
end;
function SquareMatrixClass.construct_transposed_martix() : SquareMatrixClass;
var
size : integer;
transposed_matrix : SquareMatrixClass;
i : integer;
j : integer;
begin
size := get_size();
transposed_matrix := SquareMatrixClass.create(size);
for i := 0 to size - 1 do
begin
for j := 0 to size - 1 do
begin
transposed_matrix.set_element(self.get_element(j, i), i, j)
end;
end;
construct_transposed_martix := transposed_matrix;
end;
{ ---------------------------------------------------------------------------- }
{ class MethodOfLeastSquares // Choletky method }
type
MethodOfLeastSquaresClass = class
private
_size : integer;
_a : SquareMatrixClass;
_b : VectorClass;
function construct_u() : SquareMatrixClass;
function construct_y(u : SquareMatrixClass) : VectorClass;
function construct_x(u : SquareMatrixClass; y : VectorClass) : VectorClass;
public
constructor create(size: integer; a : SquareMatrixClass; b : VectorClass);
function get_size() : integer;
function get_a() : SquareMatrixClass;
function get_b() : VectorClass;
function apply() : VectorClass;
end;
constructor MethodOfLeastSquaresClass.create(
size : integer;
a : SquareMatrixClass;
b : VectorClass
);
begin
_size := size;
_a := a;
_b := b;
end;
function MethodOfLeastSquaresClass.construct_u() : SquareMatrixClass;
var
size : integer;
a : SquareMatrixClass;
u : SquareMatrixClass;
i : integer;
j : integer;
k : integer;
sum : double;
begin
size := get_size();
a := get_a();
u := SquareMatrixClass.create(size);
{ (2.22) 1-st formula }
u.set_element(sqrt(a.get_element(0, 0)), 0, 0);
for i := 1 to size - 1 do
begin
{ (2.22) 2-nd formula }
u.set_element(a.get_element(0, i) / u.get_element(0, 0), 0, i);
end;
for i := 1 to size - 1 do
begin
sum := 0; { !!! }
for k := 0 to i - 1 do
begin
sum := sum + power(u.get_element(k, i), 2);
end;
{ (2.22) 3-rd formula }
u.set_element(sqrt(a.get_element(i, i) - sum), i, i);
for j := i to size - 1 do
begin
sum := 0; { !!! }
for k := 0 to i - 1 do
begin
sum := sum + u.get_element(k, i) * u.get_element(k, j);
end;
{ (2.23) (j > i) }
u.set_element((a.get_element(i, j) - sum) / u.get_element(i, i), i, j);
end;
for j := 0 to i - 1 do
begin
{ (2.24) (j < i) }
u.set_element(0, i, j);
end;
end;
construct_u := u;
end;
function MethodOfLeastSquaresClass.construct_y(u : SquareMatrixClass) : VectorClass;
var
size : integer;
b : VectorClass;
i : integer;
k : integer;
sum : double;
y : VectorClass;
begin
size := get_size();
b := get_b();
y := VectorClass.create(size);
for i := 0 to size - 1 do
begin
sum := 0; { !!! }
for k := 0 to i - 1 do
begin
sum := sum + u.get_element(k, i) * y.get_element(k);
end;
{ (2.27) }
y.set_element((b.get_element(i) - sum) / u.get_element(i, i), i);
end;
construct_y := y;
end;
function MethodOfLeastSquaresClass.construct_x(
u : SquareMatrixClass;
y : VectorClass
) : VectorClass;
var
size : integer;
i : integer;
k : integer;
sum : double;
x : VectorClass;
begin
size := get_size();
x := VectorClass.create(size);
for i := size - 1 downto 0 do
begin
sum := 0; { !!! }
for k := i + 1 to size - 1 do
begin
sum := sum + u.get_element(i, k) * x.get_element(k);
end;
{ (2.27) }
x.set_element((y.get_element(i) - sum) / u.get_element(i, i), i);
end;
construct_x := x;
end;
function MethodOfLeastSquaresClass.get_size() : integer;
begin
get_size := _size;
end;
function MethodOfLeastSquaresClass.get_a() : SquareMatrixClass;
begin
get_a := _a;
end;
function MethodOfLeastSquaresClass.get_b() : VectorClass;
begin
get_b := _b;
end;
function MethodOfLeastSquaresClass.apply() : VectorClass;
var
u : SquareMatrixClass;
y : VectorClass;
begin
u := construct_u();
y := construct_y(u);
apply := construct_x(u, y);
end;
{ ---------------------------------------------------------------------------- }
{ Program variables }
var
size : integer;
a : SquareMatrixClass;
b : VectorClass;
method_of_least_squares : MethodOfLeastSquaresClass;
x : VectorClass;
{ Like main }
begin
// { p.87 ex.1 }
// size := 4;
//
// { `a` must be symmetric positive-definite matrix !!! }
// a := SquareMatrixClass.create(size);
//
// a.set_element(10, 0, 0);
// a.set_element(1, 0, 1);
// a.set_element(2, 0, 2);
// a.set_element(3, 0, 3);
//
// a.set_element(1, 1, 0);
// a.set_element(11, 1, 1);
// a.set_element(3, 1, 2);
// a.set_element(1, 1, 3);
//
// a.set_element(2, 2, 0);
// a.set_element(3, 2, 1);
// a.set_element(15, 2, 2);
// a.set_element(1, 2, 3);
//
// a.set_element(3, 3, 0);
// a.set_element(1, 3, 1);
// a.set_element(1, 3, 2);
// a.set_element(14, 3, 3);
//
// b := VectorClass.create(size);
// b.set_element(18, 0);
// b.set_element(19, 1);
// b.set_element(36, 2);
// b.set_element(20, 3);
{ p.34 }
size := 4;
{ `a` must be symmetric positive-definite matrix !!! }
a := SquareMatrixClass.create(size);
a.set_element(4, 0, 0);
a.set_element(2, 0, 1);
a.set_element(2, 0, 2);
a.set_element(1, 0, 3);
a.set_element(2, 1, 0);
a.set_element(5, 1, 1);
a.set_element(1, 1, 2);
a.set_element(2, 1, 3);
a.set_element(2, 2, 0);
a.set_element(1, 2, 1);
a.set_element(5, 2, 2);
a.set_element(1, 2, 3);
a.set_element(1, 3, 0);
a.set_element(2, 3, 1);
a.set_element(1, 3, 2);
a.set_element(4.875, 3, 3);
b := VectorClass.create(size);
b.set_element(9, 0);
b.set_element(10, 1);
b.set_element(9, 2);
b.set_element(8.875, 3);
method_of_least_squares := MethodOfLeastSquaresClass.create(size, a, b);
x := method_of_least_squares.apply();
writeln('x:');
writeln('x[0] = ', x.get_element(0));
writeln('x[1] = ', x.get_element(1));
writeln('x[2] = ', x.get_element(2));
writeln('x[3] = ', x.get_element(3));
readkey;
end.
|
unit uContatoVO;
interface
uses
System.SysUtils, uKeyField, uTableName, System.Generics.Collections;
type
[TableName('Contato')]
TContatoVO = class
private
FEmail: string;
FId: Integer;
FDepartamento: string;
FIdOrcamento: Integer;
FFone2: string;
FFone1: string;
FIdCliente: Integer;
FNome: string;
procedure SetDepartamento(const Value: string);
procedure SetEmail(const Value: string);
procedure SetFone1(const Value: string);
procedure SetFone2(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdCliente(const Value: Integer);
procedure SetIdOrcamento(const Value: Integer);
procedure SetNome(const Value: string);
public
[KeyField('Cont_Id')]
property Id: Integer read FId write SetId;
[FieldNull('Cont_Cliente')]
property IdCliente: Integer read FIdCliente write SetIdCliente;
[FieldNull('Cont_orcamento')]
property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento;
[FieldName('Cont_Nome')]
property Nome: string read FNome write SetNome;
[FieldName('Cont_Fone1')]
property Fone1: string read FFone1 write SetFone1;
[FieldName('Cont_Fone2')]
property Fone2: string read FFone2 write SetFone2;
[FieldName('Cont_Depto')]
property Departamento: string read FDepartamento write SetDepartamento;
[FieldName('Cont_Email')]
property Email: string read FEmail write SetEmail;
end;
TListaContato = TObjectList<TContatoVO>;
implementation
{ TContatoVO }
procedure TContatoVO.SetDepartamento(const Value: string);
begin
FDepartamento := Value;
end;
procedure TContatoVO.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TContatoVO.SetFone1(const Value: string);
begin
FFone1 := Value;
end;
procedure TContatoVO.SetFone2(const Value: string);
begin
FFone2 := Value;
end;
procedure TContatoVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TContatoVO.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TContatoVO.SetIdOrcamento(const Value: Integer);
begin
FIdOrcamento := Value;
end;
procedure TContatoVO.SetNome(const Value: string);
begin
FNome := Value;
end;
end.
|
unit URepProfesoresAerobicos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UUniversal, Grids, DBGrids, StdCtrls, jpeg, ExtCtrls, UDatosDB,
DBCtrls, DB, IBCustomDataSet, IBQuery, ComCtrls, cxTextEdit, cxControls,
cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit, DateUtils, URepSueldoAerobicos,
cxLookAndFeelPainters, cxButtons, TeEngine, Series, TeeProcs, Chart,
DbChart, pngimage;
type
TFRepProfesoresAerobicos = class(TFUniversal)
PGrilla: TPanel;
PBotones: TPanel;
Image2: TImage;
DBGDatos: TDBGrid;
IBQGetCantidad: TIBQuery;
IBQGetCantidadPROFESOR: TIBStringField;
IBQGetCantidadDISIPLINA: TIBStringField;
IBQGetCantidadCANT_CLASES: TIntegerField;
DSGetCantidad: TDataSource;
IBQGetCantidadSUELDO_MENSUAL: TIBBCDField;
BPreview: TcxButton;
PFiltros: TPanel;
Label2: TLabel;
Label3: TLabel;
CBMes: TcxComboBox;
cxAnio: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure CBMesPropertiesCloseUp(Sender: TObject);
procedure cxAnioPropertiesChange(Sender: TObject);
procedure BPreviewClick(Sender: TObject);
private
procedure ActDatos(mes, anio : Integer);
public
{ Public declarations }
end;
var
FRepProfesoresAerobicos: TFRepProfesoresAerobicos;
implementation
{$R *.dfm}
procedure TFRepProfesoresAerobicos.ActDatos(mes, anio : Integer);
begin
try
IBQGetCantidad.Close;
IBQGetCantidad.ParamByName('mes').AsInteger := mes;
IBQGetCantidad.ParamByName('anio').AsInteger := anio;
IBQGetCantidad.Open;
except
end;
end;
procedure TFRepProfesoresAerobicos.FormCreate(Sender: TObject);
var
dia, mes, anio : word;
begin
inherited;
DecodeDate(Date(),anio,mes,dia);
CBMes.ItemIndex := mes-1;
cxAnio.Text := IntToStr(anio);
ActDatos(mes,anio);
end;
procedure TFRepProfesoresAerobicos.CBMesPropertiesCloseUp(Sender: TObject);
begin
inherited;
ActDatos(CBMes.ItemIndex+1,StrToInt(cxAnio.Text));
end;
procedure TFRepProfesoresAerobicos.cxAnioPropertiesChange(Sender: TObject);
begin
inherited;
ActDatos(CBMes.ItemIndex+1,StrToInt(cxAnio.Text));
end;
procedure TFRepProfesoresAerobicos.BPreviewClick(Sender: TObject);
var
F : TFRepSueldoAerobicos;
begin
inherited;
F := TFRepSueldoAerobicos.Create(self);
F.QRLMes.Caption := IntToStr(CBMes.ItemIndex+1);
F.QRLAnio.Caption := cxAnio.Text;
F.QRCRSueldos.Preview;
F.Destroy;
end;
end.
|
unit uFrmPaiCadastro;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.ComCtrls,
System.UITypes, Datasnap.DBClient;
type
TfrmPaiCadastro = class(TForm)
pnlCabecalho: TPanel;
pnlAcoes: TPanel;
edtCodigo: TEdit;
Label1: TLabel;
btnIncluir: TButton;
btnSalvar: TButton;
btnCancelar: TButton;
btnEditar: TButton;
ds: TDataSource;
btnExcluir: TButton;
pnlNavigator: TPanel;
btnPrimeiro: TButton;
btnAnterior: TButton;
btnProximo: TButton;
btnUltimo: TButton;
pgcDados: TPageControl;
tsPrincipal: TTabSheet;
procedure dsStateChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnIncluirClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnPrimeiroClick(Sender: TObject);
procedure btnAnteriorClick(Sender: TObject);
procedure btnProximoClick(Sender: TObject);
procedure btnUltimoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure dsDataChange(Sender: TObject; Field: TField);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure edtCodigoExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
AutoInc: Integer;
procedure focoPrimeiroControle();
procedure tratarCampoCodigo;
function registroExistente(pcodigo: Integer): Boolean;
public
cdsControleCodigo: TClientDataSet;
end;
var
frmPaiCadastro: TfrmPaiCadastro;
const
cTagCaracterMaiusculo = 0;
cTagCaracterMinusculo = 100;
cTagSomenteNumero = 101;
CTagNumerosDecimais = 102;
implementation
uses
Vcl.DBCtrls;
{$R *.dfm}
procedure TfrmPaiCadastro.dsDataChange(Sender: TObject; Field: TField);
begin
btnPrimeiro.Enabled := (btnEditar.Enabled) and not ((Sender as TDataSource).DataSet.Bof);
btnAnterior.Enabled := btnPrimeiro.Enabled;
btnProximo.Enabled := (btnEditar.Enabled) and not ((Sender as TDataSource).DataSet.Eof);
btnUltimo.Enabled := btnProximo.Enabled;
edtCodigo.Text := (Sender as TDataSource).DataSet.FieldByName('CODIGO').AsString;
end;
procedure TfrmPaiCadastro.dsStateChange(Sender: TObject);
begin
btnIncluir.Enabled := (Sender as TDataSource).State in [dsBrowse];
btnSalvar.Enabled := (Sender as TDataSource).State in [dsEdit, dsInsert];
btnCancelar.Enabled := btnSalvar.Enabled;
btnEditar.Enabled := (btnIncluir.Enabled) and not ((Sender as TDataSource).DataSet.IsEmpty);
btnExcluir.Enabled := btnEditar.Enabled;
edtCodigo.Enabled := not btnSalvar.Enabled;
end;
procedure TfrmPaiCadastro.edtCodigoExit(Sender: TObject);
begin
tratarCampoCodigo;
end;
procedure TfrmPaiCadastro.focoPrimeiroControle;
var
index: Integer;
menorTabControl: Integer;
controle: TWinControl;
begin
pgcDados.ActivePage := tsPrincipal;
tsPrincipal.SetFocus;
MenorTabControl := 999;
for index := 0 to tsPrincipal.ControlCount -1 do
begin
if (tsPrincipal.Controls[index] is TDBEdit) then
if ((tsPrincipal.Controls[index] as TDBEdit).TabOrder = 0) and
((tsPrincipal.Controls[index] as TDBEdit).Enabled) then
begin
controle := (tsPrincipal.Controls[index] as TDBEdit);
Break;
end
else
begin
if (MenorTabControl > (tsPrincipal.Controls[index] as TDBEdit).TabOrder) and
((tsPrincipal.Controls[index] as TWinControl).Enabled) then
begin
MenorTabControl := (tsPrincipal.Controls[index] as TDBEdit).TabOrder;
controle := (tsPrincipal.Controls[index] as TDBEdit);
end;
end;
end;
controle.SetFocus;
end;
procedure TfrmPaiCadastro.btnIncluirClick(Sender: TObject);
begin
if (ds.DataSet.State in [dsInsert, dsEdit]) then
Exit;
Inc(AutoInc);
while registroExistente(autoInc) do
begin
Inc(AutoInc);
end;
ds.DataSet.Insert;
ds.DataSet.FieldByName('CODIGO').AsInteger := AutoInc;
edtCodigo.Text := AutoInc.ToString;
focoPrimeiroControle();
end;
procedure TfrmPaiCadastro.btnPrimeiroClick(Sender: TObject);
begin
ds.DataSet.First;
end;
procedure TfrmPaiCadastro.btnProximoClick(Sender: TObject);
begin
ds.DataSet.Next;
end;
procedure TfrmPaiCadastro.btnSalvarClick(Sender: TObject);
begin
if (ds.DataSet.State in [dsInsert, dsEdit]) then
begin
ds.DataSet.Post;
edtCodigo.SetFocus;
end;
end;
procedure TfrmPaiCadastro.btnUltimoClick(Sender: TObject);
begin
ds.DataSet.Last;
end;
procedure TfrmPaiCadastro.btnAnteriorClick(Sender: TObject);
begin
ds.DataSet.Prior;
end;
procedure TfrmPaiCadastro.btnCancelarClick(Sender: TObject);
begin
if ds.DataSet.State in [dsInsert, dsEdit] then
begin
ds.DataSet.Cancel;
dsStateChange(ds);
edtCodigo.SetFocus;
end;
end;
procedure TfrmPaiCadastro.btnEditarClick(Sender: TObject);
begin
if not(ds.DataSet.State in [dsInsert, dsEdit]) then
begin
ds.DataSet.Edit;
focoPrimeiroControle();
end;
end;
procedure TfrmPaiCadastro.btnExcluirClick(Sender: TObject);
begin
if (MessageDlg('Deseja mesmo excluir este registro?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
ds.DataSet.Delete;
dsStateChange(ds);
edtCodigo.SetFocus;
end;
end;
procedure TfrmPaiCadastro.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if btnSalvar.Enabled then
begin
if ds.DataSet.State in [dsInsert, dsEdit] then
begin
CanClose := False;
MessageDlg('Salve ou cancele a operação corrente antes de fechar a janela.',
mtInformation, [mbOk], 0);
end;
end;
end;
procedure TfrmPaiCadastro.FormCreate(Sender: TObject);
begin
AutoInc := 0;
end;
procedure TfrmPaiCadastro.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case key of
vk_f3:begin
btnIncluir.Click;
end;
vk_f4:begin
btnSalvar.Click;
end;
vk_f5:begin
btnCancelar.Click;
end;
vk_f6:begin
btnEditar.Click;
end;
vk_f7:begin
btnExcluir.Click;
end;
end;
end;
procedure TfrmPaiCadastro.FormKeyPress(Sender: TObject; var Key: Char);
var
ComponenteAtivo: TComponent;
begin
if(Key = #13)then
begin
Perform(Wm_NextDlgCtl,0,0);
end
else
begin
ComponenteAtivo := Screen.ActiveControl;
if (ComponenteAtivo is TDBEdit) or
(ComponenteAtivo is TEdit) then
begin
case ComponenteAtivo.Tag of
cTagCaracterMaiusculo: begin
Key := Char(AnsiUpperCase(Key)[1]);
end;
cTagCaracterMinusculo: begin
Key := Char(AnsiLowerCase(Key)[1]);
end;
cTagSomenteNumero: begin
if(not(key in ['0'..'9']) and (word(key) <> vk_back))then
key := #0;
end;
CTagNumerosDecimais: begin
if not(key in ['0'..'9',',',#8]) then
key :=#0;
end;
end;
end;
end;
end;
function TfrmPaiCadastro.registroExistente(pCodigo: Integer): Boolean;
begin
result := false;
if(not(Assigned(cdsControleCodigo)))then
exit;
try
cdsControleCodigo.DisableControls;
result := (cdsControleCodigo.FindKey([pCodigo]))
finally
cdsControleCodigo.EnableControls;
end;
end;
procedure TfrmPaiCadastro.tratarCampoCodigo;
begin
if Length(Trim(edtCodigo.Text)) <> 0 then
begin
if(Assigned(cdsControleCodigo))then
begin
if(cdsControleCodigo.FindKey([StrToInt(Trim(edtCodigo.Text))]))then
begin
focoPrimeiroControle();
end
else begin
AutoInc := StrToInt(edtCodigo.Text)-1;
btnIncluir.Click;
end;
end;
end;
end;
end.
|
unit TTSLOANTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSLOANRecord = record
PLenderNum: String[4];
PLoanNum: String[20];
PModCount: Integer;
PCifNum: String[20];
PBranch: String[8];
PDivision: String[8];
PBalance: Currency;
PTapeLoan: Boolean;
POpenDate: String[10];
PMaturityDate: String[10];
PPaidOutDate: String[10];
PName1: String[40];
PName2: String[40];
PAddr1: String[40];
PAddr2: String[40];
PCity: String[25];
PState: String[2];
PZip: String[10];
PPhone: String[40];
PLetterName: String[40];
PMisc1: String[40];
PMisc2: String[40];
PMisc3: String[40];
PMisc4: String[40];
POfficer: String[6];
PHoldNotice: Boolean;
PFirstName1: String[20];
PFirstName2: String[20];
PForeclosureFlag: Boolean;
PBankruptFlag: Boolean;
PLossPayee: String[60];
PEquityLimit: Currency;
PDept: String[8];
End;
TTTSLOANBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSLOANRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSLOAN = (TTSLOANPrimaryKey, TTSLOANbyCif);
TTTSLOANTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFLoanNum: TStringField;
FDFModCount: TIntegerField;
FDFCifNum: TStringField;
FDFBranch: TStringField;
FDFDivision: TStringField;
FDFBalance: TCurrencyField;
FDFTapeLoan: TBooleanField;
FDFOpenDate: TStringField;
FDFMaturityDate: TStringField;
FDFPaidOutDate: TStringField;
FDFName1: TStringField;
FDFName2: TStringField;
FDFAddr1: TStringField;
FDFAddr2: TStringField;
FDFCity: TStringField;
FDFState: TStringField;
FDFZip: TStringField;
FDFPhone: TStringField;
FDFLetterName: TStringField;
FDFMisc1: TStringField;
FDFMisc2: TStringField;
FDFMisc3: TStringField;
FDFMisc4: TStringField;
FDFOfficer: TStringField;
FDFHoldNotice: TBooleanField;
FDFFirstName1: TStringField;
FDFFirstName2: TStringField;
FDFForeclosureFlag: TBooleanField;
FDFBankruptFlag: TBooleanField;
FDFLossPayee: TStringField;
FDFEquityLimit: TCurrencyField;
FDFDept: TStringField;
FDFNotes: TBlobField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPLoanNum(const Value: String);
function GetPLoanNum:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPCifNum(const Value: String);
function GetPCifNum:String;
procedure SetPBranch(const Value: String);
function GetPBranch:String;
procedure SetPDivision(const Value: String);
function GetPDivision:String;
procedure SetPBalance(const Value: Currency);
function GetPBalance:Currency;
procedure SetPTapeLoan(const Value: Boolean);
function GetPTapeLoan:Boolean;
procedure SetPOpenDate(const Value: String);
function GetPOpenDate:String;
procedure SetPMaturityDate(const Value: String);
function GetPMaturityDate:String;
procedure SetPPaidOutDate(const Value: String);
function GetPPaidOutDate:String;
procedure SetPName1(const Value: String);
function GetPName1:String;
procedure SetPName2(const Value: String);
function GetPName2:String;
procedure SetPAddr1(const Value: String);
function GetPAddr1:String;
procedure SetPAddr2(const Value: String);
function GetPAddr2:String;
procedure SetPCity(const Value: String);
function GetPCity:String;
procedure SetPState(const Value: String);
function GetPState:String;
procedure SetPZip(const Value: String);
function GetPZip:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetPLetterName(const Value: String);
function GetPLetterName:String;
procedure SetPMisc1(const Value: String);
function GetPMisc1:String;
procedure SetPMisc2(const Value: String);
function GetPMisc2:String;
procedure SetPMisc3(const Value: String);
function GetPMisc3:String;
procedure SetPMisc4(const Value: String);
function GetPMisc4:String;
procedure SetPOfficer(const Value: String);
function GetPOfficer:String;
procedure SetPHoldNotice(const Value: Boolean);
function GetPHoldNotice:Boolean;
procedure SetPFirstName1(const Value: String);
function GetPFirstName1:String;
procedure SetPFirstName2(const Value: String);
function GetPFirstName2:String;
procedure SetPForeclosureFlag(const Value: Boolean);
function GetPForeclosureFlag:Boolean;
procedure SetPBankruptFlag(const Value: Boolean);
function GetPBankruptFlag:Boolean;
procedure SetPLossPayee(const Value: String);
function GetPLossPayee:String;
procedure SetPEquityLimit(const Value: Currency);
function GetPEquityLimit:Currency;
procedure SetPDept(const Value: String);
function GetPDept:String;
procedure SetEnumIndex(Value: TEITTSLOAN);
function GetEnumIndex: TEITTSLOAN;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSLOANRecord;
procedure StoreDataBuffer(ABuffer:TTTSLOANRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFLoanNum: TStringField read FDFLoanNum;
property DFModCount: TIntegerField read FDFModCount;
property DFCifNum: TStringField read FDFCifNum;
property DFBranch: TStringField read FDFBranch;
property DFDivision: TStringField read FDFDivision;
property DFBalance: TCurrencyField read FDFBalance;
property DFTapeLoan: TBooleanField read FDFTapeLoan;
property DFOpenDate: TStringField read FDFOpenDate;
property DFMaturityDate: TStringField read FDFMaturityDate;
property DFPaidOutDate: TStringField read FDFPaidOutDate;
property DFName1: TStringField read FDFName1;
property DFName2: TStringField read FDFName2;
property DFAddr1: TStringField read FDFAddr1;
property DFAddr2: TStringField read FDFAddr2;
property DFCity: TStringField read FDFCity;
property DFState: TStringField read FDFState;
property DFZip: TStringField read FDFZip;
property DFPhone: TStringField read FDFPhone;
property DFLetterName: TStringField read FDFLetterName;
property DFMisc1: TStringField read FDFMisc1;
property DFMisc2: TStringField read FDFMisc2;
property DFMisc3: TStringField read FDFMisc3;
property DFMisc4: TStringField read FDFMisc4;
property DFOfficer: TStringField read FDFOfficer;
property DFHoldNotice: TBooleanField read FDFHoldNotice;
property DFFirstName1: TStringField read FDFFirstName1;
property DFFirstName2: TStringField read FDFFirstName2;
property DFForeclosureFlag: TBooleanField read FDFForeclosureFlag;
property DFBankruptFlag: TBooleanField read FDFBankruptFlag;
property DFLossPayee: TStringField read FDFLossPayee;
property DFEquityLimit: TCurrencyField read FDFEquityLimit;
property DFDept: TStringField read FDFDept;
property DFNotes: TBlobField read FDFNotes;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PLoanNum: String read GetPLoanNum write SetPLoanNum;
property PModCount: Integer read GetPModCount write SetPModCount;
property PCifNum: String read GetPCifNum write SetPCifNum;
property PBranch: String read GetPBranch write SetPBranch;
property PDivision: String read GetPDivision write SetPDivision;
property PBalance: Currency read GetPBalance write SetPBalance;
property PTapeLoan: Boolean read GetPTapeLoan write SetPTapeLoan;
property POpenDate: String read GetPOpenDate write SetPOpenDate;
property PMaturityDate: String read GetPMaturityDate write SetPMaturityDate;
property PPaidOutDate: String read GetPPaidOutDate write SetPPaidOutDate;
property PName1: String read GetPName1 write SetPName1;
property PName2: String read GetPName2 write SetPName2;
property PAddr1: String read GetPAddr1 write SetPAddr1;
property PAddr2: String read GetPAddr2 write SetPAddr2;
property PCity: String read GetPCity write SetPCity;
property PState: String read GetPState write SetPState;
property PZip: String read GetPZip write SetPZip;
property PPhone: String read GetPPhone write SetPPhone;
property PLetterName: String read GetPLetterName write SetPLetterName;
property PMisc1: String read GetPMisc1 write SetPMisc1;
property PMisc2: String read GetPMisc2 write SetPMisc2;
property PMisc3: String read GetPMisc3 write SetPMisc3;
property PMisc4: String read GetPMisc4 write SetPMisc4;
property POfficer: String read GetPOfficer write SetPOfficer;
property PHoldNotice: Boolean read GetPHoldNotice write SetPHoldNotice;
property PFirstName1: String read GetPFirstName1 write SetPFirstName1;
property PFirstName2: String read GetPFirstName2 write SetPFirstName2;
property PForeclosureFlag: Boolean read GetPForeclosureFlag write SetPForeclosureFlag;
property PBankruptFlag: Boolean read GetPBankruptFlag write SetPBankruptFlag;
property PLossPayee: String read GetPLossPayee write SetPLossPayee;
property PEquityLimit: Currency read GetPEquityLimit write SetPEquityLimit;
property PDept: String read GetPDept write SetPDept;
published
property Active write SetActive;
property EnumIndex: TEITTSLOAN read GetEnumIndex write SetEnumIndex;
end; { TTTSLOANTable }
procedure Register;
implementation
procedure TTTSLOANTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFLoanNum := CreateField( 'LoanNum' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFCifNum := CreateField( 'CifNum' ) as TStringField;
FDFBranch := CreateField( 'Branch' ) as TStringField;
FDFDivision := CreateField( 'Division' ) as TStringField;
FDFBalance := CreateField( 'Balance' ) as TCurrencyField;
FDFTapeLoan := CreateField( 'TapeLoan' ) as TBooleanField;
FDFOpenDate := CreateField( 'OpenDate' ) as TStringField;
FDFMaturityDate := CreateField( 'MaturityDate' ) as TStringField;
FDFPaidOutDate := CreateField( 'PaidOutDate' ) as TStringField;
FDFName1 := CreateField( 'Name1' ) as TStringField;
FDFName2 := CreateField( 'Name2' ) as TStringField;
FDFAddr1 := CreateField( 'Addr1' ) as TStringField;
FDFAddr2 := CreateField( 'Addr2' ) as TStringField;
FDFCity := CreateField( 'City' ) as TStringField;
FDFState := CreateField( 'State' ) as TStringField;
FDFZip := CreateField( 'Zip' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
FDFLetterName := CreateField( 'LetterName' ) as TStringField;
FDFMisc1 := CreateField( 'Misc1' ) as TStringField;
FDFMisc2 := CreateField( 'Misc2' ) as TStringField;
FDFMisc3 := CreateField( 'Misc3' ) as TStringField;
FDFMisc4 := CreateField( 'Misc4' ) as TStringField;
FDFOfficer := CreateField( 'Officer' ) as TStringField;
FDFHoldNotice := CreateField( 'HoldNotice' ) as TBooleanField;
FDFFirstName1 := CreateField( 'FirstName1' ) as TStringField;
FDFFirstName2 := CreateField( 'FirstName2' ) as TStringField;
FDFForeclosureFlag := CreateField( 'ForeclosureFlag' ) as TBooleanField;
FDFBankruptFlag := CreateField( 'BankruptFlag' ) as TBooleanField;
FDFLossPayee := CreateField( 'LossPayee' ) as TStringField;
FDFEquityLimit := CreateField( 'EquityLimit' ) as TCurrencyField;
FDFDept := CreateField( 'Dept' ) as TStringField;
FDFNotes := CreateField( 'Notes' ) as TBlobField;
end; { TTTSLOANTable.CreateFields }
procedure TTTSLOANTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSLOANTable.SetActive }
procedure TTTSLOANTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSLOANTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSLOANTable.SetPLoanNum(const Value: String);
begin
DFLoanNum.Value := Value;
end;
function TTTSLOANTable.GetPLoanNum:String;
begin
result := DFLoanNum.Value;
end;
procedure TTTSLOANTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSLOANTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSLOANTable.SetPCifNum(const Value: String);
begin
DFCifNum.Value := Value;
end;
function TTTSLOANTable.GetPCifNum:String;
begin
result := DFCifNum.Value;
end;
procedure TTTSLOANTable.SetPBranch(const Value: String);
begin
DFBranch.Value := Value;
end;
function TTTSLOANTable.GetPBranch:String;
begin
result := DFBranch.Value;
end;
procedure TTTSLOANTable.SetPDivision(const Value: String);
begin
DFDivision.Value := Value;
end;
function TTTSLOANTable.GetPDivision:String;
begin
result := DFDivision.Value;
end;
procedure TTTSLOANTable.SetPBalance(const Value: Currency);
begin
DFBalance.Value := Value;
end;
function TTTSLOANTable.GetPBalance:Currency;
begin
result := DFBalance.Value;
end;
procedure TTTSLOANTable.SetPTapeLoan(const Value: Boolean);
begin
DFTapeLoan.Value := Value;
end;
function TTTSLOANTable.GetPTapeLoan:Boolean;
begin
result := DFTapeLoan.Value;
end;
procedure TTTSLOANTable.SetPOpenDate(const Value: String);
begin
DFOpenDate.Value := Value;
end;
function TTTSLOANTable.GetPOpenDate:String;
begin
result := DFOpenDate.Value;
end;
procedure TTTSLOANTable.SetPMaturityDate(const Value: String);
begin
DFMaturityDate.Value := Value;
end;
function TTTSLOANTable.GetPMaturityDate:String;
begin
result := DFMaturityDate.Value;
end;
procedure TTTSLOANTable.SetPPaidOutDate(const Value: String);
begin
DFPaidOutDate.Value := Value;
end;
function TTTSLOANTable.GetPPaidOutDate:String;
begin
result := DFPaidOutDate.Value;
end;
procedure TTTSLOANTable.SetPName1(const Value: String);
begin
DFName1.Value := Value;
end;
function TTTSLOANTable.GetPName1:String;
begin
result := DFName1.Value;
end;
procedure TTTSLOANTable.SetPName2(const Value: String);
begin
DFName2.Value := Value;
end;
function TTTSLOANTable.GetPName2:String;
begin
result := DFName2.Value;
end;
procedure TTTSLOANTable.SetPAddr1(const Value: String);
begin
DFAddr1.Value := Value;
end;
function TTTSLOANTable.GetPAddr1:String;
begin
result := DFAddr1.Value;
end;
procedure TTTSLOANTable.SetPAddr2(const Value: String);
begin
DFAddr2.Value := Value;
end;
function TTTSLOANTable.GetPAddr2:String;
begin
result := DFAddr2.Value;
end;
procedure TTTSLOANTable.SetPCity(const Value: String);
begin
DFCity.Value := Value;
end;
function TTTSLOANTable.GetPCity:String;
begin
result := DFCity.Value;
end;
procedure TTTSLOANTable.SetPState(const Value: String);
begin
DFState.Value := Value;
end;
function TTTSLOANTable.GetPState:String;
begin
result := DFState.Value;
end;
procedure TTTSLOANTable.SetPZip(const Value: String);
begin
DFZip.Value := Value;
end;
function TTTSLOANTable.GetPZip:String;
begin
result := DFZip.Value;
end;
procedure TTTSLOANTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TTTSLOANTable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TTTSLOANTable.SetPLetterName(const Value: String);
begin
DFLetterName.Value := Value;
end;
function TTTSLOANTable.GetPLetterName:String;
begin
result := DFLetterName.Value;
end;
procedure TTTSLOANTable.SetPMisc1(const Value: String);
begin
DFMisc1.Value := Value;
end;
function TTTSLOANTable.GetPMisc1:String;
begin
result := DFMisc1.Value;
end;
procedure TTTSLOANTable.SetPMisc2(const Value: String);
begin
DFMisc2.Value := Value;
end;
function TTTSLOANTable.GetPMisc2:String;
begin
result := DFMisc2.Value;
end;
procedure TTTSLOANTable.SetPMisc3(const Value: String);
begin
DFMisc3.Value := Value;
end;
function TTTSLOANTable.GetPMisc3:String;
begin
result := DFMisc3.Value;
end;
procedure TTTSLOANTable.SetPMisc4(const Value: String);
begin
DFMisc4.Value := Value;
end;
function TTTSLOANTable.GetPMisc4:String;
begin
result := DFMisc4.Value;
end;
procedure TTTSLOANTable.SetPOfficer(const Value: String);
begin
DFOfficer.Value := Value;
end;
function TTTSLOANTable.GetPOfficer:String;
begin
result := DFOfficer.Value;
end;
procedure TTTSLOANTable.SetPHoldNotice(const Value: Boolean);
begin
DFHoldNotice.Value := Value;
end;
function TTTSLOANTable.GetPHoldNotice:Boolean;
begin
result := DFHoldNotice.Value;
end;
procedure TTTSLOANTable.SetPFirstName1(const Value: String);
begin
DFFirstName1.Value := Value;
end;
function TTTSLOANTable.GetPFirstName1:String;
begin
result := DFFirstName1.Value;
end;
procedure TTTSLOANTable.SetPFirstName2(const Value: String);
begin
DFFirstName2.Value := Value;
end;
function TTTSLOANTable.GetPFirstName2:String;
begin
result := DFFirstName2.Value;
end;
procedure TTTSLOANTable.SetPForeclosureFlag(const Value: Boolean);
begin
DFForeclosureFlag.Value := Value;
end;
function TTTSLOANTable.GetPForeclosureFlag:Boolean;
begin
result := DFForeclosureFlag.Value;
end;
procedure TTTSLOANTable.SetPBankruptFlag(const Value: Boolean);
begin
DFBankruptFlag.Value := Value;
end;
function TTTSLOANTable.GetPBankruptFlag:Boolean;
begin
result := DFBankruptFlag.Value;
end;
procedure TTTSLOANTable.SetPLossPayee(const Value: String);
begin
DFLossPayee.Value := Value;
end;
function TTTSLOANTable.GetPLossPayee:String;
begin
result := DFLossPayee.Value;
end;
procedure TTTSLOANTable.SetPEquityLimit(const Value: Currency);
begin
DFEquityLimit.Value := Value;
end;
function TTTSLOANTable.GetPEquityLimit:Currency;
begin
result := DFEquityLimit.Value;
end;
procedure TTTSLOANTable.SetPDept(const Value: String);
begin
DFDept.Value := Value;
end;
function TTTSLOANTable.GetPDept:String;
begin
result := DFDept.Value;
end;
procedure TTTSLOANTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('LoanNum, String, 20, N');
Add('ModCount, Integer, 0, N');
Add('CifNum, String, 20, N');
Add('Branch, String, 8, N');
Add('Division, String, 8, N');
Add('Balance, Currency, 0, N');
Add('TapeLoan, Boolean, 0, N');
Add('OpenDate, String, 10, N');
Add('MaturityDate, String, 10, N');
Add('PaidOutDate, String, 10, N');
Add('Name1, String, 40, N');
Add('Name2, String, 40, N');
Add('Addr1, String, 40, N');
Add('Addr2, String, 40, N');
Add('City, String, 25, N');
Add('State, String, 2, N');
Add('Zip, String, 10, N');
Add('Phone, String, 40, N');
Add('LetterName, String, 40, N');
Add('Misc1, String, 40, N');
Add('Misc2, String, 40, N');
Add('Misc3, String, 40, N');
Add('Misc4, String, 40, N');
Add('Officer, String, 6, N');
Add('HoldNotice, Boolean, 0, N');
Add('FirstName1, String, 20, N');
Add('FirstName2, String, 20, N');
Add('ForeclosureFlag, Boolean, 0, N');
Add('BankruptFlag, Boolean, 0, N');
Add('LossPayee, String, 60, N');
Add('EquityLimit, Currency, 0, N');
Add('Dept, String, 8, N');
Add('Notes, Memo, 0, N');
end;
end;
procedure TTTSLOANTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;LoanNum, Y, Y, N, N');
Add('byCif, LenderNum;CifNum, N, N, Y, N');
end;
end;
procedure TTTSLOANTable.SetEnumIndex(Value: TEITTSLOAN);
begin
case Value of
TTSLOANPrimaryKey : IndexName := '';
TTSLOANbyCif : IndexName := 'byCif';
end;
end;
function TTTSLOANTable.GetDataBuffer:TTTSLOANRecord;
var buf: TTTSLOANRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PLoanNum := DFLoanNum.Value;
buf.PModCount := DFModCount.Value;
buf.PCifNum := DFCifNum.Value;
buf.PBranch := DFBranch.Value;
buf.PDivision := DFDivision.Value;
buf.PBalance := DFBalance.Value;
buf.PTapeLoan := DFTapeLoan.Value;
buf.POpenDate := DFOpenDate.Value;
buf.PMaturityDate := DFMaturityDate.Value;
buf.PPaidOutDate := DFPaidOutDate.Value;
buf.PName1 := DFName1.Value;
buf.PName2 := DFName2.Value;
buf.PAddr1 := DFAddr1.Value;
buf.PAddr2 := DFAddr2.Value;
buf.PCity := DFCity.Value;
buf.PState := DFState.Value;
buf.PZip := DFZip.Value;
buf.PPhone := DFPhone.Value;
buf.PLetterName := DFLetterName.Value;
buf.PMisc1 := DFMisc1.Value;
buf.PMisc2 := DFMisc2.Value;
buf.PMisc3 := DFMisc3.Value;
buf.PMisc4 := DFMisc4.Value;
buf.POfficer := DFOfficer.Value;
buf.PHoldNotice := DFHoldNotice.Value;
buf.PFirstName1 := DFFirstName1.Value;
buf.PFirstName2 := DFFirstName2.Value;
buf.PForeclosureFlag := DFForeclosureFlag.Value;
buf.PBankruptFlag := DFBankruptFlag.Value;
buf.PLossPayee := DFLossPayee.Value;
buf.PEquityLimit := DFEquityLimit.Value;
buf.PDept := DFDept.Value;
result := buf;
end;
procedure TTTSLOANTable.StoreDataBuffer(ABuffer:TTTSLOANRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFLoanNum.Value := ABuffer.PLoanNum;
DFModCount.Value := ABuffer.PModCount;
DFCifNum.Value := ABuffer.PCifNum;
DFBranch.Value := ABuffer.PBranch;
DFDivision.Value := ABuffer.PDivision;
DFBalance.Value := ABuffer.PBalance;
DFTapeLoan.Value := ABuffer.PTapeLoan;
DFOpenDate.Value := ABuffer.POpenDate;
DFMaturityDate.Value := ABuffer.PMaturityDate;
DFPaidOutDate.Value := ABuffer.PPaidOutDate;
DFName1.Value := ABuffer.PName1;
DFName2.Value := ABuffer.PName2;
DFAddr1.Value := ABuffer.PAddr1;
DFAddr2.Value := ABuffer.PAddr2;
DFCity.Value := ABuffer.PCity;
DFState.Value := ABuffer.PState;
DFZip.Value := ABuffer.PZip;
DFPhone.Value := ABuffer.PPhone;
DFLetterName.Value := ABuffer.PLetterName;
DFMisc1.Value := ABuffer.PMisc1;
DFMisc2.Value := ABuffer.PMisc2;
DFMisc3.Value := ABuffer.PMisc3;
DFMisc4.Value := ABuffer.PMisc4;
DFOfficer.Value := ABuffer.POfficer;
DFHoldNotice.Value := ABuffer.PHoldNotice;
DFFirstName1.Value := ABuffer.PFirstName1;
DFFirstName2.Value := ABuffer.PFirstName2;
DFForeclosureFlag.Value := ABuffer.PForeclosureFlag;
DFBankruptFlag.Value := ABuffer.PBankruptFlag;
DFLossPayee.Value := ABuffer.PLossPayee;
DFEquityLimit.Value := ABuffer.PEquityLimit;
DFDept.Value := ABuffer.PDept;
end;
function TTTSLOANTable.GetEnumIndex: TEITTSLOAN;
var iname : string;
begin
result := TTSLOANPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSLOANPrimaryKey;
if iname = 'BYCIF' then result := TTSLOANbyCif;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSLOANTable, TTTSLOANBuffer ] );
end; { Register }
function TTTSLOANBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..33] of string = ('LENDERNUM','LOANNUM','MODCOUNT','CIFNUM','BRANCH','DIVISION'
,'BALANCE','TAPELOAN','OPENDATE','MATURITYDATE','PAIDOUTDATE'
,'NAME1','NAME2','ADDR1','ADDR2','CITY'
,'STATE','ZIP','PHONE','LETTERNAME','MISC1'
,'MISC2','MISC3','MISC4','OFFICER','HOLDNOTICE'
,'FIRSTNAME1','FIRSTNAME2','FORECLOSUREFLAG','BANKRUPTFLAG','LOSSPAYEE'
,'EQUITYLIMIT','DEPT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 33) and (flist[x] <> s) do inc(x);
if x <= 33 then result := x else result := 0;
end;
function TTTSLOANBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftCurrency;
8 : result := ftBoolean;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
13 : result := ftString;
14 : result := ftString;
15 : result := ftString;
16 : result := ftString;
17 : result := ftString;
18 : result := ftString;
19 : result := ftString;
20 : result := ftString;
21 : result := ftString;
22 : result := ftString;
23 : result := ftString;
24 : result := ftString;
25 : result := ftString;
26 : result := ftBoolean;
27 : result := ftString;
28 : result := ftString;
29 : result := ftBoolean;
30 : result := ftBoolean;
31 : result := ftString;
32 : result := ftCurrency;
33 : result := ftString;
end;
end;
function TTTSLOANBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PLoanNum;
3 : result := @Data.PModCount;
4 : result := @Data.PCifNum;
5 : result := @Data.PBranch;
6 : result := @Data.PDivision;
7 : result := @Data.PBalance;
8 : result := @Data.PTapeLoan;
9 : result := @Data.POpenDate;
10 : result := @Data.PMaturityDate;
11 : result := @Data.PPaidOutDate;
12 : result := @Data.PName1;
13 : result := @Data.PName2;
14 : result := @Data.PAddr1;
15 : result := @Data.PAddr2;
16 : result := @Data.PCity;
17 : result := @Data.PState;
18 : result := @Data.PZip;
19 : result := @Data.PPhone;
20 : result := @Data.PLetterName;
21 : result := @Data.PMisc1;
22 : result := @Data.PMisc2;
23 : result := @Data.PMisc3;
24 : result := @Data.PMisc4;
25 : result := @Data.POfficer;
26 : result := @Data.PHoldNotice;
27 : result := @Data.PFirstName1;
28 : result := @Data.PFirstName2;
29 : result := @Data.PForeclosureFlag;
30 : result := @Data.PBankruptFlag;
31 : result := @Data.PLossPayee;
32 : result := @Data.PEquityLimit;
33 : result := @Data.PDept;
end;
end;
end.
|
unit GX_IconMessageBox;
interface
uses
GX_MessageBox;
type
TShowMissingIconMessage = class(TGxMsgBoxAdaptor)
protected
function GetMessage: string; override;
function ShouldShow: Boolean; override;
end;
implementation
uses SysUtils;
{ TShowMissingIconMessage }
function TShowMissingIconMessage.GetMessage: string;
resourcestring
SBadIconFile =
'Some of the default GExperts icons are missing. Make sure that the icons ' +
'exist in a directory called "Icons" underneath the main GExperts ' +
'installation directory and is included in "GXIcons.rc". The file missing is: %s';
begin
Result := Format(SBadIconFile, [FData]);
end;
var
ShownOnce: Boolean = False;
function TShowMissingIconMessage.ShouldShow: Boolean;
begin
Result := not ShownOnce;
ShownOnce := True;
end;
end.
|
unit Order_class;
interface
uses data_module,IBX.IBTable, SysUtils;
type TOrder = Class
private
id : integer;
status : integer;
driver_id : integer;
customer : string;
date_delivery : string;
procedure push;
public
constructor Create(row : TIBTable);
destructor Destroy;
procedure Edit(P_id: integer);
// Return driver id
procedure update_driver(id_driver : integer);
function get_id : integer;
function get_status : integer;
function get_driver_id : integer;
function get_customer:string;
function get_date_delivery:tdatetime;
End;
implementation
function TOrder.get_id;
begin
get_id := id;
end;
function TOrder.get_status ;
begin
get_status := status;
end;
function TOrder.get_driver_id;
begin
get_driver_id := driver_id;
end;
function TOrder.get_customer;
begin
get_customer := customer;
end;
function TOrder.get_date_delivery;
begin
get_date_delivery := StrToDateTime(date_delivery);
end;
constructor TOrder.Create(row : TIBTable);
begin
id := row.FieldByName('ORDER_ID').AsInteger;
status := row.FieldByName('STATUS_ID').AsInteger;
driver_id := row.FieldByName('COURIER_ID').AsInteger; // Ñ ÝÒÈÌ ÍÅ ÏÎÊÀÇÛÂÀÞÒÑß ÇÀÊÀÇÛ
customer := row.FieldByName('CLIENT_NAME').AsString;
date_delivery := row.FieldByName('TIME_OF_DELIVERY').Value;
end;
destructor TOrder.Destroy;
begin
end;
procedure TOrder.Edit(P_id: Integer);
begin
id := p_id;
end;
procedure TOrder.update_driver(id_driver : integer);
begin
driver_id := id_driver;
//3 - äîñòàâëÿåòñÿ
//2 - îæèäàåò êóðüåðà
if driver_id = 0 then
status := 1
else
status := 2;
push;
end;
procedure TOrder.push;
begin
// push himself to db
// Fill db procedure parametrs with form valut
dm.spEDIT_ORDER_SET_DRIVER.ParamByName('ID_ORDER').AsInteger := id;
dm.spEDIT_ORDER_SET_DRIVER.ParamByName('ID_WORKERS').AsInteger:= driver_id ;
dm.spEDIT_ORDER_SET_DRIVER.ParamByName('NEW_STATUS').AsInteger:= status;
if driver_id = 0 then
dm.spEDIT_ORDER_SET_DRIVER.ParamByName('ID_WORKERS').Clear;
// Execute the procedure
if not dm.spEDIT_ORDER_SET_DRIVER.Transaction.InTransaction then
dm.spEDIT_ORDER_SET_DRIVER.Transaction.StartTransaction;
dm.spEDIT_ORDER_SET_DRIVER.ExecProc;
dm.spEDIT_ORDER_SET_DRIVER.Transaction.Commit;
dm.open_all;
end;
end.
|
unit l3TypedIntegerValueMap;
{* реализация мапы "строка"-"число" для чистой замены array [TSomeType] of string. Берет данные из ResourceString. }
// Модуль: "w:\common\components\rtl\Garant\L3\l3TypedIntegerValueMap.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "l3TypedIntegerValueMap" MUID: (478E1D94023E)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3ValueMap
, l3Interfaces
, TypInfo
;
type
Tl3IntegerValueMap = class(Tl3ValueMap, Il3IntegerValueMap)
private
f_TypeData: PTypeData;
protected
function DoDisplayNameToValue(const aDisplayName: Il3CString): Integer; virtual; abstract;
function DoValueToDisplayName(aValue: Integer): Il3CString; virtual; abstract;
function DisplayNameToValue(const aDisplayName: Il3CString): Integer;
function ValueToDisplayName(aValue: Integer): Il3CString;
public
constructor Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo); reintroduce;
end;//Tl3IntegerValueMap
Tl3SimpleTypedIntegerValueMap = class(Tl3IntegerValueMap)
protected
f_Values: Tl3StringArray;
protected
function DoDisplayNameToValue(const aDisplayName: Il3CString): Integer; override;
function DoValueToDisplayName(aValue: Integer): Il3CString; override;
procedure DoGetDisplayNames(const aList: Il3StringsEx); override;
function GetMapSize: Integer; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of AnsiString); reintroduce;
class function Make(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of AnsiString): Il3IntegerValueMap; reintroduce;
end;//Tl3SimpleTypedIntegerValueMap
Tl3ResStringArray = array of PResStringRec;
Tl3ResourceTypedIntegerValueMap = class(Tl3IntegerValueMap)
protected
f_Values: Tl3ResStringArray;
protected
function DoDisplayNameToValue(const aDisplayName: Il3CString): Integer; override;
function DoValueToDisplayName(aValue: Integer): Il3CString; override;
procedure DoGetDisplayNames(const aList: Il3StringsEx); override;
function GetMapSize: Integer; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of PResStringRec); reintroduce;
class function Make(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of PResStringRec): Il3IntegerValueMap; reintroduce;
end;//Tl3ResourceTypedIntegerValueMap
implementation
uses
l3ImplUses
, SysUtils
, l3String
, l3Base
//#UC START# *478E1D94023Eimpl_uses*
//#UC END# *478E1D94023Eimpl_uses*
;
constructor Tl3IntegerValueMap.Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo);
//#UC START# *478E20F70032_478E1E9E01CE_var*
//#UC END# *478E20F70032_478E1E9E01CE_var*
begin
//#UC START# *478E20F70032_478E1E9E01CE_impl*
inherited Create(aID);
Assert(Assigned(aTypeInfo),Format('Typed map %s - Unspecified typeinfo',[rMapID.rName]));
Assert(aTypeInfo^.Kind in [tkInteger, tkChar, tkEnumeration, tkWChar],Format('Typed map %s - Unsupported type',[rMapID.rName]));
f_TypeData := GetTypeData(aTypeInfo);
Assert(Assigned(f_TypeData),Format('Typed map %s - Can''t find type data',[rMapID.rName]));
//#UC END# *478E20F70032_478E1E9E01CE_impl*
end;//Tl3IntegerValueMap.Create
function Tl3IntegerValueMap.DisplayNameToValue(const aDisplayName: Il3CString): Integer;
//#UC START# *46A5FCF900E0_478E1E9E01CE_var*
//#UC END# *46A5FCF900E0_478E1E9E01CE_var*
begin
//#UC START# *46A5FCF900E0_478E1E9E01CE_impl*
Result := DoDisplayNameToValue(aDisplayName);
//#UC END# *46A5FCF900E0_478E1E9E01CE_impl*
end;//Tl3IntegerValueMap.DisplayNameToValue
function Tl3IntegerValueMap.ValueToDisplayName(aValue: Integer): Il3CString;
//#UC START# *46A5FD1B000D_478E1E9E01CE_var*
//#UC END# *46A5FD1B000D_478E1E9E01CE_var*
begin
//#UC START# *46A5FD1B000D_478E1E9E01CE_impl*
Result := DoValueToDisplayName(aValue);
//#UC END# *46A5FD1B000D_478E1E9E01CE_impl*
end;//Tl3IntegerValueMap.ValueToDisplayName
constructor Tl3SimpleTypedIntegerValueMap.Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of AnsiString);
//#UC START# *478E21AD021D_478E1E3A0182_var*
var
l_Index: Integer;
//#UC END# *478E21AD021D_478E1E3A0182_var*
begin
//#UC START# *478E21AD021D_478E1E3A0182_impl*
inherited Create(aID, aTypeInfo);
Assert(Length(aValues)=(f_TypeData.MaxValue-f_TypeData.MinValue+1),Format('Typed map %s - Mismatch map size',[rMapID.rName]));
SetLength(f_Values, f_TypeData.MaxValue-f_TypeData.MinValue+1);
for l_Index := Low(aValues) to High(aValues) do
f_Values[l_Index-Low(aValues)+Low(f_Values)] := aValues[l_Index];
Assert(Length(aValues)=(f_TypeData.MaxValue-f_TypeData.MinValue+1),Format('Typed map %s - Mismatch map size',[rMapID.rName]));
//#UC END# *478E21AD021D_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.Create
class function Tl3SimpleTypedIntegerValueMap.Make(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of AnsiString): Il3IntegerValueMap;
var
l_Inst : Tl3SimpleTypedIntegerValueMap;
begin
l_Inst := Create(aID, aTypeInfo, aValues);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tl3SimpleTypedIntegerValueMap.Make
function Tl3SimpleTypedIntegerValueMap.DoDisplayNameToValue(const aDisplayName: Il3CString): Integer;
//#UC START# *478E235D0041_478E1E3A0182_var*
var
l_Index: Integer;
//#UC END# *478E235D0041_478E1E3A0182_var*
begin
//#UC START# *478E235D0041_478E1E3A0182_impl*
for l_Index := Low(f_Values) to High(f_Values) do
if l3Same(aDisplayName, f_Values[l_Index]) then
begin
Result := l_Index + f_TypeData.MinValue - Low(f_Values);
exit;
end;//l3Same(aDisplayName,
raise El3ValueMapValueNotFound.CreateFmt('Display name %s not found in Map %d',[l3Str(aDisplayName), rMapID.rID]);
//#UC END# *478E235D0041_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.DoDisplayNameToValue
function Tl3SimpleTypedIntegerValueMap.DoValueToDisplayName(aValue: Integer): Il3CString;
//#UC START# *478E237001B3_478E1E3A0182_var*
//#UC END# *478E237001B3_478E1E3A0182_var*
begin
//#UC START# *478E237001B3_478E1E3A0182_impl*
if (aValue<f_TypeData.MinValue) or (aValue>f_TypeData.MaxValue) then
raise El3ValueMapValueNotFound.CreateFmt('Value %d not found in Map %s',[aValue,rMapID.rName]);
Result := l3CStr(f_Values[aValue - f_TypeData.MinValue + Low(f_Values)]);
//#UC END# *478E237001B3_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.DoValueToDisplayName
procedure Tl3SimpleTypedIntegerValueMap.DoGetDisplayNames(const aList: Il3StringsEx);
//#UC START# *478CFFBA017D_478E1E3A0182_var*
var
l_Index: Integer;
//#UC END# *478CFFBA017D_478E1E3A0182_var*
begin
//#UC START# *478CFFBA017D_478E1E3A0182_impl*
inherited;
for l_Index := Low(f_Values) To High(f_Values) Do
aList.Add(f_values[l_Index]);
//#UC END# *478CFFBA017D_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.DoGetDisplayNames
function Tl3SimpleTypedIntegerValueMap.GetMapSize: Integer;
//#UC START# *478CFFCE02DE_478E1E3A0182_var*
//#UC END# *478CFFCE02DE_478E1E3A0182_var*
begin
//#UC START# *478CFFCE02DE_478E1E3A0182_impl*
Result := Length(f_Values);
//#UC END# *478CFFCE02DE_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.GetMapSize
procedure Tl3SimpleTypedIntegerValueMap.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_478E1E3A0182_var*
//#UC END# *479731C50290_478E1E3A0182_var*
begin
//#UC START# *479731C50290_478E1E3A0182_impl*
f_Values := nil;
inherited;
//#UC END# *479731C50290_478E1E3A0182_impl*
end;//Tl3SimpleTypedIntegerValueMap.Cleanup
constructor Tl3ResourceTypedIntegerValueMap.Create(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of PResStringRec);
//#UC START# *478E212D0257_478E1DFA01DF_var*
var
l_Index: Integer;
//#UC END# *478E212D0257_478E1DFA01DF_var*
begin
//#UC START# *478E212D0257_478E1DFA01DF_impl*
inherited Create(aID, aTypeInfo);
Assert(Length(aValues)=(f_TypeData.MaxValue-f_TypeData.MinValue+1),Format('Typed map %s - Mismatch map size',[rMapID.rName]));
SetLength(f_Values, f_TypeData.MaxValue-f_TypeData.MinValue+1);
for l_Index := Low(aValues) to High(aValues) do
f_Values[l_Index-Low(aValues)+Low(f_Values)] := aValues[l_Index];
Assert(Length(aValues)=(f_TypeData.MaxValue-f_TypeData.MinValue+1),Format('Typed map %s - Mismatch map size',[rMapID.rName]));
//#UC END# *478E212D0257_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.Create
class function Tl3ResourceTypedIntegerValueMap.Make(const aID: Tl3ValueMapID;
aTypeInfo: PTypeInfo;
const aValues: array of PResStringRec): Il3IntegerValueMap;
var
l_Inst : Tl3ResourceTypedIntegerValueMap;
begin
l_Inst := Create(aID, aTypeInfo, aValues);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tl3ResourceTypedIntegerValueMap.Make
function Tl3ResourceTypedIntegerValueMap.DoDisplayNameToValue(const aDisplayName: Il3CString): Integer;
//#UC START# *478E235D0041_478E1DFA01DF_var*
var
l_Index: Integer;
//#UC END# *478E235D0041_478E1DFA01DF_var*
begin
//#UC START# *478E235D0041_478E1DFA01DF_impl*
for l_Index := Low(f_Values) to High(f_Values) do
if l3Same(aDisplayName, l3CStr(f_Values[l_Index])) then
begin
Result := l_Index + f_TypeData.MinValue - Low(f_Values);
exit;
end;//l3Same(aDisplayName,
raise El3ValueMapValueNotFound.CreateFmt('Display name %s not found in Map %d',[l3Str(aDisplayName),rMapID.rID]);
//#UC END# *478E235D0041_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.DoDisplayNameToValue
function Tl3ResourceTypedIntegerValueMap.DoValueToDisplayName(aValue: Integer): Il3CString;
//#UC START# *478E237001B3_478E1DFA01DF_var*
//#UC END# *478E237001B3_478E1DFA01DF_var*
begin
//#UC START# *478E237001B3_478E1DFA01DF_impl*
if (aValue<f_TypeData.MinValue) or (aValue>f_TypeData.MaxValue) then
raise El3ValueMapValueNotFound.CreateFmt('Value %d not found in Map %s',[aValue,rMapID.rName]);
Result := l3CStr(f_Values[aValue - f_TypeData.MinValue + Low(f_Values)]);
//#UC END# *478E237001B3_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.DoValueToDisplayName
procedure Tl3ResourceTypedIntegerValueMap.DoGetDisplayNames(const aList: Il3StringsEx);
//#UC START# *478CFFBA017D_478E1DFA01DF_var*
var
l_Index: Integer;
//#UC END# *478CFFBA017D_478E1DFA01DF_var*
begin
//#UC START# *478CFFBA017D_478E1DFA01DF_impl*
inherited;
for l_Index := Low(f_Values) To High(f_Values) Do
aList.Add(l3CStr(f_values[l_Index]));
//#UC END# *478CFFBA017D_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.DoGetDisplayNames
function Tl3ResourceTypedIntegerValueMap.GetMapSize: Integer;
//#UC START# *478CFFCE02DE_478E1DFA01DF_var*
//#UC END# *478CFFCE02DE_478E1DFA01DF_var*
begin
//#UC START# *478CFFCE02DE_478E1DFA01DF_impl*
Result := Length(f_Values);
//#UC END# *478CFFCE02DE_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.GetMapSize
procedure Tl3ResourceTypedIntegerValueMap.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_478E1DFA01DF_var*
//#UC END# *479731C50290_478E1DFA01DF_var*
begin
//#UC START# *479731C50290_478E1DFA01DF_impl*
f_Values := nil;
inherited;
//#UC END# *479731C50290_478E1DFA01DF_impl*
end;//Tl3ResourceTypedIntegerValueMap.Cleanup
end.
|
UNIT VIDEO;
INTERFACE
uses dos,crt;
const videoseg:word=$B800;
type twin=array[0..8003] of byte;
var win:twin;
FUNCTION ISEGAVGA:byte;
PROCEDURE GETVIDEOMODE(var modevideo,nbrecol,page:byte);
PROCEDURE SETVIDEOMODE(mode:word);
PROCEDURE SCREENOFF;
PROCEDURE SCREENON;
{Mode TEXTE seuleument}
Procedure Setpage(page:shortint);
PROCEDURE GETXYPOS(var x:integer;var y:integer);
PROCEDURE SETXYPOS(x,y:integer);
PROCEDURE SAUVEXY;
PROCEDURE RESTAUREXY;
PROCEDURE CAPTURESCREEN(x1,y1,x2,y2:integer;var win:twin);
PROCEDURE RESTORESCREEN(win:twin);
PROCEDURE CURSOROFF;
PROCEDURE CURSORON;
PROCEDURE SETMOUSE(et,ou_exclusif:word);
PROCEDURE SCROLLUP(nombre,couleur,x1,y1,x2,y2:byte);
FUNCTION CHARLOC(x,y:byte):Char;
{Mode GRAPHIQUE seuleument}
Procedure Putpixel(X,Y:word;color:byte);
Procedure Line(X1,Y1,X2,Y2,color:longint);
IMPLEMENTATION
FUNCTION ISEGAVGA:byte;
{*******************************************************}
{ Renvoie $00: Pas de carte vid‚o
{ $01: MDA monochrome
{ $02: CGA ‚cran CGA
{ $04: EGA ‚cran EGA
{ $05: EGA ‚cran monochrome
{ $07: VGA ‚cran monochrome
{ $08: VGA ‚cran couleur
{*******************************************************}
var regs:registers;
begin
regs.ax:=$1A00; { La fonction 1Ah n'existe que pour VGA }
intr($10,regs);
if (regs.al=$1A) then { La fonction est-elle disponible ? }
Isegavga:=regs.bl { Oui, une carte VGA est install‚e }
else begin { Pas de VGA, mais peut-ˆtre EGA }
regs.ah:=$12; { Appelle option 10h }
regs.bl:=$10; { de la fonction 12h }
intr($10,regs); { Interruption vid‚o }
if (regs.bl<>$10) then { Est-ce une carte EGA ? }
begin { Oui, recherche l'‚cran associ‚ }
if regs.bh=$00 then IsEgaVga:=$04 { EGA Mono }
else IsEgaVga:=$05; { EGA Couleur }
end
else IsEgaVga:=$00;
end;
end;
PROCEDURE GETVIDEOMODE(var modevideo,nbrecol,page:byte);
{*******************************************************}
{ Lit mode vid‚o:
{ $00: 40*25 car monochrome
{ $01: 40*25 car couleur
{ $02: 80*25 car monochrome
{ $03: 80*25 car couleur Mode TEXTE par d‚faut
{ $04: 320*200*4 CGA
{ $06: 640*200*2 CGA
{ $0D: 320*200*16 EGA 2 pages (64K)
{ $0E: 640*200*16 EGA 4 pages (64K)
{ $0F: 640*350 monochrome EGA 2 pages
{ $10: 640*350*16 EGA 2 pages (128K)
{ $11: 640*480*2 VGA 4 pages (256K)
{ $12: 640*480*16 VGA 1 page (256K)
{ $13: 320*200*256 VGA 4 pages (256K)
{*******************************************************}
var regs:registers;
begin
regs.ah:=$0F; { Fonction $0F: Lecture mode vid‚o }
intr($10,Regs); { Interruption vid‚o du BIOS }
modevideo:=regs.al; { Mode vid‚o }
nbrecol:=regs.ah; { Nombre colonnes par ligne }
page:=regs.bh; { Num‚ro page ‚cran courante }
end;
PROCEDURE SETVIDEOMODE(mode:word);
{*******************************************************}
{ S‚lectionne mode video:
{ $00: 40*25 car monochrome
{ $01: 40*25 car couleur
{ $02: 80*25 car monochrome
{ $03: 80*25 car couleur Mode TEXTE par d‚faut
{ $04: 320*200*4 CGA
{ $06: 640*200*2 CGA
{ $0D: 320*200*16 EGA 2 pages (64K)
{ $0E: 640*200*16 EGA 4 pages (64K)
{ $0F: 640*350 monochrome EGA 2 pages
{ $10: 640*350*16 EGA 2 pages (128K)
{ $11: 640*480*2 VGA 4 pages (256K)
{ $12: 640*480*16 VGA 1 page (256K)
{ $13: 320*200*256 VGA 4 pages (256K)
{*******************************************************}
var regs:registers;
begin
regs.ax:=mode; { Fonction AH=$00, AL=mode video }
intr($10,Regs); { Interruption vid‚o du BIOS }
end;
PROCEDURE SCREENOFF;
{*******************************************************}
{ Eteint ‚cran
{*******************************************************}
const EGAVGA_C=$3DA; { Registre d'‚tat couleur EGA/VGA }
EGAVGA_M=$3BA; { Registre d'‚tat mono EGA/VGA }
EGAVGA_A=$3C0; { Contr“leur d'attribut EGA/VGA }
var savebyte:byte; { Pour m‚moriser les contenus des registres }
begin
inline($FA); { CLI inhibe les interruptions }
savebyte:=port[EGAVGA_M]; { Reset du registre d'‚tat mono }
savebyte:=port[EGAVGA_C]; { Reset du registre d'‚tat couleur }
port[EGAVGA_A]:=$00; { Efface le bit 5 ce qui supprime la liaison avec le contr“leur d'‚cran }
inline($FB); { STI r‚tablit les interruptions }
end;
PROCEDURE SCREENON;
{*******************************************************}
{ Rallume ‚cran
{*******************************************************}
const EGAVGA_C=$3DA; { Registre d'‚tat couleur EGA/VGA }
EGAVGA_M=$3BA; { Registre d'‚tat mono EGA/VGA }
EGAVGA_A=$3C0; { Contr“leur d'attribut EGA/VGA }
var savebyte:byte;
begin
inline($FA); { CLI Inhibe les interruptions }
savebyte:=port[EGAVGA_M]; { Reset du registre d'‚tat mono }
savebyte:=port[EGAVGA_C]; { Reset du registre d'‚tat couleur }
port[EGAVGA_A]:=$20; { Active le bit 5 ce qui r‚tablit la liaison avec le contr“leur d'‚cran}
inline($FB); { STI r‚tablit les interruptions }
end;
{ En mode Texte uniquement }
FUNCTION GETPAGE:shortint;
{*******************************************************}
{ S‚lectionne nouvelle page d'‚cran
{*******************************************************}
var regs:registers;
begin
regs.ah:=$0F; { Fonction $0F: Lecture mode vid‚o }
intr($10,Regs); { Interruption vid‚o du BIOS }
GETPAGE:=regs.bh; { Num‚ro page ‚cran courante }
end;
PROCEDURE SETPAGE(page:shortint);
{*******************************************************}
{ S‚lectionne nouvelle page d'‚cran
{*******************************************************}
var regs:registers;
begin
regs.ah:=$05; { Fonction 05h: Set Page }
regs.al:=page; { Page d'‚cran }
intr($10,regs); { D‚clenche l'interruption vid‚o du BIOS }
end;
PROCEDURE GETXYPOS(var x,y:integer);
{*******************************************************}
{Retourne position absolue du curseur (x:1-80,y:1-25,1-43,1-50)
{*******************************************************}
begin
x:=wherex+lo(windmin);
y:=wherey+hi(windmin);
end;
PROCEDURE SETXYPOS(x,y:integer);
{*******************************************************}
{Positionne curseur aux coordonn‚es absolues x,y (x:1-80,y:1-25,1-43,1-50)
{*******************************************************}
var i,j:integer;
begin
i:=lo(windmin);j:=hi(windmin);
if (x>=i) and (y>=j) then gotoxy(x-i,y-i);
end;
var wmin,wmax,x,y:word;
PROCEDURE SAUVEXY;
{*******************************************************}
{Sauve configuration de windmin,windmax,wherex,wherey.
{*******************************************************}
begin
wmin:=windmin;wmax:=windmax;
x:=wherex;y:=wherey;
end;
PROCEDURE RESTAUREXY;
{*******************************************************}
{Restaure configuration de windmin,windmax,wherew,wherey.
{A appeler aprŠs SAUVEXY.
{*******************************************************}
begin
windmin:=wmin;windmax:=wmax;
gotoxy(x,y);
end;
PROCEDURE CAPTURESCREEN(x1,y1,x2,y2:integer;var win:twin);
{*******************************************************}
{Enregistre m‚moire vid‚o pour ‚cran jusque 80x50
{x1,x2 compris entre 1 et 80
{y1,y2 compris entre 1 et 50
{*******************************************************}
var x,y,i:integer;
begin
win[8000]:=x1;
win[8001]:=y1;
win[8002]:=x2;
win[8003]:=y2;
i:=0;
inline ($FA);
for y:=y1 to y2 do
for x:=x1 to x2 do begin
win[i]:=mem[videoseg:(160*(y-1)+2*(x-1))];
win[i+1]:=mem[videoseg:(160*(y-1)+2*(x-1))+1];
inc(i,2);
end;
inline($FB);
end;
PROCEDURE RESTORESCREEN(win:twin);
{*******************************************************}
{x1,x2 compris entre 1 et 80
{y1,y2 compris entre 1 et 50
{*******************************************************}
var x1,y1,x2,y2,x,y,i:integer;
begin
x1:=win[8000];
y1:=win[8001];
x2:=win[8002];
y2:=win[8003];
i:=0;
inline($FA);
for y:=y1 To y2 do
for x:=x1 To x2 do begin
mem[$B800:(160*(y-1)+2*(x-1))]:=win[i];
mem[$B800:(160*(y-1)+2*(x-1))+1]:=win[i+1];
inc(i,2);
end;
inline($FB);
end;
PROCEDURE CURSOROFF;
{*******************************************************}
{D‚sactive curseur clignotant
{*******************************************************}
begin
end;
PROCEDURE CURSORON;
{*******************************************************}
{R‚active curseur clignotant
{*******************************************************}
var regs:registers;
begin
regs.ch:=$06;
regs.cl:=$07;
regs.ah:=$01;
intr($10,regs);
end;
PROCEDURE SETMOUSE(et,ou_exclusif:word);
{*******************************************************}
{S‚lectionne type curseur souris
{Valeurs par d‚faut: et=$FFFF,ou_exclusif:=$7700
{*******************************************************}
var regs:registers;
begin
regs.ax:=$000A;
regs.bx:=0;
regs.cx:=et;
regs.dx:=ou_exclusif;
intr($33,regs);
end;
PROCEDURE SCROLLUP(nombre,couleur,x1,y1,x2,y2:byte);
{*******************************************************}
{ Fait avancer une zone fenetr‚e d'une ou plusieurs lignes
{ vers le haut ou l'efface
{ Entr‚e: NOMBRE = Nombre de lignes … faire d‚filer
{ COULEUR = Couleur ou Attribut des lignes vides
{ COLSG = Colonne du coin sup‚rieur gauche de la zone
{ LIGNSG = Ligne du coin sup‚rieur gauche de la zone
{ COLID = Colonne du coin inf‚rieur droit de la zone
{ LIGNID = Ligne du coin inf‚rieur droit de la zone
{ Sortie: Aucune
{ Infos : Si nombre=0, la zone est alors compl‚t‚e par des espaces
{*******************************************************}
var regs:registers;
begin
regs.ah:=$06;
regs.al:=nombre;
regs.bh:=couleur;
regs.cl:=x1;
regs.ch:=y1;
regs.dl:=x2;
regs.dh:=y2;
intr($10,regs);
end;
FUNCTION CHARLOC(x,y:byte):char;
{*******************************************************}
{ Retourne le char aux coordonn‚es (x,y) absolues sans
{ changer position du curseur
{*******************************************************}
begin
charloc:=chr(mem[videoseg:(80*y+x-81) shl 1])
end;
{ En mode Graphique uniquement }
PROCEDURE PUTPIXEL(x,y:word;color:byte);
{*******************************************************}
{ Allume pixel en (x,y)
{*******************************************************}
begin
mem[$A000:y*320+x]:=color;
end;
PROCEDURE SWITCH(Var First,Second:integer);
{ Echange valeur premier et second }
Var i:integer;
begin
i:=first;
first:=second;
second:=i;
end;
PROCEDURE LINE(X1,Y1,X2,Y2,color:longint);
{*******************************************************}
{ Dessine ligne avec algorithme de Bresenham
{*******************************************************}
Var LgDelta,ShDelta,LgStep,ShStep,Cycle:integer;
begin
LgDelta:=X2-X1;
ShDelta:=Y2-Y1;
if LgDelta<0 then begin
LgDelta:=-LgDelta;
LgStep:=-1;
end
else LgStep:=1;
if ShDelta<0 then begin
ShDelta:=-ShDelta;
ShStep:=-1;
end
else ShStep:=1;
if LgDelta>ShDelta then begin
Cycle:=LgDelta shr 1; { LgDelta/2 }
While X1<>X2 do begin
mem[$A000:Y1*320+X1]:=Color; { PutPixel(X1,Y1,Color); }
inc(X1,LgStep);
inc(Cycle,ShDelta);
if Cycle>LgDelta then begin
Inc(Y1,shstep);
dec(cycle,lgdelta);
end;
end;
end
else begin
Cycle:=ShDelta shr 1; { ShDelta/2 }
Switch(LgDelta,shdelta);
Switch(LgStep,shstep);
While Y1<>Y2 do begin
mem[$A000:Y1*320+X1]:=color; { PutPixel(X1,Y1,Color); }
inc(Y1,LgStep);
inc(Cycle,ShDelta);
if cycle>LgDelta then begin
inc(X1,shstep);
dec(cycle,lgdelta);
end;
end;
end;
end;
begin
if mem[$40:$63]=$3B4 then videoseg:=$B000; {Carte monochrome}
end.
|
unit TreeAttributeFirstLevelKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы TreeAttributeFirstLevel }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search\Forms\TreeAttributeFirstLevelKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "TreeAttributeFirstLevelKeywordsPack" MUID: (4AB8D5F8025F_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, TreeAttributeFirstLevel_Form
, tfwPropertyLike
, nscTreeViewWithAdapterDragDrop
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4AB8D5F8025F_Packimpl_uses*
//#UC END# *4AB8D5F8025F_Packimpl_uses*
;
type
TkwEfTreeAttributeFirstLevelFirstLevelContent = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefTreeAttributeFirstLevel.FirstLevelContent }
private
function FirstLevelContent(const aCtx: TtfwContext;
aefTreeAttributeFirstLevel: TefTreeAttributeFirstLevel): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TefTreeAttributeFirstLevel.FirstLevelContent }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent
Tkw_Form_TreeAttributeFirstLevel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы TreeAttributeFirstLevel
----
*Пример использования*:
[code]форма::TreeAttributeFirstLevel TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_TreeAttributeFirstLevel
Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола FirstLevelContent
----
*Пример использования*:
[code]контрол::FirstLevelContent TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent
Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола FirstLevelContent
----
*Пример использования*:
[code]контрол::FirstLevelContent:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push
function TkwEfTreeAttributeFirstLevelFirstLevelContent.FirstLevelContent(const aCtx: TtfwContext;
aefTreeAttributeFirstLevel: TefTreeAttributeFirstLevel): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TefTreeAttributeFirstLevel.FirstLevelContent }
begin
Result := aefTreeAttributeFirstLevel.FirstLevelContent;
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.FirstLevelContent
class function TkwEfTreeAttributeFirstLevelFirstLevelContent.GetWordNameForRegister: AnsiString;
begin
Result := '.TefTreeAttributeFirstLevel.FirstLevelContent';
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.GetWordNameForRegister
function TkwEfTreeAttributeFirstLevelFirstLevelContent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.GetResultTypeInfo
function TkwEfTreeAttributeFirstLevelFirstLevelContent.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.GetAllParamsCount
function TkwEfTreeAttributeFirstLevelFirstLevelContent.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefTreeAttributeFirstLevel)]);
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.ParamsTypes
procedure TkwEfTreeAttributeFirstLevelFirstLevelContent.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству FirstLevelContent', aCtx);
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.SetValuePrim
procedure TkwEfTreeAttributeFirstLevelFirstLevelContent.DoDoIt(const aCtx: TtfwContext);
var l_aefTreeAttributeFirstLevel: TefTreeAttributeFirstLevel;
begin
try
l_aefTreeAttributeFirstLevel := TefTreeAttributeFirstLevel(aCtx.rEngine.PopObjAs(TefTreeAttributeFirstLevel));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefTreeAttributeFirstLevel: TefTreeAttributeFirstLevel : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(FirstLevelContent(aCtx, l_aefTreeAttributeFirstLevel));
end;//TkwEfTreeAttributeFirstLevelFirstLevelContent.DoDoIt
function Tkw_Form_TreeAttributeFirstLevel.GetString: AnsiString;
begin
Result := 'efTreeAttributeFirstLevel';
end;//Tkw_Form_TreeAttributeFirstLevel.GetString
class procedure Tkw_Form_TreeAttributeFirstLevel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TefTreeAttributeFirstLevel);
end;//Tkw_Form_TreeAttributeFirstLevel.RegisterInEngine
class function Tkw_Form_TreeAttributeFirstLevel.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::TreeAttributeFirstLevel';
end;//Tkw_Form_TreeAttributeFirstLevel.GetWordNameForRegister
function Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.GetString: AnsiString;
begin
Result := 'FirstLevelContent';
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.GetString
class procedure Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.RegisterInEngine
class function Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::FirstLevelContent';
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.GetWordNameForRegister
procedure Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('FirstLevelContent');
inherited;
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push.DoDoIt
class function Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::FirstLevelContent:push';
end;//Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push.GetWordNameForRegister
initialization
TkwEfTreeAttributeFirstLevelFirstLevelContent.RegisterInEngine;
{* Регистрация efTreeAttributeFirstLevel_FirstLevelContent }
Tkw_Form_TreeAttributeFirstLevel.RegisterInEngine;
{* Регистрация Tkw_Form_TreeAttributeFirstLevel }
Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent.RegisterInEngine;
{* Регистрация Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent }
Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push.RegisterInEngine;
{* Регистрация Tkw_TreeAttributeFirstLevel_Control_FirstLevelContent_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TefTreeAttributeFirstLevel));
{* Регистрация типа TefTreeAttributeFirstLevel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
program ejericicio13;
const
Pi = 3.1415;
procedure circulo(radio:Real; var diametro: Real; var perimetro: Real);
begin
diametro:= 2 * radio;
perimetro:= 2*pi*radio;
end;
var
radio,diametro,perimetro: Real;
begin
write('Ingrese el radio de un circulo: ');
readln(radio);
circulo(radio, diametro, perimetro);
writeln('El DIAMETRO del circulo es: ', diametro:2:2);
writeln('El PERIMETRO del circulo es: ', perimetro:2:2);
readln();
end. |
unit kwPopEditorSplitCell;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSplitCell.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SplitCell
//
// *Формат:* aOrientation anEditorControl pop:editor:SplitCell
// *Описание:* Разделяет ячейку таблицы. Курсор должен уже находиться в ячейке. Параметры
// aOrientation - Boolean (True - разбивать по вертикали, False - разбивать по горизонтали).
// *Пример:*
// {code}
// True focused:control:push pop:editor:SplitCell
// {code}
// *Результат:* Разбивает ячейку, в которой установлен курсор, по верикали.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
evCustomEditor,
tfwScriptingInterfaces,
evCustomEditorWindow,
Controls,
Classes
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas}
TkwPopEditorSplitCell = {final} class(_kwEditorWithToolsFromStackWord_)
{* *Формат:* aOrientation anEditorControl pop:editor:SplitCell
*Описание:* Разделяет ячейку таблицы. Курсор должен уже находиться в ячейке. Параметры aOrientation - Boolean (True - разбивать по вертикали, False - разбивать по горизонтали).
*Пример:*
[code]
True focused:control:push pop:editor:SplitCell
[code]
*Результат:* Разбивает ячейку, в которой установлен курсор, по верикали. }
protected
// realized methods
procedure DoEditorWithTools(const aCtx: TtfwContext;
anEditor: TevCustomEditor); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorSplitCell
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
l3Interfaces,
evEditorInterfaces,
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade,
Forms
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopEditorSplitCell;
{$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas}
// start class TkwPopEditorSplitCell
procedure TkwPopEditorSplitCell.DoEditorWithTools(const aCtx: TtfwContext;
anEditor: TevCustomEditor);
//#UC START# *4F4DD89102E4_5028F0180013_var*
var
l_Cell : IedCell;
l_Table: IedTable;
//#UC END# *4F4DD89102E4_5028F0180013_var*
begin
//#UC START# *4F4DD89102E4_5028F0180013_impl*
if aCtx.rEngine.IsTopBool then
begin
l_Table := anEditor.Range.Table;
if (l_Table <> nil) then
begin
l_Cell := l_Table.Cell;
if (l_Cell <> nil) then
if aCtx.rEngine.PopBool then
l_Cell.Split(ev_orVertical)
else
l_Cell.Split(ev_orHorizontal);
end;//l_Table <> nil
end // if aCtx.rEngine.IsTopBool then
else
Assert(False, 'Не задано как делить!');
//#UC END# *4F4DD89102E4_5028F0180013_impl*
end;//TkwPopEditorSplitCell.DoEditorWithTools
class function TkwPopEditorSplitCell.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:editor:SplitCell';
end;//TkwPopEditorSplitCell.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit uFrmEditarLembrete;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.ComCtrls, Vcl.StdCtrls,
Vcl.ExtCtrls, uLembreteDAO, uLembrete;
type
TFrmEditar = class(TForm)
Label1: TLabel;
Panel1: TPanel;
EdtTitulo: TEdit;
MDescricao: TMemo;
Label2: TLabel;
Label3: TLabel;
DTData: TDateTimePicker;
BtnSalvar: TSpeedButton;
BtnExcluir: TSpeedButton;
DTHora: TDateTimePicker;
procedure FormDestroy(Sender: TObject);
procedure BtnExcluirClick(Sender: TObject);
procedure BtnSalvarClick(Sender: TObject);
private
{ Private declarations }
LembreteDAO: TLembreteDAO;
Lembrete: TLembrete;
procedure PreencherLembrete;
procedure PreencherTela;
public
{ Public declarations }
constructor Create(AOwner: TComponent; pLembrete: TLembrete);
end;
var
FrmEditarLembrete: TFrmEditar;
implementation
{$R *.dfm}
{ TFrmEditar }
procedure TFrmEditar.BtnExcluirClick(Sender: TObject);
begin
LembreteDAO.Deletar(Lembrete);
ShowMessage('Registro Deletado');
Close;
end;
procedure TFrmEditar.BtnSalvarClick(Sender: TObject);
begin
PreencherLembrete;
if LembreteDAO.Alterar(Lembrete) then
begin
ShowMessage('Registro Editado');
Close;
end;
end;
constructor TFrmEditar.Create(AOwner: TComponent; pLembrete: TLembrete);
begin
inherited Create(AOwner);
LembreteDAO := TLembreteDAO.Create;
try
if Assigned(pLembrete) then
begin
Lembrete := pLembrete;
PreencherTela;
end;
except
on e: Exception do
raise Exception.Create(e.Message);
end;
end;
procedure TFrmEditar.FormDestroy(Sender: TObject);
begin
Try
if Assigned(LembreteDAO) then
FreeAndNil(LembreteDAO);
if Assigned(Lembrete) then
FreeAndNil(Lembrete);
except
on e: Exception do
raise Exception.Create(e.Message);
End;
end;
procedure TFrmEditar.PreencherLembrete;
begin
Lembrete.titulo := EdtTitulo.Text;
Lembrete.descricao := MDescricao.Lines.Text;
Lembrete.data := DTData.Date;
Lembrete.hora := DTHora.Time;
end;
procedure TFrmEditar.PreencherTela;
begin
EdtTitulo.Text := Lembrete.titulo;
MDescricao.Lines.Text := Lembrete.descricao;
DTData.Date := Lembrete.data;
DTHora.Time := Lembrete.hora;
end;
end.
|
{ Subroutine SST_W_C_ARMODE_PUSH (MODE)
*
* Set the new mode for interpreting array identifiers. The old array identifier
* interpretation state is saved on the stack.
}
module sst_w_c_ARMODE_PUSH;
define sst_w_c_armode_push;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_armode_push ( {set new array interpret mode, save old}
in mode: array_k_t); {new array identifier interpretation mode}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
f_p: frame_array_p_t; {points to new stack frame}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
%debug; write (sst_stack^.last_p^.curr_adr, ' ');
%debug; writeln ('ARMODE PUSH');
util_stack_push (sst_stack, sizeof(f_p^), f_p); {create new stack frame}
f_p^.addr_cnt := addr_cnt_ar; {save current state on stack frame}
f_p^.mode := array_mode;
array_mode := mode; {set new array interpretation state}
case array_mode of {what does raw array name represent ?}
array_whole_k: begin {name represents data in the whole array}
addr_cnt_ar := 0; {this is what we always assume}
end;
array_pnt_whole_k, {name represents pointer to whole array data}
array_pnt_first_k: begin {name represents pointer to first element}
addr_cnt_ar := -1; {dereference pointer once to get array value}
end;
otherwise
sys_msg_parm_int (msg_parm[1], ord(array_mode));
sys_message_bomb ('sst_c_write', 'array_mode_unexpected', msg_parm, 1);
end;
end;
|
{
в таблице calculated_data (Reports) переписываются данными 2го расчета
кроме красных пределов
}
unit thread_calculated_data;
interface
uses
SysUtils, Classes, Windows, ActiveX, System.Variants, Math,
ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, ZAbstractRODataset,
Types, Generics.Collections;
type
TThreadCalculatedData = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
TIdHeat = Record
tid : integer;
Heat : string[26]; // плавка
Grade : string[50]; // марка стали
Section : string[50]; // профиль
Standard : string[50]; // стандарт
StrengthClass : string[50]; // клас прочности
c : string[50];
mn : string[50];
cr : string[50];
si : string[50];
b : string[50];
ce : string[50];
OldStrengthClass : string[50]; // старый клас прочности
old_tid : integer; // стара плавка
marker : bool;
LowRed : integer;
HighRed : integer;
LowGreen : integer;
HighGreen : integer;
step : integer;
constructor Create(_tid: integer; _Heat, _Grade, _Section, _Standard, _StrengthClass,
_c, _mn, _cr, _si, _b, _ce, _OldStrengthClass: string;
_old_tid: integer; _marker: bool; _LowRed, _HighRed,
_LowGreen, _HighGreen, _step: integer);
end;
var
ThreadCalculatedData: TThreadCalculatedData;
left, right: TIdHeat;
{$DEFINE DEBUG}
procedure WrapperCalculatedData; // обертка для синхронизации и выполнения с другим потоком
function ReadCurrentHeat: bool;
function CalculatingInMechanicalCharacteristics(InHeat: string; InSide: integer): string;
function CarbonEquivalent(InHeat: string; InSide: integer): bool;
function HeatToIn(InHeat: string): string;
function CutChar(InData: string): string;
function GetDigits(InData: string): string;
function GetMedian(aArray: TDoubleDynArray): Double;
implementation
uses
logging, settings, main, sql;
procedure TThreadCalculatedData.Execute;
begin
CoInitialize(nil);
while not Terminated do
begin
Synchronize(WrapperCalculatedData);
sleep(1000);
end;
CoUninitialize;
end;
procedure WrapperCalculatedData;
begin
try
if not PConnect.Ping then
PConnect.Reconnect;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
try
// точка вместо запятой при преобразовании в строку
FormatSettings.DecimalSeparator := '.';
ReadCurrentHeat;
except
on E: Exception do
SaveLog('error'+#9#9+E.ClassName+', с сообщением: '+E.Message);
end;
end;
function ReadCurrentHeat: bool;
var
i: integer;
HeatAllLeft, HeatAllRight: string;
begin
for i := 0 to 1 do
begin
// side left=0, side right=1
PQuery.Close;
PQuery.sql.Clear;
PQuery.sql.Add('select t1.tid, t1.heat, t1.strength_class, t1.section,');
PQuery.sql.Add('t2.grade, t2.standard, t2.c, t2.mn, t2.cr, t2.si, t2.b,');
PQuery.sql.Add('cast(t2.c+(mn/6)+(cr/5)+((si+b)/10) as numeric(6,4)) as ce');
PQuery.sql.Add('FROM temperature_current t1');
PQuery.sql.Add('LEFT OUTER JOIN');
PQuery.sql.Add('chemical_analysis t2');
PQuery.sql.Add('on t1.heat=t2.heat');
PQuery.sql.Add('where t1.side='+inttostr(i)+'');
PQuery.sql.Add('order by t1.timestamp desc LIMIT 1');
PQuery.Open;
if i = 0 then
begin
left.tid := PQuery.FieldByName('tid').AsInteger;
left.Heat := PQuery.FieldByName('heat').AsString;
left.Grade := PQuery.FieldByName('grade').AsString;
left.StrengthClass := PQuery.FieldByName('strength_class').AsString;
left.Section := PQuery.FieldByName('section').AsString;
left.Standard := PQuery.FieldByName('standard').AsString;
left.c := PQuery.FieldByName('c').AsString;
left.mn := PQuery.FieldByName('mn').AsString;
left.cr := PQuery.FieldByName('cr').AsString;
left.si := PQuery.FieldByName('si').AsString;
left.b := PQuery.FieldByName('b').AsString;
left.ce := PQuery.FieldByName('ce').AsString;
// новая плавка устанавливаем маркер
if (left.old_tid <> left.tid) or (left.OldStrengthClass <> left.StrengthClass) then
begin
left.old_tid := left.tid;
left.OldStrengthClass := left.StrengthClass;
left.marker := true;
left.LowRed := 0;
left.HighRed := 0;
left.LowGreen := 0;
left.HighGreen := 0;
end;
end
else
begin
right.tid := PQuery.FieldByName('tid').AsInteger;
right.Heat := PQuery.FieldByName('heat').AsString;
right.Grade := PQuery.FieldByName('grade').AsString;
right.StrengthClass := PQuery.FieldByName('strength_class').AsString;
right.Section := PQuery.FieldByName('section').AsString;
right.Standard := PQuery.FieldByName('standard').AsString;
right.c := PQuery.FieldByName('c').AsString;
right.mn := PQuery.FieldByName('mn').AsString;
right.cr := PQuery.FieldByName('cr').AsString;
right.si := PQuery.FieldByName('si').AsString;
right.b := PQuery.FieldByName('b').AsString;
right.ce := PQuery.FieldByName('ce').AsString;
// новая плавка устанавливаем маркер
if (right.old_tid <> right.tid) or (right.OldStrengthClass <> right.StrengthClass) then
begin
right.old_tid := right.tid;
right.OldStrengthClass := right.StrengthClass;
right.marker := true;
right.LowRed := 0;
right.HighRed := 0;
right.LowGreen := 0;
right.HighGreen := 0;
end;
end;
end;
if left.marker or right.marker then
begin
SaveLog('info'+#9#9+inttostr(left.tid)+#9+left.Heat+#9+left.Grade+#9+
left.Section+#9+left.Standard+#9+left.StrengthClass+#9+
left.c+#9+left.mn+#9+left.cr+#9+left.si+#9+left.b+#9+left.ce+#9+
inttostr(left.old_tid)+#9+booltostr(left.marker)+#9+
left.OldStrengthClass);
SaveLog('info'+#9#9+inttostr(right.tid)+#9+right.Heat+#9+right.Grade+#9+
right.Section+#9+right.Standard+#9+right.StrengthClass+#9+
right.c+#9+right.mn+#9+right.cr+#9+right.si+#9+right.b+#9+right.ce+#9+
inttostr(right.old_tid)+#9+booltostr(right.marker)+#9+
right.OldStrengthClass);
end;
if left.marker and (left.ce <> '') then
begin
try
left.marker := false;
// сброс этапа расчета
left.step := 0;
// удаляем при перерасчете
CalculatedData(0, '');
SaveLog('info'+#9#9+'start calculation left side, heat -> '+left.Heat);
// start left step 0
CalculatedData(0, 'timestamp=EXTRACT(EPOCH FROM now())');
HeatAllLeft := CalculatingInMechanicalCharacteristics(RolledMelting(0), 0);
// start left step 1
if not HeatAllLeft.IsEmpty then
begin
CalculatedData(0, 'timestamp=EXTRACT(EPOCH FROM now())');
CarbonEquivalent(HeatAllLeft, 0);
end;
SaveLog('info'+#9#9+'end calculation left side, heat -> '+left.Heat);
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
HeatAllLeft := '';
end;
if right.marker and (right.ce <> '') then
begin
try
right.marker := false;
// сброс этапа расчета
right.step := 0;
// удаляем при перерасчете
CalculatedData(1, '');
SaveLog('info'+#9#9+'start calculation right side, heat -> '+right.Heat);
// start right step 0
CalculatedData(1, 'timestamp=EXTRACT(EPOCH FROM now())');
HeatAllRight := CalculatingInMechanicalCharacteristics(RolledMelting(1), 1);
// start right step 1
if not HeatAllRight.IsEmpty then
begin
CalculatedData(1, 'timestamp=EXTRACT(EPOCH FROM now())');
CarbonEquivalent(HeatAllRight, 1);
end;
SaveLog('info' + #9#9 + 'end calculation right side, heat -> '+right.Heat);
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
HeatAllRight := '';
end;
end;
function CalculatingInMechanicalCharacteristics(InHeat: string; InSide: integer): string;
var
{ yield point - предел текучести
rupture strength - временное сопротивление }
Grade: string; // марка стали
Section: string; // профиль
Standard: string; // стандарт
StrengthClass: string; // клас прочности
ReturnValue: string;
side: string;
RollingScheme: string;
PQueryCalculation: TZQuery;
PQueryData: TZQuery;
i, a, b, CoefficientCount, AdjustmentMin, AdjustmentMax,
LimitRolledProductsMin, LimitRolledProductsMax, HeatCount: integer;
m: bool;
CoefficientYieldPointValue, CoefficientRuptureStrengthValue, MechanicsAvg,
MechanicsStdDev, MechanicsMin, MechanicsMax, MechanicsDiff, CoefficientMin,
CoefficientMax, TempAvg, TempStdDev, TempMin, TempMax, TempDiff, R: real;
TypeRolledProducts, HeatAll, HeatWorks, HeatTableAll: WideString;
HeatArray, HeatTableArray: Array of string;
MechanicsArray, TempArray: Array of Double;
RawTempArray: TDoubleDynArray;
st, HeatTmp: TStringList;
c, mn, si, HeatMechanics: string;
begin
if InSide = 0 then
begin
Grade := left.Grade;
Section := left.Section;
Standard := left.Standard;
StrengthClass := left.StrengthClass;
c := left.c;
mn := left.mn;
si := left.si;
side := 'Левая';
RollingScheme := right.Section; // схема прокатки 14x16, 16x16, 18x16
end
else
begin
Grade := right.Grade;
Section := right.Section;
Standard := right.Standard;
StrengthClass := right.StrengthClass;
c := right.c;
mn := right.mn;
si := right.si;
side := 'Правая';
RollingScheme := left.Section; // схема прокатки 14x16, 16x16, 18x16
end;
if InHeat.IsEmpty then
begin
SaveLog('warning'+#9#9+'сторона -> '+side);
SaveLog('warning'+#9#9 +'недостаточно данных по прокатанным плавкам для расчета по плавке -> '+InHeat);
exit;
end;
PQueryCalculation := TZQuery.Create(nil);
PQueryCalculation.Connection := PConnect;
PQueryData := TZQuery.Create(nil);
PQueryData.Connection := PConnect;
a := 0;
b := a;
HeatAll := HeatToIn(InHeat);
try
OraQuery.Close;
OraQuery.SQL.Clear;
OraQuery.SQL.Add('select * from');
OraQuery.SQL.Add('(select n.nplav heat, n.mst grade, n.GOST standard');
OraQuery.SQL.Add(',n.razm1 section, n.klass strength_class');
OraQuery.SQL.Add(',v.limtek yield_point, v.limproch rupture_strength');
OraQuery.SQL.Add(',ROW_NUMBER() OVER (PARTITION BY n.nplav ORDER BY n.data desc) AS number_row');
OraQuery.SQL.Add('from czl_v v, czl_n n');
//-- 305 = 10 month
OraQuery.SQL.Add('where n.data<=sysdate and n.data>=sysdate-305');
//-- OraQuery.SQL.Add('and n.mst like translate('''+CutChar(Grade)+''','); //переводим Eng буквы похожие на кирилицу
//-- OraQuery.SQL.Add('''ETOPAHKXCBMetopahkxcbm'',''ЕТОРАНКХСВМеторанкхсвм'')');
//-- OraQuery.SQL.Add('and n.GOST like translate('''+CutChar(Standard)+''','); //переводим Eng буквы похожие на кирилицу
//-- OraQuery.SQL.Add('''ETOPAHKXCBMetopahkxcbm'',''ЕТОРАНКХСВМеторанкхсвм'')');
OraQuery.SQL.Add('and n.razm1 = '+Section+'');
OraQuery.SQL.Add('and translate(n.klass,');
OraQuery.SQL.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
OraQuery.SQL.Add('like translate('''+CutChar(StrengthClass)+''',');
OraQuery.SQL.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
OraQuery.SQL.Add('and n.data=v.data and v.npart=n.npart');
OraQuery.SQL.Add('and n.npart like '''+RollingMillConfigArray[1]+'%'''); // номер стана
if InSide = 0 then
OraQuery.SQL.Add('and mod(n.npart,2)=1')// проверка на четность | 0 четная - левая | 1 - нечетная правая
else
OraQuery.SQL.Add('and mod(n.npart,2)=0');// проверка на четность | 0 четная - левая | 1 - нечетная правая
{ if (StrengthClass = 'S400') or (StrengthClass = 'S400W') then // классы при которых берется до 15 проб
OraQuery.SQL.Add('and nvl(n.npach,0)=nvl(v.npach,0) and NI<=15')
else
OraQuery.SQL.Add('and nvl(n.npach,0)=nvl(v.npach,0) and NI<=3');}
OraQuery.SQL.Add('and nvl(n.npach,0)=nvl(v.npach,0)');
OraQuery.SQL.Add('and prizn=''*'' and ROWNUM <= 251');
OraQuery.SQL.Add('and n.nplav in('+HeatAll+')');
OraQuery.SQL.Add('order by n.data desc)');
if (StrengthClass = 'S400') or (StrengthClass = 'S400W') then // классы при которых берется до 15 проб
OraQuery.SQL.Add('where number_row <= 15')
else
OraQuery.SQL.Add('where number_row <= 3');
OraQuery.Open;
OraQuery.FetchAll;
except
on E: Exception do
begin
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
ConfigOracleSetting(false);
exit;
end;
end;
{$IFDEF DEBUG }
SaveLog('debug'+#9#9+'OraQuery.SQL.Text -> '+OraQuery.SQL.Text);
SaveLog('debug' + #9#9 + 'OraQuery.RecordCount -> '+inttostr(OraQuery.RecordCount));
{$ENDIF}
if OraQuery.RecordCount < 5 then
begin
SaveLog('warning' + #9#9 + 'сторона -> '+side);
SaveLog('warning' + #9#9 + 'недостаточно данных для расчета по плавкам -> '+HeatAll);
exit;
end;
try
PQueryData.sql.Clear;
PQueryData.sql.Add('SELECT n, k_yield_point, k_rupture_strength FROM coefficient');
PQueryData.sql.Add('where n<='+inttostr(OraQuery.RecordCount)+'');
PQueryData.sql.Add('order by n desc limit 1');
PQueryData.Open;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
CoefficientCount := PQueryData.FieldByName('n').AsInteger;
CoefficientYieldPointValue := PQueryData.FieldByName('k_yield_point').AsFloat;
{ CoefficientRuptureStrengthValue - одинаковый с CoefficientYieldPointValue
k_rupture_strength используеться для другого расчета }
CoefficientRuptureStrengthValue := PQueryData.FieldByName('k_yield_point').AsFloat;//PQueryData.FieldByName('k_rupture_strength').AsFloat;
// -- report
CalculatedData(InSide, 'coefficient_count=''' + inttostr(CoefficientCount) + '''');
CalculatedData(InSide, 'coefficient_yield_point_value=''' + floattostr(CoefficientYieldPointValue) + '''');
CalculatedData(InSide, 'coefficient_rupture_strength_value=''' + floattostr(CoefficientRuptureStrengthValue) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CoefficientCount -> ' + inttostr(CoefficientCount));
SaveLog('debug' + #9#9 + 'CoefficientYieldPointValue -> ' + floattostr(CoefficientYieldPointValue));
SaveLog('debug' + #9#9 + 'CoefficientRuptureStrengthValue -> ' + floattostr(CoefficientRuptureStrengthValue));
{$ENDIF}
SQuery.Close;
SQuery.sql.Clear;
SQuery.sql.Add('CREATE TABLE IF NOT EXISTS mechanics');
SQuery.sql.Add('(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE');
SQuery.sql.Add(', heat VARCHAR(26),timestamp INTEGER(10), grade VARCHAR(16)');
SQuery.sql.Add(', standard VARCHAR(16), section VARCHAR(16)');
SQuery.sql.Add(', strength_class VARCHAR(16), yield_point NUMERIC(10,6)');
SQuery.sql.Add(', rupture_strength NUMERIC(10,6), side NUMERIC(1,1) NOT NULL)');
SQuery.ExecSQL;
// -- clean table mechanics
try
SQuery.Close;
SQuery.sql.Clear;
SQuery.sql.Add('delete from mechanics where side=' + inttostr(InSide) + '');
SQuery.ExecSQL;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
i := 1;
while not OraQuery.Eof do
begin
if i <= CoefficientCount then
begin
if (UTF8Decode(OraQuery.FieldByName('heat').AsString) <> HeatMechanics) or
(HeatCount <= 3) then
begin
if HeatCount = 4 then
HeatCount := 0;
HeatMechanics := UTF8Decode(OraQuery.FieldByName('heat').AsString);
inc(HeatCount);
try
SQuery.Close;
SQuery.sql.Clear;
SQuery.sql.Add('insert into mechanics (heat, timestamp, grade, standard');
SQuery.sql.Add(', section , strength_class, yield_point, rupture_strength, side)');
SQuery.sql.Add('values (''' + UTF8Decode(OraQuery.FieldByName('heat').AsString)+'''');
SQuery.sql.Add(', strftime(''%s'', ''now'')');
SQuery.sql.Add(', ''NULL''');
SQuery.sql.Add(', '''+UTF8Decode(OraQuery.FieldByName('standard').AsString)+'''');
SQuery.sql.Add(', '''+OraQuery.FieldByName('section').AsString+'''');
SQuery.sql.Add(', '''+UTF8Decode(OraQuery.FieldByName('strength_class').AsString)+'''');
SQuery.sql.Add(', '''+OraQuery.FieldByName('yield_point').AsString+'''');
SQuery.sql.Add(', '''+OraQuery.FieldByName('rupture_strength').AsString+'''');
SQuery.sql.Add(', '''+inttostr(InSide)+''')');
SQuery.ExecSQL;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
end;
end;
inc(i);
OraQuery.Next;
end;
// -- heat to works
try
SQuery.Close;
SQuery.sql.Clear;
SQuery.sql.Add('select distinct heat from mechanics');
SQuery.sql.Add('where side=' + inttostr(InSide) + '');
SQuery.Open;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
i := 0;
while not SQuery.Eof do
begin
if i = 0 then
HeatAll := '''' + SQuery.FieldByName('heat').AsString + ''''
else
HeatAll := HeatAll+','+''''+SQuery.FieldByName('heat').AsString+'''';
inc(i);
SQuery.Next;
end;
// -- report
CalculatedData(InSide, 'heat_to_work='''+StringReplace(HeatAll, '''', '', [rfReplaceAll])+'''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'HeatAll to works -> ' + HeatAll);
{$ENDIF}
// -- heat to works
// выбор пределов из таблицы technological_sample
try
PQueryData.Close;
PQueryData.sql.Clear;
PQueryData.sql.Add('SELECT limit_min, limit_max, type FROM technological_sample');
PQueryData.sql.Add('where translate(strength_class,');
PQueryData.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryData.sql.Add('like translate('''+StrengthClass+''',');
PQueryData.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryData.sql.Add('and diameter_min <= '+Section+' and diameter_max >= '+Section+'');
PQueryData.sql.Add('and c_min <= '+c+' and c_max >= '+c+'');
PQueryData.sql.Add('and mn_min <= '+mn+' and mn_max >= '+mn+'');
PQueryData.sql.Add('and si_min <= '+si+' and si_max >= '+si+'');
PQueryData.sql.Add('limit 1');
PQueryData.Open;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
if PQueryData.FieldByName('limit_min').IsNull then
begin
SaveLog('warning' + #9#9 + 'сторона -> '+side);
SaveLog('warning' + #9#9 + 'недостаточно данных по технологической инструкции для -> '+InHeat);
exit;
end;
LimitRolledProductsMin := PQueryData.FieldByName('limit_min').AsInteger;
LimitRolledProductsMax := PQueryData.FieldByName('limit_max').AsInteger;
TypeRolledProducts := PQueryData.FieldByName('type').AsString;
// -- report
CalculatedData(InSide, 'limit_rolled_products_min='''+inttostr(LimitRolledProductsMin)+'''');
CalculatedData(InSide, 'limit_rolled_products_max='''+floattostr(LimitRolledProductsMax)+'''');
CalculatedData(InSide, 'type_rolled_products='''+TypeRolledProducts+'''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LimitRolledProductsMin -> '+inttostr(LimitRolledProductsMin));
SaveLog('debug' + #9#9 + 'LimitRolledProductsMax -> '+inttostr(LimitRolledProductsMax));
SaveLog('debug' + #9#9 + 'TypeRolledProducts -> ' + TypeRolledProducts);
SaveLog('debug' + #9#9 + 'RolledProducts RecordCount -> '+inttostr(SQuery.RecordCount));
{$ENDIF}
try
SQuery.Close;
SQuery.sql.Clear;
SQuery.sql.Add('SELECT * FROM mechanics');
SQuery.sql.Add('where side=' + inttostr(InSide) + '');
SQuery.Open;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
if SQuery.RecordCount < 1 then
begin
SaveLog('warning'+#9#9+'сторона -> '+side);
SaveLog('warning'+#9#9+'недостаточно данных по мех. испытаниям для расчета по плавкам -> '+HeatAll);
exit;
end;
i := 0;
while not SQuery.Eof do
begin
if i = length(MechanicsArray) then
SetLength(MechanicsArray, i + 1);
MechanicsArray[i] := SQuery.FieldByName(TypeRolledProducts).AsInteger;
inc(i);
SQuery.Next;
end;
MechanicsAvg := Mean(MechanicsArray);
MechanicsStdDev := StdDev(MechanicsArray);
if TypeRolledProducts = 'yield_point' then
begin
MechanicsMin := MechanicsAvg - MechanicsStdDev * CoefficientYieldPointValue;
MechanicsMax := MechanicsAvg + MechanicsStdDev * CoefficientYieldPointValue;
end;
if TypeRolledProducts = 'rupture_strength' then
begin
MechanicsMin := MechanicsAvg - MechanicsStdDev *
CoefficientRuptureStrengthValue;
MechanicsMax := MechanicsAvg + MechanicsStdDev *
CoefficientRuptureStrengthValue;
end;
MechanicsDiff := MechanicsMax - MechanicsMin;
CoefficientMin := MechanicsMin - LimitRolledProductsMin;
CoefficientMax := MechanicsMax - LimitRolledProductsMax;
// -- report
CalculatedData(InSide, 'mechanics_avg=''' + floattostr(MechanicsAvg) + '''');
CalculatedData(InSide, 'mechanics_std_dev=''' + floattostr(MechanicsStdDev) + '''');
CalculatedData(InSide, 'mechanics_min=''' + floattostr(MechanicsMin) + '''');
CalculatedData(InSide, 'mechanics_max=''' + floattostr(MechanicsMax) + '''');
CalculatedData(InSide, 'mechanics_diff=''' + floattostr(MechanicsDiff) + '''');
CalculatedData(InSide, 'coefficient_min=''' + floattostr(CoefficientMin) + '''');
CalculatedData(InSide, 'coefficient_max=''' + floattostr(CoefficientMax) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'MechanicsAvg -> ' + floattostr(MechanicsAvg));
SaveLog('debug' + #9#9 + 'MechanicsStdDev -> ' + floattostr(MechanicsStdDev));
SaveLog('debug' + #9#9 + 'MechanicsMin -> ' + floattostr(MechanicsMin));
SaveLog('debug' + #9#9 + 'MechanicsMax -> ' + floattostr(MechanicsMax));
SaveLog('debug' + #9#9 + 'MechanicsDiff -> ' + floattostr(MechanicsDiff));
SaveLog('debug' + #9#9 + 'CoefficientMin -> ' + floattostr(CoefficientMin));
SaveLog('debug' + #9#9 + 'CoefficientMax -> ' + floattostr(CoefficientMax));
SaveLog('debug' + #9#9 + 'Section -> ' + Section);
SaveLog('debug' + #9#9 + 'RollingScheme -> ' + RollingScheme);
{$ENDIF}
try
PQueryCalculation.Close;
PQueryCalculation.sql.Clear;
PQueryCalculation.sql.Add('select t1.tid, t1.heat, t4.temperature from temperature_current t1');
PQueryCalculation.sql.Add('inner join');
PQueryCalculation.sql.Add('chemical_analysis t2');
PQueryCalculation.sql.Add('on t1.heat = t2.heat');
PQueryCalculation.sql.Add('inner join');
PQueryCalculation.sql.Add('technological_sample t3');
PQueryCalculation.sql.Add('on t3.diameter_min <= '+Section+' and t3.diameter_max >= '+Section+'');
PQueryCalculation.sql.Add('and t3.c_min <= '+c+' and t3.c_max >= '+c+'');
PQueryCalculation.sql.Add('and t3.mn_min <= '+mn+' and t3.mn_max >= '+mn+'');
PQueryCalculation.sql.Add('and t3.si_min <= '+si+' and t3.si_max >= '+si+'');
PQueryCalculation.sql.Add('and translate(t3.strength_class,');
PQueryCalculation.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryCalculation.sql.Add('like translate('''+StrengthClass+''',');
PQueryCalculation.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryCalculation.sql.Add('inner JOIN');
PQueryCalculation.sql.Add('temperature_historical t4');
PQueryCalculation.sql.Add('on t1.tid=t4.tid');
PQueryCalculation.sql.Add('where t1.timestamp<=EXTRACT(EPOCH FROM now())');
PQueryCalculation.sql.Add('and t1.timestamp>=EXTRACT(EPOCH FROM now())-(2629743*10)');
PQueryCalculation.sql.Add('and t2.heat in ('+HeatAll+')');
PQueryCalculation.sql.Add('and translate(t3.strength_class,');
PQueryCalculation.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryCalculation.sql.Add('like translate(t1.strength_class,');
PQueryCalculation.sql.Add('''ЕТОРАНКХСВМеторанкхсвм'',''ETOPAHKXCBMetopahkxcbm'')');
PQueryCalculation.sql.Add('and t3.c_min <= t2.c and t3.c_max >= t2.c');// отсекаем с несовпадающей химией
PQueryCalculation.sql.Add('and t3.mn_min <= t2.mn and t3.mn_max >= t2.mn');
PQueryCalculation.sql.Add('and t3.si_min <= t2.si and t3.si_max >= t2.si');
PQueryCalculation.sql.Add('and t1.side='+inttostr(InSide)+'');
if (strtofloat(Section) = 14) or (strtofloat(Section) = 16) or (strtofloat(Section) = 18) then
PQueryCalculation.sql.Add('and t4.rolling_scheme = '''+RollingScheme+'''');
// PQueryCalculation.sql.Add('and t3.type like ''yield_point'');
{ PQueryCalculation.sql.Add('select t1.tid, t1.heat, t2.temperature from temperature_current t1');
PQueryCalculation.sql.Add('LEFT OUTER JOIN');
PQueryCalculation.sql.Add('temperature_historical t2');
PQueryCalculation.sql.Add('on t1.tid=t2.tid');
PQueryCalculation.sql.Add('where t1.heat in ('+HeatAll+')');
PQueryCalculation.sql.Add('and t1.strength_class like '''+CutChar(StrengthClass)+'''');
PQueryCalculation.SQL.Add('and t1.grade like '''+CutChar(Grade)+'''');
PQueryCalculation.sql.Add('and t1.section = '+CutChar(Section)+'');
PQueryCalculation.sql.Add('and t1.standard like '''+GetDigits(Standard)+'%''');
PQueryCalculation.sql.Add('and t1.side='+inttostr(InSide)+'');}
PQueryCalculation.Open;
PQueryCalculation.FetchAll;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'PQueryCalculation.SQL.Text -> ' + PQueryCalculation.sql.Text);
{$ENDIF}
if PQueryCalculation.RecordCount < 1 then
begin
SaveLog('warning'+#9#9+'сторона -> '+side);
SaveLog('warning'+#9#9+'недостаточно данных по температуре для расчета по плавкам -> '+HeatAll);
exit;
end;
{ a := 0;
while not PQueryCalculation.Eof do
begin
if a = length(TempArray) then
SetLength(TempArray, a + 1);
TempArray[a] := PQueryCalculation.FieldByName('temperature').AsInteger;
inc(a);
PQueryCalculation.Next;
end;}
a := 0;
b := a;
i := a;
while not PQueryCalculation.Eof do
begin
if a = length(RawTempArray) then SetLength(RawTempArray, a + 1);
// SetLength(RawTempArray, 5);
RawTempArray[a] := PQueryCalculation.FieldByName('temperature').AsInteger;
inc(a);
{$IFDEF DEBUG}
inc(i);
{$ENDIF}
if a = 4 then
begin
if b = length(TempArray) then SetLength(TempArray, b + 1);
TempArray[b] := GetMedian(RawTempArray);
inc(b);
a := 0;
end;
PQueryCalculation.Next;
end;
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'count temperature all -> ' + inttostr(i));
SaveLog('debug' + #9#9 + 'count temperature median -> ' + inttostr(b));
{$ENDIF}
FreeAndNil(PQueryCalculation);
FreeAndNil(PQueryData);
TempAvg := Mean(TempArray);
TempStdDev := StdDev(TempArray);
SetLength(TempArray, 0); // обнуляем массив c температурой
TempMin := TempAvg - TempStdDev;
TempMax := TempAvg + TempStdDev;
TempDiff := TempMax - TempMin;
R := TempDiff / MechanicsDiff;
AdjustmentMin := Round(CoefficientMin * R);
AdjustmentMax := Round(CoefficientMax * R);
// -- report
CalculatedData(InSide, 'temp_avg=''' + floattostr(TempAvg) + '''');
CalculatedData(InSide, 'temp_std_dev=''' + floattostr(TempStdDev) + '''');
CalculatedData(InSide, 'temp_min=''' + floattostr(TempMin) + '''');
CalculatedData(InSide, 'temp_max=''' + floattostr(TempMax) + '''');
CalculatedData(InSide, 'temp_diff=''' + floattostr(TempDiff) + '''');
CalculatedData(InSide, 'r=''' + floattostr(R) + '''');
CalculatedData(InSide, 'adjustment_min=''' + inttostr(AdjustmentMin) + '''');
CalculatedData(InSide, 'adjustment_max=''' + inttostr(AdjustmentMax) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'TempAvg -> ' + floattostr(TempAvg));
SaveLog('debug' + #9#9 + 'TempStdDev -> ' + floattostr(TempStdDev));
SaveLog('debug' + #9#9 + 'TempMin -> ' + floattostr(TempMin));
SaveLog('debug' + #9#9 + 'TempMax -> ' + floattostr(TempMax));
SaveLog('debug' + #9#9 + 'TempDiff -> ' + floattostr(TempDiff));
SaveLog('debug' + #9#9 + 'R -> ' + floattostr(R));
SaveLog('debug' + #9#9 + 'AdjustmentMin -> ' + inttostr(AdjustmentMin));
SaveLog('debug' + #9#9 + 'AdjustmentMax -> ' + inttostr(AdjustmentMax));
{$ENDIF}
if ((InSide = 0) and (left.step = 0)) then
begin
// увеличиваем диапозон на 10 градусов
left.LowRed := Round(TempMin + AdjustmentMax) - 10;
left.HighRed := Round(TempMax + AdjustmentMin) + 10;
// -- report
CalculatedData(InSide, 'low=''' + inttostr(left.LowRed) + '''');
CalculatedData(InSide, 'high=''' + inttostr(left.HighRed) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LowRedLeft -> ' + inttostr(left.LowRed));
SaveLog('debug' + #9#9 + 'HighRedLeft -> ' + inttostr(left.HighRed));
SaveLog('debug' + #9#9 + 'left.step first -> ' + inttostr(left.step));
{$ENDIF}
inc(left.step); // маркер 2го прохода
// возвращаем плавки по которым произволдился расчет
Result := HeatAll;
exit;
end;
if ((InSide = 0) and (left.step = 1)) then
begin
// увеличиваем диапозон на 5 градусов
left.LowGreen := Round(TempMin + AdjustmentMax) - 5; //вместо 2.5 ибо округляется
left.HighGreen := Round(TempMax + AdjustmentMin) + 5;
// -- report
CalculatedData(InSide, 'low=''' + inttostr(left.LowGreen) + '''');
CalculatedData(InSide, 'high=''' + inttostr(left.HighGreen) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LowGreenLeft -> ' + inttostr(left.LowGreen));
SaveLog('debug' + #9#9 + 'HighGreenLeft -> ' + inttostr(left.HighGreen));
SaveLog('debug' + #9#9 + 'left.step last -> ' + inttostr(left.step));
{$ENDIF}
// left.step := 0; // сброс этапа перенесен в начало
// возвращаем плавки по которым произволдился расчет
Result := HeatAll;
exit;
end;
if ((InSide = 1) and (right.step = 0)) then
begin
// увеличиваем диапозон на 10 градусов
right.LowRed := Round(TempMin + AdjustmentMax) - 10;
right.HighRed := Round(TempMax + AdjustmentMin) + 10;
// -- report
CalculatedData(InSide, 'low=''' + inttostr(right.LowRed) + '''');
CalculatedData(InSide, 'high=''' + inttostr(right.HighRed) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LowRedRight -> ' + inttostr(right.LowRed));
SaveLog('debug' + #9#9 + 'HighRedRight -> ' + inttostr(right.HighRed));
SaveLog('debug' + #9#9 + 'right.step first -> ' + inttostr(right.step));
{$ENDIF}
inc(right.step); // маркер 2го прохода
// возвращаем плавки по которым произволдился расчет
Result := HeatAll;
exit;
end;
if ((InSide = 1) and (right.step = 1)) then
begin
// увеличиваем диапозон на 5 градусов
right.LowGreen := Round(TempMin + AdjustmentMax) - 5;
right.HighGreen := Round(TempMax + AdjustmentMin) + 5;
// -- report
CalculatedData(InSide, 'low=''' + inttostr(right.LowGreen) + '''');
CalculatedData(InSide, 'high=''' + inttostr(right.HighGreen) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LowGreenRight -> ' + inttostr(right.LowGreen));
SaveLog('debug' + #9#9 + 'HighGreenRight -> ' + inttostr(right.HighGreen));
SaveLog('debug' + #9#9 + 'right.step last -> ' + inttostr(right.step));
{$ENDIF}
// right.step := 0; // сброс этапа перенесен в начало
// возвращаем плавки по которым произволдился расчет
Result := HeatAll;
exit;
end;
end;
function CarbonEquivalent(InHeat: string; InSide: integer): bool;
var
CeMin, CeMax, CeAvg, CeMinP, CeMaxM, CeAvgP, CeAvgM, rangeMin: real;
i, a, b, c, rangeM: integer;
CeArray: TArrayArrayVariant; // array of array of variant;
CeMinHeat, CeHeatStringMin, CeHeatStringMax, CeHeatStringAvg: string;
range: array of variant;
begin
i := 0;
a := 0;
b := a;
c := a;
CeArray := SqlCarbonEquivalent(InHeat);
CeMin := CeArray[0, 1]; // Берем первое значение из матрицы
CeMax := CeMin;
For i := Low(CeArray) To High(CeArray) Do
Begin
If CeArray[i, 1] < CeMin Then
CeMin := CeArray[i, 1];
If CeArray[i, 1] > CeMax Then
CeMax := CeArray[i, 1];
End;
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMin -> ' + floattostr(CeMin));
SaveLog('debug' + #9#9 + 'CeMax -> ' + floattostr(CeMax));
{$ENDIF}
CeAvg := (CeMin + CeMax) / 2;
CeMinP := CeMin + 0.02; //было 0.03
CeMaxM := CeMax - 0.02;
CeAvgP := CeAvg + 0.01; //0.015
CeAvgM := CeAvg - 0.01;
For i := Low(CeArray) To High(CeArray) Do
Begin
If InRange(CeArray[i, 1], CeMin, CeMinP) then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMinRangeHeat -> ' + CeArray[i, 0]);
SaveLog('debug' + #9#9 + 'CeMinRangeValue -> ' +floattostr(CeArray[i, 1]));
{$ENDIF}
if a = 0 then
CeHeatStringMin := CeArray[i, 0]
else
CeHeatStringMin := CeHeatStringMin + '|' + CeArray[i, 0];
inc(a);
end;
if InRange(CeArray[i, 1], CeMaxM, CeMax) then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMaxRangeHeat -> ' + CeArray[i, 0]);
SaveLog('debug' + #9#9 + 'CeMaxRangeValue -> ' + floattostr(CeArray[i, 1]));
{$ENDIF}
if b = 0 then
CeHeatStringMax := CeArray[i, 0]
else
CeHeatStringMax := CeHeatStringMax + '|' + CeArray[i, 0];
inc(b);
end;
if InRange(CeArray[i, 1], CeAvgM, CeAvgP) then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeAvgRangeHeat -> ' + CeArray[i, 0]);
SaveLog('debug' + #9#9 + 'CeAvgRangeValue -> ' + floattostr(CeArray[i, 1]));
{$ENDIF}
if c = 0 then
CeHeatStringAvg := CeArray[i, 0]
else
CeHeatStringAvg := CeHeatStringAvg + '|' + CeArray[i, 0];
inc(c);
end;
end;
// -- report
CalculatedData(InSide, 'ce_min_down=''' + FloatToStrF(CeMin, ffGeneral,6,0) + '''');
CalculatedData(InSide, 'ce_min_up=''' + floattostr(CeMinP) + '''');
CalculatedData(InSide, 'ce_max_down=''' + floattostr(CeMaxM) + '''');
CalculatedData(InSide, 'ce_max_up=''' + floattostr(CeMax) + '''');
CalculatedData(InSide, 'ce_avg=''' + floattostr(CeAvg) + '''');
CalculatedData(InSide, 'ce_avg_down=''' + floattostr(CeAvgM) + '''');
CalculatedData(InSide, 'ce_avg_up=''' + floattostr(CeAvgP) + '''');
// -- report
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeInHeat -> ' + InHeat);
SaveLog('debug' + #9#9 + 'CeMin -> ' + floattostr(CeMin));
SaveLog('debug' + #9#9 + 'CeMax -> ' + floattostr(CeMax));
SaveLog('debug' + #9#9 + 'CeAvg -> ' + floattostr(CeAvg));
SaveLog('debug' + #9#9 + 'CeMinP -> ' + floattostr(CeMinP));
SaveLog('debug' + #9#9 + 'CeMaxM -> ' + floattostr(CeMaxM));
SaveLog('debug' + #9#9 + 'CeAvgP -> ' + floattostr(CeAvgP));
SaveLog('debug' + #9#9 + 'CeAvgM -> ' + floattostr(CeAvgM));
{$ENDIF}
if InSide = 0 then
begin
// -- Се по текущей плавке
CeArray := SqlCarbonEquivalent('''' + left.Heat + '''');
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'Currentleft.Heat -> ' + CeArray[0, 0]);
SaveLog('debug' + #9#9 + 'CurrentCeLeft -> ' + floattostr(CeArray[0, 1]));
{$ENDIF}
end
else
begin
// -- Се по текущей плавке
CeArray := SqlCarbonEquivalent('''' + right.Heat + '''');
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'Currentright.Heat -> ' + CeArray[0, 0]);
SaveLog('debug' + #9#9 + 'CurrentCeRight -> ' + floattostr(CeArray[0, 1]));
{$ENDIF}
end;
// -- текущая плавка к какому из диапозонов относится min,max,avg
if InRange(CeArray[0, 1], CeMin, CeMinP) and (CeHeatStringMin <> '') then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CurrentCeMinRange -> ' + CeArray[0, 0]);
SaveLog('debug' + #9#9 + 'CurrentCeMinRangeValue -> '+floattostr(CeArray[0, 1]));
{$ENDIF}
//-- расчет осуществляется на ближаешем значение от min
{ // -- report
CalculatedData(InSide, 'ce_category=''min''');
// -- report
if InSide = 0 then
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeMinRangeleft.Heat -> ' + CeHeatStringMin);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringMin, 0);
end
else
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeMinRangeright.Heat -> ' + CeHeatStringMin);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringMin, 1);
end;}
//-- расчет осуществляется на ближаешем значение от min
end;
if InRange(CeArray[0, 1], CeMaxM, CeMax) and (CeHeatStringMax <> '') then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CurrentCeMaxRange -> ' + CeArray[0, 0]);
SaveLog('debug' + #9#9 + 'CurrentCeMaxRangeValue -> '+floattostr(CeArray[0, 1]));
{$ENDIF}
//-- расчет осуществляется на ближаешем значение от max
{ // -- report
CalculatedData(InSide, 'ce_category=''max''');
// -- report
if InSide = 0 then
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeMaxRangeleft.Heat -> ' + CeHeatStringMax);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringMax, 0);
end
else
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeMaxRangeright.Heat -> ' + CeHeatStringMax);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringMax, 1);
end;}
//-- расчет осуществляется на ближаешем значение от max
end;
if InRange(CeArray[0, 1], CeAvgM, CeAvgP) and (CeHeatStringAvg <> '') then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CurrentCeAvgRange -> ' + CeArray[0, 0]);
SaveLog('debug' + #9#9 + 'CurrentCeAvgRangeValue -> '+floattostr(CeArray[0, 1]));
{$ENDIF}
//-- расчет осуществляется на ближаешем значение от avg
{ // -- report
CalculatedData(InSide, 'ce_category=''avg''');
// -- report
if InSide = 0 then
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeAvgRangeleft.Heat -> ' + CeHeatStringAvg);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringAvg, 0);
end
else
begin
//{$IFDEF DEBUG}
// SaveLog('debug' + #9#9 + 'CeAvgRangeright.Heat -> ' + CeHeatStringAvg);
//{$ENDIF}
{ CalculatingInMechanicalCharacteristics(CeHeatStringAvg, 1);
end;}
//-- расчет осуществляется на ближаешем значение от avg
end;
SetLength(range, 3);
//получаем минимальную разницу
range[0] := ABS(CeMin - CeArray[0, 1]);
range[1] := ABS(CeMax - CeArray[0, 1]);
range[2] := ABS(CeAvg - CeArray[0, 1]);
rangeMin := range[0];
for i := low(range) To high(range) Do
if range[i] < rangeMin then
rangeMin := range[i]; // к какому из пределов ближе
for i := low(range) To high(range) Do
begin
If range[i] = rangeMin Then
begin
if (i = 0) and (CeHeatStringMin <> '') then
begin
if InSide = 0 then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMinRangeleft.Heat -> ' + CeHeatStringMin);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''мин''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringMin, 0);
end
else
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMinRangeright.Heat -> ' + CeHeatStringMin);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''мин''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringMin, 1);
end;
end;
if (i = 1) and (CeHeatStringMax <> '') then
begin
if InSide = 0 then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMaxRangeleft.Heat -> ' + CeHeatStringMax);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''макс''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringMax, 0);
end
else
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeMaxRangeright.Heat -> ' + CeHeatStringMax);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''макс''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringMax, 1);
end;
end;
if (i = 2) and (CeHeatStringAvg <> '') then
begin
if InSide = 0 then
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeAvgRangeleft.Heat -> ' + CeHeatStringAvg);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''сред''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringAvg, 0);
end
else
begin
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeAvgRangeright.Heat -> ' + CeHeatStringAvg);
{$ENDIF}
// -- report
CalculatedData(InSide, 'ce_category=''сред''');
// -- report
CalculatingInMechanicalCharacteristics(CeHeatStringAvg, 1);
end;
end;
end;
end;
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'CeRangeMinValue -> ' + floattostr(rangeMin));
SaveLog('debug' + #9#9 + 'min range[0] -> ' + floattostr(range[0]));
SaveLog('debug' + #9#9 + 'max range[1] -> ' + floattostr(range[1]));
SaveLog('debug' + #9#9 + 'avg range[2] -> ' + floattostr(range[2]));
SaveLog('debug' + #9#9 + 'rangeM -> ' + floattostr(rangeM));
{$ENDIF}
end;
function HeatToIn(InHeat: string): string;
var
i: integer;
AllHeat: string;
st: TStringList;
begin
st := TStringList.Create;
st.Text := StringReplace(InHeat, '|', #13#10, [rfReplaceAll]);
for i := 0 to st.Count - 1 do
begin
if i <> st.Count - 1 then
st.Strings[i] := '''' + st.Strings[i] + '''' + ','
else
st.Strings[i] := '''' + st.Strings[i] + '''';
AllHeat := AllHeat + '' + st.Strings[i] + '';
end;
st.Free;
Result := AllHeat;
end;
function CutChar(InData: string): string;
var
i: integer;
BadChars: string;
begin
BadChars := ' ()/\:-;';
for i := 0 to Length(BadChars) do
InData := StringReplace(InData, BadChars[i], '%', [rfReplaceAll]);
Result := InData;
end;
function GetDigits(InData: string): string;
var
digits: string;
i: integer;
begin
for i := 1 to length(InData) do
begin
if not(InData[i] in ['0' .. '9']) then
digits := digits + '%'
else
digits := digits + InData[i];
end;
Result := digits;
end;
function GetMedian(aArray: TDoubleDynArray): Double;
var
lMiddleIndex: Integer;
begin
TArray.Sort<Double>(aArray);
lMiddleIndex := Length(aArray) div 2;
if Odd(Length(aArray)) then
Result := aArray[lMiddleIndex]
else
Result := (aArray[lMiddleIndex - 1] + aArray[lMiddleIndex]) / 2;
end;
constructor TIdHeat.Create(_tid: integer; _Heat, _Grade, _Section, _Standard, _StrengthClass,
_c, _mn, _cr, _si, _b, _ce, _OldStrengthClass: string;
_old_tid: integer; _marker: bool; _LowRed, _HighRed,
_LowGreen, _HighGreen, _step: integer);
begin
tid := _tid;
Heat := _Heat; // плавка
Grade := _Grade; // марка стали
Section := _Section; // профиль
Standard := _Standard; // стандарт
StrengthClass := _StrengthClass; // клас прочности
c := _c;
mn := _mn;
cr := _cr;
si := _si;
b := _b;
ce := _ce;
OldStrengthClass := _OldStrengthClass; // старый клас прочности
old_tid := _old_tid; // стара плавка
marker := _marker;
LowRed := _LowRed;
HighRed := _HighRed;
LowGreen := _LowGreen;
HighGreen := _HighGreen;
step := _step;
end;
// При загрузке программы класс будет создаваться
initialization
left := TIdHeat.Create(0,'','','','','','','','','','','','',0,false,0,0,0,0,0);
right := TIdHeat.Create(0,'','','','','','','','','','','','',0,false,0,0,0,0,0);
// При закрытии программы уничтожаться
finalization
FreeAndNil(left);
FreeAndNil(right);
end.
|
unit OrderParametersUnit;
interface
uses
HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit,
NullableBasicTypesUnit, GenericParametersUnit;
type
TOrderParameters = class(TGenericParameters)
private
[HttpQueryMember('limit')]
[Nullable]
FLimit: NullableInteger;
[HttpQueryMember('offset')]
[Nullable]
FOffset: NullableInteger;
public
constructor Create; override;
/// <summary>
/// Limit per page, if you use 0 you will get all records
/// </summary>
property Limit: NullableInteger read FLimit write FLimit;
/// <summary>
/// Offset
/// </summary>
property Offset: NullableInteger read FOffset write FOffset;
end;
implementation
constructor TOrderParameters.Create;
begin
Inherited Create;
FLimit := NullableInteger.Null;
FOffset := NullableInteger.Null;
end;
end.
|
unit l3MultipartTextNode;
// Простая нода с многокусочным текстом (для использования в многоколоночном дереве)
{ $Id: l3MultipartTextNode.pas,v 1.2 2006/03/27 13:20:13 lulin Exp $}
// $Log: l3MultipartTextNode.pas,v $
// Revision 1.2 2006/03/27 13:20:13 lulin
// - cleanup.
//
// Revision 1.1 2005/06/10 13:33:26 fireton
// - новый объект - Tl3MultipartTextNode
//
interface
uses l3Base, l3InternalInterfaces, l3Nodes, l3Types;
type
Tl3MultipartTextNode = class(Tl3UsualNode, Il3MultipartText)
private
f_StringList: Tl3StringList;
protected
function GetTextPart(aIndex: Integer): Tl3PCharLen;
public
constructor Create(anOwner: TObject = nil);
procedure Cleanup; override;
property StringList: Tl3StringList read f_StringList;
end;
implementation
uses l3String;
constructor Tl3MultipartTextNode.Create(anOwner: TObject = nil);
begin
inherited;
f_StringList := Tl3StringList.Create;
end;
procedure Tl3MultipartTextNode.Cleanup;
begin
l3Free(f_StringList);
inherited;
end;
function Tl3MultipartTextNode.GetTextPart(aIndex: Integer): Tl3PCharLen;
begin
if (aIndex < 0) or (aIndex > f_StringList.Count-1) then
Result := l3PCharLen('')
else
Result := f_StringList.Items[aIndex].AsPCharLen;
end;
end.
|
unit UMonthBoldStorage;
interface
type
// Verwaltet für jeden Tag eines Jahres ein Bit
// ist das Bit gesetzt, dann ist der Tag "fett"
TYearBoldManager = class(TObject)
private
FMonthBoldInfo : array[1..12] of Cardinal;
class function DayBits(day:Word):Cardinal;
public
constructor Create;
procedure Clear;
procedure MakeBold(month, day:Word); // bestimmten Tag markieren
procedure MakeNormal(month, day:Word);
procedure Toggle(month, day:Word);
function GetMonthBoldInfo(month:Integer):Cardinal;
function GetDayStatus(month, day:Word):Boolean;
end;
implementation
{ TYearBoldManager }
constructor TYearBoldManager.Create;
begin
inherited Create;
Clear;
end;
procedure TYearBoldManager.Clear;
var
i : Integer;
begin
for i := low(FMonthBoldInfo) to high(FMonthBoldInfo) do
FMonthBoldInfo[i] := 0;
end;
class function TYearBoldManager.DayBits(day: Word): Cardinal;
begin
Result := $00000001 shl (day - 1);
end;
function TYearBoldManager.GetMonthBoldInfo(month: Integer): Cardinal;
begin
Result := FMonthBoldInfo[month];
end;
procedure TYearBoldManager.MakeBold(month, day: Word);
begin
FMonthBoldInfo[month] := FMonthBoldInfo[month]
or DayBits(Day);
end;
procedure TYearBoldManager.MakeNormal(month, day: Word);
begin
FMonthBoldInfo[month] := FMonthBoldInfo[month]
and not DayBits(Day);
end;
function TYearBoldManager.GetDayStatus(month, day: Word): Boolean;
begin
Result := (FMonthBoldInfo[month] and DayBits(day)) <> 0;
end;
procedure TYearBoldManager.Toggle(month, day: Word);
begin
if GetDayStatus(month, day) then
MakeNormal(month, day)
else
MakeBold(month, day);
end;
end.
|
unit atrMail;
interface
uses mimemess, mimepart, smtpsend, Classes;
Procedure SendMail (const Host, Subject, pTo, From , TextBody, login,password : string);
Procedure SendMailinHTML(const Host, Subject, pTo, From , HTMLBody, login,password : string);
implementation
Procedure SendMail (const Host, Subject, pTo, From , TextBody, login,password : string);
var Msg : TMimeMess; //собщение
StringList : TStringList; //содержимое письма
MIMEPart : TMimePart; //части сообщения (на будущее)
begin
Msg := TMimeMess.Create; //создаем новое сообщение
StringList := TStringList.Create;
try
// Добавляем заголовки
Msg.Header.Subject := Subject;//тема сообщения
Msg.Header.From := From; //имя и адрес отправителя
Msg.Header.ToList.Add(pTo); //имя и адрес получателя
// создаем корневой элемент
MIMEPart := Msg.AddPartMultipart('alternative', nil);
StringList.Text := TextBody;
Msg.AddPartText(StringList, MIMEPart);
// Кодируем и отправляем
Msg.EncodeMessage;
smtpsend.SendToRaw(From, pTo, Host, Msg.Lines, login, password);
finally
Msg.Free;
StringList.Free;
end;
end;
Procedure SendMailinHTML(const Host, Subject, pTo, From , HTMLBody, login,password : string);
var Msg : TMimeMess; //собщение
StringList : TStringList; //содержимое письма
MIMEPart : TMimePart; //части сообщения (на будущее)
begin
Msg := TMimeMess.Create; //создаем новое сообщение
StringList := TStringList.Create;
try
// Добавляем заголовки
Msg.Header.Subject := Subject;//тема сообщения
Msg.Header.From := From; //имя и адрес отправителя
Msg.Header.ToList.Add(pTo); //имя и адрес получателя
// создаем корневой элемент
MIMEPart := Msg.AddPartMultipart('alternative', nil);
StringList.Text := HTMLBody;
Msg.AddPartHTML(StringList, MIMEPart);
// Кодируем и отправляем
Msg.EncodeMessage;
smtpsend.SendToRaw(From, pTo, Host, Msg.Lines, login, password);
finally
Msg.Free;
StringList.Free;
end;
end;
end. |
unit uDAOCardapio;
interface
uses
UCardapio, FireDAc.Comp.Client;
type TDAOCardapio = class(TCardapio)
private
FConexao : TFDConnection;
public
constructor Create(poConexao: TFDConnection);
destructor Destroy;
function fncInsereProduto: Boolean;
function fncDeletaProduto: Boolean;
published
end;
implementation
uses
System.SysUtils;
{ TDAOCardapio }
constructor TDAOCardapio.Create(poConexao: TFDConnection);
begin
inherited Create;
FConexao := poConexao;
end;
destructor TDAOCardapio.Destroy;
begin
inherited Destroy;
end;
function TDAOCardapio.fncDeletaProduto: Boolean;
var
poQuery : TFDQuery;
begin
poQuery := TFDQuery.Create(nil);
try
poQuery.Close;
poQuery.Connection := FConexao;
poQuery.SQL.Clear;
poQuery.SQL.Add('DELETE FROM CARDAPIO WHERE (PRO_CODIGO = :PRO_CODIGO) AND (PRO_GRUPO = :PRO_GRUPO)');
poQuery.ParamByName('PRO_CODIGO').AsInteger := PRO_CODIGO;
poQuery.ParamByName('PRO_GRUPO').AsInteger := PRO_GRUPO;
poQuery.ExecSQL;
finally
FreeAndNil(poQuery);
end;
end;
function TDAOCardapio.fncInsereProduto: Boolean;
var
poQuery : TFDQuery;
begin
poQuery := TFDQuery.Create(nil);
try
poQuery.Close;
poQuery.Connection := FConexao;
poQuery.SQL.Clear;
if PRO_CODIGO = 0 then
begin
poQuery.SQL.Add('INSERT INTO CARDAPIO (PRO_GRUPO, PRO_DESCRICAO,');
poQuery.SQL.Add(' PRO_VALORMEIA, PRO_VALORINTEIRA)');
poQuery.SQL.Add('VALUES (:PRO_GRUPO, :PRO_DESCRICAO, :PRO_VALORMEIA, :PRO_VALORINTEIRA)');
end
else
begin
poQuery.SQL.Add('UPDATE CARDAPIO');
poQuery.SQL.Add('SET PRO_DESCRICAO = :PRO_DESCRICAO,');
poQuery.SQL.Add(' PRO_VALORMEIA = :PRO_VALORMEIA,');
poQuery.SQL.Add(' PRO_VALORINTEIRA = :PRO_VALORINTEIRA');
poQuery.SQL.Add('WHERE (PRO_CODIGO = :PRO_CODIGO) AND (PRO_GRUPO = :PRO_GRUPO)');
poQuery.ParamByName('PRO_CODIGO').AsInteger := PRO_CODIGO;
end;
poQuery.ParamByName('PRO_GRUPO').AsInteger := PRO_GRUPO;
poQuery.ParamByName('PRO_DESCRICAO').AsString := PRO_DESCRICAO;
poQuery.ParamByName('PRO_VALORMEIA').AsFloat := PRO_VALORMEIA;
poQuery.ParamByName('PRO_VALORINTEIRA').AsFloat := PRO_VALORINTEIRA;
poQuery.ExecSQL;
finally
FreeAndNil(poQuery);
end;
end;
end.
|
unit Model.CadastroEnderecos;
interface
uses Common.ENum, FireDAC.Comp.Client, Dialogs, Control.Sistema, DAO.Conexao, System.SysUtils, Data.DB;
type
TCadastroEnderecos = class
private
FID: Integer;
FTipo: String;
FCEP: String;
FLogradouro: String;
FNumero: String;
FComplemento: String;
FBairro: String;
FCidade: String;
FUF: String;
FAcao: TAcao;
Fconexao : TConexao;
FQuery: TFDQuery;
FSequencia: Integer;
FCorrespondencia: Integer;
FReferencia: String;
function Insert(): Boolean;
function Update(): Boolean;
function Delete(): Boolean;
public
property ID: Integer read FID write FID;
property Sequencia: Integer read FSequencia write FSequencia;
property Tipo: String read FTipo write FTipo;
property CEP: String read FCEP write FCEP;
property Logradouro: String read FLogradouro write FLogradouro;
property Numero: String read FNumero write FNumero;
property Complemento: String read FComplemento write FComplemento;
property Bairro: String read FBairro write FBairro;
property Cidade: String read FCidade write FCidade;
property UF: String read FUF write FUF;
property Correspondencia: Integer read FCorrespondencia write FCorrespondencia;
property Referencia: String read FReferencia write FReferencia;
property Query: TFDQuery read FQuery write FQuery;
property Acao: TAcao read FAcao write FAcao;
constructor Create();
function Localizar(aParam: array of variant): Boolean;
function Gravar(): Boolean;
function SaveBatch(memTable: TFDMemTable): Boolean;
function SetupClass(FDQuery: TFDQuery): boolean;
function ClearClass(): boolean;
function GetID(iID: Integer): Integer;
end;
const
TABLENAME = 'tbenderecosentregadores';
implementation
{ TCadastroEnderecos }
uses Common.Utils;
function TCadastroEnderecos.ClearClass: boolean;
begin
Result := False;
FID := 0;
FTipo := '';
FCEP := '';
FLogradouro := '';
FNumero := '';
FComplemento := '';
FBairro := '';
FCidade := '';
FUF := '';
FSequencia := 0;
FCorrespondencia := 0;
FReferencia := '';
Result := True;
end;
constructor TCadastroEnderecos.Create;
begin
FConexao := TConexao.Create;
end;
function TCadastroEnderecos.Delete: Boolean;
var
FDQuery: TFDQuery;
sSQL: String;
begin
try
Result := False;
sSQL := '';
FDQuery := FConexao.ReturnQuery();
sSQL := 'delete from ' + TABLENAME + ' ' +
'where cod_entregador = :pcod_entregador;';
FDQuery.ExecSQL(sSQL,[Self.ID, Self.FTipo]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TCadastroEnderecos.GetID(iID: Integer): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(seq_endereco),0) + 1 from ' + TABLENAME + ' where cod_entregador = ' + iID.toString);
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroEnderecos.Gravar: Boolean;
begin
case FAcao of
tacIncluir: Result := Self.Insert();
tacAlterar: Result := Self.Update();
tacExcluir: Result := Self.Delete();
end;
end;
function TCadastroEnderecos.Insert: Boolean;
var
sSQL: String;
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
Self.Sequencia := GetID(Self.ID);
sSQL := 'insert into ' + TABLENAME + ' (' +
'cod_entregador, seq_endereco, des_tipo, des_logradouro, num_logradouro, des_complemento, ' +
'dom_correspondencia, des_bairro, nom_cidade, uf_estado, num_cep, des_referencia) ' +
'values (' +
':cod_entregador, :seq_endereco, :des_tipo, :des_logradouro, :num_logradouro, :des_complemento, ' +
':dom_correspondencia, :des_bairro, :nom_cidade, :uf_estado, :num_cep, :des_referencia);';
FDQuery.ExecSQL(sSQL,[Self.ID, Self.Sequencia, Self.Tipo, Self.Logradouro, Self.Numero, Self.Complemento,
Self.Correspondencia, Self.Bairro, Self.Cidade, Self.UF, Self.CEP, Self.Referencia]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;end;
function TCadastroEnderecos.Localizar(aParam: array of variant): Boolean;
begin
Result := False;
FQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FQuery.SQL.Clear;
FQuery.SQL.Add('select cod_entregador, seq_endereco, des_tipo, des_logradouro, num_logradouro, des_complemento, ' +
'dom_correspondencia, des_bairro, nom_cidade, uf_estado, num_cep, des_referencia from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FQuery.SQL.Add('where cod_cadastro = :cod_cadastro);');
FQuery.ParamByName('cod_cadastro').AsInteger := aParam[1];
end;
if aParam[0] = 'TIPO' then
begin
FQuery.SQL.Add('where cod_cadastro = :cod_cadastro and des_tipo = :des_tipo');
FQuery.ParamByName('cod_cadastro').AsInteger := aParam[1];
FQuery.ParamByName('des_tipo').AsString := aParam[2];
end;
if aParam[0] = 'CEP' then
begin
FQuery.SQL.Add('where num_cep like :num_cep');
FQuery.ParamByName('NUM_CEP').AsString := aParam[1];
end;
if aParam[0] = 'ENDERECO' then
begin
FQuery.SQL.Add('where des_logradouro like :des_logradouro');
FQuery.ParamByName('des_logradouro').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FQuery.SQL.Clear;
FQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FQuery.Open();
if FQuery.IsEmpty then
begin
Exit;
end;
Result := True;
end;
function TCadastroEnderecos.SaveBatch(memTable: TFDMemTable): Boolean;
begin
Result := False;
Self.Acao := tacExcluir;
if not Self.Gravar then
begin
Exit;
end;
memTable.First;
while not memTable.Eof do
begin
Self.ID := memTable.FieldByName('cod_entregador').AsInteger;
Self.Sequencia := GetID(memTable.FieldByName('cod_entregador').AsInteger);
Self.Tipo := memTable.FieldByName('des_tipo').AsString;
Self.Logradouro := memTable.FieldByName('des_logradouro').AsString;
Self.Numero := memTable.FieldByName('num_logradouro').AsString;
Self.Complemento := memTable.FieldByName('des_complemento').AsString;
Self.Correspondencia := memTable.FieldByName('dom_correspondencia').AsInteger;
Self.Bairro := memTable.FieldByName('nom_bairro').AsString;
Self.Cidade := memTable.FieldByName('nom_cidade').AsString;
Self.UF := memTable.FieldByName('uf_estado').AsString;
Self.CEP := memTable.FieldByName('num_cep').AsString;
Self.Referencia := memTable.FieldByName('res_referencia').AsString;
Self.Acao := tacIncluir;
if not Self.Gravar then
begin
Exit;
end;
memTable.Next;
end;
Result := True;
end;
function TCadastroEnderecos.SetupClass(FDQuery: TFDQuery): boolean;
begin
Result := False;
Self.ID := FDQuery.FieldByName('cod_entregador').AsInteger;
Self.Sequencia := FDQuery.FieldByName('seq_endereco').AsInteger;
Self.Tipo := FDQuery.FieldByName('des_tipo').AsString;
Self.Logradouro := FDQuery.FieldByName('des_logradouro').AsString;
Self.Numero := FDQuery.FieldByName('num_logradouro').AsString;
Self.Complemento := FDQuery.FieldByName('des_complemento').AsString;
Self.Correspondencia := FDQuery.FieldByName('dom_correspondencia').AsInteger;
Self.Bairro := FDQuery.FieldByName('nom_bairro').AsString;
Self.Cidade := FDQuery.FieldByName('nom_cidade').AsString;
Self.UF := FDQuery.FieldByName('uf_estado').AsString;
Self.CEP := FDQuery.FieldByName('num_cep').AsString;
Self.Referencia := FDQuery.FieldByName('res_referencia').AsString;
Result := True;
end;
function TCadastroEnderecos.Update: Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'update ' + TABLENAME + ' set ' +
'des_tipo = :des_tipo, des_logradouro = :des_logradouro, num_logradouro = :num_logradouro, des_complemento = :des_complemento, ' +
'dom_correspondencia = :dom_correspondencia, des_bairro = :des_bairro, nom_cidade = :nom_cidade, uf_estado = :uf_estado, ' +
'num_cep = :num_cep, des_referencia = :des_referencia ' +
'where cod_entregador = :cod_entregador and seq_endereco := seq_endereco';
FDQuery.ExecSQL(sSQL,[Self.Tipo, Self.Logradouro, Self.Numero, Self.Complemento, Self.Correspondencia, Self.Bairro,
Self.Cidade, Self.UF, Self.CEP, Self.Referencia, Self.ID, Self.Sequencia]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, ExtCtrls, IniFiles, Misc, NMUDP, SensorTypes, Menus,
DdhAppX, ImgList, StdCtrls, ArchManThd;
type
TFormDataCol = class(TForm)
AppExt: TDdhAppExt;
TrayPopupMenu: TPopupMenu;
pmiClose: TMenuItem;
pmiAbout: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NMUDPDataReceived(Sender: TComponent; NumberBytes: Integer;
FromIP: String; Port: Integer);
procedure pmiAboutClick(Sender: TObject);
procedure pmiCloseClick(Sender: TObject);
procedure AppExtLBtnDown(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UDPs:TList;
AMThd:TArchManThread;
LogFileName:String;
end;
TMyUDP=class(TNMUDP)
Sensors:TByteStringList;
constructor CreateFromIniSection(Owner:TFormDataCol; Ini:TIniFile;
const Section:String);
destructor Destroy;override;
end;
var
FormDataCol: TFormDataCol;
TMySensor:CSensor;
implementation
{$R *.DFM}
procedure TFormDataCol.FormCreate(Sender: TObject);
const
Section = 'config';
var
Ini:TIniFile;
FName:String;
SV:TStringList;
i:Integer;
UDP:TMyUDP;
Num,ErrPos:Integer;
S:String;
begin
InitFormattingVariables;
FName:=GetModuleFullName+'.ini';
if not FileExists(FName)
then raise Exception.Create('Программа сбора данных: Не найден файл конфигурации "'+FName+'"');
LogFileName:=ChangeFileExt(FName,'.log');
WriteToLog(LogFileName,LogMsg(Now,'ЗАПУСК DataCol'));
AMThd:=TArchManThread.Create;//('127.0.0.1');
AMThd.Resume;
Ini:=TIniFile.Create(FName);
SV:=TStringList.Create;
UDPs:=TList.Create;
S:=Ini.ReadString(Section,'JumpLimit','0.0'); //0.3
try
SensorTypes.JumpLimit:=StrToFloat(S);
except
SensorTypes.JumpLimit:=0.3;
end;
if Ini.ReadInteger(Section,'NewSensorType',0)<>0
then TMySensor:=TSensorFloat32
else TMySensor:=TSensorFixed24;
Ini.ReadSections(SV);
for i:=0 to SV.Count-1 do begin
Val(SV[i],Num,ErrPos);
if (ErrPos=0) and (0<Num) and (Num<65536) then begin
UDP:=TMyUDP.CreateFromIniSection(Self,Ini,SV[i]);
if UDP<>nil then begin
UDP.OnDataReceived:=NMUDPDataReceived;
UDPs.Add(UDP);
end;
end;
end;
SV.Free;
Ini.Free;
end;
procedure TFormDataCol.FormDestroy(Sender: TObject);
var
i:Integer;
begin
if UDPs<>nil then begin
for i:=0 to UDPs.Count-1 do TObject(UDPs[i]).Free;
UDPs.Free;
end;
AMThd.Free;
WriteToLog(LogFileName,LogMsg(Now,'ОСТАНОВ DataCol'));
end;
procedure TFormDataCol.NMUDPDataReceived(Sender: TComponent;
NumberBytes: Integer; FromIP: String; Port: Integer);
var
InBuf:String;
OutBuf:WideString;
i,Cnt:Integer;
S:TSensor;
DT:TDateTime;
UDP:TMyUDP absolute Sender;
begin
//if NumberBytes<16 then exit;
SetLength(InBuf,NumberBytes);
UDP.ReadBuffer(InBuf[1],NumberBytes);
if UDP.Sensors.Find(InBuf[1],i) then begin
S:=UDP.Sensors.Objects[i] as TSensor;
if S.Num=255
then begin
Cnt:=0;
i:=NumberBytes shr 1;
end
else begin
Cnt:=(NumberBytes - SizeOf(TLdrData)) div SizeOf(Single) + 1;
i:=(S.GetRecSize*Cnt+1) shr 1;
end;
SetLength(OutBuf,i);
try
if S.Num=255 then begin
i:=NumberBytes-1;
Move(InBuf[2],OutBuf[1],i);
DT:=0;
end
else begin
i:=Cnt;
if Cnt=1
then DT:=S.FormatData(InBuf[1],OutBuf[1])
else DT:=S.FormatDataN(InBuf[1],OutBuf[1],Cnt);
end;
AMThd.writeRecords(S.TrackID,DT,i,OutBuf);
except
on E:Exception do begin
WriteToLog(LogFileName,
'#'+IntToStr(Ord(InBuf[1]))+' : raised '+E.ClassName+' "'+E.Message+'"');
Close;
end;
end;
end;
end;
{ TMyUDP }
constructor TMyUDP.CreateFromIniSection(Owner:TFormDataCol; Ini: TIniFile;
const Section: String);
var
SV:TStringList;
i,j:Integer;
S:TSensor;
Num,ID:Integer;
Tmp:String;
begin
Create(Owner);
LocalPort:=StrToInt(Section);
SV:=TStringList.Create;
Ini.ReadSectionValues(Section,SV);
Sensors:=TByteStringList.Create;
Sensors.Sorted:=True;
for i:=0 to SV.Count-1 do begin
Num:=StrToInt(SV.Names[i]);
Tmp:=SV.Values[SV.Names[i]];
j:=Pos(',',Tmp); if j=0 then j:=Length(Tmp)+1;
Owner.AMThd.StrToTrackID(Copy(Tmp,1,j-1),ID);
Tmp:=Copy(Tmp,j+1,Length(Tmp)-j);
if Tmp='' then Tmp:='86400';
j:=StrToInt(Tmp);
S:=TMySensor.Create(Num,ID,j);
Owner.AMThd.setTrackInfo(S.TrackID,S.GetRecSize,S.GetRecsPerDay);
Sensors.AddObject(Char(Num),S);
end;
SV.Free;
// Events 'sensor'
Owner.AMThd.StrToTrackID('EVT',ID);
S:=TMySensor.Create(255,ID,0);
Owner.AMThd.setTrackInfo(ID,0,0);
Sensors.AddObject(#255,S);
end;
destructor TMyUDP.Destroy;
var
i:Integer;
begin
if Sensors<>nil then begin
for i:=0 to Sensors.Count-1 do Sensors.Objects[i].Free;
Sensors.Free;
end;
inherited;
end;
procedure TFormDataCol.pmiAboutClick(Sender: TObject);
begin
Application.MessageBox(
'СКУ'#13#13+
'Программа сбора данных'#13+
'(прием из сети и помещение в архив)'#13#13+
'(c) 2000-2002 ООО "Компания Телекомнур"'#13+
'e-mail: test@mail.rb.ru',
'О программе',
MB_ICONINFORMATION or MB_OK);
end;
procedure TFormDataCol.pmiCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFormDataCol.AppExtLBtnDown(Sender: TObject);
var
P:TPoint;
begin
GetCursorPos(P);
TrayPopupMenu.Popup(P.x,P.y);
end;
end.
|
{ Subroutine SST_R_PAS_ITEM (TERM)
*
* Read and process ITEM syntax. The appropriate fields in the expression term
* descriptor TERM are filled in.
}
module sst_r_pas_ITEM;
define sst_r_pas_item;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_item ( {create compiled item from input stream}
out term: sst_exp_term_t); {expression term descriptor to fill in}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
tag2: sys_int_machine_t; {extra syntax tag to avoid corrupting TAG}
str2_h: syo_string_t; {handle to string associated with TAG2}
token: string_var8192_t; {scratch token for number conversion, etc}
sz: sys_int_adr_t; {amount of memory to allocate}
sym_p: sst_symbol_p_t; {points to symbol descriptor}
dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor}
var_p: sst_var_p_t; {points to full variable descriptor}
exp_p: sst_exp_p_t; {points to new expression descriptor}
ifarg_p: sst_exp_chain_p_t; {points to intrinsic function args chain}
set_ele_pp: ^sst_ele_exp_p_t; {points to set elements chain pointer}
set_ele_p: sst_ele_exp_p_t; {points to curr set element/range val desc}
args_here: boolean; {TRUE if function reference has arguments}
stat: sys_err_t;
label
not_ifunc, isa_routine, loop_set, leave;
begin
token.max := sizeof(token.str); {init var string}
term.val_eval := false; {init to not attempted to evaluate this term}
term.dtype_p := nil; {init to data type is not known yet}
syo_level_down; {down into ITEM syntax level}
syo_get_tag_msg ( {get unadic operator tag}
tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
case tag of {unadic operator cases}
1: term.op1 := sst_op1_none_k; {none}
2: term.op1 := sst_op1_plus_k; {+}
3: term.op1 := sst_op1_minus_k; {-}
4: term.op1 := sst_op1_not_k; {not}
5: term.op1 := sst_op1_1comp_k; {~}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of unadic operator cases}
syo_get_tag_msg ( {get item type tag}
tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
case tag of
{
*************************************
*
* Item is a literal floating point number.
}
1: begin
term.ttype := sst_term_const_k; {this item is a constant}
syo_get_tag_string (str_h, token); {get floating point number string}
string_t_fp2 (token, term.val.float_val, stat);
syo_error_abort (stat, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
term.val.dtype := sst_dtype_float_k;
end;
{
*************************************
*
* Item is a literal integer number.
}
2: begin
term.ttype := sst_term_const_k; {this item is a constant}
sst_r_pas_integer (term.val.int_val); {get integer value}
term.val.dtype := sst_dtype_int_k;
end;
{
*************************************
*
* Item is a literal string.
}
3: begin
term.ttype := sst_term_const_k; {term is is CONSTANT}
sst_r_pas_lit_string (token); {get value of this literal string}
if token.len = 1
then begin {string is only one character}
term.val.dtype := sst_dtype_char_k; {term value is CHARACTER data type}
term.val.char_val := token.str[1]; {save character value}
end
else begin {string is not just one character}
sz := {amount of memory needed for whole var string}
sizeof(token) - sizeof(token.str) + {overhead for var string}
(sizeof(token.str[1]) * token.len); {storage for raw string}
sst_mem_alloc_scope (sz, term.val.ar_str_p); {allocate mem for string}
term.val.ar_str_p^.max := token.len; {set new var string}
string_copy (token, term.val.ar_str_p^);
term.val.dtype := sst_dtype_array_k; {term value is of ARRAY data type}
end
;
end;
{
*************************************
*
* Item is a nested expression in parenthesis.
}
4: begin
term.ttype := sst_term_exp_k; {indicate item is nested expression}
sst_r_pas_exp (str_h, false, term.exp_exp_p); {process nested expression}
end;
{
*************************************
*
* Item is a SET expression.
}
5: begin
term.ttype := sst_term_set_k; {indicate item is a SET expression}
syo_level_down; {down into SET_VALUE syntax}
term.set_first_p := nil; {init to no element expressions in set}
set_ele_pp := addr(term.set_first_p); {set pointer to current end of ranges chain}
loop_set: {back here each new tag in SET_VALUE syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {get next syntax tag}
case tag of
{
* Tag is for new SET_VALUE_RANGE syntax.
}
1: begin
sst_mem_alloc_scope (sizeof(set_ele_p^), set_ele_p); {alloc set element/range desc}
set_ele_pp^ := set_ele_p; {link new descriptor to end of chain}
set_ele_p^.next_p := nil; {indicate new descriptor is at end of chain}
set_ele_pp := addr(set_ele_p^.next_p); {update pointer to end of chain pointer}
syo_level_down; {down into SET_VALUE_RANGE syntax}
syo_get_tag_msg {get tag for ele value or start val of range}
(tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_exp (str_h, false, set_ele_p^.first_p); {process start val expression}
syo_get_tag_msg {get tag for end of ele range expression}
(tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
case tag of
1: begin {tag is for end of range expression}
sst_r_pas_exp (str_h, false, set_ele_p^.last_p);
end;
syo_tag_end_k: begin {descriptor is for one value, not a range}
set_ele_p^.last_p := nil; {indicate no end of range expression present}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
syo_level_up; {back up from SET_VALUE_RANGE syntax}
end;
{
* Tag incidates end of SET_VALUE syntax.
}
syo_tag_end_k: begin
syo_level_up; {back up from SET_VALUE syntax}
goto leave; {all done processing set value expression}
end;
{
* Unexepected TAG value in SET_VALUE syntax.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end;
goto loop_set; {back for next tag in SET_VALUE syntax}
end;
{
*************************************
*
* Item is a symbol. This could be a variable, function, enumerated constant,
* data type, or named constant. We will first check for an intrinsic function,
* since it will be handled differently.
}
6: begin
syo_push_pos; {save current syntax position on stack}
syo_level_down; {down into VARIABLE syntax}
syo_get_tag_msg ( {get tag for intrinsic function name}
tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
syo_get_tag_msg ( {must be syntax end for intrinsic function}
tag2, str2_h, 'sst_pas_read', 'exp_bad', nil, 0);
if tag2 <> syo_tag_end_k then goto not_ifunc; {not intrinsic function ?}
sst_symbol_lookup (str_h, sym_p, stat); {look up symbol name}
syo_error_abort (stat, str_h, '', '', nil, 0);
if sym_p^.symtype <> sst_symtype_front_k {not right sym type for intrinsic func ?}
then goto not_ifunc;
syo_pop_pos; {pop old syntax position from stack}
{
* This item is an intrinsic function reference. SYM_P is pointing to the
* symbol descriptor for the intrinsic function. The syntax position is
* right after the tag for the VARIABLE syntax was read in ITEM. The next
* tag should be for the function arguments.
}
sst_r_pas_ifunc (sym_p^, term); {handle intrinsic function call}
goto leave;
{
* The item is not an intrinsic function.
}
not_ifunc: {go here if "variable" wasn't intrinsic func}
syo_pop_pos; {restore syntax parsing position}
sst_r_pas_variable (var_p); {process VARIABLE syntax and build descriptor}
sst_var_funcname (var_p^); {call func instead of stuff return value}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {var/func tag}
case tag of
{
* Item looks syntactically like a variable reference. No () follows.
}
1: begin {syntactically just a variable reference}
case var_p^.vtype of {what kind of "variable" references is this}
sst_vtype_var_k, {regular variable}
sst_vtype_dtype_k, {data type}
sst_vtype_const_k: begin {named constant}
term.ttype := sst_term_var_k; {indicate term is variable reference}
term.var_var_p := var_p; {point to variable descriptor}
end;
sst_vtype_rout_k: begin {routine name}
args_here := false; {no arguments were supplied for function}
goto isa_routine;
end;
otherwise
syo_error (term.str_h, 'sst_pas_read', 'exp_symbol_type_bad', nil, 0);
end;
end; {end of syntactic variable reference}
{
* Item has () following it.
}
2: begin {function reference}
case var_p^.vtype of {what type of "variable" is this ?}
sst_vtype_dtype_k: begin {item is a type-casting function}
term.ttype := sst_term_type_k;
term.type_dtype_p := var_p^.dtype_p;
syo_level_down; {down into FUNCTION_ARGUMENTS syntax}
syo_get_tag_msg {get tag to argument expression}
(tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
if tag <> 1 then begin
syo_error_tag_unexp (tag, str_h);
end;
sst_r_pas_exp (str_h, false, term.type_exp_p); {make expression descriptor}
syo_get_tag_msg {get tag to "next" argument (should be none)}
(tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0);
if tag <> syo_tag_end_k then begin
syo_error_tag_unexp (tag, str_h);
end;
syo_level_up; {back up from FUNCTION_ARGUMENTS syntax}
end;
sst_vtype_rout_k: begin {item is a function reference}
args_here := true; {this function definately has arguments}
goto isa_routine; {to common code for all functions}
end;
otherwise {wrong item type to have () following}
syo_error (var_p^.mod1.top_str_h, 'sst_pas_read', 'exp_symbol_not_func', nil, 0);
end; {end of "variable" type cases followed by ()}
end; {end of item has () following case}
{
* Unexpected syntax tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end;
goto leave; {all done with item is a symbol}
isa_routine: {item is a routine, ARGS_HERE has been set}
if
(var_p^.rout_proc_p^.dtype_func_p = nil) or {routine is not a function ?}
addr_of {this is argument to ADDR function ?}
then begin
{
* Pass routine, instead of function value. This happens to all ADDR
* arguments.
}
if args_here then begin {definately bad if arguments exists}
syo_error (term.str_h, 'sst_pas_read', 'exp_rout_not_func', nil, 0);
end;
term.ttype := sst_term_var_k; {flag term as a variable reference}
term.dtype_p := var_p^.dtype_p; {term takes on variable's data type}
term.dtype_hard := true;
term.val_eval := true; {prevent re-evaluation later}
term.val_fnd := false; {this term has no known constant value}
term.val.dtype := sst_dtype_proc_k; {base data type is PROCEDURE}
term.rwflag := []; {no read/write access allowed to this term}
term.var_var_p := var_p; {set pointer to routine name var descriptor}
goto leave;
end; {end of routine is not a function case}
term.ttype := sst_term_func_k; {term is a function reference}
term.func_var_p := var_p; {point to descriptor for function reference}
sst_r_pas_routine ( {create descriptor for this routine reference}
str_h, {string handle for routine reference}
term.func_var_p^, {"variable" descriptor for routine name}
args_here, {TRUE if arguments were supplied for function}
term.func_proc_p); {returned routine call descriptor}
term.func_proct_p := var_p^.rout_proc_p; {save pointer to called routine template}
goto leave; {all done with VARIABLE/FUNCTION}
end;
{
*************************************
*
* Item is boolean constant TRUE
}
7: begin
term.ttype := sst_term_const_k; {this item is a constant}
term.val.bool_val := true;
term.val.dtype := sst_dtype_bool_k;
end;
{
*************************************
*
* Item is boolean constant FALSE
}
8: begin
term.ttype := sst_term_const_k; {this item is a constant}
term.val.bool_val := false;
term.val.dtype := sst_dtype_bool_k;
end;
{
*************************************
*
* Item is pointer value NIL.
}
9: begin
term.ttype := sst_term_const_k; {this item is a constant}
term.val.dtype := sst_dtype_pnt_k; {constant is of POINTER type}
term.val.pnt_dtype_p := sst_dtype_uptr_p; {point to dtype descriptor for univ ptr}
term.val.pnt_exp_p := nil;
end;
{
*************************************
*
* Unexpected TAG value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of item type TAG cases}
leave: {common exit point}
syo_level_up; {back up from ITEM syntax level}
if term.op1 = sst_op1_1comp_k then begin {term preceeded by ~ operator ?}
term.op1 := sst_op1_none_k; {temporarily disable unary operator}
if term.dtype_p = nil then begin {need to find data type to check unary op ?}
sst_term_eval (term, false); {determine term's data type}
end;
dt_p := term.dtype_p; {resolve term's base data type}
while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p;
if dt_p^.dtype = sst_dtype_set_k
{
* The term was preceeded by the "~" unary operator, and has the SET data
* type. This indicates set inversion, but is handled with the SETINV
* intrinisic function instead of a unary operator. The term that was just
* created will be set at the argument to a SETINV intrinsic function.
}
then begin {term has the SET data type}
sst_mem_alloc_scope (sizeof(exp_p^), exp_p);
exp_p^.term1 := term; {fill in mandatory part of ifunc arg exp}
exp_p^.term1.next_p := nil;
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.str_h := exp_p^.term1.str_h;
exp_p^.val_eval := false;
sst_mem_alloc_scope (sizeof(ifarg_p^), ifarg_p); {get ifunc arg descriptor}
ifarg_p^.next_p := nil; {this ifunc has only one argument}
ifarg_p^.exp_p := exp_p; {point to expression for this argument}
term.ttype := sst_term_ifunc_k; {caller's term no refers to intrinsic func}
term.val_eval := false;
term.ifunc_id := sst_ifunc_setinv_k;
term.ifunc_args_p := ifarg_p;
end
{
* The term does not represent a set inversion.
}
else begin {term is not a SET}
term.op1 := sst_op1_1comp_k; {restore unary operator}
term.val_eval := false; {reset term to not evaluated yet}
end
;
end; {done handling term has preceeding "~"}
sst_term_eval (term, false); {evaluate term, if possible}
end;
|
unit classUtil;
interface
type
TUtil = class
class function somenteNumero(texto: String) : String;
class function validarEmail(email: string): Boolean;
end;
implementation
uses
System.SysUtils;
{ Util }
class function TUtil.somenteNumero(texto: String): String;
var
index: integer;
novoTexto: string;
begin
novoTexto := '';
for index := 1 To Length(Texto) Do
begin
if (Texto[index] in ['0'..'9']) then
begin
novoTexto := novoTexto + Copy(Texto, index, 1);
end;
end;
result := novoTexto;
end;
class function TUtil.validarEmail(email: string): Boolean;
begin
email := Trim(UpperCase(email));
if Pos('@', email) > 1 then begin
Delete(email, 1, pos('@', email));
Result := (Length(email) > 0) and (Pos('.', email) > 2) and (Pos(' ', email) = 0);
end else begin
Result := False;
end;
end;
end.
|
(*---------------------------------------------------------*)
(* First List (Single Link) *)
(* Neuhold Michael *)
(* 28.11.2018 *)
(*---------------------------------------------------------*)
PROGRAM FirstList;
TYPE
NodePtr = ^Node;
Node = RECORD
value: INTEGER;
prev: NodePtr;
next: NodePtr;
END;
List = RECORD
first: NodePtr;
last: NodePtr;
END;
(* Init List - initializes list with nil *)
PROCEDURE InitList(VAR l: List);
BEGIN
l.first := NIL;
l.last := NIL;
END;
(* newNode - creates new node *)
FUNCTION NewNode(value: INTEGER): NodePtr;
VAR
n: NodePtr;
BEGIN
New(n);
n^.value := value;
n^.prev := NIL;
n^.next := NIL;
NewNode := n;
END;
(* Prepend - add node at the beginnig of the list *)
PROCEDURE Prepend(VAR l: List; n: NodePtr);
BEGIN
IF l.first = NIL THEN BEGIN
l.first := n;
l.last := n;
END
ELSE BEGIN
n^.next := l.first;
l.first^.prev := n;
l.first := n;
END;
END;
(* NrOfNodes: Count the number of nodes in list l *)
FUNCTION NrOfNodes(l: List): INTEGER;
VAR
n: NodePtr;
cnt: INTEGER; (* count number of nodes *)
BEGIN
n := l.first;
cnt := 0;
WHILE n <> NIL DO BEGIN
cnt := cnt + 1;
n := n^.next;
END;
NrOfNodes := cnt;
END;
(* Append: add node at last position in list *)
PROCEDURE Append(VAR l: List; n: NodePtr);
BEGIN
IF l.last = NIL THEN BEGIN
l.first := n;
l.last := n;
END
ELSE BEGIN
l.last^.next := n;
n^.prev := l.last;
l.last := n;
END;
END;
(* DisposeList - Dispose all Nods of List *)
PROCEDURE DisposeList(VAR l: List);
VAR
nToDespose: NodePtr;
n: NodePtr;
BEGIN
n := l.first;
WHILE n <> NIL DO BEGIN
nToDespose := n;
n := n^.next;
Dispose(nToDespose);
END;
l.first := NIL;
l.last:= NIL;
END;
(* WriteList - write all nodes of list. *)
PROCEDURE WriteList(l: List);
VAR
n: NodePtr;
BEGIN
n := l.first;
Write('< ');
WHILE n <> NIL DO BEGIN
Write(n^.value);
IF n^.next <> NIL THEN
Write(', ');
n := n^.next;
END;
Write(' >');
END;
VAR
l: List;
BEGIN
InitList(l);
Prepend(l, NewNode(15));
Prepend(l, NewNode(14));
Prepend(l, NewNode(13));
Prepend(l, NewNode(12));
Append(l, NewNode(20));
{Insert(l, NewNode(18));}
WriteList(l);
WriteLn;
WriteLn('Anzahl der Elemente: ', NrOfNodes(l));
WriteLn;
{ IF NodeWith(l, 12) <> NIL THEN
WriteLn('l contains node with!');
DeleteFirstNodeWith(l,12);
WriteList(l);}
DisposeList(l);
WriteLn('Anzahl der Elemente: ', NrOfNodes(l));
{InitList(l);
Insert(l, NewNode(18));
WriteList(l);
WriteLn;
DisposeList(l);
}
END. |
unit F1DocumentAPIPrototype;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "SandBox"
// Автор: Люлин А.В.
// Модуль: "F1DocumentAPIPrototype.pas"
// Начат: 29.07.2010 16:26
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: Interfaces::Category F1 Базовые определения предметной области::LegalDomain::SandBox::F1DocumentAPIPrototype
//
// {RequestLink:228693062}
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
IOUnit
;
type
TnsLayerID = record
{* Идентификатор нелистьевого параграфа. Конкретный вид зависит от выбора схемы хранения документа. Либо это путь, либо просто смещение }
end;//TnsLayerID
TnsChildID = record
{* Идентификатор листьевого параграфа. Конкретный вид зависит от выбора схемы хранения документа. Скорее всего просто long - т.е. порядковый номер ребёнка. Проблемы с дополнительными "дырками" от комментарие скорее всего может решить оболочка }
end;//TnsChildID
TnsExternalID = Integer;
{* Уникальный идентификатор элемента документа }
TnsBoormark = record
{* Закладка }
end;//TnsBoormark
TnsBookmarks = array of TnsBoormark;
{* Список закладок }
TnsEVDStream = IOUnit.IStream;
{* Поток с EVD }
InsContentsTreeNode = interface(IUnknown)
{* Узел дерева оглавления }
['{107BDB51-3B1E-40EF-B5AE-8D0CA2485C15}']
end;//InsContentsTreeNode
TnsEntryPoint = record
{* Точка входа в документ }
rLayer : TnsLayerID; // Уровень
rChild : TnsChildID; // Ребёнок на уровне
end;//TnsEntryPoint
TnsFoundContextEntry = record
{* Единичный найденный контекст }
rPara : TnsEntryPoint; // Параграф в котором найден контекст
rStart : Integer; // Начальная позиция
rFinish : Integer; // Конечная позиция
end;//TnsFoundContextEntry
TnsFoundContexts = array of TnsFoundContextEntry;
{* Все найденные вхождения }
TnsEVDType = Byte;
{* Тип элемента в терминах EVD }
InsContentsTree = interface(IUnknown)
{* Дерево оглавления }
['{AA4AA042-3610-48CD-84EC-E68DB2CC9868}']
function Get_RootNode: InsContentsTreeNode;
function FindContentsNode(anID: TnsExternalID;
aType: TnsEVDType;
anInheritable: Boolean): InsContentsTreeNode;
{* Которое в качестве одной из возможностей предоставляло ID блока/саба или параграфа, а также поиск по ним. Точнее поиск по паре (EVD-тип, ID) }
property RootNode: InsContentsTreeNode
read Get_RootNode;
{* Корневой узел }
end;//InsContentsTree
InsDocumentTextProvider = interface(IUnknown)
{* Ручка для доступа к тексту документа }
['{0EF6063A-18E7-41D9-AE0A-C5B83CEAE2A5}']
function Get_Contents: InsContentsTree;
function Get_ChildComment(const anID: TnsEntryPoint): TnsEVDStream;
procedure Set_ChildComment(const anID: TnsEntryPoint; const aValue: TnsEVDStream);
function Get_ChildBookMarks(const anID: TnsEntryPoint): TnsBookmarks;
procedure Set_ChildBookMarks(const anID: TnsEntryPoint; const aValue: TnsBookmarks);
function Get_ChildText(const anID: TnsEntryPoint): IString;
procedure Set_ChildText(const anID: TnsEntryPoint; const aValue: IString);
function Get_ChildType(const anID: TnsEntryPoint): TnsEVDType;
function Get_ChildID(const anID: TnsEntryPoint): TnsExternalID;
function Get_ChildEVDStyle(const anID: TnsEntryPoint): TnsEVDStream;
function Get_ChildData(const anID: TnsEntryPoint): IStream;
function Get_LayerID(const anID: TnsEntryPoint): TnsLayerID;
function AllLeafParaCount(const aLayerID: TnsLayerID): Integer;
{* Общее число "детей" вытянутых в линейку (для скроллера). Можно вообще компилятором посчитать.
М.б. эта ручка избыточна и вычитывать из стиля соответствующего уровня. Тег AllChildrenCount }
function ChildrenCount(const aLayerID: TnsLayerID): Integer;
{* Количество детей на каждом уровне }
function FindBlockOrSub(anID: TnsExternalID): TnsEntryPoint;
{* Поиск блока/саба по номеру }
function FindPara(anID: TnsExternalID): TnsEntryPoint;
{* Найти параграф по внешнему (уникальному) ID }
function FindContext(const aContext: IString): TnsFoundContexts;
{* Поиск контекста. Сейчас он идёт через механизм поиска в дереве }
property Contents: InsContentsTree
read Get_Contents;
{* ОТДЕЛЬНОЕ дерево оглавления. Которое в качестве одной из возможностей предоставляло ID блока/саба или параграфа, а также поиск по ним. Точнее поиск по паре (EVD-тип, ID) }
property ChildComment[const anID: TnsEntryPoint]: TnsEVDStream
read Get_ChildComment
write Set_ChildComment;
{* Комментарий по ID параграфа (модифицируемый). В виде EVD. Точнее в том же самом виде, в каком оболочка его же сама и записала. Они кстати "раньше" и так были сбоку от дерева документа }
property ChildBookMarks[const anID: TnsEntryPoint]: TnsBookmarks
read Get_ChildBookMarks
write Set_ChildBookMarks;
{* Список закладок по ID параграфа (модифицируемый). Они кстати "раньше" и так были сбоку от дерева документа. И по-моему и сейчас остались "сбоку" }
property ChildText[const anID: TnsEntryPoint]: IString
read Get_ChildText
write Set_ChildText;
{* текст (имя) }
property ChildType[const anID: TnsEntryPoint]: TnsEVDType
read Get_ChildType;
{* Тип ребёнка в терминах evd }
property ChildID[const anID: TnsEntryPoint]: TnsExternalID
read Get_ChildID;
{* идентификатор }
property ChildEVDStyle[const anID: TnsEntryPoint]: TnsEVDStream
read Get_ChildEVDStyle;
{* evd-стиль (который сейчас лежит либо в базе либо в индексах) }
property ChildData[const anID: TnsEntryPoint]: IStream
read Get_ChildData;
{* data (для картинок) }
property LayerID[const anID: TnsEntryPoint]: TnsLayerID
read Get_LayerID;
{* Идентификатор уровня для ребёнка (нелистьевого) }
end;//InsDocumentTextProvider
InsListForFiltering = interface(IUnknown)
['{926A12FE-12A4-47CE-A44C-950106B1258B}']
function Get_Count: Integer;
function Get_Items(anIndex: Integer): IString;
property Count: Integer
read Get_Count;
property Items[anIndex: Integer]: IString
read Get_Items;
end;//InsListForFiltering
TnsFiltered = array of Integer;
InsListFiltrator = interface(IUnknown)
['{648F2FC3-3809-4C67-918B-185CC98A24F7}']
function Filtrate(const aList: InsListForFiltering;
const aContext: IString): TnsFiltered;
end;//InsListFiltrator
implementation
end. |
{ Subroutine SST_R_SYN_UTITEM (JTARG)
*
* Process UNTAGGED_ITEM syntax.
}
module sst_r_syn_utitem;
define sst_r_syn_utitem;
%include 'sst_r_syn.ins.pas';
procedure sst_r_syn_utitem ( {process UNTAGGED_ITEM syntax}
in out jtarg: jump_targets_t); {execution block jump targets info}
val_param;
var
tag: sys_int_machine_t; {tag from syntax tree}
sym_p: sst_symbol_p_t; {scratch pointer to SST symbol}
lab_loop_p: sst_symbol_p_t; {pointer to label at start of loop}
exp_p, exp2_p, exp3_p: sst_exp_p_t; {scratch pointers to SST expressions}
arg_p: sst_exp_p_t; {scratch pointer to call argument expression}
var_p: sst_var_p_t; {scratch pointer to variable reference}
term_p: sst_exp_term_p_t; {scratch pointer to SST term in expression}
data_p: symbol_data_p_t; {pointer to symbol data in our symbol table}
ran1, ran2: sys_int_machine_t; {start and end of range character codes}
occ1, occ2: sys_int_machine_t; {min and max occurance limits}
occinf: boolean; {max occur limit infinite, OCC2 irrelevant}
jt: jump_targets_t; {jump targets for subordinate syntax}
token: string_var8192_t; {scratch token or string}
stat: sys_err_t; {completion status}
label
comp_char_sym, occur_n, occur_dnmatch,
done_item, trerr;
begin
token.max := sizeof(token.str); {init local var string}
if not syn_trav_next_down (syn_p^) {down into UNTAGGED_ITEM syntax}
then goto trerr;
tag := syn_trav_next_tag (syn_p^); {get tag indicating the type of item}
case tag of {what kind of item is it ?}
{
********************************************************************************
*
* Item is .EOL
}
1: begin
sym_p := sym_ichar_eol_p; {get pointer to constant to compare char to}
{
* Common code to compare the next input character to the constant pointed to
* by SYM_P. MATCH is set to TRUE iff the two match.
}
comp_char_sym: {common code to compare next char to SYM_P^}
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
{
* Make expression comparing the next input character to the constant at SYM_P.
}
exp_p := sst_r_syn_exp_ichar; {init expression to result of SYN_P_ICHAR function}
sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term}
exp_p^.term1.next_p := term_p; {link new term as second term in exp}
term_p^.next_p := nil; {no additional terms in expression}
term_p^.op2 := sst_op2_eq_k; {operator with previous term}
term_p^.op1 := sst_op1_none_k; {no unary operation on this term}
term_p^.ttype := sst_term_const_k; {this term is a constant}
term_p^.str_h.first_char.crange_p := nil;
term_p^.dtype_p := sym_int_p^.dtype_dtype_p; {data type is machine integer}
term_p^.dtype_hard := true; {data type is known and fixed}
term_p^.val_eval := true; {tried to resolve value}
term_p^.val_fnd := true; {found known fixed value}
term_p^.val := sym_p^.const_exp_p^.val; {copy value from the symbol to compare against}
term_p^.rwflag := [sst_rwflag_read_k]; {term is read-only}
{
* Set MATCH to the result of comparing the next input character to the
* selected constant.
}
sst_r_syn_assign_exp ( {assign expression result to a variable}
match_var_p^, {variable to assign to}
exp_p^); {expression to assign to the variable}
sst_r_syn_err_check; {abort on end of error re-parse}
sst_call (sym_cpos_pop_p^); {restore input position if no match}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_arg_match; {pass MATCH}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is .EOF
}
2: begin
sym_p := sym_ichar_eof_p; {constant next input char must match}
goto comp_char_sym;
end;
{
********************************************************************************
*
* Item is symbol reference
}
3: begin
syn_trav_tag_string (syn_p^, token); {get the symbol name string}
sst_r_syn_sym_lookup (token, data_p); {get data for this called syntax}
sst_r_syn_sym_called (token); {make this syntax as called}
exp_p := sst_r_syn_exp_pfunc (data_p^.sym_p^); {get expression for parse func value}
sst_r_syn_assign_exp ( {assign expression to variable}
match_var_p^, {assign to local MATCH variable}
exp_p^); {expression to assign to the variable}
sst_r_syn_err_check; {abort parsing on end of error re-parse}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is string constant
}
4: begin
if not syn_trav_next_down (syn_p^) {down into STRING syntax}
then goto trerr;
if syn_trav_next_tag (syn_p^) <> 1 {get tag for raw string}
then goto trerr;
syn_trav_tag_string (syn_p^, token); {get the raw string}
exp_p := sst_func_exp (sym_test_string_p^); {init SYN_P_TEST_STRING function call}
sst_func_arg (exp_p^, exp_syn_p^); {add SYN call argument}
sst_exp_const_vstr (token, arg_p); {create string constant expression}
sst_func_arg (exp_p^, arg_p^); {pass it}
sst_exp_const_int (token.len, arg_p); {create string length expression}
sst_func_arg (exp_p^, arg_p^); {pass it}
sst_r_syn_assign_exp ( {assign SYN_P_TEST_STRING result to MATCH}
match_var_p^, {variable to assign to}
exp_p^); {expression to assign to it}
sst_r_syn_err_check; {abort on end of error re-parse}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
if not syn_trav_up (syn_p^) {back up from STRING syntax}
then goto trerr;
end;
{
********************************************************************************
*
* Item is .RANGE
}
5: begin
if syn_trav_next_tag (syn_p^) <> 1 {get tag for start of range character}
then goto trerr;
if not sst_r_syn_char_get (ran1) {get start of range character code}
then goto trerr;
if syn_trav_next_tag (syn_p^) <> 1 {get tag for end of range character}
then goto trerr;
if not sst_r_syn_char_get (ran2) {get end of range character code}
then goto trerr;
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
exp_p := sst_func_exp (sym_ichar_p^); {init SYN_P_ICHAR result value expression}
sst_func_arg (exp_p^, exp_syn_p^); {add SYN call argument}
sst_r_syn_int (sym_p); {create new integer variable}
sst_sym_var (sym_p^, var_p); {make variable descriptor for new var}
sst_r_syn_assign_exp (var_p^, exp_p^); {assign function value to the new var}
sst_r_syn_err_check; {abort on end of error re-parse}
{
* Set MATCH according to whether the character code is within the range or
* not. EXP_P is set pointing to the expression:
*
* (VAR >= ran1) and (VAR <= ran2)
*
* The first sub-expression is pointed to by EXP2_P, and the second by EXP3_P.
}
sst_r_syn_comp_var_int ( {create first sub-expression}
sym_p^, {symbol of variable to compare}
ran1, {integer value to compare against}
sst_op2_ge_k, {compare operator}
exp2_p); {returned pointer to the new expresion}
sst_r_syn_comp_var_int ( {create second sub-expression}
sym_p^, {symbol of variable to compare}
ran2, {integer value to compare against}
sst_op2_le_k, {compare operator}
exp3_p); {returned pointer to the new expresion}
sst_r_syn_exp_exp2 ( {create top level expression}
exp2_p^, exp3_p^, {the two subexpressions}
sst_op2_and_k, {operator to combine subexpressions}
exp_p); {returned pointer to combined expression}
{
* Assign the value of the top level expression to the local MATCH variable.
}
sst_r_syn_assign_exp ( {assign expression value to a variable}
match_var_p^, {variable to assign to}
exp_p^); {expression to assign to it}
{
* MATCH is all set. Handle the yes/no cases accordingly>
}
sst_call (sym_cpos_pop_p^); {restore input position if no match}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_arg_match; {pass MATCH}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is .OCCURS
}
6: begin
{
* Read the min/max occurance limits and set OCC1, OCC2, and OCCINF
* accordingly.
}
{
* Get the minimum number of occurance into OCC1.
}
if syn_trav_next_tag (syn_p^) <> 1 {get tag for first value integer}
then goto trerr;
syn_trav_tag_string (syn_p^, token); {get the raw string}
string_t_int (token, occ1, stat); {get min occurance number}
syn_error_bomb (syn_p^, stat, 'sst_syn_read', 'occurs_limit_low_bad', nil, 0);
{
* Get the maximum number of occurances into OCC2, or set OCCINF to indicate
* there is no upper limit. The value of OCC2 is irrelevant when OCCINF is
* TRUE.
}
if not syn_trav_next_down (syn_p^) {down into END_RANGE syntax}
then goto trerr;
case syn_trav_next_tag(syn_p^) of {which type of end of range is it ?}
1: begin {explicit integer value}
syn_trav_tag_string (syn_p^, token); {get the raw string}
string_t_int (token, occ2, stat); {get max occurance number}
syn_error_bomb (syn_p^, stat, 'sst_syn_read', 'integer_bad', nil, 0);
occinf := false; {OCC2 contains the finite upper limit}
end;
2: begin {inifinite}
occ2 := 0; {set to fixed value, unused}
occinf := true; {indicate no upper limit on occurances}
end;
otherwise
syn_msg_tag_bomb ( {unexpected tag encountered}
syn_p^, 'sst_syn_read', 'occurs_limit_high_bad', nil, 0);
end;
if not syn_trav_up (syn_p^) {back up from END_RANGE syntax}
then goto trerr;
{
* Check for the upper limit is less than the lower limit. The .OCCURS
* condition is always FALSE then.
}
if {check for impossible condition}
(not occinf) and {upper limit exists ?}
(occ2 < occ1) {both limits can't be met ?}
then begin
sst_r_syn_assign_match (false); {indicate syntax doesn't match}
sst_r_syn_jtarg_goto_targ (jtarg.no); {go to the NO target}
goto done_item; {done procession this .OCCURS item}
end;
{
* Check for the upper limit is 0 or less. The .OCCURS condition is
* always TRUE then.
}
if {0 upper limit ?}
(not occinf) and {upper limit exists ?}
(occ2 <= 0) {limit is always met ?}
then begin
sst_r_syn_assign_match (true); {indicate syntax matched}
sst_r_syn_jtarg_goto_targ (jtarg.yes); {go to the YES target}
goto done_item; {done procession this .OCCURS item}
end;
{
* The range for valid number of occurrances is known. The following state is
* set:
*
* OCC1 - Minimum required number of occurances.
*
* OCC2 - Maximum allowed number of occurances.
*
* OCCINF - There is no upper bound on the maximum number of occurances.
* When OOCINF is TRUE, then the OCC2 value is unused and irrelevant.
*
* The above conditions have been verified to be possible to meet, and that the
* item must be run at least once.
*
* The next syntax tree entry is for the subordinate item that is to be
* repeated.
}
occur_n: {OCC1, OCC2, OCCINF all set and valid}
{
* Create the occurrance counter and initialize it to 0.
}
sst_r_syn_int (sym_p); {create new integer variable}
sst_sym_var (sym_p^, var_p); {make reference to new variable}
sst_exp_const_int (0, exp_p); {make constant 0 expression}
sst_r_syn_assign_exp ( {assign expression to variable}
var_p^, {variable}
exp_p^); {expression}
{
* Create the label to jump to for repeating the loop.
}
sst_r_syn_jtarg_label_here (lab_loop_p); {create and define top of loop label}
{
* Process the subordinate ITEM syntax.
}
sst_r_syn_jtarg_sub ( {make jump targets for subordinate item}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_fall_k, {fall thru on YES}
lab_fall_k); {fall thru on NO}
sst_r_syn_item (jt); {process the item, set MATCH accordingly}
sst_r_syn_jtarg_here (jt); {define jump target labels here}
{
* Handle the case of the item not matching the syntax template. In that case,
* the final MATCH answer is whether the number of iterations is within the
* min/max limits. Since the loop is aborted whenever the number of iterations
* matches the upper limit, there is no need to check the upper limit. The
* iteration count can't exceed the upper limit here.
}
sst_r_syn_jtarg_sub ( {make jump targets for subordinate item}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_same_k, {to same place as parent}
lab_same_k); {to same place as parent}
sst_opcode_new; {create new opcode for IF}
sst_opc_p^.opcode := sst_opc_if_k;
sst_opc_p^.if_exp_p := match_not_exp_p; {conditional expression is NOT MATCH}
sst_opc_p^.if_false_p := nil; {there is no FALSE case code}
sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code}
{
* The item did not match. Now set MATCH according to whether the number of
* iterations meets the lower limit.
}
if occ1 <= 0
then begin {no lower limit, the result is always YES}
sst_r_syn_assign_match (true); {indicate syntax matched}
sst_r_syn_jtarg_goto_targ (jt.yes); {go to target for YES}
goto occur_dnmatch; {done handling didn't match case}
end
else begin {need to check against the lower limit}
sst_r_syn_comp_var_int ( {make exp comparing count to lower limit}
var_p^.mod1.top_sym_p^, {the variable to compare value of}
occ1, {integer to compare it with}
sst_op2_ge_k, {comparison operator}
exp_p); {returned pointer to the comparison expression}
sst_r_syn_assign_exp ( {set MATCH to the comparison result}
match_var_p^, {the variable to assign to}
exp_p^); {the expression to assign to it}
end
;
{
* Done with this item, jump according to MATCH.
}
sst_r_syn_jtarg_goto ( {jump to yes/no labels according to MATCH}
jt, [jtarg_yes_k, jtarg_no_k]);
occur_dnmatch: {done with didn't match case}
sst_opcode_pos_pop; {done writing TRUE case opcodes}
{
* Increment the number of occurences.
}
exp_p := sst_exp_make_var ( {init expression to be ref to the counter}
var_p^.mod1.top_sym_p^);
sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term}
exp_p^.term1.next_p := term_p; {link new term as second term in exp}
term_p^.next_p := nil; {no additional terms in expression}
term_p^.op2 := sst_op2_add_k; {operator with previous term}
term_p^.op1 := sst_op1_none_k; {no unary operation on this term}
term_p^.ttype := sst_term_const_k; {this term is a constant}
term_p^.str_h.first_char.crange_p := nil;
term_p^.dtype_p := sym_int_p^.dtype_dtype_p; {data type is machine integer}
term_p^.dtype_hard := true; {data type is known and fixed}
term_p^.val_eval := true; {tried to resolve value}
term_p^.val_fnd := true; {found known fixed value}
term_p^.val.dtype := sst_dtype_int_k; {constant data type is integer}
term_p^.val.int_val := 1; {the constant value}
term_p^.rwflag := [sst_rwflag_read_k]; {term is read-only}
sst_r_syn_assign_exp ( {assign incremented value to the counter}
var_p^, {the variable to assign to}
exp_p^); {the expression to assign to it}
{
* Stop processing and return TRUE if the maximum number of occurences has been
* met. It was previously verified to be at least the minimum number of
* allowed occurences.
}
if not occinf then begin {there is an upper limit ?}
sst_r_syn_comp_var_int ( {create expression comparing counter to limit}
var_p^.mod1.top_sym_p^, {the variable to compare value of}
occ2, {integer to compare it with}
sst_op2_ge_k, {comparison operator}
exp_p); {returned pointer to the comparison expression}
sst_opcode_new; {create new opcode for IF}
sst_opc_p^.opcode := sst_opc_if_k;
sst_opc_p^.if_exp_p := exp_p; {conditional expression}
sst_opc_p^.if_false_p := nil; {there is no FALSE case code}
sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code}
sst_r_syn_jtarg_goto_targ (jt.yes); {go to target for YES}
sst_opcode_pos_pop; {done writing TRUE case opcodes}
end; {end of check for upper limit case}
{
* Back to try another iteration.
}
sst_r_syn_jtarg_label_goto (lab_loop_p^); {jump back to start of loop}
sst_r_syn_jtarg_here (jt); {define our local jump targets here}
end;
{
********************************************************************************
*
* Item is nested expression in parenthesis.
}
7: begin
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_jtarg_sub ( {make jump targets for subordinate expression}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_fall_k, {fall thru on YES}
lab_fall_k); {fall thru on NO}
sst_r_syn_expression (jt); {process the subordinate expression}
sst_r_syn_jtarg_here (jt); {define jump target labels here}
sst_call (sym_cpos_pop_p^); {restore input position if no match}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_arg_match; {pass MATCH}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is .CHARCASE
}
8: begin
tag := syn_trav_next_tag (syn_p^); {get tag identifying the character case}
case tag of {which character case handling is it ?}
1: sym_p := sym_charcase_up_p;
2: sym_p := sym_charcase_down_p;
3: sym_p := sym_charcase_asis_p;
otherwise {unexpected tag value}
syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'charcase_bad', nil, 0);
end;
sst_call (sym_charcase_p^); {start call to SYN_P_CHARCASE}
sst_r_syn_arg_syn; {add SYN call argument}
sst_call_arg_enum (sst_opc_p^, sym_p^); {add char case handling choice argument}
sst_r_syn_assign_match (true); {this item always matches}
sst_r_syn_jtarg_goto_targ (jtarg.yes); {go to target for YES case}
end;
{
********************************************************************************
*
* Item is .NULL
}
9: begin
sst_r_syn_assign_match (true); {this item always matches}
sst_r_syn_jtarg_goto_targ (jtarg.yes); {go to target for YES case}
end;
{
********************************************************************************
*
* Item is .UPTO
}
10: begin
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_jtarg_sub ( {make subordinate jump targets for ITEM}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_fall_k, {fall thru on YES}
lab_fall_k); {fall thru on NO}
sst_r_syn_item (jt); {process the UPTO item}
sst_r_syn_jtarg_here (jt); {define jump target labels here}
sst_call (sym_cpos_pop_p^); {restore input position}
sst_r_syn_arg_syn; {pass SYN}
sst_call_arg_exp (sst_opc_p^, exp_false_p^); {pass FALSE to always restore position}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is .NOT
}
11: begin
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_jtarg_sub ( {make subordinate jump targets for ITEM}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_fall_k, {fall thru on YES}
lab_fall_k); {fall thru on NO}
sst_r_syn_item (jt); {process the item that will be negated}
sst_r_syn_jtarg_here (jt); {define jump target labels here}
sst_call (sym_cpos_pop_p^); {restore input position}
sst_r_syn_arg_syn; {pass SYN}
sst_call_arg_exp (sst_opc_p^, exp_false_p^); {pass FALSE to always restore position}
sst_r_syn_assign_exp ( {negate the local MATCH variable}
match_var_p^, {variable to assign to}
match_not_exp_p^); {expression to assign to the variable}
sst_r_syn_jtarg_goto ( {jump according to MATCH}
jtarg, [jtarg_yes_k, jtarg_no_k]);
end;
{
********************************************************************************
*
* Item is .EOD
}
12: begin
sym_p := sym_ichar_eod_p; {constant next input char must match}
goto comp_char_sym;
end;
{
********************************************************************************
*
* Item is .OPTIONAL
}
13: begin
sst_call (sym_cpos_push_p^); {save current input position on stack}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_jtarg_sub ( {make jump targets for subordinate item}
jtarg, {parent jump targets}
jt, {new subordinate targets}
lab_fall_k, {fall thru on YES}
lab_fall_k); {fall thru on NO}
sst_r_syn_item (jt); {process the item, fall thru regardless of match}
sst_r_syn_jtarg_here (jt); {define jump target labels here}
sst_call (sym_cpos_pop_p^); {restore input position if no match}
sst_r_syn_arg_syn; {pass SYN}
sst_r_syn_arg_match; {pass MATCH}
sst_r_syn_assign_match (true); {.OPTIONAL always matches}
sst_r_syn_jtarg_goto_targ (jtarg.yes); {jump to YES target}
end;
{
********************************************************************************
*
* Unexpected tag value.
}
otherwise
syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'syerr_utitem', nil, 0);
end; {end of item format cases}
done_item: {done processing the item}
if not syn_trav_up(syn_p^) {back up from UNTAGGED_ITEM syntax}
then goto trerr;
return;
{
* The syntax tree is not as expected. We assume this is due to a syntax
* error.
}
trerr:
sys_message ('sst_syn_read', 'syerr_utitem');
syn_parse_err_show (syn_p^);
sys_bomb;
end;
|
{$I OVC.INC}
{$B-} {Complete Boolean Evaluation}
{$I+} {Input/Output-Checking}
{$P+} {Open Parameters}
{$T-} {Typed @ Operator}
{$W-} {Windows Stack Frame}
{$X+} {Extended Syntax}
{$IFNDEF Win32}
{$G+} {286 Instructions}
{$N+} {Numeric Coprocessor}
{$C MOVEABLE,DEMANDLOAD,DISCARDABLE}
{$ENDIF}
{*********************************************************}
{* OVCFXFPE.PAS 2.17 *}
{* Copyright (c) 1995-98 TurboPower Software Co *}
{* All rights reserved. *}
{*********************************************************}
unit OvcFxFPE;
{-Fixed font property editors}
{$I l3Define.inc }
interface
uses
Classes, Graphics, Controls, Forms, Dialogs, SysUtils, TypInfo,
{$IfDef Delphi6}
DesignIntf,
DesignEditors,
VCLEditors,
{$Else Delphi6}
DsgnIntf,
{$EndIf Delphi6}
OvcFxFnt, OvcHelp;
type
{fixed font name property editor}
TOvcFixFontNameProperty = class(TStringProperty)
public
function GetAttributes : TPropertyAttributes;
override;
procedure GetValues(Proc : TGetStrProc);
override;
end;
{fixed font property editor}
TOvcFixFontProperty = class(TClassProperty)
public
procedure Edit;
override;
function GetAttributes : TPropertyAttributes;
override;
end;
implementation
{*** TOvcFixFontNameProperty ***}
function TOvcFixFontNameProperty.GetAttributes : TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList];
end;
procedure TOvcFixFontNameProperty.GetValues(Proc : TGetStrProc);
var
i : integer;
begin
for i := 0 to pred(FixedFontNames.Count) do
Proc(FixedFontNames[i]);
end;
{*** TOvcFixFontProperty ***}
procedure TOvcFixFontProperty.Edit;
var
FF : TOvcFixedFont;
FontDialog : TFontDialog;
begin
FontDialog := nil;
FF := nil;
try
FontDialog := TFontDialog.Create(Application);
FF := TOvcFixedFont.Create;
FF.Assign(TOvcFixedFont(GetOrdValue));
FontDialog.Font := FF.Font;
FontDialog.Options :=
FontDialog.Options + [fdForceFontExist, fdFixedPitchOnly];
if FontDialog.Execute then begin
FF.Font.Assign(FontDialog.Font);
SetOrdValue(Longint(FF));
end;
finally
FontDialog.Free;
FF.Free;
end;
end;
function TOvcFixFontProperty.GetAttributes : TPropertyAttributes;
begin
Result := [paMultiSelect, paSubProperties, paDialog, paReadOnly];
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.