text stringlengths 14 6.51M |
|---|
(************************************* Ext2D Engine *************************************)
(* Модуль : E2DKeys.pas *)
(* Автор : Есин Владимир *)
(* Создан : 16.05.06 *)
(* Информация : Модуль содежит костанты кнопок клавиатуры. *)
(* Изменения : нет изменений. *)
(****************************************************************************************)
unit E2DKeys;
interface
const
{ Константы клавиш }
E2DKEY_ESCAPE = $01; { Escape }
E2DKEY_F1 = $3B; { F1 }
E2DKEY_F2 = $3C; { F2 }
E2DKEY_F3 = $3D; { F3 }
E2DKEY_F4 = $3E; { F4 }
E2DKEY_F5 = $3F; { F5 }
E2DKEY_F6 = $40; { F6 }
E2DKEY_F7 = $41; { F7 }
E2DKEY_F8 = $42; { F8 }
E2DKEY_F9 = $43; { F9 }
E2DKEY_F10 = $44; { F10 }
E2DKEY_F11 = $57; { F11 }
E2DKEY_F12 = $58; { F12 }
E2DKEY_SYSRQ = $B7; { SysRq }
E2DKEY_SCROLL = $46; { Scroll Lock }
E2DKEY_PAUSE = $C5; { Pause }
E2DKEY_GRAVE = $29; { ` }
E2DKEY_1 = $02; { 1 на главной клавиатуре }
E2DKEY_2 = $03; { 2 на главной клавиатуре }
E2DKEY_3 = $04; { 3 на главной клавиатуре }
E2DKEY_4 = $05; { 4 на главной клавиатуре }
E2DKEY_5 = $06; { 5 на главной клавиатуре }
E2DKEY_6 = $07; { 6 на главной клавиатуре }
E2DKEY_7 = $08; { 7 на главной клавиатуре }
E2DKEY_8 = $09; { 8 на главной клавиатуре }
E2DKEY_9 = $0A; { 9 на главной клавиатуре }
E2DKEY_0 = $0B; { 0 на главной клавиатуре }
E2DKEY_MINUS = $0C; { - на главной клавиатуре }
E2DKEY_EQUALS = $0D; { = }
E2DKEY_BACKSLASH = $2B; { \ }
E2DKEY_BACK = $0E; { Backspace }
E2DKEY_Q = $10; { Q }
E2DKEY_W = $11; { W }
E2DKEY_E = $12; { E }
E2DKEY_R = $13; { R }
E2DKEY_T = $14; { T }
E2DKEY_Y = $15; { Y }
E2DKEY_U = $16; { U }
E2DKEY_I = $17; { I }
E2DKEY_O = $18; { O }
E2DKEY_P = $19; { P }
E2DKEY_LBRACKET = $1A; { [ }
E2DKEY_RBRACKET = $1B; { ] }
E2DKEY_A = $1E; { A }
E2DKEY_S = $1F; { S }
E2DKEY_D = $20; { D }
E2DKEY_F = $21; { F }
E2DKEY_G = $22; { G }
E2DKEY_H = $23; { H }
E2DKEY_J = $24; { J }
E2DKEY_K = $25; { K }
E2DKEY_L = $26; { L }
E2DKEY_SEMICOLON = $27; { ; }
E2DKEY_APOSTROPHE = $28; { ' }
E2DKEY_Z = $2C; { Z }
E2DKEY_X = $2D; { X }
E2DKEY_C = $2E; { C }
E2DKEY_V = $2F; { V }
E2DKEY_B = $30; { B }
E2DKEY_N = $31; { N }
E2DKEY_M = $32; { M }
E2DKEY_COMMA = $33; { , }
E2DKEY_PERIOD = $34; { . главной клавиатуре }
E2DKEY_SLASH = $35; { / главной клавиатуре }
E2DKEY_TAB = $0F; { Tab }
E2DKEY_CAPITAL = $3A; { Caps Lock }
E2DKEY_LSHIFT = $2A; { Левый Shift }
E2DKEY_LCONTROL = $1D; { Левый Control }
E2DKEY_LWIN = $DB; { Левая клавиша Windows }
E2DKEY_LMENU = $38; { Левый Alt }
E2DKEY_SPACE = $39; { Прорбел }
E2DKEY_RMENU = $B8; { Правый Alt }
E2DKEY_RWIN = $DC; { Правая клавиша Windows }
E2DKEY_APPS = $DD; { Меню }
E2DKEY_RCONTROL = $9D; { Правый Control }
E2DKEY_RSHIFT = $36; { Правый Shift }
E2DKEY_RETURN = $1C; { Enter на главной клавиатуре }
E2DKEY_INSERT = $D2; { Insert на стрелочной клавиатуре }
E2DKEY_HOME = $C7; { Home на стрелочной клавиатуре }
E2DKEY_PRIOR = $C9; { Page Up на стрелочной клавиатуре }
E2DKEY_DELETE = $D3; { Delete на стрелочной клавиатуре }
E2DKEY_END = $CF; { End на стрелочной клавиатуре }
E2DKEY_NEXT = $D1; { Page Down на стрелочной клавиатуре }
E2DKEY_UP = $C8; { Стрелка вверх на стрелочной клавиатуре }
E2DKEY_LEFT = $CB; { Стрелка влево на стрелочной клавиатуре }
E2DKEY_RIGHT = $CD; { Стрелка вправо на стрелочной клавиатуре }
E2DKEY_DOWN = $D0; { Стрелка вниз на стрелочной клавиатуре }
E2DKEY_NUMPAD1 = $4F; { 1 на цифровой клавиатуре }
E2DKEY_NUMPAD2 = $50; { 2 на цифровой клавиатуре }
E2DKEY_NUMPAD3 = $51; { 3 на цифровой клавиатуре }
E2DKEY_NUMPAD4 = $4B; { 4 на цифровой клавиатуре }
E2DKEY_NUMPAD5 = $4C; { 5 на цифровой клавиатуре }
E2DKEY_NUMPAD6 = $4D; { 6 на цифровой клавиатуре }
E2DKEY_NUMPAD7 = $47; { 7 на цифровой клавиатуре }
E2DKEY_NUMPAD8 = $48; { 8 на цифровой клавиатуре }
E2DKEY_NUMPAD9 = $49; { 9 на цифровой клавиатуре }
E2DKEY_NUMPAD0 = $52; { 0 на цифровой клавиатуре }
E2DKEY_NUMLOCK = $45; { Num Lock }
E2DKEY_NUMPADSLASH = $B5; { / на цифровой клавиатуре }
E2DKEY_NUMPADMULTIPLY = $37; { * на цифровой клавиатуре }
E2DKEY_NUMPADMINUS = $4A; { - на цифровой клавиатуре }
E2DKEY_NUMPADADD = $4E; { + на цифровой клавиатуре }
E2DKEY_NUMPADRETURN = $9C; { Enter на цифровой клавиатуре }
E2DKEY_NUMPADPERIOD = $53; { . на цифровой клавиатуре }
implementation
end.
|
unit Repositorio.GenericRepository;
interface
uses
System.Classes, Vcl.Controls, DBClient, Forms, Dialogs, Vcl.Grids, DB,
Vcl.DBGrids, Variants, Vcl.StdCtrls, Vcl.DBCtrls,
EF.Engine.DbSet, FactoryEntity, Repositorio.Interfaces.Base, EF.Mapping.Base, Context;
type
{$M+}
TRepository<T:TEntityBase> = class(TInterfacedPersistent, IRepository<T>)
private
FRefCount: integer;
protected
FDbContext: TContext<T>;
private
function GetEntity: T;
function GetContext:TContext<T>;
public
constructor Create(dbContext: TContext<T>);virtual;
destructor Destroy;override;
procedure RefreshDataSet;virtual;
function LoadDataSet(iId:Integer ; Fields: string = '') : TDataSet;virtual;
function Load(iId: Integer = 0): T;virtual;
procedure Delete;virtual;
procedure AddOrUpdate( State:TEntityState);virtual;
procedure Commit;virtual;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{$M-}
implementation
uses Winapi.Windows, System.SysUtils, FireDAC.Comp.Client, EF.QueryAble.Base,
EF.QueryAble.Linq;
{ TRepository }
constructor TRepository<T>.Create(dbContext: TContext<T>);
begin
Inherited Create;
FDbContext := dbContext;
end;
function TRepository<T>.LoadDataSet(iId: Integer; Fields: string = ''): TDataSet;
var
DataSet:TDataSet;
Q:IQueryAble;
begin
if iId = 0 then
Q := From(GetEntity).Select( Fields)
else
Q := From(GetEntity).where( GetEntity.Id = iId ).Select( Fields);
DataSet := FDbContext.ToDataSet( Q ) as TDataSet;
FDbContext.DBSet:= DataSet as TFDQuery;
result:= FDbContext.DBSet;
end;
function TRepository<T>.Load(iId: Integer): T;
begin
if iId = 0 then
result := FDbContext.Find(From(GetEntity).Select) as T
else
result := FDbContext.Find(From(GetEntity).where( GetEntity.Id = iId ).Select) as T;
end;
procedure TRepository<T>.Delete;
begin
//FDbContext.Remove;
end;
destructor TRepository<T>.Destroy;
begin
inherited;
if FDbContext <> nil then
begin
FDbContext.Database.Free;
FreeAndNil(FDbContext);
end;
end;
function TRepository<T>.GetContext: TContext<T>;
begin
result := FDbContext;
end;
function TRepository<T>.GetEntity: T;
begin
result:= FDbContext.Entity;
end;
procedure TRepository<T>.AddOrUpdate(State:TEntityState);
begin
case State of
esInsert: FDbContext.Add(GetEntity , true);
esEdit : FDbContext.Update(true);
else
FDbContext.RefreshDataSet;
end;
end;
procedure TRepository<T>.Commit;
begin
FDbContext.SaveChanges;
end;
procedure TRepository<T>.RefreshDataSet;
begin
FDbContext.RefreshDataSet;
end;
function TRepository<T>._AddRef: Integer;
begin
Result := inherited _AddRef;
InterlockedIncrement(FRefCount);
end;
function TRepository<T>._Release: Integer;
begin
Result := inherited _Release;
InterlockedDecrement(FRefCount);
if FRefCount <=0 then
Free;
end;
end.
|
{ Private include file for system-dependent routines in STRING library.
*
* This version is for the Microsoft Win32 API. We access the command line
* with a call to GetCommandLine, which returns a pointer to a null-terminated
* string. We parse individual tokens ourselves, using the rules for
* STRING_TOKEN.
}
%include 'sys_sys2.ins.pas';
var (string_sys)
vcmline: string_var8192_t; {saved var string copy of command line}
vcmline_parse: string_index_t; {VCMLINE parse index}
vcmline_parse_start: string_index_t; {parse index for start of cmline argument}
|
unit StringTable;
interface
type
HCkStringTable = Pointer;
HCkStringBuilder = Pointer;
HCkString = Pointer;
function CkStringTable_Create: HCkStringTable; stdcall;
procedure CkStringTable_Dispose(handle: HCkStringTable); stdcall;
function CkStringTable_getCount(objHandle: HCkStringTable): Integer; stdcall;
procedure CkStringTable_getDebugLogFilePath(objHandle: HCkStringTable; outPropVal: HCkString); stdcall;
procedure CkStringTable_putDebugLogFilePath(objHandle: HCkStringTable; newPropVal: PWideChar); stdcall;
function CkStringTable__debugLogFilePath(objHandle: HCkStringTable): PWideChar; stdcall;
procedure CkStringTable_getLastErrorHtml(objHandle: HCkStringTable; outPropVal: HCkString); stdcall;
function CkStringTable__lastErrorHtml(objHandle: HCkStringTable): PWideChar; stdcall;
procedure CkStringTable_getLastErrorText(objHandle: HCkStringTable; outPropVal: HCkString); stdcall;
function CkStringTable__lastErrorText(objHandle: HCkStringTable): PWideChar; stdcall;
procedure CkStringTable_getLastErrorXml(objHandle: HCkStringTable; outPropVal: HCkString); stdcall;
function CkStringTable__lastErrorXml(objHandle: HCkStringTable): PWideChar; stdcall;
function CkStringTable_getLastMethodSuccess(objHandle: HCkStringTable): wordbool; stdcall;
procedure CkStringTable_putLastMethodSuccess(objHandle: HCkStringTable; newPropVal: wordbool); stdcall;
function CkStringTable_getVerboseLogging(objHandle: HCkStringTable): wordbool; stdcall;
procedure CkStringTable_putVerboseLogging(objHandle: HCkStringTable; newPropVal: wordbool); stdcall;
procedure CkStringTable_getVersion(objHandle: HCkStringTable; outPropVal: HCkString); stdcall;
function CkStringTable__version(objHandle: HCkStringTable): PWideChar; stdcall;
function CkStringTable_Append(objHandle: HCkStringTable; value: PWideChar): wordbool; stdcall;
function CkStringTable_AppendFromFile(objHandle: HCkStringTable; maxLineLen: Integer; charset: PWideChar; path: PWideChar): wordbool; stdcall;
function CkStringTable_AppendFromSb(objHandle: HCkStringTable; sb: HCkStringBuilder): wordbool; stdcall;
procedure CkStringTable_Clear(objHandle: HCkStringTable); stdcall;
function CkStringTable_IntAt(objHandle: HCkStringTable; index: Integer): Integer; stdcall;
function CkStringTable_SaveLastError(objHandle: HCkStringTable; path: PWideChar): wordbool; stdcall;
function CkStringTable_SaveToFile(objHandle: HCkStringTable; charset: PWideChar; bCrlf: wordbool; path: PWideChar): wordbool; stdcall;
function CkStringTable_SplitAndAppend(objHandle: HCkStringTable; inStr: PWideChar; delimiterChar: PWideChar; exceptDoubleQuoted: wordbool; exceptEscaped: wordbool): wordbool; stdcall;
function CkStringTable_StringAt(objHandle: HCkStringTable; index: Integer; outStr: HCkString): wordbool; stdcall;
function CkStringTable__stringAt(objHandle: HCkStringTable; index: Integer): PWideChar; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkStringTable_Create; external DLLName;
procedure CkStringTable_Dispose; external DLLName;
function CkStringTable_getCount; external DLLName;
procedure CkStringTable_getDebugLogFilePath; external DLLName;
procedure CkStringTable_putDebugLogFilePath; external DLLName;
function CkStringTable__debugLogFilePath; external DLLName;
procedure CkStringTable_getLastErrorHtml; external DLLName;
function CkStringTable__lastErrorHtml; external DLLName;
procedure CkStringTable_getLastErrorText; external DLLName;
function CkStringTable__lastErrorText; external DLLName;
procedure CkStringTable_getLastErrorXml; external DLLName;
function CkStringTable__lastErrorXml; external DLLName;
function CkStringTable_getLastMethodSuccess; external DLLName;
procedure CkStringTable_putLastMethodSuccess; external DLLName;
function CkStringTable_getVerboseLogging; external DLLName;
procedure CkStringTable_putVerboseLogging; external DLLName;
procedure CkStringTable_getVersion; external DLLName;
function CkStringTable__version; external DLLName;
function CkStringTable_Append; external DLLName;
function CkStringTable_AppendFromFile; external DLLName;
function CkStringTable_AppendFromSb; external DLLName;
procedure CkStringTable_Clear; external DLLName;
function CkStringTable_IntAt; external DLLName;
function CkStringTable_SaveLastError; external DLLName;
function CkStringTable_SaveToFile; external DLLName;
function CkStringTable_SplitAndAppend; external DLLName;
function CkStringTable_StringAt; external DLLName;
function CkStringTable__stringAt; external DLLName;
end.
|
unit uFlyweightFactory;
interface
uses
Classes, uFlyweight, uConcreteFlyweight;
type
TFlyweightFactory = class
private
// variável para armazenar os objetos compartilhados
ListaCartoes: TStringList;
public
constructor Create;
destructor Destroy; override;
// método principal do Flyweight,
// responsável por encontrar e retornar o objeto já criado
// ou criá-lo caso não exista, adicionando-o na lista de objetos compartilhados
function GetCartao(const Pais: string): TCartao;
end;
implementation
uses
SysUtils;
{ TFlyweightFactory }
constructor TFlyweightFactory.Create;
begin
// cria a lista de objetos compartilhados
ListaCartoes := TStringList.Create;
ListaCartoes.Sorted := True;
end;
destructor TFlyweightFactory.Destroy;
var
Contador: integer;
begin
for Contador := 0 to Pred(ListaCartoes.Count) do
ListaCartoes.Objects[Contador].Free;
// libera a lista de objetos compartilhados da memória
FreeAndNil(ListaCartoes);
inherited;
end;
function TFlyweightFactory.GetCartao(const Pais: string): TCartao;
var
Indice: integer;
begin
result := nil;
// tenta encontrar o objeto compartilhado através do nome do país
if ListaCartoes.Find(Pais, Indice) then
begin
// caso seja encontrado, o objeto compartilhado é retornado
result := (ListaCartoes.Objects[Indice]) as TCartao;
Exit;
end;
// caso não seja encontrado, é criado...
if Pais = 'Espanha' then
result := TCartaoEspanha.Create
else if Pais = 'EUA' then
result := TCartaoEUA.Create
else if Pais = 'Brasil' then
result := TCartaoBrasil.Create
else if Pais = 'Itália' then
result := TCartaoItalia.Create;
// ... e depois adicionado na lista de objetos compartilhados
// para que não precise ser criado novamente nas próximas iterações
ListaCartoes.AddObject(Pais, result);
end;
end.
|
unit base;
{$mode objfpc}{$H+}
{$MODESWITCH TYPEHELPERS}
interface
uses
Classes, SysUtils, FileUtil, RTTICtrls, TATools, Forms, Controls, Graphics,
Dialogs, ActnList, ComCtrls, StdCtrls, Buttons,
EditBtn, ExtCtrls,windows,
ValEdit,process,LazFileUtils,fpjson,jsonparser,dateutils,localizedforms,DefaultTranslator;
const
BUF_SIZE = 2048;
ffmpeg = 'ffmpeg.exe';
ffprobe = 'ffprobe.exe';
type
{ TTLabeledEditHelper }
TTLabeledEditHelper = class helper for TLabeledEdit
function toHHMMSS:String;
end;
{ TfrmBase }
TfrmBase = class(TLocalizedForm)
btnVideo: TButton;
btnAudioPuvodni: TButton;
btnAudioMP3: TButton;
btnSmazLog: TButton;
btnExit: TButton;
FileNameEdit1: TFileNameEdit;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
ImageList1: TImageList;
Label1: TLabel;
lblPocetSouboru: TLabel;
leVelikostSegmentu: TLabeledEdit;
memLog: TMemo;
prbUkazatel: TProgressBar;
vleVlastnosti: TValueListEditor;
procedure btnAudioMP3Click(Sender: TObject);
procedure btnAudioPuvodniClick(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnSmazLogClick(Sender: TObject);
procedure btnVideoClick(Sender: TObject);
procedure FileNameEdit1AcceptFileName(Sender: TObject; var Value: String);
procedure FileNameEdit1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure runFFMPEG(exeFile,myParameters:String;progressBegin:Integer);
private
public
procedure UpdateTranslation(ALang: String); override;
end;
var
frmBase: TfrmBase;
implementation
{$R *.lfm}
{ TTLabeledEditHelper }
function TTLabeledEditHelper.toHHMMSS: String;
begin
if not(self.Text='') then
Result:=TimeToStr(incminute( 0,strtoint(self.Text)));
// great document about TDateTime see:
// https://www.freepascal.org/~michael/articles/datetime/datetime.pdf
end;
{ TfrmBase }
procedure TfrmBase.FileNameEdit1AcceptFileName(Sender: TObject; var Value: String);
// fired before property DialogFile filled
// intend as validation of user input but uncount more files could be selected
begin
end;
procedure TfrmBase.FileNameEdit1Change(Sender: TObject);
// only here is possible to use property DialogFile
var
jData:TJSONData;
jObject:TJSONObject;
i: Integer;
progressMax:Integer;
begin
// vleVlastnosti.Rows[0].Text:='aaaaa'+LineEnding+'bbbbb';
// vleVlastnosti.Keys[2]:='audio 1';
// vleVlastnosti.Values['audio 1'] :='value 1';
progressMax:=0;
vleVlastnosti.Clear;
lblPocetSouboru.Caption:='Celkem vybráno souborů: ' + IntToStr(FileNameEdit1.DialogFiles.Count);
for i:=0 to FileNameEdit1.DialogFiles.Count-1 do
begin
memLog.Clear;
runFFMPEG(ffprobe,'-v quiet, -print_format json, -show_format, -show_streams, '+
AnsiQuotedStr(FileNameEdit1.DialogFiles[i],'"'),0);
// capture json ffmpeg output from memLog component
jData:=GetJSON(memLog.Text); // !!! object created it needs to be freed in the end :-)
jObject:=TJSONObject(jData);
try
try
progressMax:=progressMax+round(jObject.FindPath('format.duration').AsFloat);
vleVlastnosti.InsertRow(ExtractFileName(jObject.FindPath('format.filename').AsString),
jObject.FindPath('streams[0].codec_type').AsString +': ' +
jObject.FindPath('streams[0].codec_name').AsString,
True);
vleVlastnosti.InsertRow(ExtractFileName(jObject.FindPath('format.filename').AsString),
jObject.FindPath('streams[1].codec_type').AsString+': '+
jObject.FindPath('streams[1].codec_name').AsString,
True);
except
Continue;
end;
finally
jData.Free; // Object cleaned after 5 min debugging :-)
end;
end;
prbUkazatel.Max:=progressMax;
end;
procedure TfrmBase.btnVideoClick(Sender: TObject);
// ExtractFileDir(pomFile) i:\Jirka-video-audiobook čárka
// ExtractFileNameOnly(pomFile) Astrid_Lindgrenová_Děti_z_Bullerbynu
// ExtractFileName(pomFile) Astrid_Lindgrenová_Děti_z_Bullerbynu.mp4
// ExtractFileExt(pomFile) .mp4
// ExtractFilePath(pomFile) i:\Jirka-video-audiobook čárka\
var
pomFile:String;
i: Integer;
begin
prbUkazatel.Position:=0;
for i:=0 to FileNameEdit1.DialogFiles.Count-1 do
begin
try
pomFile:=FileNameEdit1.DialogFiles[i];
runFFMPEG(ffmpeg,'-progress stats.txt, -i, '+AnsiQuotedStr(pomFile,'"')+
' -c copy, -map 0, -segment_time '+leVelikostSegmentu.toHHMMSS +
', -f segment, -reset_timestamps 1,'+
AnsiQuotedStr(ExtractFilePath(pomFile)+ExtractFileNameOnly(pomFile)+
'_%03d.mp4','"'),prbUkazatel.Position);
except
on E:Exception do
begin
memLog.Append('Chyba: ' + e.Message);
exit;
end;
end;
end;
memLog.Append('HOTOVO :-)');
end;
procedure TfrmBase.btnAudioPuvodniClick(Sender: TObject);
var
pomFile: String;
i: Integer;
begin
prbUkazatel.Position:=0;
for i:=0 to FileNameEdit1.DialogFiles.Count-1 do
begin
pomFile:=FileNameEdit1.DialogFiles[i];
runFFMPEG(ffmpeg,' -progress stats.txt, -i, '+AnsiQuotedStr(pomFile,'"')+
' -vn, -c copy, -map 0, -segment_time '+leVelikostSegmentu.toHHMMSS +
', -f segment, -reset_timestamps 1,'+
AnsiQuotedStr(ExtractFilePath(pomFile)+ExtractFileNameOnly(pomFile)+
'_%03d.aac','"'),prbUkazatel.Position);
end;
end;
procedure TfrmBase.btnAudioMP3Click(Sender: TObject);
var
pomFile: String;
i: Integer;
begin
prbUkazatel.Position:=0;
for i:=0 to FileNameEdit1.DialogFiles.Count-1 do
begin
pomFile:=FileNameEdit1.DialogFiles[i];;
runFFMPEG(ffmpeg,' -progress stats.txt, -i, '+AnsiQuotedStr(pomFile,'"')+
' -vn, -c mp3, -map 0, -segment_time '+leVelikostSegmentu.toHHMMSS +
', -f segment, -reset_timestamps 1,'+
AnsiQuotedStr(ExtractFilePath(pomFile)+ExtractFileNameOnly(pomFile)+
'_%03d.mp3','"'),prbUkazatel.Position);
end;
end;
procedure TfrmBase.runFFMPEG(exeFile,myParameters:String;progressBegin:Integer);
var
AProcess : TProcess;
B: array[0..BUF_SIZE] of Char;
N: Integer;
pomS: AnsiString;
progresFile:TFileStream;
progresTStrings:TStringList;
pomS2: String;
begin
AProcess := TProcess.Create(nil);
// setup ffmpeg process (Tprocess) parametres
AProcess.Executable := 'exes\'+exeFile;
AProcess.Parameters.Delimiter:=',';
AProcess.Parameters.DelimitedText:=myParameters;
AProcess.Options := [poUsePipes,poStderrToOutPut,poNoConsole];
// run ffmpeg
AProcess.Execute;
// create objects needed for progress displaying
// stat.txt is written by ffmpeg process see: -progress stats.txt
progresFile:=TFileStream.Create('stats.txt',fmCreate or fmShareDenyNone);
// TStringList needed for simple processing key=value lines in stats.txt
progresTStrings:=TStringList.Create;
// repeat until ffmpeg process is finished
repeat
// copy ffmpeg process output to memLog component
N := AProcess.Output.Read(B, BUF_SIZE);
if N <> 0 then
begin
SetLength(pomS, N);
Move(B, PomS[1], N);
memLog.Text:= memLog.Text + pomS;
SendMessage(memLog.Handle, WM_VSCROLL, SB_BOTTOM, 0);
end;
// read and "parse" stats.txt
progresTStrings.LoadFromStream(progresFile);
pomS2:=progresTStrings.Values['out_time_ms'];
if not (poms2 = '') then
prbUkazatel.position:=progressBegin+round(StrToFloat(pomS2)/1e6);
// application needs to be responsive
Application.ProcessMessages;
until (N = 0) and (not AProcess.Running);
// clean up objects including stats.txt file
progresFile.Free;
progresTStrings.Free;
AProcess.Free;
DeleteFileUTF8('stats.txt');
end;
procedure TfrmBase.UpdateTranslation(ALang: String);
begin
inherited UpdateTranslation(ALang);
lblPocetSouboru.Refresh;
end;
procedure TfrmBase.btnExitClick(Sender: TObject);
begin
frmBase.Close;
end;
procedure TfrmBase.FormCreate(Sender: TObject);
begin
// fixed file name and its duration for debugging
//prbUkazatel.Max:=3764;
//FileNameEdit1.FileName:='i:\Jirka-video-audiobook čárka\Astrid_Lindgrenová_Děti_z_Bullerbynu.mp4';
frmBase.Caption:=frmBase.Caption + ' v1.3';
memLog.MaxLength:=0;
vleVlastnosti.ColWidths[0]:=473;
vleVlastnosti.ColWidths[1]:=100;
end;
procedure TfrmBase.btnSmazLogClick(Sender: TObject);
begin
memLog.Clear;
prbUkazatel.Position:=0;
end;
end.
|
unit uB2SP_SzOW;
//-------------------------------------------------------------[ in0k (c) 2018 ]
// Screen Z-Order Work
//----------------------------------------------------------------------------//
{$mode objfpc}{$H+}
interface
uses Forms;
function SzOW_get_topForm_inZOrder:TCustomForm; {$ifOPT D-}inline;{$endIf}
function SzOW_form_is_TOP_inZOrder(const form:TCustomForm):boolean; {$ifOPT D-}inline;{$endIf}
function SzOW_SecondPlane_possible(const form:TCustomForm):boolean; {$ifOPT D-}inline;{$endIf}
implementation
// получить форму с вершины списка `Z-Order`
function SzOW_get_topForm_inZOrder:TCustomForm;
begin
if Screen.CustomFormZOrderCount>0
then result:=Screen.CustomFormsZOrdered[0]
else result:=nil;
end;
// Форма находится на ВЕРШИНЕ списка `Z-Order`
function SzOW_form_is_TOP_inZOrder(const form:TCustomForm):boolean;
begin {$ifOPT D+} Assert(Assigned(form),'`form`: must be defined'); {$endIf}
result:= form=SzOW_get_topForm_inZOrder;
end;
// Перемещение формы на второй план ВОЗМОЖНО
// @prm form форма для которой проводим ТЕСТ
function SzOW_SecondPlane_possible(const form:TCustomForm):boolean;
begin {$ifOPT D+} Assert(Assigned(form),'`form`: must be defined'); {$endIf}
result:=(Screen.CustomFormZOrderCount>1) AND // форм ДОЛЖНО быть МИНИМУМ две
(Screen.CustomFormsZOrdered[1]<>form); // и Форма НЕ-На-Месте
end;
end.
|
{
Copyright (c) 2021 by Ryan Joseph
Based on the Public Domain MaxRectsBinPack.cpp source by Jukka Jylänki
https://github.com/juj/RectangleBinPack/
}
{$mode objfpc}
{$modeswitch autoderef}
unit RectangleBinPack;
interface
uses
GLCanvas, Math, FGL;
type
TBinPacker = class
public type
TRect = TRecti;
TRectList = specialize TFPGList<TRect>;
TChoiceHeuristic = (
RectBestShortSideFit, // BSSF: Positions the rectangle against the short side of a free rectangle into which it fits the best.
RectBestLongSideFit, // BLSF: Positions the rectangle against the long side of a free rectangle into which it fits the best.
RectBestAreaFit, // BAF: Positions the rectangle into the smallest free rect into which it fits.
RectBottomLeftRule, // BL: Does the Tetris placement.
RectContactPointRule // CP: Choosest the placement where the rectangle touches other rects as much as possible.
);
private
binWidth: integer;
binHeight: integer;
allowRotations: boolean;
procedure PlaceRect(node: TRect);
function ScoreRect(width, height: integer; method: TChoiceHeuristic; out score1, score2: integer): TRect;
function FindPositionForNewNodeBottomLeft(width, height: integer; var bestY, bestX: integer): TRect;
function FindPositionForNewNodeBestShortSideFit(width, height: integer; var bestShortSideFit, bestLongSideFit: integer): TRect;
function FindPositionForNewNodeBestLongSideFit(width, height: integer; var bestShortSideFit, bestLongSideFit: integer): TRect;
function FindPositionForNewNodeBestAreaFit(width, height: integer; var bestAreaFit, bestShortSideFit: integer): TRect;
function CommonIntervalLength(i1start, i1end, i2start, i2end: integer): integer;
function ContactPointScoreNode(x, y, width, height: integer): integer;
function FindPositionForNewNodeContactPoint(width, height: integer; var bestContactScore: integer): TRect;
function SplitFreeNode(freeNode: TRect; var usedNode: TRect): boolean;
procedure PruneFreeList;
function IsContainedIn(a, b: TRect): boolean; inline;
public
usedRectangles: TRectList;
freeRectangles: TRectList;
public
{ Constructors }
constructor Create(width, height: integer; rotations: boolean = true);
destructor Destroy; override;
{ Methods }
function Insert(width, height: integer; method: TChoiceHeuristic = RectBestShortSideFit): TRect;
procedure Insert(rects, dst: TRectList; method: TChoiceHeuristic = RectBestShortSideFit);
function Occupancy: float;
end;
implementation
function TBinPacker.Insert(width, height: integer; method: TChoiceHeuristic): TRect;
var
newNode: TRect;
i,
score1,
score2,
numRectanglesToProcess: integer;
begin
score1 := 0;
score2 := 0;
case method of
RectBestShortSideFit:
newNode := FindPositionForNewNodeBestShortSideFit(width, height, score1, score2);
RectBottomLeftRule:
newNode := FindPositionForNewNodeBottomLeft(width, height, score1, score2);
RectContactPointRule:
newNode := FindPositionForNewNodeContactPoint(width, height, score1);
RectBestLongSideFit:
newNode := FindPositionForNewNodeBestLongSideFit(width, height, score2, score1);
RectBestAreaFit:
newNode := FindPositionForNewNodeBestAreaFit(width, height, score1, score2);
end;
if newNode.height = 0 then
exit(newNode);
numRectanglesToProcess := freeRectangles.Count;
i := 0;
while i < numRectanglesToProcess do
begin
if SplitFreeNode(freeRectangles[i], newNode) then
begin
freeRectangles.Delete(i);
Dec(i);
Dec(numRectanglesToProcess);
end;
Inc(i);
end;
PruneFreeList;
usedRectangles.Add(newNode);
result := newNode;
end;
procedure TBinPacker.Insert(rects, dst: TRectList; method: TChoiceHeuristic);
var
bestScore1: integer = MaxInt;
bestScore2: integer = MaxInt;
bestRectIndex: integer = -1;
bestNode: TRect;
i,
score1,
score2: integer;
newNode: TRect;
begin
dst.Clear;
while rects.Count > 0 do
begin
for i := 0 to rects.Count - 1 do
begin
score1 := 0;
score2 := 0;
newNode := ScoreRect(rects[i].width, rects[i].height, method, score1, score2);
if (score1 < bestScore1) or ((score1 = bestScore1) and (score2 < bestScore2)) then
begin
bestScore1 := score1;
bestScore2 := score2;
bestNode := newNode;
bestRectIndex := i;
end;
end;
if bestRectIndex = -1 then
exit;
PlaceRect(bestNode);
rects.Delete(bestRectIndex);
end;
end;
procedure TBinPacker.PlaceRect(node: TRect);
var
numRectanglesToProcess: integer;
i: integer;
begin
numRectanglesToProcess := freeRectangles.Count;
i := 0;
while i < numRectanglesToProcess do
begin
if SplitFreeNode(freeRectangles[i], node) then
begin
freeRectangles.Delete(i);
Dec(i);
Dec(numRectanglesToProcess);
end
else
Inc(i);
end;
PruneFreeList;
usedRectangles.Add(node);
end;
function TBinPacker.ScoreRect(width, height: integer; method: TChoiceHeuristic; out score1, score2: integer): TRect;
var
newNode: TRect;
begin
score1 := MaxInt;
score2 := MaxInt;
case method of
RectBestShortSideFit:
newNode := FindPositionForNewNodeBestShortSideFit(width, height, score1, score2);
RectBottomLeftRule:
newNode := FindPositionForNewNodeBottomLeft(width, height, score1, score2);
RectContactPointRule:
begin
newNode := FindPositionForNewNodeContactPoint(width, height, score1);
score1 := -score1; // Reverse since we are minimizing, but for contact point score bigger is better.
end;
RectBestLongSideFit:
newNode := FindPositionForNewNodeBestLongSideFit(width, height, score2, score1);
RectBestAreaFit:
newNode := FindPositionForNewNodeBestAreaFit(width, height, score1, score2);
end;
// Cannot fit the current rectangle.
if newNode.height = 0 then
begin
score1 := MaxInt;
score2 := MaxInt;
end;
result := newNode;
end;
{ Computes the ratio of used surface area. }
function TBinPacker.Occupancy: float;
var
usedSurfaceArea: longint;
i: integer;
begin
usedSurfaceArea := 0;
for i := 0 to usedRectangles.Count - 1 do
usedSurfaceArea += usedRectangles[i].width * usedRectangles[i].height;
result := usedSurfaceArea / (binWidth * binHeight);
end;
function TBinPacker.FindPositionForNewNodeBottomLeft(width, height: integer; var bestY, bestX: integer): TRect;
var
i,
topSideY: integer;
bestNode: TRect;
begin
bestY := MaxInt;
for i := 0 to freeRectangles.Count - 1 do
begin
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width) and (freeRectangles[i].height >= height) then
begin
topSideY := freeRectangles[i].y + height;
if (topSideY < bestY) or ((topSideY = bestY) and (freeRectangles[i].x < bestX)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := width;
bestNode.height := height;
bestY := topSideY;
bestX := freeRectangles[i].x;
end;
end;
if allowRotations and (freeRectangles[i].width >= height) and (freeRectangles[i].height >= width) then
begin
topSideY := freeRectangles[i].y + width;
if (topSideY < bestY) or ((topSideY = bestY) and (freeRectangles[i].x < bestX)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := height;
bestNode.height := width;
bestY := topSideY;
bestX := freeRectangles[i].x;
end;
end;
end;
result := bestNode;
end;
function TBinPacker.FindPositionForNewNodeBestShortSideFit(width, height: integer; var bestShortSideFit, bestLongSideFit: integer): TRect;
var
bestNode: TRect;
i,
leftoverHoriz,
leftoverVert,
shortSideFit,
longSideFit,
flippedLeftoverHoriz,
flippedLeftoverVert,
flippedShortSideFit,
flippedLongSideFit: integer;
begin
bestShortSideFit := MaxInt;
for i := 0 to freeRectangles.Count - 1 do
begin
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width) and (freeRectangles[i].height >= height) then
begin
leftoverHoriz := Abs(freeRectangles[i].width - width);
leftoverVert := Abs(freeRectangles[i].height - height);
shortSideFit := Min(leftoverHoriz, leftoverVert);
longSideFit := Max(leftoverHoriz, leftoverVert);
if (shortSideFit < bestShortSideFit) or ((shortSideFit = bestShortSideFit) and (longSideFit < bestLongSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := width;
bestNode.height := height;
bestShortSideFit := shortSideFit;
bestLongSideFit := longSideFit;
end;
end;
if allowRotations and (freeRectangles[i].width >= height) and (freeRectangles[i].height >= width) then
begin
flippedLeftoverHoriz := Abs(freeRectangles[i].width - height);
flippedLeftoverVert := Abs(freeRectangles[i].height - width);
flippedShortSideFit := Min(flippedLeftoverHoriz, flippedLeftoverVert);
flippedLongSideFit := Max(flippedLeftoverHoriz, flippedLeftoverVert);
if (flippedShortSideFit < bestShortSideFit) or ((flippedShortSideFit = bestShortSideFit) and (flippedLongSideFit < bestLongSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := height;
bestNode.height := width;
bestShortSideFit := flippedShortSideFit;
bestLongSideFit := flippedLongSideFit;
end;
end;
end;
result := bestNode;
end;
function TBinPacker.FindPositionForNewNodeBestLongSideFit(width, height: integer; var bestShortSideFit, bestLongSideFit: integer): TRect;
var
bestNode: TRect;
i: integer;
leftoverHoriz,
leftoverVert,
shortSideFit,
longSideFit: integer;
begin
bestLongSideFit := MaxInt;
for i := 0 to freeRectangles.Count - 1 do
begin
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width) and (freeRectangles[i].height >= height) then
begin
leftoverHoriz := Abs(freeRectangles[i].width - width);
leftoverVert := Abs(freeRectangles[i].height - height);
shortSideFit := Min(leftoverHoriz, leftoverVert);
longSideFit := Max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit) or ((longSideFit = bestLongSideFit) and (shortSideFit < bestShortSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := width;
bestNode.height := height;
bestShortSideFit := shortSideFit;
bestLongSideFit := longSideFit;
end;
end;
if allowRotations and (freeRectangles[i].width >= height) and (freeRectangles[i].height >= width) then
begin
leftoverHoriz := Abs(freeRectangles[i].width - height);
leftoverVert := Abs(freeRectangles[i].height - width);
shortSideFit := Min(leftoverHoriz, leftoverVert);
longSideFit := Max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit) or ((longSideFit = bestLongSideFit) and (shortSideFit < bestShortSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := height;
bestNode.height := width;
bestShortSideFit := shortSideFit;
bestLongSideFit := longSideFit;
end;
end;
end;
result := bestNode;
end;
function TBinPacker.FindPositionForNewNodeBestAreaFit(width, height: integer; var bestAreaFit, bestShortSideFit: integer): TRect;
var
bestNode: TRect;
i,
areaFit,
leftoverHoriz,
leftoverVert,
shortSideFit: integer;
begin
bestAreaFit := MaxInt;
for i := 0 to freeRectangles.Count - 1 do
begin
areaFit := freeRectangles[i].width * freeRectangles[i].height - width * height;
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width) and (freeRectangles[i].height >= height) then
begin
leftoverHoriz := Abs(freeRectangles[i].width - width);
leftoverVert := Abs(freeRectangles[i].height - height);
shortSideFit := Min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit) or ((areaFit = bestAreaFit) and (shortSideFit < bestShortSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := width;
bestNode.height := height;
bestShortSideFit := shortSideFit;
bestAreaFit := areaFit;
end;
end;
if allowRotations and (freeRectangles[i].width >= height) and (freeRectangles[i].height >= width) then
begin
leftoverHoriz := Abs(freeRectangles[i].width - height);
leftoverVert := Abs(freeRectangles[i].height - width);
shortSideFit := Min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit) or ((areaFit = bestAreaFit) and (shortSideFit < bestShortSideFit)) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := height;
bestNode.height := width;
bestShortSideFit := shortSideFit;
bestAreaFit := areaFit;
end;
end;
end;
result := bestNode;
end;
function TBinPacker.CommonIntervalLength(i1start, i1end, i2start, i2end: integer): integer;
begin
if (i1end < i2start) or (i2end < i1start) then
exit(0);
result := Min(i1end, i2end) - Max(i1start, i2start);
end;
function TBinPacker.ContactPointScoreNode(x, y, width, height: integer): integer;
var
i,
score: integer;
begin
score := 0;
if (x = 0) or (x + width = binWidth) then
score += height;
if (y = 0) or (y + height = binHeight) then
score += width;
for i := 0 to usedRectangles.Count - 1 do
begin
if (usedRectangles[i].x = x + width) or (usedRectangles[i].x + usedRectangles[i].width = x) then
score += CommonIntervalLength(usedRectangles[i].y, usedRectangles[i].y + usedRectangles[i].height, y, y + height);
if (usedRectangles[i].y = y + height) or (usedRectangles[i].y + usedRectangles[i].height = y) then
score += CommonIntervalLength(usedRectangles[i].x, usedRectangles[i].x + usedRectangles[i].width, x, x + width);
end;
result := score;
end;
function TBinPacker.FindPositionForNewNodeContactPoint(width, height: integer; var bestContactScore: integer): TRect;
var
bestNode: TRect;
i,
score: integer;
begin
bestContactScore := -1;
for i := 0 to freeRectangles.Count - 1 do
begin
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width) and (freeRectangles[i].height >= height) then
begin
score := ContactPointScoreNode(freeRectangles[i].x, freeRectangles[i].y, width, height);
if (score > bestContactScore) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := width;
bestNode.height := height;
bestContactScore := score;
end;
end;
if allowRotations and (freeRectangles[i].width >= height) and (freeRectangles[i].height >= width) then
begin
score := ContactPointScoreNode(freeRectangles[i].x, freeRectangles[i].y, height, width);
if (score > bestContactScore) then
begin
bestNode.x := freeRectangles[i].x;
bestNode.y := freeRectangles[i].y;
bestNode.width := height;
bestNode.height := width;
bestContactScore := score;
end;
end;
end;
result := bestNode;
end;
function TBinPacker.SplitFreeNode(freeNode: TRect; var usedNode: TRect): boolean;
var
newNode: TRect;
begin
// Test with SAT if the rectangles even intersect.
if (usedNode.x >= freeNode.x + freeNode.width) or (usedNode.x + usedNode.width <= freeNode.x) or
(usedNode.y >= freeNode.y + freeNode.height) or (usedNode.y + usedNode.height <= freeNode.y) then
exit(false);
if (usedNode.x < freeNode.x + freeNode.width) and (usedNode.x + usedNode.width > freeNode.x) then
begin
// New node at the top side of the used node.
if (usedNode.y > freeNode.y) and (usedNode.y < freeNode.y + freeNode.height) then
begin
newNode := freeNode;
newNode.height := usedNode.y - newNode.y;
freeRectangles.Add(newNode);
end;
// New node at the bottom side of the used node.
if usedNode.y + usedNode.height < freeNode.y + freeNode.height then
begin
newNode := freeNode;
newNode.y := usedNode.y + usedNode.height;
newNode.height := freeNode.y + freeNode.height - (usedNode.y + usedNode.height);
freeRectangles.Add(newNode);
end;
end;
if (usedNode.y < freeNode.y + freeNode.height) and (usedNode.y + usedNode.height > freeNode.y) then
begin
// New node at the left side of the used node.
if (usedNode.x > freeNode.x) and (usedNode.x < freeNode.x + freeNode.width) then
begin
newNode := freeNode;
newNode.width := usedNode.x - newNode.x;
freeRectangles.Add(newNode);
end;
// New node at the right side of the used node.
if (usedNode.x + usedNode.width < freeNode.x + freeNode.width) then
begin
newNode := freeNode;
newNode.x := usedNode.x + usedNode.width;
newNode.width := freeNode.x + freeNode.width - (usedNode.x + usedNode.width);
freeRectangles.Add(newNode);
end;
end;
result := true;
end;
procedure TBinPacker.PruneFreeList;
var
i, j: integer;
begin
i := 0;
while i < freeRectangles.Count do
begin
j := i + 1;
while j < freeRectangles.Count do
begin
if (IsContainedIn(freeRectangles[i], freeRectangles[j])) then
begin
freeRectangles.Delete(i);
Dec(i);
break;
end;
if (IsContainedIn(freeRectangles[j], freeRectangles[i])) then
begin
freeRectangles.Delete(j);
Dec(j);
end;
Inc(j);
end;
Inc(i);
end;
end;
function TBinPacker.IsContainedIn(a, b: TRect): boolean;
begin
result := (a.x >= b.x) and
(a.y >= b.y) and
(a.x + a.width <= b.x + b.width) and
(a.y + a.height <= b.y + b.height);
end;
destructor TBinPacker.Destroy;
begin
usedRectangles.Free;
freeRectangles.Free;
inherited;
end;
constructor TBinPacker.Create(width, height: integer; rotations: boolean);
begin
binWidth := width;
binHeight := height;
allowRotations := rotations;
usedRectangles := TRectList.Create;
freeRectangles := TRectList.Create;
freeRectangles.Add(RectMake(0, 0, width, height));
end;
end. |
unit typelist;
interface
type
tanggal = record
hari: integer;
bulan: integer;
tahun: integer;
end;
Buku = record
ID_Buku: integer;
Judul_Buku: string;
Author: string;
Jumlah_Buku: integer;
Tahun_Penerbit: integer;
Kategori : string;
end;
List_Buku = record
listbuku : array [1..100] of Buku;
Neff : integer; {list yang terisi}
end;
User = record
Nama : string;
Alamat: string;
Username : string;
Password : string;
Role : string;
end;
List_User = record
listuser : array [1..100] of User;
Neff : integer; {list yang terisi}
end;
Peminjaman = record
Username:string;
ID_Buku: integer;
Tanggal_Peminjaman: tanggal;
Tanggal_Batas_Pengembalian: tanggal;
Status_Pengembalian: string;
end;
List_Peminjaman = record
listPeminjaman : array [1..100] of Peminjaman;
Neff : integer; {list yang terisi}
end;
Pengembalian = record
Username:string;
ID_Buku: integer;
Tanggal_Pengembalian: tanggal;
end;
List_Pengembalian = record
listPengembalian : array [1..100] of Pengembalian;
Neff : integer; {list yang terisi}
end;
Buku_Hilang = record
Username:string;
ID_Buku_Hilang: integer;
Tanggal_Laporan: tanggal;
end;
List_Buku_Hilang = record
listBuku_Hilang : array [1..100] of Buku_Hilang;
Neff : integer; {list yang terisi}
end;
implementation
end.
|
unit uSlowCode;
interface
function SlowIsPrime(aInteger: integer): Boolean;
function PrimesBelow(aInteger: integer): integer;
function PrimesBelowParallel(aInteger: integer): integer;
implementation
uses
System.Threading
, System.SyncObjs
;
// An incredibly inefficient way to calculate primes
// And it gets slower the bigger the input is.
function SlowIsPrime(aInteger: integer): Boolean;
var
i: Integer;
begin
Assert (aInteger > 0);
// Remember, 1 is not prime.
if aInteger = 1 then
begin
Result := False;
Exit;
end;
Result := True;
for i := 2 to aInteger - 1 do
begin
if aInteger mod i = 0 then
begin
Result := False;
Exit;
end;
end;
end;
function PrimesBelow(aInteger: integer): integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to aInteger do
begin
if SlowIsPrime(i) then
begin
Result := Result + 1;
end;
end;
end;
function PrimesBelowParallel(aInteger: integer): integer;
var
Temp: integer;
begin
Temp := 0;
TParallel.For(1, aInteger, procedure(aIndex: integer)
begin
if SlowIsPrime(aIndex) then
begin
TInterlocked.Increment(Temp);
end;
end);
Result := Temp;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiWebDriver }
{ }
{ Copyright 2017 inpwtepydjuf@gmail.com }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit Commands.PostElementElements;
interface
uses
Vcl.Forms,
System.Classes,
generics.collections,
CommandRegistry,
HttpServerCommand;
Type
/// <summary>
/// Handles 'POST' '/session/(.*)/element(.*)/elements'
/// </summary>
TPostElementElementsCommand = class(TRestCommand)
private
function OKResponse(const sessionId: String; elements: TStringList): String;
public
class function GetCommand: String; override;
class function GetRoute: String; override;
procedure Execute(AOwner: TForm); override;
end;
implementation
uses
System.JSON,
Vcl.Grids,
Vcl.controls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
System.Types,
Vcl.ComCtrls,
System.SysUtils,
System.StrUtils,
System.JSON.Types,
System.JSON.Writers,
System.JSON.Builders,
utils;
procedure TPostElementElementsCommand.Execute(AOwner: TForm);
var
ctrl: TWinControl;
comp: TComponent;
handle: Integer;
i: integer;
comps: TStringList;
begin
ctrl := nil;
comp := nil;
comps := TStringList.Create;
if (isNumber(self.Params[2])) then
begin
handle := StrToInt(self.Params[2]);
ctrl := FindControl(handle);
end
else
comp := (AOwner.FindComponent(self.Params[2]));
if (ctrl <> nil) then
begin
if (ctrl is TStringGrid) then
begin
for i := 0 to (ctrl as TStringGrid).RowCount -1 do
begin
comps.Add(ctrl.name + '.' + IntToStr(i));
end;
end
else if (ctrl is TListBox) then
begin
for i := 0 to (ctrl as TListBox).Count -1 do
begin
comps.Add(ctrl.name + '.' + IntToStr(i));
end;
end
else if (ctrl is TPageControl) then
begin
for i := 0 to (ctrl as TPageControl).PageCount -1 do
begin
comps.Add(ctrl.name + '.' + IntToStr(i));
end;
end
else if (ctrl is TToolBar) then
begin
for i := 0 to (ctrl as TToolBar).ButtonCount -1 do
begin
comps.Add(ctrl.name + '.' + IntToStr(i));
end;
end;
if comps = nil then
raise Exception.Create('Control(s) not found');
ResponseJSON(self.OKResponse(self.Params[1], comps));
end
else
Error(404);
end;
function TPostElementElementsCommand.OKResponse(const sessionId: String; elements: TStringList): String;
var
i: Integer;
jsonPair: TJSONPair;
jsonObject, arrayObject: TJSONObject;
jsonArray: TJSONArray;
begin
jsonArray := TJSONArray.Create;
jsonObject := TJSONObject.Create;
jsonPair := TJSONPair.Create('value', jsonArray);
jsonObject.AddPair(TJSONPair.Create('sessionId', sessionId));
// jsonObject.AddPair(TJSONPair.Create('status', '0'));
for i := 0 to elements.count -1 do
begin
arrayObject := TJSONObject.Create;
arrayObject.AddPair(TJSONPair.Create('ELEMENT', elements[i]));
jsonArray.AddElement(arrayObject);
end;
jsonObject.AddPair(jsonPair);
result := jsonObject.ToString;
end;
class function TPostElementElementsCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TPostElementElementsCommand.GetRoute: String;
begin
result := '/session/(.*)/element/(.*)/elements';
end;
end.
|
unit Expedicao.Controller.uVeiculo;
interface
uses
System.SysUtils,
System.JSON,
FireDAC.Comp.Client,
Base.uControllerBase,
Expedicao.Models.uVeiculo,
Expedicao.Models.uCombustivel,
Expedicao.Models.uSeguro;
type
TVeiculoController = class(TControllerBase)
private
{ Private declarations }
procedure ValidarVeiculo(pVeiculoEnviado: TVeiculo);
function ObterVeiculoDaQuery(pQry: TFDQuery): TVeiculo;
function ObterVeiculoPeloOID(pVeiculoOID: Integer): TVeiculo;
function TestarVeiculoCadastrado(pVeiculoOID: Integer): Boolean;
function IncluirVeiculo(pVeiculo: TVeiculo): Boolean;
function AlterarVeiculo(pVeiculo: TVeiculo): Boolean;
function ConverterVeiculoParaJSON(pVeiculo: TVeiculo): TJSONValue;
procedure AtualizaVeiculoCombustivel(pVeiculo: TVeiculo);
procedure AtualizaSeguroVeiculo(pVeiculo: TVeiculo);
public
{ Public declarations }
function Veiculos: TJSONValue;
function Veiculo(ID: Integer): TJSONValue;
function updateVeiculo(Veiculo: TJSONObject): TJSONValue;
function acceptVeiculo(Veiculo: TJSONObject): TJSONValue;
function cancelVeiculo(ID: Integer): TJSONValue;
end;
implementation
uses
uDataModule,
REST.jSON,
Expedicao.Services.uCombustivel,
Expedicao.Services.uSeguro;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TVeiculoController }
function TVeiculoController.ObterVeiculoDaQuery(pQry: TFDQuery): TVeiculo;
procedure CarregarListaSeguro(pVeiculo: TVeiculo);
var
lQry: TFDQuery;
lSvcSeguro: TSeguroService;
lSeguro: TSeguro;
begin
lQry := DataModule1.ObterQuery;
lSvcSeguro := TSeguroService.Create;
try
with lQry do
begin
Open('SELECT * FROM SeguroVeiculo WHERE VeiculoOID = :VeiculoOID',
[pVeiculo.VeiculoOID]);
if IsEmpty then
Exit;
while not Eof do
begin
lSeguro := lSvcSeguro.ObterSeguroPeloOID(FieldByName('SeguroOID').AsInteger);
pVeiculo.Seguros.Add(lSeguro);
Next;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
lSvcSeguro.Free;
end;
end;
procedure CarregarListaCombustivel(pVeiculo: TVeiculo);
var
lQry: TFDQuery;
lSvcCombustivel: TCombustivelService;
lCombustivel: TCombustivel;
begin
lQry := DataModule1.ObterQuery;
lSvcCombustivel := TCombustivelService.Create;
try
with lQry do
begin
Open('SELECT * FROM VeiculoCombustivel WHERE VeiculoID = :VeiculoOID',
[pVeiculo.VeiculoOID]);
if IsEmpty then
Exit;
while not Eof do
begin
lCombustivel := lSvcCombustivel.ObterCombustivelPeloOID(FieldByName('CombustivelID').AsInteger);
pVeiculo.Combustiveis.Add(lCombustivel);
Next;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
lSvcCombustivel.Free;
end;
end;
begin
Result := TVeiculo.Create;
with Result do
begin
VeiculoOID := pQry.FieldByName('VeiculoOID').AsInteger;
Marca := pQry.FieldByName('Marca').AsString;
Modelo := pQry.FieldByName('Modelo').AsString;
Placa := pQry.FieldByName('Placa').AsString;
Renavam := pQry.FieldByName('Renavam').AsString;
Cor := pQry.FieldByName('Cor').AsString;
Ano := pQry.FieldByName('Ano').AsString;
CarregarListaSeguro(Result);
CarregarListaCombustivel(Result);
end;
end;
function TVeiculoController.ObterVeiculoPeloOID(pVeiculoOID: Integer): TVeiculo;
var
lQry: TFDQuery;
begin
Result := nil;
lQry := DataModule1.ObterQuery;
try
lQry.Open('SELECT * FROM Veiculo WHERE VeiculoOID = :VeiculoOID',
[pVeiculoOID]);
if lQry.IsEmpty then
Exit;
Result := ObterVeiculoDaQuery(lQry);
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TVeiculoController.ConverterVeiculoParaJSON(
pVeiculo: TVeiculo): TJSONValue;
var
lSeguro: TSeguro;
lSeguroJSONArray: TJSONArray;
lSeguroJSON: TJSONObject;
lCombustivel: TCombustivel;
lCombustivelTJSONArray: TJSONArray;
lCombustivelJSON: TJSONObject;
begin
Result := TJSONObject.Create;
with (Result as TJSONObject) do
begin
AddPair('VeiculoOID', pVeiculo.VeiculoOID.ToString);
AddPair('Marca', pVeiculo.Marca);
AddPair('Modelo', pVeiculo.Modelo);
AddPair('Placa', pVeiculo.Placa);
AddPair('Renavam', pVeiculo.Renavam);
AddPair('Cor', pVeiculo.Cor);
AddPair('Ano', pVeiculo.Ano);
lSeguroJSONArray := TJSONArray.Create;
for lSeguro in pVeiculo.Seguros do
begin
lSeguroJSON := TJson.ObjectToJsonObject(lSeguro);
lSeguroJSONArray.AddElement(lSeguroJSON);
end;
AddPair('Seguros', lSeguroJSONArray);
lCombustivelTJSONArray := TJSONArray.Create;
for lCombustivel in pVeiculo.Combustiveis do
begin
lCombustivelJSON := TJson.ObjectToJsonObject(lCombustivel);
lCombustivelTJSONArray.AddElement(lCombustivelJSON);
end;
AddPair('Combustiveis', lCombustivelTJSONArray);
end;
end;
function TVeiculoController.TestarVeiculoCadastrado(
pVeiculoOID: Integer): Boolean;
var
lVeiculo: TVeiculo;
begin
lVeiculo := ObterVeiculoPeloOID(pVeiculoOID);
if Assigned(lVeiculo) then
begin
Result := True;
Exit;
end
else
Result := False;
end;
function TVeiculoController.IncluirVeiculo(pVeiculo: TVeiculo): Boolean;
var
lQry, lQryLastID, lQryInsertCombustivel, lQryInsertSeguro: TFDQuery;
lCombustivel: TCombustivel;
lSeguro: TSeguro;
begin
Result := False;
lQry := DataModule1.ObterQuery;
lQryLastID := DataModule1.ObterQuery;
lQryInsertCombustivel := DataModule1.ObterQuery;
lQryInsertSeguro := DataModule1.ObterQuery;
try
lQryLastID.Connection := lQry.Connection;
with lQry do
begin
SQL.Add('INSERT INTO Veiculo (');
SQL.Add('Marca, Modelo, Placa, Renavam, Cor, Ano');
SQL.Add(') VALUES (');
SQL.Add(':Marca, :Modelo, :Placa, :Renavam, :Cor, :Ano');
SQL.Add(');');
ParamByName('Marca').AsString := pVeiculo.Marca;
ParamByName('Modelo').AsString := pVeiculo.Modelo;
ParamByName('Placa').AsString := pVeiculo.Placa;
ParamByName('Renavam').AsString := pVeiculo.Renavam;
ParamByName('Cor').AsString := pVeiculo.Cor;
ParamByName('Ano').AsString := pVeiculo.Ano;
ExecSQL;
end;
lQryLastID.Open('SELECT LAST_INSERT_ID() AS VeiculoOID');
with lQryInsertSeguro do
begin
SQL.Add('INSERT INTO SeguroVeiculo (SeguroOID, VeiculoOID)');
SQL.Add('VALUES (:SeguroOID, :VeiculoOID)');
ParamByName('VeiculoOID').AsInteger := lQryLastID.FieldByName('VeiculoOID').AsInteger;
for lSeguro in pVeiculo.Seguros do
begin
ParamByName('SeguroOID').AsInteger := lSeguro.SeguroOID;
ExecSQL;
end;
end;
with lQryInsertCombustivel do
begin
SQL.Add('INSERT INTO VeiculoCombustivel (VeiculoID, CombustivelID)');
SQL.Add('VALUES (:VeiculoOID, :CombustivelID)');
ParamByName('VeiculoOID').AsInteger := lQryLastID.FieldByName('VeiculoOID').AsInteger;
for lCombustivel in pVeiculo.Combustiveis do
begin
ParamByName('CombustivelID').AsInteger := lCombustivel.CombustivelOID;
ExecSQL;
end;
end;
Result := True;
finally
DataModule1.DestruirQuery(lQry);
DataModule1.DestruirQuery(lQryLastID);
DataModule1.DestruirQuery(lQryInsertCombustivel);
DataModule1.DestruirQuery(lQryInsertSeguro);
end;
end;
function TVeiculoController.AlterarVeiculo(pVeiculo: TVeiculo): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('UPDATE Veiculo SET ');
SQL.Add(' Marca = :Marca,');
SQL.Add(' Modelo = :Modelo, ');
SQL.Add(' Placa = :Placa, ');
SQL.Add(' Renavam = :Renavam, ');
SQL.Add(' Cor = :Cor, ');
SQL.Add(' Ano = :Ano ');
SQL.Add('WHERE VeiculoOID = :VeiculoOID');
ParamByName('Marca').AsString := pVeiculo.Marca;
ParamByName('Modelo').AsString := pVeiculo.Modelo.Trim;
ParamByName('Placa').AsString := pVeiculo.Placa.Trim;
ParamByName('Renavam').AsString := pVeiculo.Renavam.Trim;
ParamByName('Cor').AsString := pVeiculo.Cor.Trim;
ParamByName('Ano').AsString := pVeiculo.Ano.Trim;
ParamByName('VeiculoOID').AsInteger := pVeiculo.VeiculoOID;
ExecSQL;
AtualizaVeiculoCombustivel(pVeiculo);
AtualizaSeguroVeiculo(pVeiculo);
Result := True;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
procedure TVeiculoController.AtualizaSeguroVeiculo(pVeiculo: TVeiculo);
var
lQry: TFDQuery;
lSeguro: TSeguro;
begin
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('DELETE FROM SeguroVeiculo WHERE VeiculoOID = :VeiculoOID');
ParamByName('VeiculoOID').AsInteger := pVeiculo.VeiculoOID;
ExecSql;
SQL.Clear;
SQL.Add('INSERT INTO SeguroVeiculo (VeiculoOID, SeguroOID) VALUES(:VeiculoOID, :SeguroOID)');
ParamByName('VeiculoOID').AsInteger := pVeiculo.VeiculoOID;
for lSeguro in pVeiculo.Seguros do
begin
ParamByName('SeguroOID').AsInteger := lSeguro.SeguroOID;
ExecSQL;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
procedure TVeiculoController.AtualizaVeiculoCombustivel(pVeiculo: TVeiculo);
var
lQry: TFDQuery;
lCombustivel: TCombustivel;
begin
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('DELETE FROM VeiculoCombustivel WHERE VeiculoID = :VeiculoOID');
ParamByName('VeiculoOID').AsInteger := pVeiculo.VeiculoOID;
ExecSql;
SQL.Clear;
SQL.Add('INSERT INTO VeiculoCombustivel (VeiculoID, CombustivelID) VALUES(:VeiculoOID, :CombustivelOID)');
ParamByName('VeiculoOID').AsInteger := pVeiculo.VeiculoOID;
for lCombustivel in pVeiculo.Combustiveis do
begin
ParamByName('CombustivelOID').AsInteger := lCombustivel.CombustivelOID;
ExecSQL;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TVeiculoController.Veiculos: TJSONValue;
var
lVeiculo: TVeiculo;
lQry: TFDQuery;
// lVeiculoJSON: TJSONValue;
begin
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
Open('SELECT * FROM Veiculo');
if IsEmpty then
begin
Result := TJSONString.Create('Nenhum Veículo encontrado!');
ConfigurarResponse(tmNotFound);
end;
Result := TJSONArray.Create;
while not Eof do
begin
lVeiculo := ObterVeiculoDaQuery(lQry);
// lVeiculoJSON := ConverterVeiculoParaJSON(lVeiculo);
// (Result as TJSONArray).AddElement(TJson.ObjectToJsonObject(lVeiculo));
// (Result as TJSONArray).AddElement(lVeiculoJSON);
(Result as TJSONArray).AddElement(lVeiculo.ToJson);
ConfigurarResponse(tmOK);
Next;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
procedure TVeiculoController.ValidarVeiculo(pVeiculoEnviado: TVeiculo);
var
lSvcSeguro: TSeguroService;
lSvcCombustivel: TCombustivelService;
lSeguro, lSeguroExiste: TSeguro;
lCombustivel, lCombustivelExiste: TCombustivel;
begin
lSvcSeguro := TSeguroService.Create;
lSvcCombustivel := TCombustivelService.Create;
try
for lSeguro in pVeiculoEnviado.Seguros do
begin
lSeguroExiste := lSvcSeguro.ObterSeguroPeloOID(lSeguro.SeguroOID);
if not Assigned(lSeguroExiste) then
raise Exception.Create('Seguro não encontrado. OID: ' + lSeguro.SeguroOID.ToString)
else
lSeguroExiste.Free;
end;
for lCombustivel in pVeiculoEnviado.Combustiveis do
begin
lCombustivelExiste := lSvcCombustivel.ObterCombustivelPeloOID(lCombustivel.CombustivelOID);
if not Assigned(lCombustivelExiste) then
raise Exception.Create('Combustível não encontrado. OID: ' + lCombustivel.CombustivelOID.ToString)
else
lCombustivelExiste.Free;
end;
finally
lSvcSeguro.Free;
lSvcCombustivel.Free;
end;
end;
function TVeiculoController.Veiculo(ID: Integer): TJSONValue;
var
lVeiculo: TVeiculo;
begin
lVeiculo := ObterVeiculoPeloOID(ID);
if not Assigned(lVeiculo) then
begin
Result := TJSONString.Create('Veiculo não encontrado!');
ConfigurarResponse(tmNotFound);
end
else
begin
Result := TJson.ObjectToJsonObject(lVeiculo);
ConfigurarResponse(tmOK);
lVeiculo.Free;
end;
end;
function TVeiculoController.acceptVeiculo(Veiculo: TJSONObject): TJSONValue;
var
lVeiculoEnviado, lVeiculoCadastrado: TVeiculo;
begin
lVeiculoEnviado := TVeiculo.Create(Veiculo);
try
lVeiculoCadastrado := ObterVeiculoPeloOID(lVeiculoEnviado.VeiculoOID);
if Assigned(lVeiculoCadastrado) then
begin
Result := TJSONString.Create('Veículo já cadastrado. Inclusão cancelada!');
ConfigurarResponse(tmObjectAlreadyExists);
lVeiculoCadastrado.Free;
Exit;
end;
try
ValidarVeiculo(lVeiculoEnviado);
if IncluirVeiculo(lVeiculoEnviado) then
begin
Result := TJSONString.Create('Veículo gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar o Veículo!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lVeiculoEnviado.Free;
end;
end;
function TVeiculoController.updateVeiculo(Veiculo: TJSONObject): TJSONValue;
var
lVeiculoEnviado, lVeiculoCadastrado: TVeiculo;
begin
lVeiculoEnviado := TVeiculo.Create(Veiculo);
try
lVeiculoCadastrado := ObterVeiculoPeloOID(lVeiculoEnviado.VeiculoOID);
if not Assigned(lVeiculoCadastrado) then
begin
Result := TJSONString.Create('Veículo já não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lVeiculoCadastrado.Free;
try
ValidarVeiculo(lVeiculoEnviado);
if AlterarVeiculo(lVeiculoEnviado) then
begin
Result := TJSONString.Create('Veículo gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar o Veículo!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lVeiculoEnviado.Free;
end;
end;
function TVeiculoController.cancelVeiculo(ID: Integer): TJSONValue;
var
lQry: TFDQuery;
lVeiculo: TVeiculo;
begin
lVeiculo := ObterVeiculoPeloOID(ID);
if not Assigned(lVeiculo) then
begin
Result := TJSONString.Create('Veículo não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lVeiculo.Free;
lQry := DataModule1.ObterQuery;
try
try
with lQry do
begin
SQL.Add('DELETE FROM Veiculo WHERE VeiculoOID = :VeiculoOID');
ParamByName('VeiculoOID').AsInteger := ID;
ExecSQL;
Result := TJSONString.Create('Veículo excluído com sucesso!');
ConfigurarResponse(tmOK);
end;
except
on e: Exception do
begin
Result := TJSONString.Create('Erro ao excluir o Veículo!');
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
end.
|
unit Names;
interface
uses
Protocol;
const
Name_Advance: array[0..nAdv-1] of string=
('Advanced Flight',
'Amphibious Warfare',
'Astronomy',
'Atomic Theory',
'Automobile',
'Ballistics',
'Banking',
'Bridge Building',
'Bronze Working',
'Ceremonial Burial',
'Chemistry',
'Chivalry',
'Composites',
'Code of Laws',
'Combined Arms',
'Combustion Engine',
'Communism',
'Computers',
'Conscription',
'Construction',
'The Corporation',
'Space Flight',
'Currency',
'Democracy',
'Economics',
'Electricity',
'Electronics',
'Engineering',
'Environmentalism',
'The Wheel',
'Explosives',
'Flight',
'Intelligence',
'Gunpowder',
'Horseback Riding',
'Impulse Drive',
'Industrialization',
'Intelligent Arms',
'Invention',
'Iron Working',
'The Laser',
'Nuclear Power',
'Literature',
'Internet',
'Magnetism',
'Map Making',
'Masonry',
'Mass Production',
'Mathematics',
'Medicine',
'Metallurgy',
'Miniaturization',
'Mobile Warfare',
'Monarchy',
'Mysticism',
'Navigation',
'Nuclear Fission',
'Philosophy',
'Physics',
'Plastics',
'Poetry',
'Pottery',
'Radio Communication',
'Recycling',
'Refrigeration',
'Monotheism',
'The Republic',
'Robotics',
'Rocketry',
'Railroad',
'Sanitation',
'Science',
'Writing',
'Seafaring',
'Self-Contained Environment',
'Stealth',
'Steam Engine',
'Steel',
'Synthetic Food',
'Tactics',
'Theology',
'Theory of Gravity',
'Trade',
'Transstellar Colonization',
'University',
'Advanced Rocketry',
'Warrior Code',
'Alphabet',
'Polytheism',
'Refining',
'Computing Technology',
'Nano Technology',
'Material Technology',
'Artificial Intelligence');
Name_Improvement: array[0..nImp-1] of string=
('The Pyramids',
'The Temple of Zeus',
'The Hanging Gardens',
'The Colossus',
'The Lighthouse',
'The Great Library',
'The Oracle',
'Sun Tzu''s War Academy',
'Leonardo''s Workshop',
'Magellan''s Expedition',
'Michelangelo''s Chapel',
'*',
'Newton''s College',
'Bach''s Cathedral',
'*',
'The Statue of Liberty',
'The Eiffel Tower',
'The Hoover Dam',
'The Shinkansen Express',
'The Manhattan Project',
'MIR Space Station',
'*',
'*',
'*',
'*',
'*',
'*',
'*',
'Trade Goods',
'Barracks',
'Granary',
'Temple',
'Marketplace',
'Library',
'Courthouse',
'City Walls',
'Aqueduct',
'Bank',
'Cathedral',
'University',
'Harbor',
'Theater',
'Factory',
'Manufacturing Plant',
'Recycling Center',
'Power Station',
'Hydroelectric Dam',
'Nuclear Plant',
'Offshore Platform',
'Town Hall',
'Sewer System',
'Supermarket',
'Superhighways',
'Research Lab',
'SAM Missile Battery',
'Coastal Fortress',
'Airport',
'Dockyard',
'Palace',
'Great Wall',
'Colosseum',
'Observatory',
'Military Academy',
'Command Bunker',
'Algae Plant',
'Stock Exchange',
'Space Port',
'Colony Ship Component',
'Power Module',
'Habitation Module');
Name_Feature: array[0..nFeature-1] of string=
('Weapons',
'Armor',
'Mobility',
'Sea Transport',
'Carrier',
'Turbines',
'Bombs',
'Fuel',
'Air Transport',
'Navigation',
'Radar / Sonar',
'Submarine',
'Artillery',
'Alpine',
'Supply Ship',
'Overweight',
'Air Defence',
'Spy Plane',
'Steam Power',
'Nuclear Power',
'Jet Engines',
'Stealth',
'Fanatic',
'First Strike',
'Power of Will',
'Academy Training',
'Line Production');
Name_TerrainType: array[0..11] of string=
('Ocean',
'Coast',
'Grassland',
'Desert',
'Prairie',
'Tundra',
'Arctic',
'Swamp',
'*',
'Forest',
'Hills',
'Mountains');
Name_Government: array[0..nGov-1] of string=
('Anarchy',
'Despotism',
'Monarchy',
'Republic',
'Fundamentalism',
'Communism',
'Democracy',
'Future Society');
implementation
end.
|
unit UFrmUsuario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, UFrmCRUD, Menus, Buttons,
StdCtrls, PwCtrls, ExtCtrls
, UUtilitarios
, UUsuario
, URegraCRUDUsuario, pngimage
;
type
TFrmUsuario = class(TFrmCRUD)
gbInformacoes: TGroupBox;
lbNome: TLabel;
lbEmail: TLabel;
lbSenha: TLabel;
lbConfirmarSenha: TLabel;
edNome: TEdit;
edEmail: TEdit;
edSenha: TEdit;
edConfirmarSenha: TEdit;
procedure edConfirmarSenhaExit(Sender: TObject);
private
FUSUARIO : TUSUARIO;
FRegraCRUDUsuario : TRegraCRUDUsuario;
protected
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
FrmUsuario: TFrmUsuario;
implementation
{$R *.dfm}
{ TFrmUsuario }
uses
UOpcaoPesquisa
, UEntidade
, UMensagens
, UDialogo
;
procedure TFrmUsuario.edConfirmarSenhaExit(Sender: TObject);
begin
inherited;
try
FRegraCRUDUsuario.ValidaSenha(edSenha.Text, edConfirmarSenha.Text);
except
on E: Exception do
begin
TDialogo.Excecao(E);
end;
end;
end;
procedure TFrmUsuario.Finaliza;
begin
inherited;
FreeAndNil(FUSUARIO);
FreeAndNil(FRegraCRUDUsuario);
end;
procedure TFrmUsuario.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmUsuario.Inicializa;
begin
inherited;
DefineEntidade(@FUSUARIO, TUSUARIO);
DefineRegraCRUD(@FRegraCRUDUsuario, TRegraCRUDUsuario);
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_USUARIO)
.DefineNomeCampoRetorno(VW_USUARIO_ID)
.AdicionaFiltro(VW_USUARIO_NOME)
.DefineNomePesquisa(STR_USUARIO));
FUSUARIO := TUSUARIO.Create;
FRegraCRUDUsuario := TRegraCRUDUsuario.Create;
end;
procedure TFrmUsuario.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmUsuario.PreencheEntidade;
begin
inherited;
FUSUARIO.NOME := edNome.Text;
FUSUARIO.EMAIL := edEmail.Text;
FUSUARIO.SENHA := edSenha.Text;
FRegraCRUDUsuario.SENHA_ATUAL := edSenha.Text;
FRegraCRUDUsuario.CONFIRMACAO_SENHA := edConfirmarSenha.Text;
end;
procedure TFrmUsuario.PreencheFormulario;
begin
inherited;
edNome.Text := FUSUARIO.NOME;
edEmail.Text := FUSUARIO.EMAIL;
edSenha.Text := FUSUARIO.SENHA;
edConfirmarSenha.Text := FUSUARIO.SENHA;
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2009-09-13
描述: 车辆管理
*******************************************************************************}
unit UFormTruckInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFormNormal, dxLayoutControl, StdCtrls, cxControls,
cxMemo, cxTextEdit, cxDropDownEdit, cxContainer, cxEdit, cxMaskEdit,
cxCalendar, cxGraphics, cxMCListBox, cxImage, cxButtonEdit,
cxLookAndFeels, cxLookAndFeelPainters;
type
TfFormTruckInfo = class(TfFormNormal)
EditNo: TcxTextEdit;
dxLayout1Item5: TdxLayoutItem;
EditMemo: TcxMemo;
dxLayout1Item6: TdxLayoutItem;
EditType: TcxComboBox;
dxLayout1Item13: TdxLayoutItem;
EditPhone: TcxTextEdit;
dxLayout1Item14: TdxLayoutItem;
EditOwner: TcxTextEdit;
dxLayout1Item16: TdxLayoutItem;
dxGroup2: TdxLayoutGroup;
dxLayout1Group3: TdxLayoutGroup;
dxLayout1Group2: TdxLayoutGroup;
ListInfo1: TcxMCListBox;
dxLayout1Item3: TdxLayoutItem;
EditInfo: TcxTextEdit;
dxLayout1Item4: TdxLayoutItem;
InfoItems: TcxTextEdit;
dxLayout1Item7: TdxLayoutItem;
BtnDel: TButton;
dxLayout1Item8: TdxLayoutItem;
BtnAdd: TButton;
dxLayout1Item9: TdxLayoutItem;
dxLayout1Group4: TdxLayoutGroup;
dxLayout1Group5: TdxLayoutGroup;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnAddClick(Sender: TObject);
procedure BtnDelClick(Sender: TObject);
procedure ListInfo1Click(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
protected
FRecordID: string;
//记录编号
function OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean; override;
//基类方法
procedure InitFormData(const nID: string);
//初始化数据
public
{ Public declarations }
class function CreateForm(const nPopedom: string = '';
const nParam: Pointer = nil): TWinControl; override;
class function FormID: integer; override;
end;
implementation
{$R *.dfm}
uses
IniFiles, UMgrControl, UAdjustForm, UFormCtrl, ULibFun, UDataModule,
UFormBase, USysFun, USysGrid, USysConst, USysDB;
var
gForm: TfFormTruckInfo = nil;
//------------------------------------------------------------------------------
class function TfFormTruckInfo.CreateForm(const nPopedom: string;
const nParam: Pointer): TWinControl;
var nP: PFormCommandParam;
begin
Result := nil;
if Assigned(nParam) then
nP := nParam
else Exit;
case nP.FCommand of
cCmd_AddData:
with TfFormTruckInfo.Create(Application) do
begin
FRecordID := '';
Caption := '车辆信息 - 添加';
InitFormData('');
nP.FCommand := cCmd_ModalResult;
nP.FParamA := ShowModal;
Free;
end;
cCmd_EditData:
with TfFormTruckInfo.Create(Application) do
begin
FRecordID := nP.FParamA;
Caption := '车辆信息 - 修改';
InitFormData(FRecordID);
nP.FCommand := cCmd_ModalResult;
nP.FParamA := ShowModal;
Free;
end;
cCmd_ViewData:
begin
if not Assigned(gForm) then
begin
gForm := TfFormTruckInfo.Create(Application);
gForm.Caption := '车辆信息 - 查看';
gForm.FormStyle := fsStayOnTop;
gForm.BtnOK.Visible := False;
gForm.BtnAdd.Enabled := False;
gForm.BtnDel.Enabled := False;
end;
with gForm do
begin
FRecordID := nP.FParamA;
InitFormData(FRecordID);
if not gForm.Showing then gForm.Show;
end;
end;
cCmd_FormClose:
begin
if Assigned(gForm) then FreeAndNil(gForm);
end;
end;
end;
class function TfFormTruckInfo.FormID: integer;
begin
Result := cFI_FormTruckInfo;
end;
procedure TfFormTruckInfo.FormCreate(Sender: TObject);
var nIni: TIniFile;
begin
dxGroup1.AlignHorz := ahClient;
AdjustCtrlData(Self);
ResetHintAllCtrl(Self, 'T', sTable_TruckInfo);
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadFormConfig(Self);
LoadMCListBoxConfig(Name, ListInfo1);
finally
nIni.Free;
end;
end;
procedure TfFormTruckInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveFormConfig(Self);
SaveMCListBoxConfig(Name, ListInfo1);
finally
nIni.Free;
end;
gForm := nil;
Action := caFree;
ReleaseCtrlData(Self);
end;
//------------------------------------------------------------------------------
//Desc: 添加信息项
procedure TfFormTruckInfo.BtnAddClick(Sender: TObject);
begin
InfoItems.Text := Trim(InfoItems.Text);
if InfoItems.Text = '' then
begin
InfoItems.SetFocus;
ShowMsg('请填写有效的信息项', sHint); Exit;
end;
EditInfo.Text := Trim(EditInfo.Text);
if EditInfo.Text = '' then
begin
EditInfo.SetFocus;
ShowMsg('请填写有效的信息内容', sHint); Exit;
end;
ListInfo1.Items.Add(InfoItems.Text + ListInfo1.Delimiter + EditInfo.Text);
end;
//Desc: 删除信息项
procedure TfFormTruckInfo.BtnDelClick(Sender: TObject);
var nIdx: integer;
begin
if ListInfo1.ItemIndex < 0 then
begin
ShowMsg('请选择要删除的内容', sHint); Exit;
end;
nIdx := ListInfo1.ItemIndex;
ListInfo1.Items.Delete(ListInfo1.ItemIndex);
if nIdx >= ListInfo1.Count then Dec(nIdx);
ListInfo1.ItemIndex := nIdx;
ShowMsg('信息项已删除', sHint);
end;
procedure TfFormTruckInfo.ListInfo1Click(Sender: TObject);
var nStr: string;
nPos: integer;
begin
if ListInfo1.ItemIndex > -1 then
begin
nStr := ListInfo1.Items[ListInfo1.ItemIndex];
nPos := Pos(ListInfo1.Delimiter, nStr);
InfoItems.Text := Copy(nStr, 1, nPos - 1);
System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1);
EditInfo.Text := nStr;
end;
end;
procedure TfFormTruckInfo.InitFormData(const nID: string);
var nStr: string;
begin
if EditType.Properties.Items.Count < 1 then
begin
EditType.Clear;
nStr := MacroValue(sQuery_SysDict, [MI('$Table', sTable_SysDict),
MI('$Name', sFlag_TruckType)]);
//数据字典中车辆类型
with FDM.QueryTemp(nStr) do
begin
First;
while not Eof do
begin
EditType.Properties.Items.Add(FieldByName('D_Value').AsString);
Next;
end;
end;
end;
if nID <> '' then
begin
nStr := 'Select * From %s Where T_ID=%s';
nStr := Format(nStr, [sTable_TruckInfo, nID]);
LoadDataToCtrl(FDM.QueryTemp(nStr), Self, '');
ListInfo1.Clear;
nStr := MacroValue(sQuery_ExtInfo, [MI('$Table', sTable_ExtInfo),
MI('$Group', sFlag_TruckItem), MI('$ID', nID)]);
//扩展信息
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
First;
while not Eof do
begin
nStr := FieldByName('I_Item').AsString + ListInfo1.Delimiter +
FieldByName('I_Info').AsString;
ListInfo1.Items.Add(nStr);
Next;
end;
end;
end;
end;
//Desc: 验证数据
function TfFormTruckInfo.OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean;
begin
Result := True;
if Sender = EditNo then
begin
EditNo.Text := Trim(EditNo.Text);
Result := EditNo.Text <> '';
nHint := '请填写有效的车牌号';
end;
end;
//Desc: 保存数据
procedure TfFormTruckInfo.BtnOKClick(Sender: TObject);
var i,nCount,nPos: integer;
nStr,nSQL,nTmp,nID: string;
begin
if not IsDataValid then Exit;
if FRecordID = '' then
begin
nSQL := MakeSQLByForm(Self, sTable_TruckInfo, '', True);
end else
begin
nStr := 'T_ID=' + FRecordID;
nSQL := MakeSQLByForm(Self, sTable_TruckInfo, nStr, False);
end;
FDM.ADOConn.BeginTrans;
try
FDM.ExecuteSQL(nSQL);
if FRecordID = '' then
begin
nID := IntToStr(FDM.GetFieldMax(sTable_TruckInfo, 'T_ID'));
end else
begin
nID := FRecordID;
nSQL := 'Delete From %s Where I_Group=''%s'' and I_ItemID=''%s''';
nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_TruckItem, FRecordID]);
FDM.ExecuteSQL(nSQL);
end;
nCount := ListInfo1.Items.Count - 1;
for i:=0 to nCount do
begin
nStr := ListInfo1.Items[i];
nPos := Pos(ListInfo1.Delimiter, nStr);
nTmp := Copy(nStr, 1, nPos - 1);
System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1);
nSQL := 'Insert Into %s(I_Group, I_ItemID, I_Item, I_Info) ' +
'Values(''%s'', ''%s'', ''%s'', ''%s'')';
nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_TruckItem, nID, nTmp, nStr]);
FDM.ExecuteSQL(nSQL);
end;
FDM.ADOConn.CommitTrans;
ModalResult := mrOK;
ShowMsg('数据已保存', sHint);
except
FDM.ADOConn.RollbackTrans;
ShowMsg('数据保存失败', '未知原因');
end;
end;
initialization
gControlManager.RegCtrl(TfFormTruckInfo, TfFormTruckInfo.FormID);
end.
|
unit ServiceController;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
{$WARN SYMBOL_DEPRECATED OFF}
{$WARN SYMBOL_PLATFORM OFF}
uses
Classes,
AdvObjects,
Windows,
WinSvc;
const
USER_CONTROL_OFFSET = $80;
type
TServiceManagerHandle = class (TAdvObject)
private
FMachine : String;
FHandle : SC_HANDLE;
FHndErr : Cardinal;
public
Constructor create(AMachine : String = ''); { default = local }
destructor Destroy; override;
procedure Install(ASystemName, ADisplayName, AExecutable : String);
procedure ListServices(AList : TStringList);
end;
TServiceStatusEnum = (ssError, ssNotInstalled, ssRunning, ssStopped, ssStarting, ssStopping, ssOther);
TServiceHandle = class (TAdvObject)
private
FManHnd : SC_HANDLE;
FService : String;
FHandle : SC_HANDLE;
FHndErr : Cardinal;
FStatus: TServiceStatus;
function GetAutoStart: Boolean;
procedure SetAutoStart(const Value: Boolean);
public
Constructor create(AServiceManager : TServiceManagerHandle; AName : string);
destructor Destroy; override;
function ServiceIsRunning : boolean;
procedure Query;
procedure SendMessageToService(AMsg : Integer);
procedure Remove;
procedure Stop;
procedure Start;
procedure ListDependencies(AList : TStrings);
procedure SetDependencies(AList : TStrings);
Function AccountName : AnsiString;
Procedure SetAccount(aUser, aPassword : String);
function GetStatus(Var VMsg : String) : TServiceStatusEnum;
property AutoStart : Boolean read GetAutoStart write SetAutoStart;
function InstalledOK : Boolean;
procedure Bind;
procedure Update(ATitle : String; AExecutable : String);
end;
function DescribeServiceStatus(ACode: DWord): String;
implementation
uses
SysUtils;
const
ASSERT_UNIT = 'ServiceController';
{ TServiceManagerHandle }
constructor TServiceManagerHandle.create(AMachine : String = '');
const ASSERT_LOCATION = ASSERT_UNIT+'.TServiceManagerHandle.Create';
begin
inherited create;
FMachine := AMachine;
FHandle := OpenSCManager(pchar(AMachine), NIL, SC_MANAGER_ALL_ACCESS);
FHndErr := GetLastError;
end;
destructor TServiceManagerHandle.destroy;
const ASSERT_LOCATION = ASSERT_UNIT+'.TServiceManagerHandle.destroy';
begin
if FHandle <> 0 then
CloseServiceHandle(FHandle);
inherited;
end;
procedure TServiceManagerHandle.Install(ASystemName, ADisplayName, AExecutable: String);
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if CreateService(FHandle, pchar(ASystemName), pchar(ADisplayName),
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pchar(AExecutable), NIL, NIL, NIL, NIL, NIL) = 0 then
begin
RaiseLastWin32Error;
end;
end;
procedure TServiceManagerHandle.ListServices(AList: TStringList);
var
LSvc: packed array [0..1000] of TEnumServiceStatus;
LNeeded, LReturned, LResume : DWord;
i : integer;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
LNeeded := 0;
LReturned := 0;
LResume := 0;
repeat
if not EnumServicesStatus(FHandle, SERVICE_WIN32, SERVICE_ACTIVE or SERVICE_INACTIVE,
LSvc[0], sizeof(TEnumServiceStatus) * 1000, LNeeded, LReturned, LResume) then
RaiseLastWin32Error;
for i := 0 to LReturned - 1 do
AList.Values[LSvc[i].lpServiceName] := LSvc[i].lpDisplayName;
until LResume = 0;
end;
{ TServiceHandle }
constructor TServiceHandle.create(AServiceManager : TServiceManagerHandle; AName: string);
begin
inherited create;
FService := AName;
FManHnd := AServiceManager.FHandle;
FHndErr := AServiceManager.FHndErr;
Bind;
end;
destructor TServiceHandle.destroy;
begin
if FHandle <> 0 then
CloseServiceHandle(FHandle);
inherited;
end;
procedure TServiceHandle.Query;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if not QueryServiceStatus(FHandle, FStatus) then
begin
RaiseLastWin32Error;
end;
end;
function TServiceHandle.ServiceIsRunning: boolean;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
Query;
result := FStatus.dwCurrentState <> SERVICE_STOPPED;
end;
procedure TServiceHandle.SendMessageToService(AMsg: Integer);
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
Query;
win32Check(ControlService(FHandle, AMsg + USER_CONTROL_OFFSET, FStatus));
end;
(*
ServiceHandle :=
Write('.');
if ServiceHandle = 0 then
writeln(MakeWinError(GetLastError, 'stopping the service'))
else
try
Write('.');
if (lpServiceStatus.dwCurrentState <> SERVICE_STOPPED) then
i := 0;
repeat
Write('.');
QueryServiceStatus(serviceHandle, lpServiceStatus);
inc(i);
if lpServiceStatus.dwCurrentState <> SERVICE_STOPPED then
sleep(100);
until (i = 10) or (lpServiceStatus.dwCurrentState = SERVICE_STOPPED);
if lpServiceStatus.dwCurrentState <> SERVICE_STOPPED then
writeln('The ' + FTitle + ' Service could not be stopped')
else
writeln('The ' + FTitle + ' Service has been stopped');
finally
end;
*)
procedure TServiceHandle.Remove;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if ServiceIsRunning then
begin
Stop;
end;
win32Check(DeleteService(FHandle));
CloseServiceHandle(FHandle);
FHandle := 0;
end;
procedure TServiceHandle.Start;
var
p: PChar;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
p := nil;
win32Check(StartService(FHandle, 0, p));
end;
procedure TServiceHandle.Stop;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
Query;
win32Check(ControlService(FHandle, SERVICE_CONTROL_STOP, FStatus));
end;
procedure TServiceHandle.ListDependencies(AList: TStrings);
var
LNeeded : DWord;
LConfig : array [0..11] of _QUERY_SERVICE_CONFIG;
p : pchar;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if not QueryServiceConfig(FHandle, @LConfig[0], sizeof(_QUERY_SERVICE_CONFIG)* 10, LNeeded) then
RaiseLastWin32Error;
p := LConfig[0].lpDependencies;
while assigned(p) and (p[0] <> #0) do
begin
AList.Add(p);
inc(p, strlen(p)+1);
end;
end;
procedure TServiceHandle.SetDependencies(AList: TStrings);
var
i : integer;
s : String;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
s := '';
for i := 0 to AList.count - 1 do
s := s + AList[i]+#0;
s := s + #0;
if not ChangeServiceConfig(FHandle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
nil, nil, nil, pchar(s), nil, nil, nil) then
RaiseLastWin32Error;
end;
function TServiceHandle.GetAutoStart: Boolean;
var
LNeeded : DWord;
LConfig : array [0..11] of _QUERY_SERVICE_CONFIGA;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if not QueryServiceConfig(FHandle, @LConfig[0], sizeof(_QUERY_SERVICE_CONFIGA)* 10, LNeeded) then
RaiseLastWin32Error;
result := LConfig[0].dwStartType = SERVICE_AUTO_START;
end;
procedure TServiceHandle.SetAutoStart(const Value: Boolean);
var
v : DWord;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if Value then
v := SERVICE_AUTO_START
else
v := SERVICE_DEMAND_START;
if not ChangeServiceConfig(FHandle, SERVICE_NO_CHANGE, v, SERVICE_NO_CHANGE,
nil, nil, nil, nil, nil, nil, nil) then
RaiseLastWin32Error;
end;
function DescribeServiceStatus(ACode: DWord): String;
begin
case ACode of
SERVICE_STOPPED:
Result := 'Stopped';
SERVICE_START_PENDING:
Result := 'Starting';
SERVICE_STOP_PENDING:
Result := 'Stopping';
SERVICE_RUNNING:
Result := 'Running';
SERVICE_CONTINUE_PENDING:
Result := 'Continuing';
SERVICE_PAUSE_PENDING:
Result := 'Pausing';
SERVICE_PAUSED:
Result := 'Paused';
else
Result := 'Unknown (' + IntToStr(ACode) + ')';
end;
end;
function TServiceHandle.GetStatus(var VMsg: String): TServiceStatusEnum;
begin
if FHandle = 0 then
begin
if FHndErr = 1060 then
result := ssNotInstalled
else
begin
result := ssError;
VMsg := SysErrorMessage(FHndErr);
end;
end
else
begin
Query;
if FStatus.dwCurrentState = SERVICE_RUNNING then
Begin
result := ssRunning;
VMsg := 'Running';
End
else if FStatus.dwCurrentState = SERVICE_STOPPED then
Begin
result := ssStopped;
VMsg := 'Stopped';
End
else if FStatus.dwCurrentState = SERVICE_START_PENDING then
Begin
result := ssStarting;
VMsg := 'Starting';
End
else if FStatus.dwCurrentState = SERVICE_STOP_PENDING then
Begin
result := ssStopping;
VMsg := 'Stopping';
End
else
begin
result := ssOther;
VMsg := DescribeServiceStatus(FStatus.dwCurrentState);
end;
end;
end;
function TServiceHandle.InstalledOK: Boolean;
begin
result := FHandle <> 0;
end;
procedure TServiceHandle.Bind;
begin
if FHandle <> 0 then
begin
CloseServiceHandle(FHandle);
sleep(20);
end;
if FManHnd <> 0 then
begin
FHandle := OpenService(FManHnd, pchar(FService), SERVICE_ALL_ACCESS);
FHndErr := GetLastError;
end;
end;
procedure TServiceHandle.Update(ATitle, AExecutable: String);
begin
if not ChangeServiceConfig(FHandle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
pchar(AExecutable), nil, nil, nil, nil, nil, pchar(ATitle)) then
RaiseLastWin32Error;
end;
function TServiceHandle.AccountName: AnsiString;
var
LNeeded : DWord;
LConfig : array [0..11] of _QUERY_SERVICE_CONFIGA;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if not QueryServiceConfig(FHandle, @LConfig[0], sizeof(_QUERY_SERVICE_CONFIGA)* 10, LNeeded) then
RaiseLastWin32Error;
result := LConfig[0].lpServiceStartName;
end;
procedure TServiceHandle.SetAccount(aUser, aPassword: String);
var
LNeeded : DWord;
LConfig : array [0..11] of _QUERY_SERVICE_CONFIGA;
begin
if FHandle = 0 then
raise EWin32Error.Create(SysErrorMessage(FHndErr));
if not QueryServiceConfig(FHandle, @LConfig[0], sizeof(_QUERY_SERVICE_CONFIGA)* 10, LNeeded) then
RaiseLastWin32Error;
if (aUser = '') and (aPassword = '') Then
Begin
if not changeServiceConfig(FHandle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, lConfig[0].dwErrorControl, nil,
nil, nil, nil, 'LocalSystem', nil, nil) Then
RaiseLastWin32Error;
End
Else
Begin
if not changeServiceConfig(FHandle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, lConfig[0].dwErrorControl, nil,
nil, nil, nil, pchar(AUser), pchar(APassword), nil) Then
RaiseLastWin32Error;
End;
end;
end. |
unit CatFiles;
{
Catarinka - File System functions
Copyright (c) 2003-2014 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
CopyAfterFirstLine and WipeFile functions by Peter Below
FileCopy function by David Stidolph
}
interface
{$I Catarinka.inc}
uses
{$IF CompilerVersion > 22}
Winapi.Windows, System.Classes, System.SysUtils, Winapi.ShellAPI,
System.IOUtils;
{$ELSE}
Windows, Classes, SysUtils, ShellAPI;
{$IFEND}
function CleanFilename(const filename: string;
const invCharRep: Char = '_'): string;
function DeleteFolder(const dir: string): boolean;
function DirExists(const dir: string): boolean;
function FileCanBeOpened(const filename: String): boolean;
function FileCopy(const source, dest: string): boolean;
function FilenameToMimeType(const filename: string): string;
function ForceDir(const dir: string): boolean;
function GetDiskSerialNumber(const drive: string): string;
function GetFileSize(const filename: string): Int64;
function GetFileToStr(const filename: string): string;
function GetFileVersion(const filename: string;
const ResFormat: string = '%d.%d.%d.%d'): string;
function GetSizeDescription(const bytes: cardinal): string;
function GetTextFileLinesCount(const filename: string): integer;
function GetTempFile(const ext: string): string;
function GetWindowsTempDir: string;
function SendToLog(const filename: TFilename; const s: string): boolean;
function SL_LoadFromFile(const SL: TStringList; const filename: string)
: boolean;
function SL_SaveToFile(const SL: TStringList; const filename: string): boolean;
procedure CatReadLn(const f: Text; var s: string);
procedure CopyAfterFirstLine(const sourcefile, targetfile: string;
appendln: boolean = false; lnstr: string = '');
procedure GetDirs(const dir: string; const Result: TStrings;
SortResult: boolean = true);
procedure GetFiles(const dir: string; const Result: TStrings;
const IncludeDir: boolean = false; const IncludeExt: boolean = true);
procedure WipeFile(const filename: string);
implementation
uses
CatStrings;
procedure CatReadLn(const f: Text; var s: string);
var
c: Char;
tempStr: string;
begin
tempStr := emptystr;
while not Eof(f) do
begin
read(f, c);
case Ord(c) of
10:
Break;
13:
begin
read(f, c);
if Ord(c) = 13 then
begin // hides H2077 compiler warning
end;
Break;
end;
else
tempStr := tempStr + c;
end;
end;
s := tempStr;
end;
// Deletes a directory and its sub directories
function DeleteFolder(const dir: string): boolean;
var
sdir: string;
st: TSHFileOpStruct;
begin
sdir := dir;
if LastChar(sdir) = '\' then
sdir := copy(sdir, 1, Length(sdir) - 1);
try
FillChar(st, SizeOf(st), #0);
sdir := sdir + #0#0;
with st do
begin
Wnd := 0;
wFunc := FO_DELETE;
pFrom := PChar(sdir);
fFlags := FOF_SILENT or FOF_NOCONFIRMATION;
end;
Result := (SHFileOperation(st) = 0);
except
Result := false;
end;
end;
function DirExists(const dir: string): boolean;
begin
Result := DirectoryExists(dir);
end;
function FileCanBeOpened(const filename: string): boolean;
var
h: integer;
begin
try
h := FileOpen(filename, fmOpenRead or fmShareDenyNone);
if h > 0 then
begin
Result := true;
FileClose(h);
end
else
Result := false;
except
Result := false
end;
end;
function FilenameToMimeType(const filename: string): string;
var
ext: string;
begin
ext := LowerCase(ExtractFileExt(filename));
if Length(ext) > 1 then
ext := copy(ext, 2, Length(ext));
if ext = 'css' then
Result := 'text/css'
else if (ext = 'htm') or (ext = 'html') then
Result := 'text/html'
else if ext = 'bmp' then
Result := 'image/bmp'
else if ext = 'gif' then
Result := 'image/gif'
else if (ext = 'jpg') or (ext = 'jpeg') then
Result := 'image/jpeg'
else if ext = 'js' then
Result := 'text/javascript'
else if (ext = 'png') then
Result := 'image/png'
else if ext = 'txt' then
Result := 'text/plain'
else
Result := 'application/octet-stream'; // Unknown Type
end;
function CleanFilename(const filename: string;
const invCharRep: Char = '_'): string;
const
invChars = ['\', ':', '*', '?', '"', '<', '>', '|', '/'];
begin
Result := ReplaceChars(filename, invChars, invCharRep);
end;
function ForceDir(const dir: string): boolean;
var
d: string;
begin
d := ReplaceStr(dir, '\\', '\');
d := ReplaceStr(d, '//', '/');
Result := ForceDirectories(d);
end;
procedure GetDirs(const dir: string; const Result: TStrings;
SortResult: boolean = true);
var
SL: TStringList;
sr: TSearchRec;
begin
SL := TStringList.Create;
try
if FindFirst(dir + '*.*', faDirectory, sr) = 0 then
begin
repeat
if ((sr.Attr and faDirectory) = faDirectory) and (sr.name <> '.') and
(sr.name <> '..') then
SL.Add(sr.name);
until FindNext(sr) <> 0;
FindClose(sr);
end;
if SortResult = true then
SL.sort;
Result.Text := SL.Text;
finally
SL.Free;
end;
end;
function GetDiskSerialNumber(const drive: string): string;
var
sn, len, flags: DWORD;
begin
GetVolumeInformation(PChar(drive), nil, 0, @sn, len, flags, nil, 0);
Result := IntToHex(HiWord(sn), 4) + '-' + IntToHex(LoWord(sn), 4);
end;
procedure GetFiles(const dir: string; const Result: TStrings;
const IncludeDir: boolean = false; const IncludeExt: boolean = true);
var
rc: integer;
tmpPath, ffound: string;
sr: TSearchRec;
begin
if Result = nil then
exit;
tmpPath := IncludeTrailingPathDelimiter(ExtractFilePath(dir));
rc := FindFirst(dir, faAnyFile, sr);
while rc = 0 do
begin
ffound := sr.name;
if IncludeExt = false then
ffound := changefileext(ffound, emptystr);
if IncludeDir then
Result.Add(tmpPath + ffound)
else
Result.Add(ffound);
rc := FindNext(sr);
end;
FindClose(sr);
end;
function GetFileSize(const filename: string): Int64;
var
f: TWin32FindData;
h: THandle;
begin
Result := -1;
try
if not FileExists(filename) then
exit;
h := FindFirstFile({$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(filename), f);
if h = INVALID_HANDLE_VALUE then
RaiseLastOSError;
try
Result := f.nFileSizeHigh shl 32 + f.nFileSizeLow;
finally
{$IF CompilerVersion > 22}Winapi.{$IFEND}Windows.FindClose(h);
end;
except
end;
end;
function GetFileToStr(const filename: string): string;
var
SL: TStringList;
f: TFileStream;
begin
SL := TStringList.Create;
f := TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite);
with f do
begin
try
SL.LoadFromStream(f);
Result := SL.Text;
except
Result := emptystr;
end;
Free;
end;
SL.Free;
end;
// Returns the version of a binary file (DLL, EXE, etc)
function GetFileVersion(const filename: string;
const ResFormat: string = '%d.%d.%d.%d'): string;
var
p, pi: Pointer;
infosz, plen: DWORD;
verinfo: VS_FIXEDFILEINFO;
begin
Result := emptystr;
infosz := GetFileVersionInfoSize({$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(filename), plen);
FillChar(verinfo, SizeOf(verinfo), 0);
if infosz > 0 then
begin
GetMem(p, infosz);
GetFileVersionInfo({$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(filename),
0, infosz, p);
VerQueryValue(p, '\', pi, plen);
move(pi^, verinfo, SizeOf(verinfo));
Result := Format(ResFormat, [verinfo.dwFileVersionMS shr 16,
verinfo.dwFileVersionMS and 65535, verinfo.dwFileVersionLS shr 16,
verinfo.dwFileVersionLS and 65535]);
FreeMem(p);
end;
end;
function GetSizeDescription(const bytes: cardinal): string;
const
cFF = '0.0';
begin
if bytes < 1 then
Result := '0 bytes'
else
case bytes of
1 .. 1023:
Result := InttoStr(bytes) + ' bytes';
1024 .. 1048575:
Result := FormatFloat(cFF, bytes / 1024) + ' KB';
1048576 .. 1073741823:
Result := FormatFloat(cFF, bytes / 1048576) + ' MB';
else
Result := FormatFloat(cFF, bytes / 1073741824) + ' GB';
end;
end;
// Returns a temporary filename (located in the Windows Temporary directory)
// This function will not create the temporary file, just return a filename suggestion
// Usage Example: ShowMessage(GetTempFile('.tmp'))
function GetTempFile(const ext: string): string;
var
buf: array [0 .. MAX_PATH] of {$IFDEF UNICODE}WideChar{$ELSE}Char{$ENDIF};
begin
GetTempPath({$IFDEF UNICODE}Length{$ELSE}SizeOf{$ENDIF}(buf) - 1, buf);
GetTempFileName(buf, '~', 0, buf);
Result := StrPas(buf);
if ext <> emptystr then // if the extension is empty will return a .tmp
Result := changefileext(Result, ext);
end;
function GetTextFileLinesCount(const filename: string): integer;
var
f: Textfile;
s: string;
begin
AssignFile(f, filename);
Reset(f);
Result := 0;
while not seekeof(f) do
begin
Result := Result + 1;
CatReadLn(f, s);
end;
Closefile(f);
end;
function GetWindowsTempDir: String;
var
bufFolder: array [0 .. MAX_PATH] of
{$IFDEF UNICODE}WideChar{$ELSE}Char{$ENDIF};
begin
GetTempPath({$IFDEF UNICODE}Length{$ELSE}SizeOf{$ENDIF}(bufFolder),
bufFolder);
Result := IncludeTrailingPathDelimiter(String(bufFolder));
end;
function SendToLog(const filename: TFilename; const s: String): boolean;
var
f: Textfile;
begin
try
AssignFile(f, filename);
if FileExists(filename) = false then
ReWrite(f)
else
begin
Reset(f);
Append(f);
end;
WriteLn(f, s);
Closefile(f);
Result := true;
except
Result := false;
end;
end;
function SL_SaveToFile(const SL: TStringList; const filename: string): boolean;
var
fs: TStream;
begin
Result := false;
if filename = emptystr then
exit;
if FileExists(filename) = false then
begin
fs := TFileStream.Create(filename, fmCreate or fmOpenWrite or
fmShareDenyWrite);
fs.Free;
end;
fs := TFileStream.Create(filename, fmOpenWrite or fmShareDenyWrite);
fs.Size := 0;
try
SL.SaveToStream(fs);
Result := true;
except
end;
fs.Free;
end;
function SL_LoadFromFile(const SL: TStringList; const filename: string)
: boolean;
var
fs: TStream;
begin
Result := false;
if filename = emptystr then
exit;
fs := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
try
SL.LoadFromStream(fs);
Result := true;
except
end;
fs.Free;
end;
// Copies a file, based on a source and destination filename, and returns true
// if successful or false if the operation failed
function FileCopy(const source, dest: string): boolean;
{$IF CompilerVersion < 22}
var
fSrc, fDst, len: integer;
Size: LongInt;
buffer: packed array [0 .. 2047] of Byte;
{$IFEND}
begin
{$IF CompilerVersion > 22}
Result := true;
if FileExists(source) and FileExists(dest) then
DeleteFile(dest);
try
TFile.copy(source, dest);
except
Result := false;
end;
{$ELSE}
// By David Stidolph, 21 Jun 1995
Result := false;
if source <> dest then
begin
fSrc := FileOpen(source, fmOpenRead);
if fSrc >= 0 then
begin
Size := FileSeek(fSrc, 0, 2);
FileSeek(fSrc, 0, 0);
fDst := FileCreate(dest);
if fDst >= 0 then
begin
while Size > 0 do
begin
len := FileRead(fSrc, buffer, SizeOf(buffer));
FileWrite(fDst, buffer, len);
Size := Size - len;
end;
FileSetDate(fDst, FileGetDate(fSrc));
FileClose(fDst);
FileSetAttr(dest, FileGetAttr(source));
Result := true;
end;
FileClose(fSrc);
end;
end;
{$IFEND}
end;
// Peter Below ------------------------------------------------------------//
// Based on an example from PB (4/5/1998)
procedure CopyAfterFirstLine(const sourcefile, targetfile: string;
appendln: boolean = false; lnstr: string = '');
var
s: string;
source, Target: Textfile;
begin
AssignFile(source, sourcefile);
AssignFile(Target, targetfile);
Reset(source);
try
ReWrite(Target);
try
CatReadLn(source, s);
while not Eof(source) do
begin
CatReadLn(source, s);
WriteLn(Target, s);
end;
if appendln then
WriteLn(lnstr);
finally
Closefile(Target);
end;
finally
Closefile(source);
end;
end;
{
If you want to get rid of a file normally you just delete it.
But someone else can undelete it if the file hasn't been wiped correctly.
For security purposes, to insure that certain files are permanently
gone, the WipeFile procedure writes over the data in the file with
random characters and then erases it.
}
procedure WipeFile(const filename: string); // PB
var
buffer: array [0 .. 4095] of Byte;
max, n: LongInt;
i: integer;
fs: TFileStream;
procedure RandomizeBuffer;
var
i: integer;
begin
for i := Low(buffer) to High(buffer) do
buffer[i] := Random(256);
end;
begin
fs := TFileStream.Create(filename, fmOpenReadWrite or fmShareExclusive);
try
for i := 1 to 3 do
begin
RandomizeBuffer;
max := fs.Size;
fs.Position := 0;
while max > 0 do
begin
if max > SizeOf(buffer) then
n := SizeOf(buffer)
else
n := max;
fs.Write(buffer, n);
max := max - n;
end;
FlushFileBuffers(fs.Handle);
end;
finally
fs.Free;
end;
DeleteFile(filename);
end;
// ------------------------------------------------------------------------//
end.
|
{**************************************************************************************
* Copyright (c)
* All rights reserved.
*
* FileName:
*
*
*******************************************************************************************}
unit ET_API;
interface
uses
Windows;
// const definition
const ET_TYPE_99 = $1;
const ET_TYPE_299 = $2;
const ET_TYPE_99TIME = $3;
//Return Value Status Definition
const ET_SUCCESS = $00; //函数执行成功
const ET_ACCESS_DENY = $01; //访问被拒绝,权限不够
const ET_COMMUNICATIONS_ERROR = $02; //通讯错误,没有打开设备
const ET_INVALID_PARAMETER = $03; //无效的参数,参数出错
const ET_NOT_SET_PID = $04; //没有设置PID
const ET_UNIT_NOT_FOUND = $05; //打开指定的设备失败
const ET_HARD_ERROR = $06; //硬件错误
const ET_UNKNOWN = $07; //一般性错误
const ET_PIN_ERR_MASK = $0F; //验证PIN码掩码
const ET_PIN_ERR_MAX = $FF; //验证PIN码最大剩余次数,如果验证错误还还回ET_PIN_ERR_MAX则表示PIN码永远不被锁死
//新增错误码
const ET_KEY_TYPE = $10; //密钥类型错误
const ET_LICENSE_TYPE = $11; //授权类型错误
const ET_LICENSE_UNINIT = $12; //授权单元未启用,出厂时,全部授权单元都未启用,只有当设置授权后才会被启用
const ET_NO_LICENSE = $13; //授权失败
const ET_UNKNOWN_UPDATE_FILE = $14; //未知的升级文件格式
const ET_INVALID_DATA_LEN = $15; //非法的数据长度
const ET_NO_TDES_KEY = $16; //无效的TDES密钥
const ET_INVALID_UPDATE_FILE = $17; //无效的升级文件
const ET_UNSUPPORTED = $18; //不支持的功能
const ET_ADJUST_TIMER = $19; //调整系统时钟失败
const ET_KEY_INDEX = $1A; //错误的密钥索引
const ET_KEY_ZERO = $1B; //0号密钥为系统专用
//常量定义
const ET_VERIFY_USERPIN = $0; //校验用户密码
const ET_VERIFY_SOPIN = $1; //校验开发商密码
const ET_USER_WRITE_READ = $0; //读写
const ET_USER_READ_ONLY = $1; //只读
const ET_KEY_HMAC_MD5 = $0; //选择HMAC-MD5密钥
const ET_KEY_TDES = $1; //选择3DES密钥
const ET_EXPIRE_DATE = $0; //截止日期授权
const ET_TIME_MINUTE = $1; //计时授权(单位:分)
const ET_TIME_DAY = $2; //计日授权(单位:日)
const ET99_MEMORY_SIZE = 1 * 1024; //ET99的数据区大小
const ET299_MEMORY_SIZE = 6 * 1024; //ET299的数据区大小
const ET99_TIME_MEMORY_SIZE = 512; //ET99 time的数据区大小
//出厂设置的PID
const CONST_PID = 'FFFFFFFF';
type
ET_HANDLE = Pointer;
PET_HANDLE = ^ET_HANDLE;
PWord = ^Word;
PLongword = ^Longword;
PHIDP_PREPARSED_DATA = ^Byte;
PPHIDP_PREPARSED_DATA = ^PHIDP_PREPARSED_DATA;
PInteger = ^Integer;
PCSTR = ^Char;
PByte = ^Byte;
psize_t = ^size_t;
size_t = Cardinal;
//时间数据格式
TimeData = record
m_Year: Byte; //年(0-99)
m_Month: Byte; //月(1-12)
m_Day: Byte; //日(1-31)
m_Hour: Byte; //时(0-23)
m_Minute: Byte; //分(0-59)
m_Second: Byte; //秒(0-59)
end;
//时间限制数据格式
//作为输入数据时m_hours的含义:
//0:m_end为截止时间 >0:可运行小时数, m_end忽略 <0:取消时间限制(典型值:-1)
//作为输出数据时 m_hours的含义:
//0:m_end为截止时间 >0:可运行小时数, m_end为截止时间 <0:无时间限制 m_end忽略
LimitData = record
m_hours: short; //最大26280
m_end: TimeData;
end;
//远程升级数据格式
UpdateData = record
m_limit: LimitData; //新的时间限制数据
m_sn: array[0..7] of Byte; //全0xFF表示不限制硬件SN,否则表示允许升级的硬件SN
m_md5: array[0..15] of Byte; //(sizeof(UpdateData)-16)的由keyid=9运算出的md5签名值
end;
{$EXTERNALSYM et_FindToken}
function et_FindToken(PIDstr: PChar; pcount: PInteger): DWORD; stdcall;
{$EXTERNALSYM et_OpenToken}
function et_OpenToken(hHandle: PET_HANDLE; PIDstr: PAnsiChar; index: integer): DWORD; stdcall;
{$EXTERNALSYM et_CloseToken}
function et_CloseToken(hHandle: ET_HANDLE): DWORD; stdcall;
{$EXTERNALSYM et_Read}
function et_Read(hHandle: ET_HANDLE; offset: Word; Len: Integer; pucReadBuf: PByte): DWORD; stdcall;
{$EXTERNALSYM et_Write}
function et_Write(hHandle: ET_HANDLE; offset: Word; Len: Integer; pucWriteBuf: PByte): DWORD; stdcall;
{$EXTERNALSYM et_GenPID}
function et_GenPID(hHandle: ET_HANDLE; SeedLen: Integer; pucSeed: PByte; pid: PChar): DWORD; stdcall;
{$EXTERNALSYM et_GenRandom}
function et_GenRandom(hHandle: ET_HANDLE; pucRandBuf: PByte): DWORD; stdcall;
{$EXTERNALSYM et_GenSOPIN}
function et_GenSOPIN(hHandle: ET_HANDLE; SeedLen: Integer; pucSeed: PByte; pucNewSoPIN: PChar): DWORD; stdcall;
{$EXTERNALSYM et_ResetPIN}
function et_ResetPIN(hHandle: ET_HANDLE; pucSoPIN: PChar): DWORD; stdcall;
{$EXTERNALSYM et_SetKey}
function et_SetKey(hHandle: ET_HANDLE; Keyid: Integer; pucKeyBuf: PByte): DWORD; stdcall;
{$EXTERNALSYM et_HMAC_MD5}
function et_HMAC_MD5(hHandle: ET_HANDLE; keyID: Integer; textLen: Integer; pucText: PByte; digest: PByte): DWORD; stdcall;
{$EXTERNALSYM et_Verify}
function et_Verify(hHandle: ET_HANDLE; Flags: Integer; pucPIN: PChar): DWORD; stdcall;
{$EXTERNALSYM et_ChangeUserPIN}
function et_ChangeUserPIN(hHandle: ET_HANDLE; pucOldPIN: PChar; pucNewPIN: PChar): DWORD; stdcall;
{$EXTERNALSYM et_ResetSecurityState}
function et_ResetSecurityState(hHandle: ET_HANDLE): DWORD; stdcall;
{$EXTERNALSYM et_GetSN}
function et_GetSN(hHandle: ET_HANDLE; pucSN: PByte): DWORD; stdcall;
{$EXTERNALSYM et_SetupToken}
function et_SetupToken(hHandle: ET_HANDLE; bSoPINRetries: Byte; bUserPINRetries: Byte; bUserReadOnly: Byte; bBack: Byte): DWORD; stdcall;
{$EXTERNALSYM et_TurnOnLED}
function et_TurnOnLED(hHandle: ET_HANDLE): DWORD; stdcall;
{$EXTERNALSYM et_TurnOffLED}
function et_TurnOffLED(hHandle: ET_HANDLE): DWORD; stdcall;
{$EXTERNALSYM et_TurnOffLED}
function MD5_HMAC(pucText: PByte; ulText_Len: DWORD; pucKey: PByte; ulKey_Len: DWORD; pucToenKey: PByte; pucDigest: PByte): DWORD; stdcall;
type
GUID = record
Data1: Longword;
Data2: Word;
Data3: Word;
Data4: array[0..7] of Byte;
end;
LPGUID = ^GUID;
HIDP_CAPS = record
Usage: Word;
UsagePage: Word;
InputReportByteLength: Word;
OutputReportByteLength: Word;
FeatureReportByteLength: Word;
Reserved: array[0..16] of Word;
NumberLinkCollectionNodes: Word;
NumberInputButtonCaps: Word;
NumberInputValueCaps: Word;
NumberInputDataIndices: Word;
NumberOutputButtonCaps: Word;
NumberOutputValueCaps: Word;
NumberOutputDataIndices: Word;
NumberFeatureButtonCaps: Word;
NumberFeatureValueCaps: Word;
NumberFeatureDataIndices: Word;
end;
PHIDP_CAPS = ^HIDP_CAPS;
HIDD_ATTRIBUTES = record
Size: Longword;
VendorID: Word;
ProductID: Word;
VersionNumber: Word;
end;
PHIDD_ATTRIBUTES = ^HIDD_ATTRIBUTES;
SP_DEVICE_INTERFACE_DATA = record
cbSize: Longword;
InterfaceClassGuid: GUID;
Flags: Longword;
Reserved: Longword;
end;
PSP_DEVICE_INTERFACE_DATA = ^SP_DEVICE_INTERFACE_DATA;
SP_DEVICE_INTERFACE_DETAIL_DATA = record
cbSize: Longword;
DevicePath: array[0..4096] of Char;
end;
//PSP_DEVICE_INTERFACE_DETAIL_DATA_A = ^SP_DEVICE_INTERFACE_DETAIL_DATA_A;
PSP_DEVICE_INTERFACE_DETAIL_DATA = ^SP_DEVICE_INTERFACE_DETAIL_DATA;
SP_DEVINFO_DATA = record
cbSize: Longword;
ClassGuid: GUID;
DevInst: Longword;
Reserved: Longword;
end;
PSP_DEVINFO_DATA = ^SP_DEVINFO_DATA;
tm = record
tm_sec: integer;
tm_min: integer;
tm_hour: integer;
tm_mday: integer;
tm_mon: integer;
tm_year: integer;
tm_wday: integer;
tm_yday: integer;
tm_isdst: integer;
end;
ptm = ^tm;
{$EXTERNALSYM HidD_FreePreparsedData}
function HidD_FreePreparsedData(PreparsedData: PHIDP_PREPARSED_DATA): Boolean; cdecl;
{$EXTERNALSYM HidP_GetCaps}
function HidP_GetCaps(PreparsedData: PHIDP_PREPARSED_DATA; Capabilities: PHIDP_CAPS): Longint; cdecl;
{$EXTERNALSYM HidD_GetPreparsedData}
function HidD_GetPreparsedData(HidDeviceObject: THandle; PreparsedData: PPHIDP_PREPARSED_DATA): Boolean; cdecl;
{$EXTERNALSYM HidD_SetFeature}
function HidD_SetFeature(HidDeviceObject: THandle; ReportBuffer: pointer; ReportBufferLength: Longword): Boolean; cdecl;
{$EXTERNALSYM HidD_GetFeature}
function HidD_GetFeature(HidDeviceObject: THandle; ReportBuffer: pointer; ReportBufferLength: Longword): Boolean; cdecl;
{$EXTERNALSYM HidD_FlushQueue}
function HidD_FlushQueue(HidDeviceObject: THandle): Boolean; cdecl;
{$EXTERNALSYM HidD_GetSerialNumberString}
function HidD_GetSerialNumberString(HidDeviceObject: THandle; Buffer: PChar; BufferLength: Longword): Boolean; cdecl;
{$EXTERNALSYM HidD_GetProductString}
function HidD_GetProductString(HidDeviceObject: THandle; Buffer: PChar; BufferLength: Longword): Boolean; cdecl;
{$EXTERNALSYM HidD_GetAttributes}
function HidD_GetAttributes(HidDeviceObject: THandle; Attributes: PHIDD_ATTRIBUTES): Boolean; cdecl;
{$EXTERNALSYM HidD_GetHidGuid}
function HidD_GetHidGuid(HidGuid: LPGUID): integer; cdecl;
{$EXTERNALSYM HidD_GetManufacturerString}
function HidD_GetManufacturerString(HidDeviceObject: THANDLE; Buffer: PCHAR; BufferLength: ULONG): Boolean; cdecl;
{$EXTERNALSYM SetupDiDestroyDeviceInfoList}
function SetupDiDestroyDeviceInfoList(DeviceInfoSet: THandle): Boolean; cdecl;
{$EXTERNALSYM SetupDiGetDeviceInterfaceDetailA}
function SetupDiGetDeviceInterfaceDetailA(DeviceInfoSet: THandle; DeviceInterfaceData: PSP_DEVICE_INTERFACE_DATA; DeviceInterfaceDetailData: PSP_DEVICE_INTERFACE_DETAIL_DATA; DeviceInterfaceDetailDataSize: Longword; RequiredSize: PLongword; DeviceInfoData: PSP_DEVINFO_DATA): Boolean; cdecl;
{$EXTERNALSYM SetupDiEnumDeviceInterfaces}
function SetupDiEnumDeviceInterfaces(DeviceInfoSet: THandle; DeviceInfoData: PSP_DEVINFO_DATA; InterfaceClassGuid: LPGUID; MemberIndex: Longword; DeviceInterfaceData: PSP_DEVICE_INTERFACE_DATA): Boolean; cdecl;
{$EXTERNALSYM SetupDiGetClassDevsA}
function SetupDiGetClassDevsA(ClassGuid: LPGUID; Enumerator: PCSTR; hwndParent: HWND; Flags: Longword): THandle; cdecl;
{$EXTERNALSYM _memset}
function _memset(s: Pointer; c: Integer; n: size_t): Pointer; cdecl;
{$EXTERNALSYM _memcpy}
function _memcpy(s1: Pointer; const s2: Pointer; n: size_t): Pointer; cdecl;
{$EXTERNALSYM _memcmp}
function _memcmp(s1: Pointer; const s2: Pointer; n: size_t): Integer; cdecl;
{$EXTERNALSYM _strcpy}
function _strcpy(s1: PChar; const s2: PChar): PChar; cdecl;
{$EXTERNALSYM _strlen}
function _strlen(const s: PChar): size_t; cdecl;
{$EXTERNALSYM _strcmp}
function _strcmp(const s1, s2: PChar): Integer; cdecl;
{$EXTERNALSYM _strncmp}
function _strncmp(const s1, s2: PChar; n: size_t): Integer; cdecl;
{$EXTERNALSYM _strncpy}
function _strncpy(s1: PChar; const s2: PChar; n: size_t): PChar; cdecl;
{$EXTERNALSYM _sscanf}
function _sscanf(const s, format: PChar): Integer; cdecl; varargs;
{$EXTERNALSYM _sprintf}
function _sprintf(s: PChar; const format: PChar): Integer; cdecl; varargs;
{$EXTERNALSYM _mktime}
function _mktime(timeptr: ptm): Integer; cdecl;
{$EXTERNALSYM _localtime}
function _localtime(const timer: Integer): ptm; cdecl;
{$EXTERNALSYM _srand}
procedure _srand(seed: Integer); cdecl;
{$EXTERNALSYM _rand}
function _rand(): Integer; cdecl;
{$EXTERNALSYM __ltoupper}
function __ltoupper(seed: Integer): Integer; cdecl;
implementation
const
msvcrtdll = 'msvcrt.dll';
hiddll = 'HID.DLL';
setupapidll = 'SETUPAPI.DLL';
//et functions
{$LINK 'ET_Delphi.obj'} //链接外部OBJ文件
function et_FindToken; external;
function et_OpenToken; external;
function et_CloseToken; external;
function et_Read; external;
function et_Write; external;
function et_GenPID; external;
function et_GenRandom; external;
function et_GenSOPIN; external;
function et_ResetPIN; external;
function et_SetKey; external;
function et_HMAC_MD5; external;
function et_Verify; external;
function et_ChangeUserPIN; external;
function et_ResetSecurityState; external;
function et_GetSN; external;
function et_SetupToken; external;
function et_TurnOnLED; external;
function et_TurnOffLED; external;
function MD5_HMAC; external;
//hid function
function HidD_FreePreparsedData; external hiddll name 'HidD_FreePreparsedData';
function HidP_GetCaps; external hiddll name 'HidP_GetCaps';
function HidD_GetPreparsedData; external hiddll name 'HidD_GetPreparsedData';
function HidD_SetFeature; external hiddll name 'HidD_SetFeature';
function HidD_GetFeature; external hiddll name 'HidD_GetFeature';
function HidD_FlushQueue; external hiddll name 'HidD_FlushQueue';
function HidD_GetSerialNumberString; external hiddll name 'HidD_GetSerialNumberString';
function HidD_GetProductString; external hiddll name 'HidD_GetProductString';
function HidD_GetAttributes; external hiddll name 'HidD_GetAttributes';
function HidD_GetHidGuid; external hiddll name 'HidD_GetHidGuid';
function HidD_GetManufacturerString; external hiddll name 'HidD_GetManufacturerString';
//setupapi function
function SetupDiDestroyDeviceInfoList; external setupapidll name 'SetupDiDestroyDeviceInfoList';
function SetupDiGetDeviceInterfaceDetailA; external setupapidll name 'SetupDiGetDeviceInterfaceDetailA';
function SetupDiEnumDeviceInterfaces; external setupapidll name 'SetupDiEnumDeviceInterfaces';
function SetupDiGetClassDevsA; external setupapidll name 'SetupDiGetClassDevsA';
//msvcrt function
function _memset; external msvcrtdll name 'memset';
function _memcpy; external msvcrtdll name 'memcpy';
function _memcmp; external msvcrtdll name 'memcmp';
function _strcpy; external msvcrtdll name 'strcpy';
function _strlen; external msvcrtdll name 'strlen';
function _strcmp; external msvcrtdll name 'strcmp';
function _strncmp; external msvcrtdll name 'strncmp';
function _strncpy; external msvcrtdll name 'strncpy';
function _sscanf; external msvcrtdll name 'sscanf';
function _sprintf; external msvcrtdll name 'sprintf';
function _mktime; external msvcrtdll name 'mktime';
function _localtime; external msvcrtdll name 'localtime';
procedure _srand; external msvcrtdll name 'srand';
function _rand; external msvcrtdll name 'rand';
function __ltoupper; external msvcrtdll name 'toupper';
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela Cadastro de Horários para o Ponto Eletrônico
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (alberteije@gmail.com)
@version 2.0
******************************************************************************* }
unit UPontoHorario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids,
DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, PontoHorarioVO,
PontoHorarioController, Tipos, Atributos, Constantes, LabeledCtrls, Mask,
JvExMask, JvToolEdit, JvBaseEdits, StrUtils, Controller;
type
[TFormDescription(TConstantes.MODULO_PONTO_ELETRONICO, 'Ponto Horário')]
TFPontoHorario = class(TFTelaCadastro)
BevelEdits: TBevel;
EditCargaHoraria: TLabeledMaskEdit;
ComboboxTipo: TLabeledComboBox;
EditCodigo: TLabeledEdit;
EditNome: TLabeledEdit;
ComboboxTipoTrabalho: TLabeledComboBox;
GroupBoxRegistros: TGroupBox;
EditEntrada01: TLabeledMaskEdit;
EditEntrada02: TLabeledMaskEdit;
EditEntrada03: TLabeledMaskEdit;
EditEntrada04: TLabeledMaskEdit;
EditEntrada05: TLabeledMaskEdit;
EditSaida01: TLabeledMaskEdit;
EditSaida02: TLabeledMaskEdit;
EditSaida03: TLabeledMaskEdit;
EditSaida04: TLabeledMaskEdit;
EditSaida05: TLabeledMaskEdit;
EditHoraInicioJornada: TLabeledMaskEdit;
EditHoraFimJornada: TLabeledMaskEdit;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
// Controles CRUD
function DoInserir: Boolean; override;
function DoEditar: Boolean; override;
function DoExcluir: Boolean; override;
function DoSalvar: Boolean; override;
end;
var
FPontoHorario: TFPontoHorario;
implementation
{$R *.dfm}
{$REGION 'Infra'}
procedure TFPontoHorario.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TPontoHorarioVO;
ObjetoController := TPontoHorarioController.Create;
inherited;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFPontoHorario.DoInserir: Boolean;
begin
Result := inherited DoInserir;
if Result then
begin
ComboboxTipo.SetFocus;
end;
end;
function TFPontoHorario.DoEditar: Boolean;
begin
Result := inherited DoEditar;
if Result then
begin
ComboboxTipo.SetFocus;
end;
end;
function TFPontoHorario.DoExcluir: Boolean;
begin
if inherited DoExcluir then
begin
try
TController.ExecutarMetodo('PontoHorarioController.TPontoHorarioController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean');
Result := TController.RetornoBoolean;
except
Result := False;
end;
end
else
begin
Result := False;
end;
if Result then
TController.ExecutarMetodo('PontoHorarioController.TPontoHorarioController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
end;
function TFPontoHorario.DoSalvar: Boolean;
begin
Result := inherited DoSalvar;
if Result then
begin
try
if not Assigned(ObjetoVO) then
ObjetoVO := TPontoHorarioVO.Create;
TPontoHorarioVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id;
TPontoHorarioVO(ObjetoVO).Tipo := Copy(ComboboxTipo.Text, 1, 1);
TPontoHorarioVO(ObjetoVO).Codigo := EditCodigo.Text;
TPontoHorarioVO(ObjetoVO).Nome := EditNome.Text;
TPontoHorarioVO(ObjetoVO).TipoTrabalho := Copy(ComboboxTipoTrabalho.Text, 1, 1);
TPontoHorarioVO(ObjetoVO).CargaHoraria := EditCargaHoraria.Text;
TPontoHorarioVO(ObjetoVO).Entrada01 := EditEntrada01.Text;
TPontoHorarioVO(ObjetoVO).Entrada02 := EditEntrada02.Text;
TPontoHorarioVO(ObjetoVO).Entrada03 := EditEntrada03.Text;
TPontoHorarioVO(ObjetoVO).Entrada04 := EditEntrada04.Text;
TPontoHorarioVO(ObjetoVO).Entrada05 := EditEntrada05.Text;
TPontoHorarioVO(ObjetoVO).Saida01 := EditSaida01.Text;
TPontoHorarioVO(ObjetoVO).Saida02 := EditSaida02.Text;
TPontoHorarioVO(ObjetoVO).Saida03 := EditSaida03.Text;
TPontoHorarioVO(ObjetoVO).Saida04 := EditSaida04.Text;
TPontoHorarioVO(ObjetoVO).Saida05 := EditSaida05.Text;
TPontoHorarioVO(ObjetoVO).HoraInicioJornada := EditHoraInicioJornada.Text;
TPontoHorarioVO(ObjetoVO).HoraFimJornada := EditHoraFimJornada.Text;
if StatusTela = stInserindo then
begin
TController.ExecutarMetodo('PontoHorarioController.TPontoHorarioController', 'Insere', [TPontoHorarioVO(ObjetoVO)], 'PUT', 'Lista');
end
else if StatusTela = stEditando then
begin
if TPontoHorarioVO(ObjetoVO).ToJSONString <> StringObjetoOld then
begin
TController.ExecutarMetodo('PontoHorarioController.TPontoHorarioController', 'Altera', [TPontoHorarioVO(ObjetoVO)], 'POST', 'Boolean');
end
else
Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
end;
except
Result := False;
end;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFPontoHorario.GridParaEdits;
begin
inherited;
if not CDSGrid.IsEmpty then
begin
ObjetoVO := TPontoHorarioVO(TController.BuscarObjeto('PontoHorarioController.TPontoHorarioController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET'));
end;
if Assigned(ObjetoVO) then
begin
case AnsiIndexStr(TPontoHorarioVO(ObjetoVO).Tipo, ['F', 'D', 'S', 'M']) of
0:
ComboboxTipo.ItemIndex := 0;
1:
ComboboxTipo.ItemIndex := 1;
2:
ComboboxTipo.ItemIndex := 2;
3:
ComboboxTipo.ItemIndex := 3;
end;
EditCodigo.Text := TPontoHorarioVO(ObjetoVO).Codigo;
EditNome.Text := TPontoHorarioVO(ObjetoVO).Nome;
case AnsiIndexStr(TPontoHorarioVO(ObjetoVO).TipoTrabalho, ['N', 'C', 'F']) of
0:
ComboboxTipoTrabalho.ItemIndex := 0;
1:
ComboboxTipoTrabalho.ItemIndex := 1;
2:
ComboboxTipoTrabalho.ItemIndex := 2;
end;
EditCargaHoraria.Text := TPontoHorarioVO(ObjetoVO).CargaHoraria;
EditEntrada01.Text := TPontoHorarioVO(ObjetoVO).Entrada01;
EditEntrada02.Text := TPontoHorarioVO(ObjetoVO).Entrada02;
EditEntrada03.Text := TPontoHorarioVO(ObjetoVO).Entrada03;
EditEntrada04.Text := TPontoHorarioVO(ObjetoVO).Entrada04;
EditEntrada05.Text := TPontoHorarioVO(ObjetoVO).Entrada05;
EditSaida01.Text := TPontoHorarioVO(ObjetoVO).Saida01;
EditSaida02.Text := TPontoHorarioVO(ObjetoVO).Saida02;
EditSaida03.Text := TPontoHorarioVO(ObjetoVO).Saida03;
EditSaida04.Text := TPontoHorarioVO(ObjetoVO).Saida04;
EditSaida05.Text := TPontoHorarioVO(ObjetoVO).Saida05;
EditHoraInicioJornada.Text := TPontoHorarioVO(ObjetoVO).HoraInicioJornada;
EditHoraFimJornada.Text := TPontoHorarioVO(ObjetoVO).HoraFimJornada;
// Serializa o objeto para consultar posteriormente se houve alterações
FormatSettings.DecimalSeparator := '.';
StringObjetoOld := ObjetoVO.ToJSONString;
FormatSettings.DecimalSeparator := ',';
end;
end;
{$ENDREGION}
end.
|
unit crpFileUtility;
{written by Charles Richard Peterson, 2007; You can reach me at
www.houseofdexter.com or houseofdexter@gmail.com; The code is released under
Mozilla Public License 1.1 (MPL 1.1); }
interface
uses
SysUtils;
type
TcrpFileUtility = class(TObject)
public
class function ExtractName(aFileName: string): string;
class function FullDirectory(aDirectory: string): string;
class function FullFileName(aDirectory: string; aFilename: string; aExtension: string): string;
class function ExeDirectory(aExeName: string): string;
end;
implementation
{ TcrpFileUtility }
{______________________________________________________________________________}
class function TcrpFileUtility.ExtractName(aFileName: string): string;
begin
Result := ExtractFileName(aFileName);
if Pos('.', Result) <> 0 then
Result := Copy(Result, 1, POS('.', Result) -1);
end;
class function TcrpFileUtility.FullDirectory(aDirectory: string): string;
begin
Result := IncludeTrailingPathDelimiter(aDirectory);
end;
class function TcrpFileUtility.FullFileName(aDirectory: string;
aFilename: string; aExtension: string): string;
begin
Result := FullDirectory(aDirectory) + aFileName + aExtension;
end;
class function TcrpFileUtility.ExeDirectory(aExeName: string): string;
begin
Result := FullDirectory(ExtractFilePath(aExeName));
end;
end.
|
unit SimpleMap;
interface
uses
SysUtils, Contnrs;
type
TObjectMap = class
private
keySet: array of string;
objectList: TObjectList;
size: integer;
count: integer;
procedure grow();
function indexOfKey(const key: string): integer;
public
constructor create();
destructor destroy(); override;
procedure clear();
procedure put(key: string; value: TObject);
function get(key: string): TObject;
end;
implementation
{ TObjectMap }
procedure TObjectMap.clear;
begin
size := 0;
count := 0;
setLength(keySet, size);
objectList.clear;
end;
constructor TObjectMap.Create;
begin
inherited;
size := 0;
count := 0;
objectList := TObjectList.create;
end;
destructor TObjectMap.Destroy;
begin
size := 0;
setLength(keySet, size);
objectList.free;
inherited;
end;
function TObjectMap.get(key: string): TObject;
var
keyIndex: integer;
begin
keyIndex := indexOfKey(key);
if keyIndex = -1 then
result := nil
else
result := objectList.Items[keyIndex];
end;
procedure TObjectMap.grow;
begin
size := size + 4;
setLength(keySet, size);
end;
function TObjectMap.indexOfKey(const key: string): integer;
var
keyLoop: integer;
begin
result := -1;
for keyLoop := 0 to (count - 1) do
begin
if ( compareText(keySet[keyLoop], key) = 0 ) then begin
result := keyLoop;
break;
end;
end;
end;
procedure TObjectMap.put(key: string; value: TObject);
var
old: TObject;
oldIndex: integer;
begin
old := get(key);
if (old = nil) then begin
if (count = size) then grow;
keySet[count] := key;
objectList.add(value);
inc(count);
end else begin
oldIndex := indexOfKey(key);
objectList.Items[oldIndex] := value;
end;
end;
end.
|
{
Adjust the height of cells of a region.
What is adjusted:
- landscape records
- temporary cells references
- persistent worldspace references belonging to region cells; if they are referenced by
any teleportation doors then teleport positions are also updated accordinly
- water height in cells
What is not adjusted:
- navmeshes and pathgrids, they are deleted if bRemoveNavmeshes = True
Apply to plugin. All games are supported from Oblivion to Fallout 4.
}
unit WorldspaceRegionChangeHeight;
const
// remove navmeshes, pathgrids and other records from the moved cells
bRemoveNavmeshes = True;
CellSize = 4096;
sRefSignatures = 'REFR,ACHR,PGRE,PMIS,PHZD,PARW,PBAR,PBEA,PCON,PFLA';
var
Plugin, Worldspace, Region: IInterface;
AddPosZ: Double;
slCells: THashedStringList;
//============================================================================
// get persistent cell record of a worldspace
function GetWorldspacePersistentCell(Worldspace: IInterface): IInterface;
begin
Result := ElementByIndex(ChildGroup(Worldspace), 0);
if Signature(Result) <> 'CELL' then
Result := nil;
end;
//============================================================================
// adjust the height of a cell including it's children records
function AdjustCellHeight(cell: IInterface; h: Double): Boolean;
var
ChildRefs, r: IInterface;
i, GroupType: integer;
begin
Result := True;
AddMessage(Format('Updating cell %s', [Name(cell)]));
// update CELL water height
if ElementExists(cell, 'XCLW') then
if GetElementEditValues(cell, 'XCLW') <> 'Default' then
SetElementNativeValues(cell, 'XCLW', GetElementNativeValues(cell, 'XCLW') + h);
// update CELL max height data offset
if ElementExists(cell, 'MHDT') then
SetElementNativeValues(cell, 'MHDT\Offset', GetElementNativeValues(cell, 'MHDT\Offset') + h);
// adjust child records
// process CELL child groups: 8 - temporary, 9 - persistent, 10 - vwd
for GroupType := 8 to 10 do begin
ChildRefs := FindChildGroup(ChildGroup(cell), GroupType, cell);
for i := Pred(ElementCount(ChildRefs)) downto 0 do begin
r := ElementByIndex(ChildRefs, i);
// update references position
if Pos(Signature(r), sRefSignatures) <> 0 then
SetElementNativeValues(r, 'DATA\Position\Z', GetElementNativeValues(r, 'DATA\Position\X') + h)
// update the offset height of landscape
else if Signature(r) = 'LAND' then
SetElementNativeValues(r, 'VHGT\Offset', GetElementNativeValues(r, 'VHGT\Offset') + h/8)
// remove everything else (navmeshes, pathgrids, etc.)
else if bRemoveNavmeshes then begin
AddMessage(#9'Removing ' + Name(r));
RemoveNode(r);
end;
end;
end;
end;
//============================================================================
function Process(e: IInterface): integer;
var
i, j, x, y: integer;
refs, cell, entries, r, rref: IInterface;
grid: TwbGridCell;
begin
Result := 1;
if wbSimpleRecords then begin
MessageDlg('Uncheck "Simple records" in xEdit options and restart', mtInformation, [mbOk], 0);
Result := 1;
Exit;
end;
Plugin := GetFile(e);
if ContainerStates(Plugin) and (1 shl csRefsBuild) = 0 then begin
MessageDlg(Format('References are not built for "%s". Please use right click "Other\Build Reference Info" menu of %sEdit', [
GetFileName(Plugin),
wbAppName
]), mtInformation, [mbOk], 0);
Exit;
end;
if not OptionsForm then begin
AddMessage('Region was not selected!');
Exit;
end;
//Exit;
slCells := THashedStringList.Create;
AddMessage(#13#10'*** Building list of cells to adjust ***');
// list of cells referencing our region (cells to be adjusted)
for i := 0 to Pred(ReferencedByCount(Region)) do begin
cell := ReferencedByIndex(Region, i);
if Signature(cell) <> 'CELL' then
Continue;
// ensure they are indeed referenced by cell's regions list and not by something else
entries := ElementBySignature(cell, 'XCLR');
for j := 0 to Pred(ElementCount(entries)) do
if GetLoadOrderFormID(LinksTo(ElementByIndex(entries, j))) = GetLoadOrderFormID(Region) then begin
slCells.AddObject(GetElementEditValues(cell, 'XCLC\X') + ',' + GetElementEditValues(cell, 'XCLC\Y'), cell);
Break;
end;
end;
AddMessage(IntToStr(slCells.Count) + ' cells found in region ' + Name(Region));
// adjust cells
AddMessage(#13#10'*** Adjust cells landscape and temporary references ***');
for i := 0 to Pred(slCells.Count) do begin
cell := ObjectToElement(slCells.Objects[i]);
if not AdjustCellHeight(cell, AddPosZ) then
Exit;
end;
// update position of worldspace persistent refs located in region cells
AddMessage(#13#10'*** Adjusting persistent references ***');
refs := GetWorldspacePersistentCell(Worldspace);
refs := FindChildGroup(ChildGroup(refs), 8, refs); // get Persistent group of cell
for i := 0 to Pred(ElementCount(refs)) do begin
r := ElementByIndex(refs, i);
// convert absolute position to X,Y cells grid coordinates
grid := wbPositionToGridCell(GetPosition(r));
// skips refs not belonging to region cells
if slCells.IndexOf(IntToStr(grid.X) + ',' + IntToStr(grid.Y)) = -1 then
Continue;
// update ref position
SetElementNativeValues(r, 'DATA\Position\Z', GetElementNativeValues(r, 'DATA\Position\Z') + AddPosZ);
// if moved persistent ref is referenced by a DOOR with teleport data then update it
for j := 0 to Pred(ReferencedByCount(r)) do begin
rref := ReferencedByIndex(r, j);
// check DOORs only
if Signature(BaseRecord(rref)) <> 'DOOR' then
Continue;
// update if teleport is linked to the moved persistent ref
if GetElementEditValues(rref, 'XTEL\Door') = Name(r) then begin
SetElementNativeValues(rref, 'XTEL\Position/Rotation\Position\Z', GetElementNativeValues(rref, 'XTEL\Position/Rotation\Position\X') + AddPosZ);
// if we removed navmeshes, then also remove navmesh ref from door
if bRemoveNavmeshes then
RemoveElement(rref, 'XNDP');
AddMessage('Updated teleport position on ' + Name(rref));
end;
end;
end;
slCells.Free;
end;
//============================================================================
// fill regions list when worldspace is selected
procedure WorldspaceSelect(Sender: TObject);
var
cmbWorldspace, cmbRegion: TComboBox;
g, e: IInterface;
i: integer;
sl: TStringList;
begin
cmbWorldspace := TComboBox(Sender);
Worldspace := ObjectToElement(cmbWorldspace.Items.Objects[cmbWorldspace.ItemIndex]);
cmbRegion := TComboBox(TForm(cmbWorldspace.Parent).FindComponent('Region'));
sl := TStringList.Create;
g := GroupBySignature(Plugin, 'REGN');
for i := 0 to Pred(ElementCount(g)) do begin
e := ElementByIndex(g, i);
if (GetElementEditValues(e, 'WNAM') = Name(Worldspace)) and ElementExists(e, 'Region Areas') then
sl.AddObject(EditorID(e), e);
end;
sl.Sort;
cmbRegion.Items.Assign(sl);
if sl.Count <> 0 then cmbRegion.ItemIndex := 0;
sl.Free;
end;
//============================================================================
function OptionsForm: Boolean;
var
g, e: IInterface;
i: integer;
sl: TStringList;
frm: TForm;
btnOk, btnCancel: TButton;
cmbWorldspace, cmbRegion: TComboBox;
edZ: TEdit;
lbl: TLabel;
begin
frm := TForm.Create(nil);
try
frm.Caption := 'Adjust the height of worldspace region';
frm.Width := 400;
frm.Height := 250;
frm.Position := poMainFormCenter;
cmbWorldspace := TComboBox.Create(frm); cmbWorldspace.Parent := frm;
cmbWorldspace.Left := 12;
cmbWorldspace.Top := 32;
cmbWorldspace.Width := frm.Width - 40;
cmbWorldspace.Style := csDropDownList;
cmbWorldspace.DropDownCount := 20;
cmbWorldspace.OnSelect := WorldspaceSelect;
lbl := TLabel.Create(frm); lbl.Parent := frm;
lbl.Top := cmbWorldspace.Top - 18;
lbl.Left := cmbWorldspace.Left;
lbl.Caption := 'Worldspace';
sl := TStringList.Create;
g := GroupBySignature(Plugin, 'WRLD');
for i := 0 to Pred(ElementCount(g)) do begin
e := ElementByIndex(g, i);
if Signature(e) = 'WRLD' then
sl.AddObject(EditorID(e), e);
end;
sl.Sort;
cmbWorldspace.Items.Assign(sl);
sl.Free;
cmbRegion := TComboBox.Create(frm); cmbRegion.Parent := frm;
cmbRegion.Name := 'Region';
cmbRegion.Left := cmbWorldspace.Left;
cmbRegion.Top := cmbWorldspace.Top + 48;
cmbRegion.Width := cmbWorldspace.Width;
cmbRegion.Style := csDropDownList;
cmbRegion.DropDownCount := 20;
lbl := TLabel.Create(frm); lbl.Parent := frm;
lbl.Top := cmbRegion.Top - 18;
lbl.Left := cmbRegion.Left;
lbl.Caption := 'Region';
edZ := TEdit.Create(frm); edZ.Parent := frm;
edZ.Left := cmbWorldspace.Left;
edZ.Top := cmbRegion.Top + 48;
edZ.Width := 60;
edZ.Text := '32';
lbl := TLabel.Create(frm); lbl.Parent := frm;
lbl.Top := edZ.Top - 18;
lbl.Left := edZ.Left;
lbl.Caption := 'Height adjustment (positive or negative, divisible by 8)';
btnOk := TButton.Create(frm); btnOk.Parent := frm;
btnOk.Top := frm.Height - 70;
btnOk.Left := frm.Width - 220;
btnOk.Width := 90;
btnOk.Caption := 'OK';
btnOk.ModalResult := mrOk;
btnCancel := TButton.Create(frm); btnCancel.Parent := frm;
btnCancel.Top := frm.Height - 70;
btnCancel.Left := frm.Width - 120;
btnCancel.Width := 90;
btnCancel.Caption := 'Cancel';
btnCancel.ModalResult := mrCancel;
if cmbWorldspace.Items.Count <> 0 then begin
cmbWorldspace.ItemIndex := 0;
WorldspaceSelect(cmbWorldspace);
end;
if frm.ShowModal <> mrOk then
Exit;
if cmbRegion.ItemIndex = -1 then
Exit;
Region := ObjectToElement(cmbRegion.Items.Objects[cmbRegion.ItemIndex]);
AddPosZ := StrToInt(edZ.Text);
if AddPosZ mod 8 <> 0 then
AddMessage('Height is not divisible by 8 !!!')
else
Result := True;
finally
frm.Free;
end;
end;
end.
|
{$include kode.inc}
unit syn_thetic_waveform;
{
phase in -> blep out
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
syn_thetic_phase;
const
waveform_type_off = 0;
waveform_type_const = 1;
waveform_type_input = 2;
waveform_type_prev = 3;
waveform_type_sin = 4;
waveform_type_saw_naive = 5;
waveform_type_saw_urs = 6;
waveform_type_saw_eptr = 7;
waveform_type_saw_dpw = 8;
waveform_type_saw_dpw2 = 9;
waveform_type_saw_dpw3 = 10;
waveform_type_saw_polyblep = 11;
waveform_type_saw_sinc = 12;
waveform_type_squ_naive = 13;
waveform_type_squ_polyblep = 14;
waveform_type_tri_naive = 15;
waveform_type_tri_polyblep = 16;
waveform_type_ramp_naive = 17;
waveform_type_noise = 18;
waveform_type_count = 19;
waveform_names : array[0..waveform_type_count-1] of PChar = (
'off',
'const',
'input',
'prev',
'sin',
'saw_naive',
'saw_urs',
'saw_eptr',
'saw_dpw',
'saw_dpw2',
'saw_dpw3',
'saw_polyblep',
'saw_sinc',
'squ_naive',
'squ_polyblep',
'tri_naive',
'tri_polyblep',
'ramp_naive',
'noise'
);
type
Synthetic_Waveform = class
private
FType : LongInt;
x1,x2 : single;
public
constructor create;
destructor destroy; override;
procedure setType(AType:LongInt);
function process(APhase:Synthetic_Phase; AInput:Single=0) : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
kode_random,
kode_osc_naive,
kode_osc_polyblep,
kode_osc_dpw,
kode_osc_eptr,
//kode_osc_urs,
kode_osc_sinc;
//----------
constructor Synthetic_Waveform.create;
begin
inherited;
FType := waveform_type_off;
x1 := 0;
x2 := 0;
end;
//----------
destructor Synthetic_Waveform.destroy;
begin
inherited;
end;
//----------
procedure Synthetic_Waveform.setType(AType:LongInt);
begin
FType := AType;
x1 := 0;
x2 := 0;
end;
//----------------------------------------
// osc
//----------------------------------------
function Synthetic_Waveform.process(APhase:Synthetic_Phase; AInput:Single=0) : Single;
var
t,dt : single;
begin
result := 0;
t := APhase.getPhase;
dt := APhase.getPhaseAdd;
case FType of
waveform_type_off: result := 0;
waveform_type_const: result := 1;
waveform_type_input: result := AInput;
waveform_type_prev: result := 0;
waveform_type_sin: result := KOsc_Sin_Naive(t);
waveform_type_saw_naive: result := KOsc_Saw_Naive(t);
waveform_type_saw_urs: result := 0;//KOsc_Saw_Urs(t,x1,x2);
waveform_type_saw_eptr: result := KOsc_Saw_EPTR(t,dt);
waveform_type_saw_dpw: result := KOsc_Saw_DPW(t,dt,x1);
waveform_type_saw_dpw2: result := KOsc_Saw_DPW2(t,dt,x1);
waveform_type_saw_dpw3: result := KOsc_Saw_DPW3(t,dt,x1,x2);
waveform_type_saw_polyblep: result := KOsc_Saw_PolyBlep(t,dt);
waveform_type_saw_sinc: result := KOsc_Saw_Sinc(t,dt); // doesn't work
waveform_type_squ_naive: result := KOsc_Squ_Naive(t);
waveform_type_squ_polyblep: result := KOsc_Squ_PolyBlep(t,dt);
waveform_type_tri_naive: result := KOsc_Tri_Naive(t);
waveform_type_tri_polyblep: result := KOsc_Tri_PolyBlep(t,dt,x1);
waveform_type_ramp_naive: result := KOsc_Ramp_Naive(t);
waveform_type_noise: result := KRandomSigned;
end;
end;
//----------------------------------------------------------------------
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene3D.Renderer.Passes.AntialiasingNoneRenderPass;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.FrameGraph,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Instance;
type { TpvScene3DRendererPassesAntialiasingNoneRenderPass }
TpvScene3DRendererPassesAntialiasingNoneRenderPass=class(TpvFrameGraph.TRenderPass)
private
fInstance:TpvScene3DRendererInstance;
fVulkanRenderPass:TpvVulkanRenderPass;
fResourceColor:TpvFrameGraph.TPass.TUsedImageResource;
fResourceSurface:TpvFrameGraph.TPass.TUsedImageResource;
fVulkanTransferCommandBuffer:TpvVulkanCommandBuffer;
fVulkanTransferCommandBufferFence:TpvVulkanFence;
fVulkanVertexShaderModule:TpvVulkanShaderModule;
fVulkanFragmentShaderModule:TpvVulkanShaderModule;
fVulkanPipelineShaderStageVertex:TpvVulkanPipelineShaderStage;
fVulkanPipelineShaderStageFragment:TpvVulkanPipelineShaderStage;
fVulkanGraphicsPipeline:TpvVulkanGraphicsPipeline;
fVulkanSampler:TpvVulkanSampler;
fVulkanDescriptorPool:TpvVulkanDescriptorPool;
fVulkanDescriptorSetLayout:TpvVulkanDescriptorSetLayout;
fVulkanImageViews:array[0..MaxInFlightFrames-1] of TpvVulkanImageView;
fVulkanDescriptorSets:array[0..MaxInFlightFrames-1] of TpvVulkanDescriptorSet;
fVulkanPipelineLayout:TpvVulkanPipelineLayout;
public
constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce;
destructor Destroy; override;
procedure AcquirePersistentResources; override;
procedure ReleasePersistentResources; override;
procedure AcquireVolatileResources; override;
procedure ReleaseVolatileResources; override;
procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override;
procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override;
end;
implementation
{ TpvScene3DRendererPassesAntialiasingNoneRenderPass }
constructor TpvScene3DRendererPassesAntialiasingNoneRenderPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance);
begin
inherited Create(aFrameGraph);
fInstance:=aInstance;
Name:='AntialiasingNoneRenderPass';
MultiviewMask:=fInstance.SurfaceMultiviewMask;
Queue:=aFrameGraph.UniversalQueue;
//SeparatePhysicalPass:=true;
//SeparateCommandBuffer:=true;
Size:=TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,
1.0,
1.0,
1.0,
fInstance.CountSurfaceViews);
fResourceColor:=AddImageInput('resourcetype_color_tonemapping',
'resource_tonemapping_color',
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
fResourceSurface:=AddImageOutput('resourcetype_color_antialiasing',
'resource_antialiasing_color',
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear,
TpvVector4.InlineableCreate(0.0,0.0,0.0,1.0)),
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
fInstance.LastOutputResource:=fResourceSurface;
end;
destructor TpvScene3DRendererPassesAntialiasingNoneRenderPass.Destroy;
begin
inherited Destroy;
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.AcquirePersistentResources;
var Stream:TStream;
begin
inherited AcquirePersistentResources;
fVulkanTransferCommandBuffer:=TpvVulkanCommandBuffer.Create(FrameGraph.TransferQueue.CommandPool,VK_COMMAND_BUFFER_LEVEL_PRIMARY);
fVulkanTransferCommandBufferFence:=TpvVulkanFence.Create(fInstance.Renderer.VulkanDevice);
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('fullscreen_vert.spv');
try
fVulkanVertexShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('antialiasing_none_frag.spv');
try
fVulkanFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
fVulkanPipelineShaderStageVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fVulkanVertexShaderModule,'main');
fVulkanPipelineShaderStageFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fVulkanFragmentShaderModule,'main');
fVulkanGraphicsPipeline:=nil;
fVulkanSampler:=TpvVulkanSampler.Create(fInstance.Renderer.VulkanDevice,
TVkFilter.VK_FILTER_LINEAR,
TVkFilter.VK_FILTER_LINEAR,
TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_LINEAR,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
0.0,
false,
0.0,
false,
VK_COMPARE_OP_ALWAYS,
0.0,
0.0,
VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
false);
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.ReleasePersistentResources;
begin
FreeAndNil(fVulkanSampler);
FreeAndNil(fVulkanPipelineShaderStageVertex);
FreeAndNil(fVulkanPipelineShaderStageFragment);
FreeAndNil(fVulkanFragmentShaderModule);
FreeAndNil(fVulkanVertexShaderModule);
FreeAndNil(fVulkanTransferCommandBufferFence);
FreeAndNil(fVulkanTransferCommandBuffer);
inherited ReleasePersistentResources;
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.AcquireVolatileResources;
var InFlightFrameIndex:TpvSizeInt;
begin
inherited AcquireVolatileResources;
fVulkanRenderPass:=VulkanRenderPass;
fVulkanDescriptorPool:=TpvVulkanDescriptorPool.Create(fInstance.Renderer.VulkanDevice,
TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT),
fInstance.Renderer.CountInFlightFrames);
fVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,fInstance.Renderer.CountInFlightFrames);
fVulkanDescriptorPool.Initialize;
fVulkanDescriptorSetLayout:=TpvVulkanDescriptorSetLayout.Create(fInstance.Renderer.VulkanDevice);
fVulkanDescriptorSetLayout.AddBinding(0,
VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fVulkanDescriptorSetLayout.Initialize;
for InFlightFrameIndex:=0 to FrameGraph.CountInFlightFrames-1 do begin
fVulkanImageViews[InFlightFrameIndex]:=TpvVulkanImageView.Create(fInstance.Renderer.VulkanDevice,
fResourceColor.VulkanImages[InFlightFrameIndex],
VK_IMAGE_VIEW_TYPE_2D_ARRAY,
TpvFrameGraph.TImageResourceType(fResourceColor.ResourceType).Format,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
1,
0,
fInstance.CountSurfaceViews
);
fVulkanDescriptorSets[InFlightFrameIndex]:=TpvVulkanDescriptorSet.Create(fVulkanDescriptorPool,
fVulkanDescriptorSetLayout);
fVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(0,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT),
[TVkDescriptorImageInfo.Create(VK_NULL_HANDLE,//fVulkanSampler.Handle,
fResourceColor.VulkanImageViews[InFlightFrameIndex].Handle,
fResourceColor.ResourceTransition.Layout)],// TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))],
[],
[],
false
);
fVulkanDescriptorSets[InFlightFrameIndex].Flush;
end;
fVulkanPipelineLayout:=TpvVulkanPipelineLayout.Create(fInstance.Renderer.VulkanDevice);
fVulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetLayout);
fVulkanPipelineLayout.Initialize;
fVulkanGraphicsPipeline:=TpvVulkanGraphicsPipeline.Create(fInstance.Renderer.VulkanDevice,
fInstance.Renderer.VulkanPipelineCache,
0,
[],
fVulkanPipelineLayout,
fVulkanRenderPass,
VulkanRenderPassSubpassIndex,
nil,
0);
fVulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageVertex);
fVulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageFragment);
fVulkanGraphicsPipeline.InputAssemblyState.Topology:=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
fVulkanGraphicsPipeline.InputAssemblyState.PrimitiveRestartEnable:=false;
fVulkanGraphicsPipeline.ViewPortState.AddViewPort(0.0,0.0,fInstance.Width,fInstance.Height,0.0,1.0);
fVulkanGraphicsPipeline.ViewPortState.AddScissor(0,0,fInstance.Width,fInstance.Height);
fVulkanGraphicsPipeline.RasterizationState.DepthClampEnable:=false;
fVulkanGraphicsPipeline.RasterizationState.RasterizerDiscardEnable:=false;
fVulkanGraphicsPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL;
fVulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE);
fVulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_CLOCKWISE;
fVulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=false;
fVulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.0;
fVulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0;
fVulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0;
fVulkanGraphicsPipeline.RasterizationState.LineWidth:=1.0;
fVulkanGraphicsPipeline.MultisampleState.RasterizationSamples:=VK_SAMPLE_COUNT_1_BIT;
fVulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=false;
fVulkanGraphicsPipeline.MultisampleState.MinSampleShading:=0.0;
fVulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0;
fVulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=false;
fVulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false;
fVulkanGraphicsPipeline.ColorBlendState.LogicOpEnable:=false;
fVulkanGraphicsPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY;
fVulkanGraphicsPipeline.ColorBlendState.BlendConstants[0]:=0.0;
fVulkanGraphicsPipeline.ColorBlendState.BlendConstants[1]:=0.0;
fVulkanGraphicsPipeline.ColorBlendState.BlendConstants[2]:=0.0;
fVulkanGraphicsPipeline.ColorBlendState.BlendConstants[3]:=0.0;
fVulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(false,
VK_BLEND_FACTOR_SRC_ALPHA,
VK_BLEND_FACTOR_DST_ALPHA,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
fVulkanGraphicsPipeline.DepthStencilState.DepthTestEnable:=true;
fVulkanGraphicsPipeline.DepthStencilState.DepthWriteEnable:=true;
fVulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_ALWAYS;
fVulkanGraphicsPipeline.DepthStencilState.DepthBoundsTestEnable:=false;
fVulkanGraphicsPipeline.DepthStencilState.StencilTestEnable:=false;
fVulkanGraphicsPipeline.Initialize;
fVulkanGraphicsPipeline.FreeMemory;
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.ReleaseVolatileResources;
var InFlightFrameIndex:TpvSizeInt;
begin
FreeAndNil(fVulkanGraphicsPipeline);
FreeAndNil(fVulkanPipelineLayout);
for InFlightFrameIndex:=0 to FrameGraph.CountInFlightFrames-1 do begin
FreeAndNil(fVulkanDescriptorSets[InFlightFrameIndex]);
FreeAndNil(fVulkanImageViews[InFlightFrameIndex]);
end;
FreeAndNil(fVulkanDescriptorSetLayout);
FreeAndNil(fVulkanDescriptorPool);
fVulkanRenderPass:=nil;
inherited ReleaseVolatileResources;
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt);
begin
inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex);
end;
procedure TpvScene3DRendererPassesAntialiasingNoneRenderPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt);
begin
inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex);
aCommandBuffer.CmdBindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS,
fVulkanPipelineLayout.Handle,
0,
1,
@fVulkanDescriptorSets[aInFlightFrameIndex].Handle,0,nil);
aCommandBuffer.CmdBindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS,fVulkanGraphicsPipeline.Handle);
aCommandBuffer.CmdDraw(3,1,0,0);
end;
end.
|
unit uFrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TFrmMain = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
const
CON_INPUT_X = 800;
CON_INPUT_ACC_Y = 215;
CON_INPUT_PWD_Y = 240;
implementation
uses uWinIO;
{$R *.dfm}
function MsShowMessage(AMsg: string): Integer;
begin
//ClipCursor(nil);
Result := MessageBox(FrmMain.Handle, PWideChar(AMsg), '警告', MB_ICONWARNING);
end;
function fnForeWindow(AGameHandle: THandle): Boolean;
begin
ShowWindow(AGameHandle, SW_RESTORE);
Sleep(100);
Result := SetForegroundWindow(AGameHandle);
Sleep(100);
end;
function fnLeftClick(APoint: TPoint): Boolean;
begin
SetCursorPos(APoint.X, APoint.Y); //设置目的地位置。
Sleep(50);
mouse_event(MOUSEEVENTF_LEFTDOWN, APoint.X, APoint.Y, 0, GetMessageExtraInfo()); // 模拟按下鼠标左键。
Sleep(20);
mouse_event(MOUSEEVENTF_LEFTUP, APoint.X, APoint.Y, 0, GetMessageExtraInfo()); // 模拟放开鼠标左键。
end;
function fnDelText(): Boolean;
var
I: Integer;
begin
for I := 0 to 20 do
begin
Sleep(20);
uWinIO.MsKeyPress(VK_BACK);
end;
for I := 0 to 10 do
begin
Sleep(20);
uWinIO.MsKeyPress(VK_DELETE);
end;
end;
function fnGetColor(AHandle: THandle; APoint: TPoint): DWORD;
var
C : TColor;
DC : HDC;
begin
DC := GetDC(AHandle);
C := GetPixel(DC, APoint.x, APoint.y);
{$IFDEF DEBUG}
FrmMain.edit1.text := FORMAT('%.6x',[C]);
{$ENDIF}
Result := DWORD(C);
end;
function fnCheckWeGame(AGameHandle: THandle): Boolean;
const
CON_CHECK_COLOR = $393737;
var
hTmp, hEdit: HWND;
vPoint: TPoint;
dwColor1, dwColor2: DWORD;
begin
Result := False;
try
fnForeWindow(AGameHandle);
vPoint.X := CON_INPUT_X;
vPoint.Y := CON_INPUT_PWD_Y;
dwColor1 := fnGetColor(AGameHandle, vPoint); //-- 获取坐标点的颜色
vPoint.Y := CON_INPUT_ACC_Y;
dwColor2 := fnGetColor(AGameHandle, vPoint); //-- 获取坐标点的颜色
if (dwColor1 <> CON_CHECK_COLOR) or (dwColor2 <> CON_CHECK_COLOR) then
begin
MsShowMessage('请切换到账号输入页面, 再进行尝试!');
Exit;
end;
{$REGION '校验密码框'}
hTmp := FindWindowEx(AGameHandle, 0, 'Normal', '');
hEdit := FindWindowEx(hTmp, 0, 'Edit', '');
if not IsWindowVisible(hEdit) then
hEdit := FindWindowEx(hTmp, hEdit, 'Edit', '');
{$IFDEF DEBUG}
FrmMain.Edit1.Text := Format('%.8X', [hEdit]);
{$ENDIF}
if not IsWindow(hEdit) then
begin
MsShowMessage('没有切换到账号输入页面?');
Exit;
end;
if not IsWindowVisible(hEdit) then
begin
MsShowMessage('查找密码框失败, WeGame是否升级了?');
Exit;
end;
{$ENDREGION}
Result := True;
except
end;
end;
function fnLoginGame(AAccount: string; APassword: string): Boolean;
var
hGame: HWND;
vPoint: TPoint;
I: Integer;
cRect: TRect;
begin
Result := False;
cRect.Top := 0;
cRect.Left := 0;
cRect.Height := 5;
cRect.Width := 5;
ClipCursor(@cRect);
try
try
if AAccount.IsEmpty then
begin
MsShowMessage('账号不能为空');
Exit;
end;
if APassword.IsEmpty then
begin
MsShowMessage('密码不能为空');
Exit;
end;
// hGame := FindWindow('TWINCONTROL', 'WeGame');
//
// if not IsWindow(hGame) then
// begin
// MsShowMessage('请先启动WeGame');
// Exit
// end;
//
// if not fnCheckWeGame(hGame) then Exit;
//
// vPoint.X := CON_INPUT_X;
// vPoint.Y := CON_INPUT_ACC_Y;
//
// Winapi.Windows.ClientToScreen(hGame, vPoint);
// for I := 0 to 3 do
// begin
// Sleep(50);
// fnLeftClick(vPoint);
// end;
//--删除账号
fnDelText();
//--输入账号
uWinIO.IoPressPwd(AAccount);
//--光标切换至密码框
uWinIO.MsKeyPress(VK_TAB);
//--输入密码
uWinIO.IoPressPwd(APassword);
//--回车登录
uWinIO.MsKeyPress(VK_RETURN);
Result := True;
except
//---
end;
finally
ClipCursor(nil);
end;
end;
procedure TFrmMain.Button1Click(Sender: TObject);
begin
Sleep(3000);
//uWinIO.IoPressPwd('Aa09137320286');
fnLoginGame(Edit1.Text, Edit2.Text);
// TThread.Queue(nil,
// procedure
// begin
// fnLoginGame('275175822', 'Aa09137320286');
// end
// );
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
sAccount, sPassword: string;
begin
{$IFNDEF DEBUG}
try
Self.Visible := False;
if ParamCount < 2 then
begin
MsShowMessage('启动参数不正确');
Exit;
end;
sAccount := ParamStr(1);
sPassword := ParamStr(2);
fnLoginGame(sAccount, sPassword);
finally
Application.Terminate;
end;
{$ENDIF}
end;
end.
|
{*******************************************************}
{ }
{ NTS Code Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit NTS.Code.Graphics.Gradient;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils, System.Classes, Winapi.Windows, Vcl.Graphics;
{$ELSE}
Windows, SysUtils, Graphics, Classes;
{$ENDIF}
type
TGradientType = ( gtHorizontal, gtVertical, gtRainbow, gtCircle, gtltTopBottom, gtWindow );
TRGB = record
B,G,R: byte;
end;
ARGB = array [0..1] of TRGB;
PARGB = ^ARGB;
TGradientClass = class
Private
class procedure HGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
class procedure VGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
class procedure RGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
class procedure CGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
class procedure BGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
class procedure WGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
Public
class procedure Get(gType:TGradientType;Canvas: TCanvas; X1,Y1,X2,Y2: integer; Color1,Color2: TColor); OverLoad;
class procedure Get(gType:TGradientType;Canvas: TCanvas; gRect: TRect; Color1,Color2: TColor); OverLoad;
end;
implementation
{ TGradientClass }
class procedure TGradientClass.Get(gType: TGradientType; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
Bitmap: TBitmap;
begin
Bitmap:= TBitmap.Create;
Bitmap.PixelFormat:=pf24bit;
case gType of
gtHorizontal : HGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
gtVertical : VGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
gtRainbow : RGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
gtCircle : CGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
gtltTopBottom: BGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
gtWindow : WGradientRect(Bitmap, Canvas,X1,Y1,X2,Y2,Color1,Color2);
end;
Bitmap.Free;
end;
class procedure TGradientClass.Get(gType: TGradientType; Canvas: TCanvas; gRect: TRect; Color1, Color2: TColor);
begin
Get(gType,Canvas,gRect.Left,gRect.Top,gRect.Right,gRect.Bottom,Color1,Color2);
end;
class procedure TGradientClass.HGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
x, y, c1, c2, r1, g1, b1: integer;
dr, dg, db: real;
p: PARGB;
begin
Bitmap.Width:=abs(X1-X2);
Bitmap.Height:=abs(Y1-Y2);
c1:=ColorToRGB(Color1);
r1:=getRValue(c1);
g1:=getGValue(c1);
b1:=getBValue(c1);
c2:=ColorToRGB(Color2);
dr:=(getRValue(c2)-r1)/Bitmap.Width;
dg:=(getGValue(c2)-g1)/Bitmap.Width;
db:=(getBValue(c2)-b1)/Bitmap.Width;
for y:=0 to Bitmap.Height-1 do
begin
p:= Bitmap.ScanLine[y];
for x:=0 to Bitmap.Width-1 do
begin
p[x].R:=round(r1+x*dr);
p[x].G:=round(g1+x*dg);
p[x].B:=round(b1+x*db)
end
end;
Canvas.Draw(X1, Y1, Bitmap)
end;
class procedure TGradientClass.VGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
x, y, c1, c2, r1, g1, b1: integer;
dr, dg, db: real;
p: PARGB;
begin
Bitmap.Width:= abs(X1-X2);
Bitmap.Height:= abs(Y1-Y2);
c1:= ColorToRGB(Color1);
r1:= getRValue(c1);
g1:= getGValue(c1);
b1:= getBValue(c1);
c2:= ColorToRGB(Color2);
dr:= (getRValue(c2)-r1)/Bitmap.Height;
dg:= (getGValue(c2)-g1)/Bitmap.Height;
db:= (getBValue(c2)-b1)/Bitmap.Height;
for y:=0 to Bitmap.Height-1 do
begin
p:= Bitmap.ScanLine[y];
for x:=0 to Bitmap.Width-1 do
begin
p[x].R:= round(r1+y*dr);
p[x].G:= round(g1+y*dg);
p[x].B:= round(b1+y*db)
end
end;
Canvas.Draw(X1, Y1, Bitmap)
end;
class procedure TGradientClass.WGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer;Color1, Color2: TColor);
begin
Canvas.Brush.Color:= clWhite;
Canvas.FillRect(Rect(X1,Y1,X2,Y2));
Get(gtVertical,Canvas,0,0,X2,40,Color1,clWhite);
Get(gtVertical,Canvas,0,40,X2,Y2,clWhite,Color2);
end;
class procedure TGradientClass.RGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
x, y, c1, c2, r1, g1, b1: integer;
dr, dg, db, d: real;
p: PARGB;
begin
Bitmap.Width:=abs(X1-X2);
Bitmap.Height:=abs(Y1-Y2);
c1:=ColorToRGB(Color1);
r1:=getRValue(c1);
g1:=getGValue(c1);
b1:=getBValue(c1);
c2:=ColorToRGB(Color2);
d:= sqrt(Bitmap.Width*Bitmap.Width+Bitmap.Height*Bitmap.Height)/2;
dr:=(getRValue(c2)-r1)/d;
dg:=(getGValue(c2)-g1)/d;
db:=(getBValue(c2)-b1)/d;
for y:=0 to Bitmap.Height-1 do
begin
p:=Bitmap.ScanLine[y];
for x:=0 to Bitmap.Width-1 do
begin
// d:=sqrt(((Bitmap.Width-2*x)*(Bitmap.Width-2*x)+(Bitmap.Height-2*y)*(Bitmap.Height-2*y))/4);
d:=sqrt(((Bitmap.Width-2*x)*(Bitmap.Width-2*x))/4);
p[x].R:=round(r1+d*dr);
p[x].G:=round(g1+d*dg);
p[x].B:=round(b1+d*db)
end
end;
Canvas.Draw(X1, Y1, Bitmap)
end;
class procedure TGradientClass.CGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
x, y, c1, c2, r1, g1, b1: integer;
dr, dg, db, d: real;
p: PARGB;
begin
Bitmap.Width:=abs(X1-X2);
Bitmap.Height:=abs(Y1-Y2);
c1:=ColorToRGB(Color1);
r1:=getRValue(c1);
g1:=getGValue(c1);
b1:=getBValue(c1);
c2:=ColorToRGB(Color2);
d:= sqrt(Bitmap.Width*Bitmap.Width+Bitmap.Height*Bitmap.Height)/2;
dr:=(getRValue(c2)-r1)/d;
dg:=(getGValue(c2)-g1)/d;
db:=(getBValue(c2)-b1)/d;
for y:=0 to Bitmap.Height-1 do
begin
p:=Bitmap.ScanLine[y];
for x:=0 to Bitmap.Width-1 do
begin
d:=sqrt(((Bitmap.Width-2*x)*(Bitmap.Width-2*x)+(Bitmap.Height-2*y)*(Bitmap.Height-2*y))/4);
p[x].R:=round(r1+d*dr);
p[x].G:=round(g1+d*dg);
p[x].B:=round(b1+d*db)
end
end;
Canvas.Draw(X1, Y1, Bitmap)
end;
class procedure TGradientClass.BGradientRect(Bitmap: TBitmap; Canvas: TCanvas; X1, Y1, X2, Y2: integer; Color1, Color2: TColor);
var
x, y, c1, c2, r1, g1, b1: integer;
dr, dg, db, d: real;
p: PARGB;
begin
Bitmap.Width:=abs(X1-X2);
Bitmap.Height:=abs(Y1-Y2);
c1:=ColorToRGB(Color1);
r1:=getRValue(c1);
g1:=getGValue(c1);
b1:=getBValue(c1);
c2:=ColorToRGB(Color2);
d:= sqrt(Bitmap.Width*Bitmap.Width+Bitmap.Height*Bitmap.Height)/2;
dr:=(getRValue(c2)-r1)/d;
dg:=(getGValue(c2)-g1)/d;
db:=(getBValue(c2)-b1)/d;
for y:=0 to Bitmap.Height-1 do
begin
p:=Bitmap.ScanLine[y];
for x:=0 to Bitmap.Width-1 do
begin
d:=sqrt(((Bitmap.Height-2*y)*(Bitmap.Height-2*y))/4);
// d:=sqrt(((Bitmap.Width-2*x)*(Bitmap.Width-2*x))/4);
p[x].R:=round(r1+d*dr);
p[x].G:=round(g1+d*dg);
p[x].B:=round(b1+d*db)
end
end;
Canvas.Draw(X1, Y1, Bitmap)
end;
end.
|
unit CatJSON;
{
Catarinka TCatJSON - JSON Manipulation Object
Copyright (c) 2010-2017 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
23.07.2017:
- Added Count property and fixed handling of integer types
- Added SetValues() for setting the value of multiple paths at the same time
Renamed the SetVal() to SetValue() and added result to IncValue()
- Added TCatJSON_Bool and TCatJSON_Int classes (practical if you want to
manipulate a JSON string that will only or mostly contain boolean or
integer types)
25.11.2015:
- Set empty JSON string when calling SetText('')
2013:
- Added the HasPath method
- Changed the default property from string to variant
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils, System.Variants,
{$ELSE}
Classes, SysUtils, Variants,
{$ENDIF}
SuperObject;
const
EmptyJSONStr = '{}';
type
TCatJSON = class
private
fDefaultValue: Variant;
fObject: ISuperObject;
function GetCount:integer;
function GetText: string;
function GetTextUnquoted: string;
function GetValue_(const Name: string): Variant;
procedure SetText(const Text: string);
public
function GetValue(const Name: string; DefaultValue: Variant): Variant;
function HasPath(const Name: string): Boolean;
function IncValue(const Name: string; Int: integer = 1) : Integer;
procedure LoadFromFile(const Filename: string);
procedure SaveToFile(const Filename: string);
procedure SetValue(const Name: string; const Value: Variant);
procedure SetValues(const Name:array of string; const Value: Variant);
procedure Clear;
constructor Create(const JSON: string = '');
destructor Destroy; override;
// properties
property Count: integer read GetCount;
property GlobalDefaultValue: Variant read fDefaultValue write fDefaultValue;
property sObject: ISuperObject read fObject;
property Text: string read GetText write SetText;
property TextUnquoted:string read GetTextUnquoted; // JSON with UnquotedKeys
property Values[const Name: string]: Variant read GetValue_ write SetValue; default;
end;
type
TCatJSON_Bool = class
private
fDefaultValue: boolean;
fJSON: TCatJSON;
function GetValue_(const Name: string): boolean;
public
function GetValue(const Name: string; const DefaultValue: boolean): boolean;
procedure Clear;
procedure SetValue(const Name: string; const DefaultValue: boolean);
constructor Create(JSON: string = ''); overload;
constructor Create(const DefaultValue: boolean;
const JSON: string = ''); overload;
destructor Destroy; override;
// properties
property JSON: TCatJSON read fJSON;
property Values[const Name: string]: boolean read GetValue_
write SetValue; default;
end;
type
TCatJSON_Int = class
private
fDefaultValue: integer;
fJSON: TCatJSON;
function GetValue_(const Name: string): integer;
public
function GetValue(const Name: string; const DefaultValue: integer): integer;
function IncValue(const Name: string; Int: integer = 1): integer;
procedure Clear;
procedure SetValue(const Name: string; const DefaultValue: integer);
constructor Create(JSON: string = ''); overload;
constructor Create(const DefaultValue: integer;
const JSON: string = ''); overload;
destructor Destroy; override;
// properties
property JSON: TCatJSON read fJSON;
property Values[const Name: string]: integer read GetValue_
write SetValue; default;
end;
function GetJSONVal(const JSON, Name: string;const DefaultValue: Variant): Variant;
function IsValidJSONName(const S: string): Boolean;
implementation
uses CatFiles, CatStrings;
function IsValidJSONName(const s: string): Boolean;
const
cJSONChars = ['-', '_', 'a' .. 'z', 'A' .. 'Z', '0' .. '9'];
var
i: integer;
begin
Result := True;
for i := 1 to Length(S) do
if not(CharInSet(S[i], cJSONChars)) then
begin
Result := False;
Break;
end;
end;
function GetJSONVal(const JSON, Name: string;const DefaultValue: Variant): Variant;
var
d: TCatJSON;
begin
d := TCatJSON.Create(JSON);
Result := d.GetValue(Name, DefaultValue);
d.Free;
end;
function TCatJSON.GetCount:integer;
var
ite: TSuperObjectIter;
begin
Result := 0;
if ObjectFindFirst(fObject, ite) then
repeat
Inc(Result)
until not ObjectFindNext(ite);
ObjectFindClose(ite);
end;
function TCatJSON.GetTextUnquoted: string;
var
ite: TSuperObjectIter;
begin
Result := '{';
if ObjectFindFirst(fObject, ite) then
repeat
Result := Result + crlf + ite.key + ': ' + ite.Val.AsJson + ',';
until not ObjectFindNext(ite);
ObjectFindClose(ite);
Result := Result + '}';
end;
function TCatJSON.GetText: string;
begin
Result := fObject.AsJson(True);
end;
procedure TCatJSON.LoadFromFile(const Filename: string);
var
sl: tstringlist;
begin
sl := tstringlist.Create;
SL_LoadFromFile(sl, Filename);
SetText(sl.Text);
sl.Free;
end;
procedure TCatJSON.SaveToFile(const Filename: string);
var
sl: tstringlist;
begin
sl := tstringlist.Create;
sl.Text := GetText;
SL_SaveToFile(sl, Filename);
sl.Free;
end;
procedure TCatJSON.SetText(const Text: string);
var
JSON: string;
begin
JSON := Text;
if JSON = emptystr then
JSON := EmptyJSONStr;
fObject := nil;
fObject := TSuperObject.ParseString(StrToPWideChar(JSON), False);
end;
procedure TCatJSON.Clear;
begin
fObject.Clear;
end;
constructor TCatJSON.Create(const JSON: string = '');
begin
fObject := TSuperObject.Create(stObject);
fDefaultValue := null;
Text := JSON;
end;
destructor TCatJSON.Destroy;
begin
fObject := nil;
inherited;
end;
function TCatJSON.IncValue(const Name: string; Int: integer = 1):integer;
begin
result := GetValue(Name,0) + Int;
fObject.I[name] := result;
end;
procedure TCatJSON.SetValue(const Name: string; const Value: Variant);
begin
case TVarData(Value).vType of
varString, {$IFDEF UNICODE}varUString, {$ENDIF}varOleStr:
fObject.S[name] := Value;
varBoolean:
fObject.b[name] := Value;
varInteger, varByte, varSmallInt, varShortInt, varWord, varLongWord,
{$IFDEF UNICODE}varUInt64, {$ENDIF} varInt64:
fObject.i[name] := Value;
varDouble:
fObject.d[name] := Value;
end;
end;
procedure TCatJSON.SetValues(const Name:array of string; const Value: Variant);
var b: Byte;
begin
for b := Low(Name) to High(Name) do
if (Name[b] <> emptystr) then
SetValue(Name[b],Value);
end;
function TCatJSON.HasPath(const Name: string): Boolean;
begin
Result := False;
if fObject.O[name] <> nil then
Result := True;
end;
function TCatJSON.GetValue(const Name: string;
DefaultValue: Variant): Variant;
begin
Result := DefaultValue;
if HasPath(Name) then
begin
case fObject.O[name].DataType of
stNull:
Result := DefaultValue;
stBoolean:
Result := fObject.b[Name];
stDouble:
Result := fObject.d[Name];
stInt:
Result := fObject.i[Name];
stString:
Result := fObject.S[Name];
stObject, stArray, stMethod:
Result := DefaultValue;
end;
end;
end;
function TCatJSON.GetValue_(const Name: string): Variant;
begin
Result := GetValue(name, fDefaultValue);
end;
// ----------------------------------------------------------------------------//
procedure TCatJSON_Bool.Clear;
begin
fJSON.Clear;
end;
procedure TCatJSON_Bool.SetValue(const Name: string;
const DefaultValue: boolean);
begin
fJSON.SetValue(Name, DefaultValue);
end;
function TCatJSON_Bool.GetValue(const Name: string;
const DefaultValue: boolean): boolean;
begin
result := fJSON.GetValue(Name, DefaultValue)
end;
function TCatJSON_Bool.GetValue_(const Name: string): boolean;
begin
result := fJSON.GetValue(Name, fDefaultValue);
end;
constructor TCatJSON_Bool.Create(JSON: string = '');
begin
inherited Create;
fJSON := TCatJSON.Create(JSON);
fDefaultValue := false;
end;
constructor TCatJSON_Bool.Create(const DefaultValue: boolean;
const JSON: string = '');
begin
Create(JSON);
fDefaultValue := DefaultValue;
end;
destructor TCatJSON_Bool.Destroy;
begin
fJSON.Free;
inherited;
end;
// ----------------------------------------------------------------------------//
procedure TCatJSON_Int.Clear;
begin
fJSON.Clear;
end;
procedure TCatJSON_Int.SetValue(const Name: string;
const DefaultValue: integer);
begin
fJSON.SetValue(Name, DefaultValue);
end;
function TCatJSON_Int.GetValue(const Name: string;
const DefaultValue: integer): integer;
begin
result := fJSON.GetValue(Name, DefaultValue)
end;
function TCatJSON_Int.GetValue_(const Name: string): integer;
begin
result := fJSON.GetValue(Name, fDefaultValue);
end;
function TCatJSON_Int.IncValue(const Name: string; Int: integer = 1): integer;
begin
result := fJSON.IncValue(Name, Int)
end;
constructor TCatJSON_Int.Create(JSON: string = '');
begin
inherited Create;
fJSON := TCatJSON.Create(JSON);
fDefaultValue := 0;
end;
constructor TCatJSON_Int.Create(const DefaultValue: integer;
const JSON: string = '');
begin
Create(JSON);
fDefaultValue := DefaultValue;
end;
destructor TCatJSON_Int.Destroy;
begin
fJSON.Free;
inherited;
end;
end.
|
unit Classe.Unidade;
interface
uses
Controller.UnidadeInterface;
type
TUnidade = class(TInterfacedObject, IUnidade)
private
FId: Integer;
FNome: string;
FUnitario: Boolean;
public
function GETId(): Integer;
function GETNome(): string;
function GETUnitario(): Boolean;
function Id(const pValue: Integer): IUnidade;
function Nome(const pValue: string): IUnidade;
function Unitario(const pValue: Boolean): IUnidade;
constructor Create();
destructor Destroy(); override;
class function New(): IUnidade;
end;
implementation
{ TUnidade }
class function TUnidade.New: IUnidade;
begin
Result := Self.Create;
end;
constructor TUnidade.Create;
begin
end;
destructor TUnidade.Destroy;
begin
inherited;
end;
function TUnidade.GETId: Integer;
begin
Result := FId;
end;
function TUnidade.GETNome: string;
begin
Result := FNome;
end;
function TUnidade.GETUnitario: Boolean;
begin
Result := FUnitario;
end;
function TUnidade.Id(const pValue: Integer): IUnidade;
begin
Result := Self;
FId := pValue;
end;
function TUnidade.Nome(const pValue: string): IUnidade;
begin
Result := Self;
FNome := pValue;
end;
function TUnidade.Unitario(const pValue: Boolean): IUnidade;
begin
Result := Self;
FUnitario := pValue;
end;
end.
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Menus, ComCtrls, StdCtrls, EushullyGame, Grids, ValEdit,
EushullyALF, EushullyFile, Eushullybin, GR32_Image, GR32, GR32_Resamplers,
EushullyAGF;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
Panel1: TPanel;
Panel3: TPanel;
StatusBar1: TStatusBar;
tv_files: TTreeView;
Label1: TLabel;
Panel2: TPanel;
Label2: TLabel;
m_log: TMemo;
N1: TMenuItem;
mm_open: TMenuItem;
OpenDialog1: TOpenDialog;
Splitter1: TSplitter;
Splitter2: TSplitter;
vleParams: TValueListEditor;
ImgView321: TImgView32;
PopupMenu1: TPopupMenu;
oo_extract: TMenuItem;
procedure mm_openClick(Sender: TObject);
procedure tv_filesClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure oo_extractClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
fGame: TEushullyGame;
fImage: TBitmap32;
procedure load(path: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
fImage := TBitmap32.Create;
ImgView321.Bitmap := fImage;
fGame := nil;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if (fGame <> nil) then
fGame.Free;
end;
procedure TForm1.load(path: string);
begin
if (fGame <> nil) then
fGame.Free;
fGame := TEushullyGame.Create();
fGame.load(path);
Form1.Caption := 'AGEEditor: "' + fGame.Title + '"';
fGame.FS.MakeTree(tv_files, tv_files.Items.AddChild(nil, fGame.Title));
tv_files.Items.Item[0].data := fGame;
tv_files.SortType := stText
end;
procedure TForm1.mm_openClick(Sender: TObject);
begin
if (OpenDialog1.Execute()) then
begin
load(ExtractFilePath(OpenDialog1.FileName));
end;
end;
procedure TForm1.oo_extractClick(Sender: TObject);
var
i: integer;
f: TEushullyFile;
begin
if (tv_files.Selected = nil) then
Exit;
for i := 0 to tv_files.Items.Count - 1 do
if (tv_files.Items[i].Selected) and
(UInt32(tv_files.Items[i].data) < $100000) then
begin
f := fGame.FS.open(tv_files.Items[i].Text);
f.SaveToFile('.\' + tv_files.Items[i].Text);
f.Free;
end;
end;
procedure TForm1.tv_filesClick(Sender: TObject);
var
data: TObject;
i: integer;
alf: TEushullyALF;
f: TEushullyFile;
bmp: TEushullyAGF;
str: TMemoryStream;
begin
if (tv_files.Selected = nil) then
Exit;
data := TObject(tv_files.Selected.data);
vleParams.Strings.Clear;
if (UInt32(tv_files.Selected.data) < $100000) then
begin
// выбран файл
f := fGame.FS.open(tv_files.Selected.Text);
vleParams.Values['Размер'] := IntToStr(f.Size);
if (TEushullyBIN.isFormat(f)) then
vleParams.Values['Тип'] := 'Eushully Script File'
else if (TEushullyAGF.isFormat(f)) then
begin
bmp:=TEushullyAGF.Create;
bmp.load(f);
str:=bmp.toMemory();
str.Seek(0, soFromBeginning);
fImage.LoadFromStream(str);
ImgView321.Bitmap:=fImage;
str.Free;
bmp.Free;
end
else
vleParams.Values['Тип'] := '-';
f.Free;
// ImgView321.
// fImage.lo
end
else if (data.ClassName = 'TEushullyALF') then
begin
// выбран архив
alf := TEushullyALF(data);
vleParams.Values['Тип'] := '-';
vleParams.Values['Заголовок'] := alf.Title;
vleParams.Values['Файлов'] := IntToStr(alf.FilesCount);
end
else if (data.ClassName = 'TEushullyGame') then
begin
// выбрана игра
alf := fGame.FS.MainArchive;
for i := 0 to alf.SettingsCount - 1 do
begin
vleParams.Values[alf.SettingName[i]] := alf.Settings[i];
end;
end;
// vleParams.AutoSizeColumns();
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela de Cadastro dos Grupos Tributários
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije
@version 2.0
******************************************************************************* }
unit UTributGrupoTributario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids,
JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, LabeledCtrls, Atributos, Constantes,
Mask, JvExMask, JvToolEdit, JvBaseEdits, StrUtils, Controller;
type
[TFormDescription(TConstantes.MODULO_ADMINISTRATIVO, 'Grupo Tributário')]
TFTributGrupoTributario = class(TFTelaCadastro)
EditDescricao: TLabeledEdit;
BevelEdits: TBevel;
MemoObservacao: TLabeledMemo;
ComboboxOrigemMercadoria: TLabeledComboBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
// Controles CRUD
function DoInserir: Boolean; override;
function DoEditar: Boolean; override;
function DoExcluir: Boolean; override;
function DoSalvar: Boolean; override;
end;
var
FTributGrupoTributario: TFTributGrupoTributario;
implementation
uses ULookup, TributGrupoTributarioVO, TributGrupoTributarioController;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFTributGrupoTributario.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TTributGrupoTributarioVO;
ObjetoController := TTributGrupoTributarioController.Create;
inherited;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFTributGrupoTributario.DoInserir: Boolean;
begin
Result := inherited DoInserir;
if Result then
begin
EditDescricao.SetFocus;
end;
end;
function TFTributGrupoTributario.DoEditar: Boolean;
begin
Result := inherited DoEditar;
if Result then
begin
EditDescricao.SetFocus;
end;
end;
function TFTributGrupoTributario.DoExcluir: Boolean;
begin
if inherited DoExcluir then
begin
try
TController.ExecutarMetodo('TributGrupoTributarioController.TTributGrupoTributarioController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean');
Result := TController.RetornoBoolean;
except
Result := False;
end;
end
else
begin
Result := False;
end;
if Result then
TController.ExecutarMetodo('TributGrupoTributarioController.TTributGrupoTributarioController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
end;
function TFTributGrupoTributario.DoSalvar: Boolean;
begin
Result := inherited DoSalvar;
if Result then
begin
try
if not Assigned(ObjetoVO) then
ObjetoVO := TTributGrupoTributarioVO.Create;
TTributGrupoTributarioVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id;
TTributGrupoTributarioVO(ObjetoVO).Descricao := EditDescricao.Text;
TTributGrupoTributarioVO(ObjetoVO).Observacao := MemoObservacao.Text;
TTributGrupoTributarioVO(ObjetoVO).OrigemMercadoria := Copy(ComboboxOrigemMercadoria.Text, 1, 1);
if StatusTela = stInserindo then
begin
TController.ExecutarMetodo('TributGrupoTributarioController.TTributGrupoTributarioController', 'Insere', [TTributGrupoTributarioVO(ObjetoVO)], 'PUT', 'Lista');
end
else if StatusTela = stEditando then
begin
if TTributGrupoTributarioVO(ObjetoVO).ToJSONString <> StringObjetoOld then
begin
TController.ExecutarMetodo('TributGrupoTributarioController.TTributGrupoTributarioController', 'Altera', [TTributGrupoTributarioVO(ObjetoVO)], 'POST', 'Boolean');
end
else
Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
end;
except
Result := False;
end;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFTributGrupoTributario.GridParaEdits;
begin
inherited;
if not CDSGrid.IsEmpty then
begin
ObjetoVO := TTributGrupoTributarioVO(TController.BuscarObjeto('TributGrupoTributarioController.TTributGrupoTributarioController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET'));
end;
if Assigned(ObjetoVO) then
begin
EditDescricao.Text := TTributGrupoTributarioVO(ObjetoVO).Descricao;
MemoObservacao.Text := TTributGrupoTributarioVO(ObjetoVO).Observacao;
ComboboxOrigemMercadoria.ItemIndex := StrToInt(TTributGrupoTributarioVO(ObjetoVO).OrigemMercadoria);
// Serializa o objeto para consultar posteriormente se houve alterações
FormatSettings.DecimalSeparator := '.';
StringObjetoOld := ObjetoVO.ToJSONString;
FormatSettings.DecimalSeparator := ',';
end;
end;
{$ENDREGION}
end.
|
unit ufrmDialogBarcodeRequest;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
ufrmMasterDialogBrowse, StdCtrls, ExtCtrls, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer,
Vcl.Menus, cxLabel, Vcl.ComCtrls, dxCore, cxDateUtils, cxButtonEdit,
cxButtons, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid;
type
TProcessType = (ptAdd, ptEdit, ptNone);
TfrmDialogBarcodeRequest = class(TfrmMasterDialogBrowse)
Panel1: TPanel;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
lbl5: TLabel;
lbl6: TLabel;
bvl1: TBevel;
edtSupplierName: TEdit;
edtProductName: TEdit;
btnAddRow: TcxButton;
edtBarNo: TEdit;
Panel2: TPanel;
Label1: TLabel;
IntEdtQty: TcxCurrencyEdit;
lblDelete: TcxLabel;
Label2: TLabel;
dtTgl: TcxDateEdit;
Label3: TLabel;
cbUOM: TComboBox;
grpProduct: TGroupBox;
grpPurchaseOrder: TGroupBox;
lbl7: TLabel;
edtPONo: TEdit;
bSearchPO: TcxButton;
edtDatePO: TcxDateEdit;
lbl8: TLabel;
lblStatusPO: TLabel;
lbl9: TLabel;
edbSupplierCode: TcxButtonEdit;
curredtUnitPrice: TcxCurrencyEdit;
edbProductCode: TcxButtonEdit;
curredtTotal: TcxCurrencyEdit;
edbUOM: TcxButtonEdit;
curreditTotalPrice: TcxCurrencyEdit;
procedure actDeleteExecute(Sender: TObject);
procedure btnAddRowClick(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure IntEdtQtyExit(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer;
var Allow: Boolean);
procedure lblDeleteClick(Sender: TObject);
procedure strgGridSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure FormCreate(Sender: TObject);
procedure edbSupplierCodeButtonClick(Sender: TObject);
procedure edbSupplierCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edbProductCodeButtonClick(Sender: TObject);
procedure edbProductCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure footerDialogMasterbtnCloseClick(Sender: TObject);
procedure IntEdtQtyKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edbUOMButtonClick(Sender: TObject);
procedure edbProductCodeExit(Sender: TObject);
procedure edbSupplierCodeExit(Sender: TObject);
procedure edbSupplierCodeKeyPress(Sender: TObject; var Key: Char);
procedure edbProductCodeKeyPress(Sender: TObject; var Key: Char);
procedure edtBarNoKeyPress(Sender: TObject; var Key: Char);
procedure dtTglKeyPress(Sender: TObject; var Key: Char);
procedure cbUOMKeyPress(Sender: TObject; var Key: Char);
procedure IntEdtQtyKeyPress(Sender: TObject; var Key: Char);
procedure bSearchPOClick(Sender: TObject);
procedure edtPONoKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FBarcodeList : TStringList;
FProcessType : TProcessType;
procedure ClearAtributPLU;
// procedure PrintReport;
procedure GetBarcodeRequest;
procedure GetDetilBarcodeRequest;
procedure RefreshDetilNo;
function FindOnGrid(aProductCode: String; aUOM:String): Boolean;
procedure ParseHeader;
procedure SetProcessType(const Value: TProcessType);
public
RowID : Integer;
procedure FillComboUOM(aBrgCode : String ; aUnitID : Integer);
function GenerateNoBarcodeRequest: string;
function GetGeneratorName: string;
procedure LoadDataPOToForm(aPONo : string);
function SaveDataBarcodeRequest: Boolean;
{ Public declarations }
published
property Process: TProcessType read FProcessType write SetProcessType;
end;
var
frmDialogBarcodeRequest: TfrmDialogBarcodeRequest;
IsSuccessfull : Boolean;
implementation
uses
uTSCommonDlg, uRetnoUnit;
{$R *.dfm}
const
{
NO
PLU
PRODUCT NAME
QTY LABEL
UNIT PRICE
TOTAL PRICE
UOM
}
_KolNo : Integer = 0;
_KolKode : Integer = 1;
_KolNama : Integer = 2;
_KolQTY : Integer = 3;
_KolPrice : Integer = 4;
_KolTotal : Integer = 5;
_KolStatus : Integer = 7;
_kolUOM : Integer = 6;
_RowCount : Integer = 2;
_ColCount : Integer = 7;
procedure TfrmDialogBarcodeRequest.actDeleteExecute(Sender: TObject);
begin
inherited;
{
if not IsValidDateKarenaEOD(masternewunit.id,cGetServerTime,FMasterIsStore) then
Exit;
if CommonDlg.Confirm('Are you wish to delete barcode request ' + strgGrid.Cells[1, strgGrid.Row]) = mrYes then
begin
FBarcodeRequest := TBARCODEREQUEST.Create(nil);
try
if FBarcodeRequest.LoadByBAR_NO(strgGrid.Cells[1, strgGrid.Row], masternewunit.id) then
begin
if FBarcodeRequest.RemoveFromDB then
begin
cCommitTrans;
FetchDataBarcodeRequest;
CommonDlg.ShowConfirmSuccessfull(atDelete);
end
else
begin
cRollbackTrans;
CommonDlg.ShowMessage('Gagal Hapus Barcode Request');
end;
end;
finally
cRollbackTrans;
if FBarcodeRequest <> nil then FreeAndNil(FBarcodeRequest);
end;
end;
}
end;
procedure TfrmDialogBarcodeRequest.btnAddRowClick(Sender: TObject);
procedure AddNewDetil();
begin
if edbProductCode.Text = '' then exit;
{
if strgGrid.Cells[_KolNo, strgGrid.RowCount - 1] <> '' then
strgGrid.AddRow;
curreditTotalPrice.Value := curreditTotalPrice.Value + curredtTotal.Value;
strgGrid.Cells[_KolNo, strgGrid.RowCount - 1] := IntToStr(strgGrid.RowCount - 1) + '.';
strgGrid.Cells[_KolKode, strgGrid.RowCount - 1] := edbProductCode.Text;
strgGrid.Cells[_KolNama, strgGrid.RowCount - 1] := edtProductName.Text;
strgGrid.Cells[_KolQTY, strgGrid.RowCount - 1] := FloatToStr(IntEdtQty.Value);
strgGrid.Cells[_KolPrice, strgGrid.RowCount - 1] := CurrToStr(curredtUnitPrice.Value);
strgGrid.Cells[_KolTotal, strgGrid.RowCount - 1] := CurrToStr(curredtTotal.Value);
strgGrid.Cells[_KolStatus, strgGrid.RowCount - 1] := 'NEW';
strgGrid.Cells[_kolUOM, strgGrid.RowCount - 1] := Trim(cbUOM.Text) ;
strgGrid.AutoSize := True;
}
end;
begin
if edbProductCode.Text ='' then
begin
CommonDlg.ShowError('Kode Product masih kosong !');
edbProductCode.SetFocus;
Exit;
end;
if edbSupplierCode.Text ='' then
begin
CommonDlg.ShowError('Kode Supplier masih kosong !');
edbSupplierCode.SetFocus;
Exit;
end;
if cbUOM.Text ='' then
begin
CommonDlg.ShowError('UOM belum dipilih !');
cbUOM.SetFocus;
Exit;
end;
if IntEdtQty.Value <= 0 then
begin
CommonDlg.ShowError('Qty Harus > 0. Tolong Dicek Lagi');
IntEdtQty.SetFocus;
Exit;
end;
{
if (not FindOnGrid(edbProductCode.Text, cbUOM.Text)) then
begin
if strgGrid.RowCount > 1 then
AddNewDetil
end else
begin
curreditTotalPrice.Value := (curreditTotalPrice.Value - StrToCurr(strgGrid.Cells[5, strgGrid.Row]) + curredtTotal.Value);
strgGrid.Cells[_KolQTY, RowID] := IntToStr(IntEdtQty.EditValue);
strgGrid.Cells[_KolTotal, RowID] := CurrToStr(curredtTotal.Value);
strgGrid.Cells[_KolStatus, RowID] := 'UPDATE'; end;
edbProductCode.Text := '';
edbUOM.Text := '';
edtProductName.Text := '';
IntEdtQty.Value := 0;
curredtTotal.Value := 0;
cbUOM.Items.Clear;
edbProductCode.SetFocus;
}
end;
procedure TfrmDialogBarcodeRequest.SetProcessType(
const Value: TProcessType);
begin
FProcessType := Value;
end;
procedure TfrmDialogBarcodeRequest.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
{
if not (Process = ptEdit) and not IsValidDateKarenaEOD(dialogunit,dtTgl.Date,FMasterIsStore) then
Exit;
try
Self.Enabled := False;
IsSuccessfull := False;
if ((strgGrid.RowCount = 2) and (strgGrid.Cells[0, strgGrid.RowCount - 1] = '')) then
begin
CommonDlg.ShowMessage('Product Belum Dipilih');
Exit;
end;
IsSuccessfull := SaveDataBarcodeRequest;
if IsSuccessfull then
begin
if CommonDlg.Confirm('Anda Akan Mencetak Slip Barcode Request ?') = mrYes then
DoSlipBarcodeReq(edtBarNo.Text,dialogunit,FLoginFullname,FDialogUnitName);
end;
finally
Self.Enabled := True;
if IsSuccessfull then Close;
end;
}
end;
procedure TfrmDialogBarcodeRequest.FormShow(Sender: TObject);
var
iTemp: Double;
begin
inherited;
if not TryStrToFloat(getGlobalVar('PRICE_BARCODE_REQ'), iTemp) then
begin
CommonDlg.ShowMessage('Harga default per unit Barcode belum didaftarkan dalam SYS$PARAMETER.'+#13#10
+ 'Menggunakan nilai default [PRICE_BARCODE_REQ] = Rp.100,-');
iTemp := 100;
end;
curredtUnitPrice.Value := iTemp;
IntEdtQty.Value := 0;
curredtTotal.Value := 0;
dtTgl.Date := now;
curreditTotalPrice.Value := 0;
if Process = ptEdit then
begin
GetBarcodeRequest;
GetDetilBarcodeRequest;
edbSupplierCode.Properties.ReadOnly := True;
edtSupplierName.ReadOnly:= True;
edbProductCode.SetFocus;
end else
if Process = ptAdd then
edtBarNo.Text := GenerateNoBarcodeRequest;
end;
procedure TfrmDialogBarcodeRequest.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
action := caFree;
end;
procedure TfrmDialogBarcodeRequest.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogBarcodeRequest := nil;
end;
function TfrmDialogBarcodeRequest.FindOnGrid(aProductCode: String;
aUOM:String): Boolean;
var
sCellUOM: string;
sCellKode: string;
iRowCount: Integer;
iInitRow: Integer;
i: Integer;
begin
Result := False;
if (aProductCode <> '') and (aUOM <> '') then
begin
{
iInitRow := strgGrid.FixedRows;
iRowCount := strgGrid.RowCount;
for i := iInitRow to iRowCount - 1 do
begin
result := False;
sCellKode := strgGrid.Cells[_KolKode,i];
sCellUOM := strgGrid.Cells[_kolUOM,i];
if (scellKode = aProductCode) and
(scelluom = auom) then
begin
Result := True;
RowID := i;
Exit;
end;
end;
}
end;
end;
procedure TfrmDialogBarcodeRequest.IntEdtQtyExit(Sender: TObject);
begin
curredtTotal.Value := curredtUnitPrice.Value * IntEdtQty.Value;
end;
procedure TfrmDialogBarcodeRequest.GetBarcodeRequest;
var
s: string;
begin
s := 'SELECT DISTINCT a.*, b.SUP_CODE, b.SUP_NAME, a.BAR_TOTAL_PRICE'
+ ' FROM BARCODE_REQUEST a'
+ ' LEFT JOIN SUPLIER b ON a.BAR_SUP_CODE = b.SUP_CODE'
+ ' AND a.BAR_SUP_UNT_ID = b.SUP_UNT_ID'
+ ' LEFT JOIN BARCODE_REQUEST_DETIL c ON a.BAR_NO = c.BARD_BAR_NO'
+ ' AND a.BAR_UNT_ID = c.BARD_BAR_UNT_ID'
+ ' WHERE a.BAR_NO = ' + QuotedStr(edtBarNo.Text)
+ ' AND a.BAR_UNT_ID = ' + IntToStr(dialogunit)
+ ' ORDER BY a.BAR_NO, a.BAR_DATE, b.SUP_CODE, b.SUP_NAME';
{
with cOpenQuery(s) do
begin
try
if not Eof then
begin
edbSupplierCode.Text := FieldByName('SUP_CODE').AsString;
edtSupplierName.Text := FieldByName('SUP_NAME').AsString;
curreditTotalPrice.Value := FieldByName('BAR_TOTAL_PRICE').AsCurrency;
end;
finally
Free;
end;
end;
}
end;
procedure TfrmDialogBarcodeRequest.GetDetilBarcodeRequest;
var
s: string;
I: Integer;
begin
s := 'SELECT b.*, c.BRG_NAME, c.BRG_MERK'
+ ' FROM BARCODE_REQUEST a'
+ ' LEFT JOIN BARCODE_REQUEST_DETIL b ON a.BAR_NO = b.BARD_BAR_NO'
+ ' AND a.BAR_UNT_ID = b.BARD_BAR_UNT_ID'
+ ' LEFT JOIN BARANG c ON b.BARD_BRG_CODE = c.BRG_CODE'
+ ' AND b.BARD_BRG_UNT_ID = c.BRG_UNT_ID'
+ ' WHERE a.BAR_NO = ' + QuotedStr(edtBarNo.Text)
+ ' AND b.BARD_BRG_UNT_ID = ' + IntToStr(dialogunit)
+ ' ORDER BY b.BARD_BRG_CODE';
{
with copenquery(s, False) do
begin
Try
I := 1;
Last;
First;
strgGrid.RowCount := RecordCount + I;
while not eof do
begin
strgGrid.Cells[_KolNo, I] := IntToStr(I) + '.';
strgGrid.Cells[_KolKode, I] := FieldByName('BARD_BRG_CODE').AsString;
strgGrid.Cells[_KolNama, I] := FieldByName('BRG_NAME').AsString +
FieldByName('BRG_MERK').AsString;
strgGrid.Cells[_KolQTY, I] := FieldByName('BARD_QTY').AsString;
strgGrid.Cells[_KolPrice, I] := FieldByName('BARD_SAT_PRICE').AsString;
strgGrid.Cells[_KolTotal, I] := FieldByName('BARD_TOTAL_PRICE').AsString;
strgGrid.Cells[_kolUOM, I] := FieldByName('BARD_UOM').AsString;
strgGrid.Cells[_KolStatus, I] := 'OLD';
Inc(I);
Next;
end;
strgGrid.AutoSize:= True;
Finally
Free;
End
end;
}
end;
procedure TfrmDialogBarcodeRequest.FormKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = Ord('R')) and (ssCtrl in Shift) then
lblDeleteClick(Self)
end;
procedure TfrmDialogBarcodeRequest.RefreshDetilNo;
var
I: Integer;
begin
{
if strgGrid.Cells[1, 1] <> '' then
for I := 1 to strgGrid.RowCount-1 do
strgGrid.Cells[0, I] := IntToStr(I) + '.';
}
end;
procedure TfrmDialogBarcodeRequest.strgGridRowChanging(Sender: TObject;
OldRow, NewRow: Integer; var Allow: Boolean);
begin
inherited;
if Process = ptEdit then
begin
{
Allow:= True;
edbProductCode.Text := strgGrid.Cells[1, NewRow];
FillComboUOM(edbProductCode.Text,dialogunit);
cbUOM.ItemIndex := cbUOM.Items.IndexOf(strgGrid.Cells[6, NewRow]);
edtProductName.Text := strgGrid.Cells[2, NewRow];
IntEdtQty.Value := StrToInt(strgGrid.Cells[3, NewRow]);
curredtTotal.Value := StrToCurr(strgGrid.Cells[5, NewRow]);
btnAddRow.Caption := 'Update';
}
end;
end;
procedure TfrmDialogBarcodeRequest.lblDeleteClick(Sender: TObject);
var
AValue : Double;
begin
inherited;
{
if (strgGrid.Cells[1, strgGrid.Row] <> '') then
begin
if CommonDlg.Confirm('Anda Yakin Akan Menghapus Data') = mrNo then
Exit
else
begin
AValue := strgGrid.Floats[5, strgGrid.Row];
if strgGrid.RowCount = 2 then
begin
strgGrid.Cells[_KolKode, strgGrid.Row] := '';
HapusBarisKosong(strgGrid, _KolKode);
end
else strgGrid.RemoveRows(strgGrid.Row, 1);
curreditTotalPrice.Value := curreditTotalPrice.Value - AValue;
RefreshDetilNo;
end;
end;
}
end;
procedure TfrmDialogBarcodeRequest.strgGridSelectCell(Sender: TObject;
ACol, ARow: Integer; var CanSelect: Boolean);
begin
inherited;
{if strgGrid.Cells[1, Arow] <> '' then
begin
edbProductCode.Text := strgGrid.Cells[1, Arow];
edtProductName.Text := strgGrid.Cells[2, Arow];
FillComboUOM(edbProductCode.Text,dialogunit);
cbUOM.ItemIndex := cbUOM.Items.IndexOf(strgGrid.Cells[6, Arow]);
IntEdtQty.Value := StrToInt(strgGrid.Cells[3, Arow]);
curredtTotal.Value := StrToCurr(strgGrid.Cells[5, Arow]);
btnAddRow.Caption := 'Update';
end;
}
end;
procedure TfrmDialogBarcodeRequest.FormCreate(Sender: TObject);
begin
inherited;
FBarcodeList := TStringList.Create;
end;
procedure TfrmDialogBarcodeRequest.edbSupplierCodeButtonClick(
Sender: TObject);
var
s: string;
begin
inherited;
if Process = ptEdit then
Exit;
s := 'SELECT SUP_CODE as KODESUPLIER, SUP_NAME as NAMASUPLIER, SUP_ADDRESS as ALAMATSUPLIER'
+ ' FROM SUPLIER'
+ ' WHERE SUP_UNT_ID = ' + IntToStr(dialogunit);
{
with clookup('Daftar Supplier', s) do
begin
Try
if Strings[0] = '' then Exit;
ClearAtributPLU;
ParseHeader;
edbSupplierCode.Text := Strings[0];
edtSupplierName.Text := Strings[1];
curredtUnitPrice.SetFocus;
Finally
Free;
End;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edbSupplierCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (key = VK_F5) Or (key = VK_DOWN) then
begin
edbSupplierCodeButtonClick(Self);
end;
// Key := UpCase(Ord(Key));
end;
procedure TfrmDialogBarcodeRequest.edbProductCodeButtonClick(
Sender: TObject);
var
sSQL: String;
begin
inherited;
if edbSupplierCode.Text = '' then
begin
CommonDlg.ShowMessage('Supliernya belum dipilih');
Exit;
end;
sSQL := 'select b.Brg_Code, b.Brg_Alias '
+ ' from barang_suplier a, barang b '
+ ' where a.brgsup_brg_code = b.brg_code '
+ ' and a.brgsup_brg_unt_id = b.brg_unt_id '
+ ' and a.brgsup_sup_code = ' + QuotedStr(edbSupplierCode.Text)
+ ' and a.brgsup_brg_unt_id = ' + IntToStr(dialogunit) ;
{
with clookup('Daftar Product', sSQL) do
begin
Try
if Strings[0] = '' then Exit;
edbProductCode.Text := Strings[0];
edtProductName.Text:= Strings[1];
if FindOnGrid(edbProductCode.Text,cbUOM.Text) then
btnAddRow.Caption:= 'Update'
else btnAddRow.Caption:= 'Add';
cbUOM.SetFocus;
Finally
Free;
End;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edbProductCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if(key = VK_F5) Or (key = VK_DOWN) then edbProductCodeButtonClick(Self);
end;
function TfrmDialogBarcodeRequest.GetGeneratorName: string;
begin
Result := 'GEN_BARCODE_REQ';
end;
function TfrmDialogBarcodeRequest.SaveDataBarcodeRequest: Boolean;
var
i: Integer;
sBarNo: string;
// FBarcodeRequest: TBARCODEREQUEST;
begin
Result := False;
{
FBarcodeRequest := TBARCODEREQUEST.Create(Self);
try
sBarNo := '';
if FBarcodeRequest.LoadByBAR_NO(edtBarNo.Text, dialogunit)
then sBarNo := FBarcodeRequest.BAR_NO;
if sBarNo = '' then
begin
sBarNo := GenerateNoBarcodeRequest;
if sBarNo <> edtBarNo.Text then
begin
edtBarNo.Text := sBarNo;
end;
sBarNo := '';
end;
FBarcodeRequest.UpdateData(dtTgl.Date,
edtBarNo.Text,
edbSupplierCode.Text,
dialogunit,
curreditTotalPrice.Value,
dialogunit);
FBarcodeRequest.BARCODEREQUESTDETILS.Clear;
for i := strgGrid.FixedRows to strgGrid.RowCount - 1 do
begin
FBarcodeRequest.UpdateBARCODEREQUESTDETILS(edtBarNo.Text,
dialogunit,
strgGrid.Cells[_KolKode, i],
dialogunit,
0,
strgGrid.Ints[_KolQTY, i],
strgGrid.Floats[_KolPrice, i],
strgGrid.Floats[_KolTotal, i],
dialogunit,
strgGrid.Cells[_kolUOM,i],
dialogunit
);
end;
if not FBarcodeRequest.SaveToDB(sBarNo) then
begin
cRollbackTrans;
Exit;
end;
cCommitTrans;
Result := True;
finally
cRollbackTrans;
FreeAndNil(FBarcodeRequest);
end;
}
end;
procedure TfrmDialogBarcodeRequest.footerDialogMasterbtnCloseClick(
Sender: TObject);
begin
IsSuccessfull := False;
Close;
inherited;
end;
function TfrmDialogBarcodeRequest.GenerateNoBarcodeRequest: string;
var
iCounter: Integer;
//s: string;
begin
// TODO -cMM: TfrmDialogBarcodeRequest.GenerateNoBarcodeRequest default body inserted
// iCounter := GetCounterNoBukti('BARCODE_REQUEST', 'BAR_NO', 'BAR_DATE', dtTgl.Date, 'BAR_UNT_ID', dialogunit, 'BR');
// Result := 'BR/' + FormatDateTime('YY', dtTgl.Date) + '/' + StrPadLeft(IntToStr(iCounter), _DigitNoBukti, '0');
end;
procedure TfrmDialogBarcodeRequest.IntEdtQtyKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = vk_return then
begin
curredtTotal.Value := IntEdtQty.Value * curredtUnitPrice.Value;
btnAddRow.SetFocus;
end;
end;
procedure TfrmDialogBarcodeRequest.edbUOMButtonClick(Sender: TObject);
var
sSQL: String;
begin
inherited;
sSQL := 'select a.konvsat_sat_code_from as "Kode Satuan"'
+ ' from ref$konversi_satuan a'
+ ' where a.konvsat_scf_unt_id = ' + IntToStr(dialogunit)
+ ' and a.konvsat_brg_code = ' + QuotedStr(edbProductCode.Text);
{
with clookup('Daftar UOM', sSQL) do
begin
Try
if Strings[0] = '' then Exit;
edbUOM.Text := Strings[0];
edbUOM.SetFocus;
Finally
Free;
End;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edbProductCodeExit(Sender: TObject);
var
sSQL: String;
begin
inherited;
sSQL := 'select b.Brg_Code, b.Brg_Alias '
+ ' from barang_suplier a, barang b '
+ ' where a.brgsup_brg_code = b.brg_code '
+ ' and a.brgsup_brg_unt_id = b.brg_unt_id '
+ ' and a.brgsup_sup_code = ' + QuotedStr(edbSupplierCode.Text)
+ ' and a.brgsup_brg_unt_id = ' + IntToStr(dialogunit)
+ ' and b.brg_code = ' + QuotedStr(edbProductCode.Text) ;
{
with cOpenQuery(sSQL) do
Begin
Try
if Fields[0].AsString = '' then
Begin
edbProductCode.Text := '';
edtProductName.Text := 'Kode Barang Salah !';
Exit;
End Else
Begin
edbProductCode.Text := Fields[0].Text;
edtProductName.Text := Fields[1].AsString;
FillComboUOM(edbProductCode.Text,dialogunit);
if cbUOM.Items.Count > 0 then
cbUOM.ItemIndex := 0;
End;
Finally
Free;
End;
End;
}
end;
procedure TfrmDialogBarcodeRequest.FillComboUOM(aBrgCode : String ; aUnitID :
Integer);
var
sSQL: String;
begin
sSQL := 'select a.konvsat_sat_code_from as "Kode Satuan"'
+ ' from ref$konversi_satuan a'
+ ' where a.konvsat_scf_unt_id = ' + IntToStr(dialogunit)
+ ' and a.konvsat_brg_code = ' + QuotedStr(edbProductCode.Text);
{
with cOpenQuery(sSQL) do
begin
Try
if Fields[0].AsString = '' then
Begin
Exit;
End;
cbUOM.Clear;
while not Eof do
Begin
cbUOM.Items.Add(Fields[0].AsString);
Next;
end;
Finally
Free;
End;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edbSupplierCodeExit(Sender: TObject);
var
sSQL: String;
begin
inherited;
sSQL := 'SELECT SUP_NAME'
+ ' FROM SUPLIER'
+ ' WHERE SUP_UNT_ID = ' + IntToStr(dialogunit)
+ ' and sup_code=' + QuotedStr(edbSupplierCode.Text);
{
with cOpenQuery(sSQL) do
begin
Try
if Fields[0].AsString = '' then
Begin
edbSupplierCode.Text := '';
edtSupplierName.Text := 'Kode Supplier Salah !';
Exit;
End Else
Begin
edtSupplierName.Text := Fields[0].AsString;
edbProductCode.SetFocus;
End;
Finally
Free;
End;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edbSupplierCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
Key := UpCase(Key);
end;
procedure TfrmDialogBarcodeRequest.edbProductCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
Key := UpCase(Key);
end;
procedure TfrmDialogBarcodeRequest.edtBarNoKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
end;
procedure TfrmDialogBarcodeRequest.dtTglKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
end;
procedure TfrmDialogBarcodeRequest.cbUOMKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
end;
procedure TfrmDialogBarcodeRequest.IntEdtQtyKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
Begin
Perform(WM_NEXTDLGCTL,0,0);
Key := #0;
End;
end;
procedure TfrmDialogBarcodeRequest.ClearAtributPLU;
begin
edbProductCode.Clear;
edtProductName.Clear;
cbUOM.Clear;
IntEdtQty.Clear;
curredtTotal.Clear;
end;
procedure TfrmDialogBarcodeRequest.ParseHeader;
begin
{with strgGrid do
begin
Clear;
RowCount := _RowCount;
ColCount := _ColCount;
Cells[_KolNo, 0] := 'NO';
Cells[_KolKode, 0] := 'PLU';
Cells[_KolNama, 0] := 'PRODUCT NAME';
Cells[_KolQTY, 0] := 'QTY LABEL';
Cells[_KolPrice, 0] := 'UNIT PRICE';
Cells[_KolTotal, 0] := 'TOTAL PRICE';
Cells[_kolUOM, 0] := 'UOM';
end;
}
end;
procedure TfrmDialogBarcodeRequest.bSearchPOClick(Sender: TObject);
var
sSQL: string;
begin
if edbSupplierCode.Text = '' then
begin
CommonDlg.ShowMessage('Kode suplier belum di isi ');
Exit;
end;
lblStatusPO.Caption := '';
lblStatusPO.Tag := 0;
sSQL := ' select a.po_no as"NO PO", a.PO_date as "TGL PO", d.merchan_name AS "MERCHANDISE",f.stapo_name AS "STATUS",'
+ ' e.sup_code AS "KODE SUPLIER", e.sup_name AS "NAMA SUPLIER" '
+ ' from PO a, suplier_merchan_grup b, ref$merchandise_grup c, '
+ ' ref$merchandise d, suplier e, ref$Status_po f '
+ ' where a.IS_PO_BONUS = 0 and b.supmg_sub_code = a.po_supmg_sub_code '
+ ' and b.supmg_unt_id = a.po_supmg_unt_id '
+ ' and c.merchangrup_id = b.supmg_merchangrup_id '
+ ' and c.merchangrup_unt_id = b.supmg_unt_id '
+ ' and d.merchan_id = c.merchangrup_merchan_id '
+ ' and d.merchan_unt_id = c.merchangrup_merchan_unt_id '
+ ' and e.sup_code = b.supmg_code '
+ ' and e.sup_unt_id = b.supmg_unt_id '
+ ' and f.stapo_id = a.po_stapo_id '
+ ' and f.stapo_unt_id = a.po_stapo_unt_id '
+ ' and a.po_stapo_id in (5)';
if (edbSupplierCode.Text<>'') then
sSQL := sSQL + ' and e.sup_code = ' + QuotedStr(edbSupplierCode.Text);
{
with cLookUp('Daftar PO Yang Sudah Diterima',sSQL,200,1,True) do
begin
try
edtPONo.Text := Strings[0];
ClearAtributPLU;
edtSupplierName.Text := Strings[5];
curredtUnitPrice.SetFocus;
LoadDataPOToForm(edtPONo.Text);
finally
Free;
end;
end;
}
end;
procedure TfrmDialogBarcodeRequest.edtPONoKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key=#13 then
begin
LoadDataPOToForm(edtPONo.Text);
end else if(not(Key in['0'..'9',Chr(VK_BACK)]))then
Key:=#0;
end;
procedure TfrmDialogBarcodeRequest.LoadDataPOToForm(aPONo : string);
var
// FPO: TPO;
i: Integer;
dQty : Double;
begin
{
FPO := TPO.Create(Self);
FPO.LoadByNoBukti(aPONo, dialogunit);
edtPONo.Text := FPO.NoBukti;
lblStatusPO.Caption := FPO.StatusPO.Nama;
lblStatusPO.Tag := FPO.StatusPO.ID;
edtDatePO.Date := FPO.TglBukti;
with strgGrid do
begin
// ini yg PO Biasa
if FPO.POItems.Count > 0 then
begin
for i := 0 to FPO.POItems.Count - 1 do
begin
if strgGrid.Cells[_KolNo, strgGrid.RowCount - 1] <> '' then
strgGrid.AddRow;
Cells[_KolNo, strgGrid.RowCount - 1] := IntToStr(i + 1);
Cells[_KolKode, strgGrid.RowCount - 1] := FPO.POItems[i].Barang.Kode;
Cells[_KolNama, strgGrid.RowCount - 1] := FPO.POItems[i].Barang.Alias;
if FPO.StatusPO.ID = 5 then
begin
dQty := FPO.POItems[i].GetQtyReceive
end else
dQty := FPO.POItems[i].QtyOrder;
Cells[_KolQTY, strgGrid.RowCount - 1] := FloatToStr(dQty);
Cells[_KolPrice, strgGrid.RowCount - 1] := CurrToStr(curredtUnitPrice.Value);
Cells[_KolTotal, strgGrid.RowCount - 1] := CurrToStr(dQty * curredtUnitPrice.Value);
Cells[_KolStatus, strgGrid.RowCount - 1] := 'NEW';
Cells[_kolUOM, strgGrid.RowCount - 1] := FPO.POItems[i].SatCodeOrder.UOM;
curreditTotalPrice.Value := curreditTotalPrice.Value + dQty * curredtUnitPrice.Value;
end;
end;
AutoSize := True;
end;
}
end;
procedure TfrmDialogBarcodeRequest.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if(Key = VK_F2) then
bSearchPOClick(Sender)
end;
initialization
IsSuccessfull := False;
end.
|
program CorDepthCombine;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp
{ you can add units after this };
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TMyApplication }
procedure TMyApplication.DoRun;
var
ErrorMsg: String;
//Program Var
liblist: TextFile;
lib_file: array of File of Single;
Combined: File of Single;
libname: String;
Output, Buffer: array[1..65536] of Single;
I: QWord;
J: Word;
Read_size, Read_buf, K: Cardinal;
begin
// quick check parameters
ErrorMsg:=CheckOptions('hl','help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h','help') then begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
if HasOption('l') then
AssignFile(liblist,GetOptionValue('l'))
else begin
WriteHelp;
Terminate;
Exit;
end;
WriteLN('Load list: '+GetOptionValue('l'));
Reset(liblist);
I:=0;
SetLength(lib_file,0);
while not EOF(liblist) do
begin
ReadLN(liblist, libname);
if FileExists(libname) then
begin
J:=Length(lib_file)+1;
WriteLN(InttoStr(Length(lib_file)));
SetLength(lib_file, J);
AssignFile(lib_file[J-1],libname);
Reset(lib_file[J-1]);
WriteLN(libname);
if I = 0 then
I:=FileSize(lib_file[0])
else if FileSize(lib_file[J-1]) <> I then
begin
WriteLN('File size inconsistant: '+libname+' '+IntToStr(FileSize(lib_file[J-1])));
WriteLN('Other size: '+IntToStr(I)+' Bytes');
Exit;
end;
end;
end;
CloseFile(liblist);
if Length(lib_file) =0 then
begin
WriteLN('No file exist, exiting');
Terminate;
Exit;
end;
AssignFile(Combined,ChangeFileExt(GetOptionValue('l'),'_merged.bin'));
WriteLN('File created for output');
Rewrite(Combined);
I:=0;
repeat
BlockRead(lib_file[0],Output[1],Length(Output),Read_size);
for J := 1 to Length(lib_file)-1 do
begin
BlockRead(lib_file[J],Buffer[1],Length(Buffer),Read_buf);
for K := 1 to Read_size do
begin
Output[K]:=Output[K]+Buffer[K];
end;
end;
BlockWrite(Combined,Output[1],Read_size);
Inc(I,Read_size);
until EOF(lib_file[1]);
//File Close
for J := 0 to Length(lib_file)-1 do
begin
CloseFile(lib_file[J]);
end;
CloseFile(Combined);
// stop program loop
Terminate;
end;
constructor TMyApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TMyApplication.Destroy;
begin
inherited Destroy;
end;
procedure TMyApplication.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ',ExeName,' -h');
WriteLN('Option: -l [library.txt]');
WriteLN('library.txt should contain each .bin file of equal size separate by lines');
end;
var
Application: TMyApplication;
begin
Application:=TMyApplication.Create(nil);
Application.Title:='Combine Corrected Depth';
Application.Run;
Application.Free;
end.
|
unit uDump;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfDump = class(TForm)
btnExec: TButton;
btnCancel: TButton;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
edtEnd: TEdit;
edtStart: TEdit;
btnWholeCore: TButton;
GroupBox2: TGroupBox;
cbxNotEmpty: TCheckBox;
cbxUsedA: TCheckBox;
cbxShownInWatches: TCheckBox;
Label3: TLabel;
edtFileName: TEdit;
btnSelectFile: TButton;
SaveDialog: TSaveDialog;
cbxUsedB: TCheckBox;
procedure edtEndKeyPress(Sender: TObject; var Key: Char);
procedure OthersKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure btnWholeCoreClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnExecClick(Sender: TObject);
procedure btnSelectFileClick(Sender: TObject);
procedure edtFileNameChange(Sender: TObject);
private
public userSelection : Integer;
CORE_SIZE : Integer;
end;
const usCancel = 0;
usExec = 1;
var
fDump: TfDump;
implementation
{$R *.dfm}
function StoI( s : String ) : Integer;
var c : Integer;
Ret : Integer;
begin Val( s, Ret, c );
StoI := Ret;
end;
function MMod( a : Integer ) : Integer;
begin if (a < 0)
then
MMod := fDump.CORE_SIZE - (Abs(a) MOD fDump.CORE_SIZE)
else
MMod := a MOD fDump.CORE_SIZE;
end;
function formatAdress( a : Integer ) : String;
var Ret : String;
begin Str( MMod(a), Ret );
While( Length(Ret) < 6 )
do
Ret := '0' + Ret;
FormatAdress := Ret;
end;
procedure TfDump.btnSelectFileClick(Sender: TObject);
begin if (SaveDialog.Execute)
then begin
edtFileName.Text := SaveDialog.FileName;
btnExec.Enabled := TRUE;
end;
end;
procedure TfDump.FormShow(Sender: TObject);
begin userSelection := usCancel;
btnWholeCoreClick( Sender );
end;
procedure TfDump.btnWholeCoreClick(Sender: TObject);
begin edtStart.Text := formatAdress( 0 );
edtEnd.Text := formatAdress( fDump.CORE_SIZE - 1 );
end;
procedure TfDump.edtEndKeyPress(Sender: TObject; var Key: Char);
begin if (Key = #27)
then begin
userSelection := usCancel;
fDump.Close;
end;
if (Pos( Key, '1234567890' + #8 ) = 0)
then
Key := #0
else
btnExec.Enabled := TRUE;
end;
procedure TfDump.OthersKeyPress(Sender: TObject; var Key: Char);
begin if (Key = #27)
then begin
userSelection := usCancel;
Key := #0;
fDump.Close;
end;
end;
procedure TfDump.btnCancelClick(Sender: TObject);
begin userSelection := usCancel;
fDump.Close;
end;
procedure TfDump.btnExecClick(Sender: TObject);
label finish;
begin /// ?? btnExec.Enabled := FALSE;
if (StoI( edtStart.Text ) > StoI( edtEnd.Text ))
then begin
edtStart.Text := edtEnd.Text;
edtStart.SetFocus;
goto finish;
end;
if (StoI( edtStart.Text ) >= CORE_SIZE)
then begin
edtStart.Text := formatAdress( CORE_SIZE - 1 );
edtStart.SetFocus;
goto finish;
end;
if (StoI( edtEnd.Text ) >= CORE_SIZE)
then begin
edtEnd.Text := formatAdress( CORE_SIZE - 1 );
edtEnd.SetFocus;
goto finish;
end;
if not DirectoryExists( ExtractFilePath( edtFileName.Text ))
then begin
edtFileName.SetFocus;
goto finish;
end;
userSelection := usExec;
fDump.Close;
finish:
end;
procedure TfDump.edtFileNameChange(Sender: TObject);
begin btnExec.Enabled := TRUE;
end;
end.
|
{$INCLUDE switches}
unit StringTables;
interface
const
MaxCount=4000;
type
TCharList=array[0..9999999] of char;
TStringTable=class
constructor Create;
destructor Destroy; override;
function LoadFromFile(const FileName: string): boolean;
function GetHandle(const Item: string): integer;
function LookupByHandle(Handle: integer; Index: integer =-1): string;
function Lookup(const Item: string; Index: integer =-1): string;
function Search(const Content: string; var Handle, Index: integer): boolean;
protected
Count: integer;
Data: ^TCharList;
Lines: array[0..MaxCount-1] of PChar;
end;
implementation
uses
Classes,SysUtils;
constructor TStringTable.Create;
begin
Data:=nil;
end;
destructor TStringTable.Destroy;
begin
if Data<>nil then FreeMem(Data);
end;
function TStringTable.LoadFromFile(const FileName: string): boolean;
var
nData, i: integer;
f: TFileStream;
begin
if Data<>nil then FreeMem(Data);
try
f:=TFileStream.Create(FileName, fmOpenRead or fmShareExclusive);
except
result:=false;
exit;
end;
result:=true;
nData:=f.Size;
GetMem(Data,nData+1);
f.read(Data^,nData);
f.Free;
i:=0;
Count:=0;
while (i<nData) and (Count<MaxCount) do
begin
Lines[Count]:=@Data[i];
while (i<nData) and (Data[i]<>#13) do inc(i);
Data[i]:=#0;
inc(i,2);
inc(Count);
end;
end;
function TStringTable.GetHandle(const Item: string): integer;
var
i,l: integer;
begin
l:=Length(Item);
i:=Count-1;
while (i>=0) and ((Lines[i][0]<>'#')
or (StrLComp(Lines[i]+1,@Item[1],l)<>0)
or (Lines[i][l+1]<>#0) and (Lines[i][l+1]<>' ')) do
dec(i);
result:=i
end;
function TStringTable.LookupByHandle(Handle: Integer; Index: integer): string;
var
s: string;
begin
if Index<0 then
if Handle<0 then begin result:=''; exit end
else
begin
if pos(' ',Lines[Handle])=0 then s:=''
else s:=copy(Lines[Handle],pos(' ',Lines[Handle])+1,MaxInt);
while (Handle+1<Count) and (Lines[Handle+1][0]<>'#') do
begin
inc(Handle);
if (Lines[Handle][0]<>#0) and (Lines[Handle][0]<>'''') then
begin
if (s<>'') and (s[Length(s)]<>'\') then s:=s+' ';
s:=s+Lines[Handle];
end
end;
result:=s
end
else if Handle+Index+1>=Count then begin result:=''; exit end
else result:=Lines[Handle+Index+1];
while (result<>'') and ((result[1]=' ') or (result[1]=#9)) do
Delete(result,1,1);
while (result<>'')
and ((result[Length(result)]=' ') or (result[Length(result)]=#9)) do
Delete(result,Length(result),1);
if result='' then result:='*';
end;
function TStringTable.Lookup(const Item: string; Index: integer): string;
var
Handle: integer;
begin
Handle:=Gethandle(Item);
if Handle>=0 then result:=LookupByHandle(Handle, Index)
else result:='';
if result='' then
if Index<0 then result:=Format('[%s]',[Item])
else result:=Format('[%s %d]',[Item,Index])
end;
{might become necessary for 1.3
function TStringTable.Lookup(const Fallback: TStringTable; const Item: string; Index: integer): string;
var
Handle: integer;
begin
Handle:=Gethandle(Item);
if Handle>=0 then result:=LookupByHandle(Handle, Index)
else result:='';
if result='' then
result:=Fallback.Lookup(Item, Index);
end;
function TStringTable.TryLookup(const Item: string; Index: integer): string;
var
Handle: integer;
begin
Handle:=Gethandle(Item);
if Handle>=0 then result:=LookupByHandle(Handle, Index)
else result:='';
end;}
function TStringTable.Search(const Content: string; var Handle, Index: integer): boolean;
var
h,i: integer;
UContent: string;
begin
UContent:=UpperCase(Content);
h:=Handle;
if h<0 then i:=0
else i:=Index+1;
repeat
if h+i+1>=Count then
begin result:=false; exit end;
if Lines[h+i+1][0]='#' then
begin h:=h+i+1; i:=-1 end;
if (h>=0) and not (Lines[h+i+1][0] in ['#',':',';'])
and (pos(UContent, UpperCase(Lines[h+i+1]))>0) then
begin Index:=i; Handle:=h; result:=true; exit end;
inc(i);
until false;
end;
end.
|
unit LogSocket;
interface
uses
IdTCPClient, BasisFunction, Windows, SysUtils, Classes, SyncObjs, DefineUnit,
Types, BaseClientSocket, IdIOHandlerSocket, Messages;
type
TLogThread = class;
TOnLog = procedure(const ALogMessage: string) of object;
TLogSocket = class(TBaseClientSocket)
private
{* 日志响应消息 *}
FOnLog: TOnLog;
{* 接收线程 *}
FLogThread: TLogThread;
public
constructor Create; override;
destructor Destroy; override;
{* 连接服务器 *}
function Connect(const ASvr: string; APort: Integer): Boolean;
{* 断开连接 *}
procedure Disconnect;
{* 获取日志 *}
function GetLog: string;
{* 启动 *}
procedure Start;
{* 停止 *}
procedure Stop;
property OnLog: TOnLog read FOnLog write FOnLog;
end;
TLogThread = class(TThread)
private
{* 日志信息 *}
FLogMessage: string;
{* Socket *}
FLogSocket: TLogSocket;
{* 触发日志接收消息 *}
procedure DoLog;
protected
procedure Execute; override;
end;
implementation
uses DataMgrCtr, ClientDefineUnit, Logger;
{ TLogSocket }
constructor TLogSocket.Create;
begin
inherited;
FTimeOutMS := 60 * 1000; //超时设置为60S
end;
destructor TLogSocket.Destroy;
begin
inherited;
end;
function TLogSocket.Connect(const ASvr: string; APort: Integer): Boolean;
begin
FHost := ASvr;
FPort := APort;
Result := inherited Connect(#9);
end;
procedure TLogSocket.Disconnect;
begin
inherited Disconnect;
end;
function TLogSocket.GetLog: string;
begin
if FClient.Socket.Readable then
Result := FClient.CurrentReadBuffer
else
Result := '';
end;
procedure TLogSocket.Start;
begin
FLogThread := TLogThread.Create(True);
FLogThread.FreeOnTerminate := False;
FLogThread.FLogSocket := Self;
FLogThread.Resume;
end;
procedure TLogSocket.Stop;
begin
Disconnect;
FLogThread.Terminate;
FLogThread.WaitFor;
FLogThread.Free;
end;
{ TLogThread }
procedure TLogThread.DoLog;
begin
if Assigned(FLogSocket.OnLog) then
FLogSocket.OnLog(FLogMessage);
end;
procedure TLogThread.Execute;
begin
inherited;
while (not Terminated) and (FLogSocket.Connected) do
begin
try
FLogMessage := FLogSocket.GetLog;
if FLogMessage <> '' then
Synchronize(DoLog);
Sleep(10);
except
on E: Exception do
begin
WriteLogMsg(ltError, 'Get Log Error, Message: ' + E.Message);
Break;
end;
end;
end;
PostMessage(GDataMgrCtr.NotifyHandle, WM_Disconnect, 0, 0);
end;
end.
|
program iris;
{$mode objfpc}{$H+}
uses
noe,
noe.Math,
noe.neuralnet,
noe.utils,
noe.optimizer;
var
X, y: TTensor;
yPred, Loss: TVariable;
Enc: TOneHotEncoder;
Dataset: TTensor;
MyModel: TModel;
opt: TAdamOptimizer;
i: longint;
begin
Dataset := ReadCSV('../datasets/iris.csv');
X := GetColumnRange(Dataset, 0, 4);
X := StandardScaler(X);
y := GetColumn(Dataset, 4);
{ One-hot encoding the raw label }
Enc := TOneHotEncoder.Create;
y := Enc.Encode(y);
MyModel := TModel.Create([
TDenseLayer.Create(4, 30),
TLeakyReLULayer.Create(0.1),
TDenseLayer.Create(30, 3),
TSoftMaxLayer.Create(1)
]);
opt := TAdamOptimizer.Create;
opt.LearningRate := 0.01;
{ To show loss value at each iteration. Default: True }
opt.Verbose := True;
for i := 0 to 1 do
begin
yPred := MyModel.Eval(X);
Loss := CrossEntropyLoss(yPred, y);
opt.UpdateParams(Loss, MyModel.Params);
end;
WriteLn('Tranining accuracy: ', AccuracyScore(Enc.Decode(yPred.Data),
Enc.Decode(y)): 2: 3);
noe.Cleanup;
Enc.Cleanup;
MyModel.Cleanup;
ReadLn;
end.
|
unit iaDemo.ExecutionProfiler.MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TDemoExecutionProfilerForm = class(TForm)
butExecuteDemoCode: TButton;
butViewCurrentStatistics: TButton;
memLog: TMemo;
butExecMultiThreaded: TButton;
procedure butExecuteDemoCodeClick(Sender: TObject);
procedure butViewCurrentStatisticsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure butExecMultiThreadedClick(Sender: TObject);
private
procedure DoSomeComplexCode;
public
{ Public declarations }
end;
TMySimpleThread = class(TThread)
private
fSleepTime:Integer;
public
constructor Create(const pSleepTime:Integer);
procedure Execute(); override;
end;
var
DemoExecutionProfilerForm: TDemoExecutionProfilerForm;
implementation
uses
System.DateUtils,
iaRTL.ExecutionProfiler;
{$R *.dfm}
procedure TDemoExecutionProfilerForm.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
memLog.Clear;
memLog.Lines.Add(iaRTL.ExecutionProfiler.CSVHeaderLine);
end;
//Example how to automatically save performance metrics to a file when the program exits
procedure TDemoExecutionProfilerForm.FormDestroy(Sender: TObject);
{$IFDEF PROFILER}
var
vAutoSaveStats:TStringList;
{$ENDIF}
begin
{$IFDEF PROFILER}
vAutoSaveStats := TStringList.Create;
try
if TiaProfiler.ExportStats(vAutoSaveStats, TiaExportResolution.Milliseconds) > 0 then
begin
vAutoSaveStats.SaveToFile('PerformanceStats.csv');
end;
finally
vAutoSaveStats.Free;
end;
{$ENDIF}
end;
procedure TDemoExecutionProfilerForm.butViewCurrentStatisticsClick(Sender: TObject);
begin
{$IFDEF PROFILER}
TiaProfiler.ExportStats(memLog.Lines, TiaExportResolution.Milliseconds);
{$ENDIF}
end;
procedure TDemoExecutionProfilerForm.butExecuteDemoCodeClick(Sender: TObject);
var
i:integer;
begin
for i := 1 to 10 do
begin
DoSomeComplexCode;
end;
end;
//Here's an example "Old school" way of doing timing:
//procedure TDemoExecutionProfilerForm.DoSomeComplexCode;
//var
// StartTime:TDateTime;
// DebugMessage:String;
//begin
// StartTime := Now;
// Sleep(75); //some time intensive code block
// DebugMessage := Format('DoSomeComplexCode took %dms', [MillisecondsBetween(Now, StartTime)]);
// OutputDebugString(PChar(DebugMessage));
//end;
//Here's the old school method upgraded to TiaProfiler:
//procedure TDemoExecutionProfilerForm.DoSomeComplexCode;
//begin
// TiaProfiler.StartTimer('DoSomeComplexCode');
// Sleep(75); //some time intensive code block
// TiaProfiler.StopTimer('DoSomeComplexCode');
//end;
//The same TiaProfiler code surrounded with compiler define, as recommended.
procedure TDemoExecutionProfilerForm.DoSomeComplexCode;
begin
{$IFDEF PROFILER}TiaProfiler.StartTimer('DoSomeComplexCode');{$ENDIF}
Sleep(75); //some time intensive code block
{$IFDEF PROFILER}TiaProfiler.StopTimer('DoSomeComplexCode');{$ENDIF}
end;
//Example used for Issue #2 correction
//https://github.com/ideasawakened/iaLib/issues/2
procedure TDemoExecutionProfilerForm.butExecMultiThreadedClick(Sender: TObject);
begin
//Before fix, this will produce incorrect results (around 1 second min and 3 second max)
//After fix, this should produce correct results (around 2 second min, max, average)
TMySimpleThread.Create(2000);
Sleep(1000);
TMySimpleThread.Create(2000);
end;
constructor TMySimpleThread.Create(const pSleepTime:Integer);
begin
fSleepTime := pSleepTime;
FreeOnTerminate := True;
inherited Create;
end;
procedure TMySimpleThread.Execute;
begin
{$IFDEF PROFILER}TiaProfiler.StartTimer('ThreadedExample1');{$ENDIF}
Sleep(fSleepTime); //some time intensive code block
{$IFDEF PROFILER}TiaProfiler.StopTimer('ThreadedExample1');{$ENDIF}
end;
end.
|
{
Copy VMAD subrecord (attached papyrus scripts data) to selected record(s)
from provided source record.
}
unit UserScript;
var
BaseRecord: IInterface;
function Initialize: integer;
var
s: string;
i: integer;
plug: IInterface;
begin
if not InputQuery('Record FormID', 'Copy VMAD from', s) then begin
Result := 1;
Exit;
end;
i := StrToIntDef('$' + s, 0);
if i = 0 then begin
AddMessage('Invalid input, enter hexadecimal FormID');
Result := 1;
Exit;
end;
plug := FileByLoadOrder(i shr 24);
if not Assigned(plug) then begin
AddMessage('Can''t locate source plugin with load order ' + IntToStr(FileByLoadOrder(i shr 24)));
Result := 1;
Exit;
end;
BaseRecord := WinningOverride(RecordByFormID(plug, LoadOrderFormIDToFileFormID(plug, i), False));
if not Assigned(BaseRecord) then begin
AddMessage('Can''t locate source record ' + s + ' in ' + GetFileName(plug));
Result := 1;
Exit;
end;
end;
function Process(e: IInterface): integer;
begin
Add(e, 'VMAD', True);
if ElementExists(e, 'VMAD') then
ElementAssign(ElementByPath(e, 'VMAD'), LowInteger, ElementByPath(BaseRecord, 'VMAD'), False);
end;
end.
|
unit U_ROTINASGENERICAS;
interface
uses Windows, SysUtils, Forms;
procedure Mensagem(strTexto: string);
function Confirma(strTexto: string): integer;
function MostraData(dtData: TDateTime): string;
function StrZero(intValor,intComprimento: integer): string;
procedure PontoDecimal(var Key: char);
implementation
// Rotina para apresentar uma caixa de mensagem.
procedure Mensagem(strTexto: string);
begin
Application.MessageBox(PChar(strTexto),'Mensagem',mb_OK + mb_IconInformation);
end;
// Função para pedir confirmação de uma operação.
function Confirma(strTexto: string): integer;
begin
Result := Application.MessageBox(PChar(strTexto),'Confirmação',mb_YesNo+mb_DefButton2+mb_IconQuestion);
end;
// Função para apresentação de uma data no formato 'Dia da semanada - Dia do mês/Mês/Ano'.
function MostraData(dtData: TDateTime): string;
var
intDiaSemana: integer;
strDiaSemana: string;
begin
intDiaSemana := DayOfWeek(dtData);
case intDiaSemana of
1: strDiaSemana := 'Domingo - ';
2: strDiaSemana := 'Segunda-feira - ';
3: strDiaSemana := 'Terça-feira - ';
4: strDiaSemana := 'Quarta-feira - ';
5: strDiaSemana := 'Quinta-feira - ';
6: strDiaSemana := 'Sexta-feira - ';
7: strDiaSemana := 'Sábado - ';
end;
Result := strDiaSemana+DateToStr(dtData);
end;
// Funcao para converte valor numerico inteiro em string com zeros a esquerda
function StrZero(intValor,intComprimento: integer): string;
var
strValor,strZeros,strRetorno: string;
intTamanho,intContador: integer;
begin
strValor := IntToStr(intValor);
intTamanho := Length(Trim(strValor));
strZeros := '';
for intContador := 1 to intComprimento do
strZeros := strZeros + '0';
strRetorno := Copy(Trim(strZeros)+Trim(strValor),intTamanho+1,intComprimento);
Result := strRetorno;
end;
// Converte o ponto decimal em virgula
procedure PontoDecimal(var Key: char);
begin
if (Key <> Chr(8)) then
if (Key = '.') then
Key := ','
else if ((Ord(Key) <> Ord(',')) and ((Ord(Key) < Ord('0')) or (Ord(Key) > Ord('9')))) then
Key := Chr(0);
end;
end.
|
// CHANGES
//
// 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers)
unit MappedPortWinshoe;
interface
uses
ServerWinshoe
, Winshoes;
type
TWinshoeMappedPortData = class
public
OutboundClient: TWinshoeClient;
end;
TWinshoeMappedPort = class(TWinshoeListener)
private
fiMappedPort: Integer;
fsMappedHost: String;
protected
procedure DoConnect(Thread: TWinshoeServerThread); override;
function DoExecute(Thread: TWinshoeServerThread): boolean; override;
public
published
property MappedHost: string read fsMappedHost write fsMappedHost;
property MappedPort: Integer read fiMappedPort write fiMappedPort;
end;
// Procs
procedure Register;
implementation
uses
Classes
, WinsockIntf;
procedure Register;
begin
RegisterComponents('Winshoes Servers', [TWinshoeMappedPort]);
end;
procedure TWinshoeMappedPort.DoConnect(Thread: TWinshoeServerThread);
begin
inherited;
Thread.SessionData := TWinshoeMappedPortData.Create;
TWinshoeMappedPortData(Thread.SessionData).OutboundClient := TWinshoeClient.Create(nil);
with TWinshoeMappedPortData(Thread.SessionData).OutboundClient do begin
Port := MappedPort;
Host := MappedHost;
{TODO Handle connect failures}
Connect;
end;
end;
function TWinshoeMappedPort.DoExecute(Thread: TWinshoeServerThread): boolean;
var
FDRead: TFDSet;
OutClient: TWinshoeClient;
begin
{TODO Cache this info - no need to reconstruct each time}
OutClient := TWinshoeMappedPortData(Thread.SessionData).OutboundClient;
try
result := false;
FDRead.fd_count := 2;
FDRead.fd_array[0] := Thread.Connection.Handle;
FDRead.fd_array[1] := OutClient.Handle;
if WinsockInterface.Select(0, @FDRead, nil, nil, nil) > 0 then begin
if Thread.Connection.Readable(1) then
OutClient.Write(Thread.Connection.ReadBuffer);
if OutClient.Readable(1) then
Thread.Connection.Write(OutClient.ReadBuffer);
end;
finally
if not OutClient.Connected then
Thread.Connection.Disconnect;
end;
end;
end.
|
unit AddSessionFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls;
type
TAddSessionForm = class(TForm)
NewRadio: TRadioButton;
Label1: TLabel;
OpenRadio: TRadioButton;
OKButton: TBitBtn;
CancelButton: TBitBtn;
FileNameLabel: TLabel;
FileNameEdit: TEdit;
BrowseButton: TSpeedButton;
DescrLabel: TLabel;
DescrEdit: TEdit;
OpenDialog: TOpenDialog;
procedure NewRadioClick(Sender: TObject);
procedure OpenRadioClick(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function AddSession(var FileName, Descr: string): Boolean;
function CreateSession(var FileName, Descr: string): Boolean;
end;
var
AddSessionForm: TAddSessionForm;
implementation
uses CreateSessionFrm;
{$R *.DFM}
function TAddSessionForm.CreateSession(var FileName, Descr: string): Boolean;
begin
Result:=CreateSessionForm.CreateSession(FileName,Descr);
end;
function TAddSessionForm.AddSession(var FileName, Descr: string): Boolean;
begin
EditChange(nil);
FileName:='';
Descr:='';
Result:=ShowModal=mrOk;
if Result then
if NewRadio.Checked then
Result:=CreateSession(FileName,Descr)
else
begin
FileName:=FileNameEdit.Text;
if Copy(LowerCase(FileName),Length(FileName)-3,4)='.msc' then
Delete(FileName,Length(FileName)-3,4);
Descr:=DescrEdit.Text;
end
end;
procedure TAddSessionForm.NewRadioClick(Sender: TObject);
begin
FileNameLabel.Enabled:=False;
FileNameEdit.Enabled:=False;
BrowseButton.Enabled:=False;
DescrLabel.Enabled:=False;
DescrEdit.Enabled:=False;
FileNameEdit.Color:=clBtnFace;
DescrEdit.Color:=clBtnFace;
EditChange(Sender);
end;
procedure TAddSessionForm.OpenRadioClick(Sender: TObject);
begin
FileNameLabel.Enabled:=True;
FileNameEdit.Enabled:=True;
BrowseButton.Enabled:=True;
DescrLabel.Enabled:=True;
DescrEdit.Enabled:=True;
FileNameEdit.Color:=clWindow;
DescrEdit.Color:=clWindow;
EditChange(Sender);
end;
procedure TAddSessionForm.EditChange(Sender: TObject);
begin
OkButton.Enabled:=(NewRadio.Checked) or ((FileNameEdit.Text<>'') and (DescrEdit.Text<>''));
end;
procedure TAddSessionForm.BrowseButtonClick(Sender: TObject);
begin
OpenDialog.FileName:=FileNameEdit.Text;
if OpenDialog.Execute then
FileNameEdit.Text:=OpenDialog.FileName;
end;
end.
|
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Contributor(s):
* Jody Dawkins <jdawkins@delphixtreme.com>
*)
unit dSpecBehavoirs;
interface
uses Classes, dSpec, dSpecIntf;
type
TAutoDocContext = class(TContext)
{ using a base context simply to turn on AutoDoc }
public
constructor Create(MethodName : string); override;
end;
AutoDoc = class(TContext)
private
FAutoDoc : IAutoDoc;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ShouldHaveSpecs;
procedure ShouldDocumentSpecNames;
procedure ShouldDocumentSpecs;
procedure ShouldNotOutputAnythingWhenDisabled;
end;
Context = class(TAutoDocContext)
published
procedure ShouldHaveSpecs;
procedure ShouldModifyTheEqualSpecifier;
procedure ShouldEvaluateUnlessModifier;
procedure ShouldEvaluateToleranceModifier;
procedure ShouldEvaluateManyModifiers;
procedure ShouldModifyTheNotEqualSpecifier;
procedure ShouldAllowMultipleSpecifiers;
procedure ShouldNegateSpecs;
procedure ShouldAllowOptionalNamingOfSpecs;
procedure ShouldHaveAnAutoDocInterface;
procedure ShouldNotAllowANullAutoDoc;
end;
IntegerSpecification = class(TAutoDocContext)
private
FInteger: Integer;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateEquality;
procedure ShouldEvaluateInequality;
procedure ShouldEvaluateRange;
procedure ShouldEvaluateOdd;
procedure ShouldEvaluateEven;
procedure ShouldEvaluatePositive;
procedure ShouldEvaluateNegative;
procedure ShouldEvaluatePrime;
procedure ShouldEvaluateZero;
procedure ShouldEvaluateComposite;
end;
BooleanSpecification = class(TAutoDocContext)
private
FBoolean : Boolean;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateEquality;
procedure ShouldEvaluateInequality;
end;
FloatSpecification = class(TAutoDocContext)
private
FFloat : Extended;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateEquality;
procedure ShouldEvaluateInequality;
procedure ShouldEvalulateRange;
procedure ShouldEvaluatePositive;
procedure ShouldEvaluateNegative;
procedure ShouldEvaluateZero;
procedure ShouldEvaluatePercentages;
end;
StringSpecification = class(TAutoDocContext)
private
FString : string;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateEquality;
procedure ShouldEvaluateInequality;
procedure ShouldEvaluateNumeric;
procedure ShouldEvaluateAlpha;
procedure ShouldEvaluateAlphaNumeric;
procedure ShouldEvaluateBeginningOfStrings;
procedure ShouldEvaluateStringContents;
procedure ShouldEvaluateEndOfStrings;
procedure ShouldHaveCaseInsentiveModifier;
procedure ShouldEvaluateEmpty;
end;
DateTimeSpecification = class(TAutoDocContext)
private
FDateTime : TDateTime;
FLowDate: TDateTime;
FHighDate: TDateTime;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateEquality;
procedure ShouldEvaluateInequality;
procedure ShouldEvalulateRange;
end;
ClassSpecification = class(TAutoDocContext)
private
FClass : TClass;
protected
procedure SetUp; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateInheritance;
procedure ShouldEvaluateType;
end;
ObjectSpecification = class(TAutoDocContext)
private
FInterfacedObject : TInterfaceList;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateInheritance;
procedure ShouldEvaluateType;
procedure ShouldEvaluateAssignment;
procedure ShouldEvaluateInterfaceImplementation;
procedure ShouldEvaluteSupportedInterfaces;
end;
PointerSpecification = class(TAutoDocContext)
private
FPointer : Pointer;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateAssignment;
end;
InterfaceSpecification = class(TAutoDocContext)
private
FInterface: IInterfaceList;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ShouldHaveSpecs;
procedure ShouldEvaluateAssignment;
procedure ShouldEvaluateSupportedInterfaces;
procedure ShouldEvaluateImplementingObject;
end;
implementation
uses SysUtils, TestFramework, AutoDocObjects;
{ TDSpecContext }
constructor TAutoDocContext.Create(MethodName: string);
begin
inherited Create(MethodName);
AutoDoc.Enabled := True;
end;
{ TContextBehaviors }
procedure Context.ShouldAllowMultipleSpecifiers;
var
TheNumber: Integer;
begin
TheNumber := 3;
Specify.That(TheNumber).Should.Equal(3).And_.Not_.Equal(2).And_.Not_.Equal(4); // 5 is right out! :P
end;
procedure Context.ShouldHaveAnAutoDocInterface;
var
ContextIntf: IContext;
begin
ContextIntf := Self as IContext;
Specify.That(ContextIntf.AutoDoc, 'AutoDoc').Should.Be.Assigned;
end;
procedure Context.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure Context.ShouldAllowOptionalNamingOfSpecs;
var
Rate: Extended;
begin
Rate := 0.15;
Specify.That(Rate, 'Tax rate').Should.Equal(0.15);
end;
procedure Context.ShouldEvaluateManyModifiers;
var
TheToleranceDoesntMatter: Boolean;
begin
TheToleranceDoesntMatter := False;
Specify.That(3.51).Should.Equal(3.5).WithAToleranceOf(0.1).Unless(TheToleranceDoesntMatter);
end;
procedure Context.ShouldEvaluateUnlessModifier;
var
ImInAnotherUniverse: Boolean;
begin
ImInAnotherUniverse := False;
Specify.That(2 + 2).Should.Equal(4).Unless(ImInAnotherUniverse);
end;
procedure Context.ShouldModifyTheEqualSpecifier;
var
WeAreInSectorZZ9PluralZAlpha: Boolean;
TheAnwserToLifeTheUniverseAndEverything: Integer;
begin
WeAreInSectorZZ9PluralZAlpha := False;
TheAnwserToLifeTheUniverseAndEverything := 42;
Specify.That(TheAnwserToLifeTheUniverseAndEverything).Should.Equal(42).Unless(WeAreInSectorZZ9PluralZAlpha);
end;
procedure Context.ShouldModifyTheNotEqualSpecifier;
var
b: Boolean;
IWantAnError: Boolean;
begin
b := True;
IWantAnError := False;
Specify.That(b).Should.Not_.Equal(True).Unless(IWantAnError);
end;
procedure Context.ShouldNegateSpecs;
begin
Specify.That(False).Should.Not_.Be.True.And_.Be.False.And_.Not_.Be.True;
Specify.That(42).Should.Be.AtLeast(40).And_.Not_.Be.GreaterThan(50).And_.Be.LessThan(50);
end;
procedure Context.ShouldNotAllowANullAutoDoc;
var
ContextIntf: IContext;
begin
ContextIntf := Self as IContext;
ContextIntf.AutoDoc := nil;
{ TBaseAutoDoc defaults Enabled to False .. we have to turn it back on }
ContextIntf.AutoDoc.Enabled := True;
Specify.That(ContextIntf.AutoDoc, 'AutoDoc').Should.Be.Assigned;
end;
procedure Context.ShouldEvaluateToleranceModifier;
begin
Specify.That(3.51).Should.Equal(3.5).WithAToleranceOf(0.1);
end;
{ TIntegerSpecBehaviors }
procedure IntegerSpecification.SetUp;
begin
FInteger := 42;
ContextDescription := 'When an integer = 42';
end;
procedure IntegerSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure IntegerSpecification.ShouldEvaluateComposite;
begin
Specify.That(FInteger).Should.Be.Composite;
end;
procedure IntegerSpecification.ShouldEvaluateEquality;
begin
Specify.That(FInteger).Should.Equal(42)
end;
procedure IntegerSpecification.ShouldEvaluateEven;
begin
Specify.That(FInteger).Should.Be.Even;
end;
procedure IntegerSpecification.ShouldEvaluateInEquality;
begin
Specify.That(FInteger).Should.Not_.Equal(0)
end;
procedure IntegerSpecification.ShouldEvaluateNegative;
begin
Specify.That(FInteger).Should.Not_.Be.Negative;
end;
procedure IntegerSpecification.ShouldEvaluateOdd;
begin
Specify.That(FInteger).Should.Not_.Be.Odd;
end;
procedure IntegerSpecification.ShouldEvaluatePositive;
begin
Specify.That(FInteger).Should.Be.Positive;
end;
procedure IntegerSpecification.ShouldEvaluatePrime;
begin
Specify.That(FInteger).Should.Not_.Be.Prime;
end;
procedure IntegerSpecification.ShouldEvaluateRange;
begin
Specify.That(FInteger).Should.Be.GreaterThan(40).And_.Be.LessThan(50);
Specify.That(FInteger).Should.Be.AtLeast(40).And_.Be.AtMost(50);
end;
procedure IntegerSpecification.ShouldEvaluateZero;
begin
Specify.That(FInteger).Should.Not_.Be.Zero;
end;
{ TBooleanSpecBehaviors }
procedure BooleanSpecification.SetUp;
begin
FBoolean := True;
ContextDescription := 'When a boolean = True';
end;
procedure BooleanSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure BooleanSpecification.ShouldEvaluateEquality;
begin
Specify.That(FBoolean).Should.Equal(True);
Specify.That(FBoolean).Should.Be.True;
end;
procedure BooleanSpecification.ShouldEvaluateInEquality;
begin
Specify.That(FBoolean).Should.Not_.Equal(False);
Specify.That(FBoolean).Should.Not_.Be.False;
end;
{ TFloatSpecBehaviors }
procedure FloatSpecification.SetUp;
begin
FFloat := 1.618;
ContextDescription := 'When a float = 1.618';
end;
procedure FloatSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True)
end;
procedure FloatSpecification.ShouldEvaluateEquality;
begin
Specify.That(FFloat).Should.Equal(1.618)
end;
procedure FloatSpecification.ShouldEvaluateInEquality;
begin
Specify.That(FFloat).Should.Not_.Equal(2)
end;
procedure FloatSpecification.ShouldEvaluateNegative;
begin
Specify.That(FFloat).Should.Not_.Be.Negative;
end;
procedure FloatSpecification.ShouldEvaluatePercentages;
begin
Specify.That(FFloat).Should.Equal(161.8).Percent;
end;
procedure FloatSpecification.ShouldEvaluatePositive;
begin
Specify.That(FFloat).Should.Be.Positive;
end;
procedure FloatSpecification.ShouldEvaluateZero;
begin
Specify.That(FFloat).Should.Not_.Be.Zero;
end;
procedure FloatSpecification.ShouldEvalulateRange;
begin
Specify.That(FFloat).Should.Be.GreaterThan(1).And_.Be.LessThan(2);
Specify.That(FFloat).Should.Be.AtLeast(1).And_.Be.AtMost(2);
end;
{ TStringSpecBehaviors }
procedure StringSpecification.SetUp;
begin
FString := 'Greetings Footpad!';
ContextDescription := 'When a string = ''Greetings Footpad!''';
end;
procedure StringSpecification.ShouldHaveCaseInsentiveModifier;
begin
Specify.That(FString).Should.Equal(UpperCase(FString)).IgnoringCase;
end;
procedure StringSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True)
end;
procedure StringSpecification.ShouldEvaluateAlpha;
begin
Specify.That(FString).Should.Be.Alpha;
end;
procedure StringSpecification.ShouldEvaluateAlphaNumeric;
begin
Specify.That(FString).Should.Be.AlphaNumeric;
end;
procedure StringSpecification.ShouldEvaluateBeginningOfStrings;
begin
Specify.That(FString).Should.StartWith('Greetings');
end;
procedure StringSpecification.ShouldEvaluateEmpty;
begin
Specify.That(FString).Should.Not_.Be.Empty;
end;
procedure StringSpecification.ShouldEvaluateEndOfStrings;
begin
Specify.That(FString).Should.EndWith('pad!');
end;
procedure StringSpecification.ShouldEvaluateEquality;
begin
Specify.That(FString).Should.Equal('Greetings Footpad!');
end;
procedure StringSpecification.ShouldEvaluateInEquality;
begin
Specify.That(FString).Should.Not_.Equal('');
end;
procedure StringSpecification.ShouldEvaluateNumeric;
begin
Specify.That(FString).Should.Not_.Be.Numeric;
end;
procedure StringSpecification.ShouldEvaluateStringContents;
begin
Specify.That(FString).Should.Contain('Foot');
end;
{ TDateTimeSpecBehaviors }
procedure DateTimeSpecification.SetUp;
begin
FDateTime := EncodeDate(1999, 1, 1);
FLowDate := EncodeDate(1998, 12, 31);
FHighDate := EncodeDate(2000, 1, 1);
ContextDescription := 'When a date = ' + DateToStr(FDateTime);
end;
procedure DateTimeSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True)
end;
procedure DateTimeSpecification.ShouldEvaluateEquality;
begin
Specify.That(FDateTime).Should.Equal(EncodeDate(1999, 1, 1))
end;
procedure DateTimeSpecification.ShouldEvaluateInEquality;
begin
Specify.That(FDateTime).Should.Not_.Equal(EncodeDate(1999, 1, 2))
end;
procedure DateTimeSpecification.ShouldEvalulateRange;
begin
Specify.That(FDateTime).Should.Be.GreaterThan(FLowDate).And_.Be.LessThan(FHighDate);
Specify.That(FDateTime).Should.Be.AtLeast(FLowDate).And_.Be.AtMost(FHighDate);
end;
{ TClassSpecBehaviors }
procedure ClassSpecification.SetUp;
begin
FClass := TStringList;
ContextDescription := 'When a class = TStringList';
end;
procedure ClassSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure ClassSpecification.ShouldEvaluateInheritance;
begin
Specify.That(FClass).Should.DescendFrom(TObject);
end;
procedure ClassSpecification.ShouldEvaluateType;
begin
Specify.That(FClass).Should.Be.OfType(TStringList)
end;
{ TObjectSpecBehaviors }
procedure ObjectSpecification.SetUp;
begin
FInterfacedObject := TInterfaceList.Create;
ContextDescription := 'When an object = TInterfaceList';
end;
procedure ObjectSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True)
end;
procedure ObjectSpecification.ShouldEvaluateAssignment;
begin
Specify.That(FInterfacedObject).Should.Not_.Be.Nil_;
Specify.That(FInterfacedObject).Should.Be.Assigned;
FInterfacedObject := nil;
Specify.That(FInterfacedObject).Should.Be.Nil_;
Specify.That(FInterfacedObject).Should.Not_.Be.Assigned;
end;
procedure ObjectSpecification.ShouldEvaluateInheritance;
begin
Specify.That(FInterfacedObject).Should.DescendFrom(TObject)
end;
procedure ObjectSpecification.ShouldEvaluateInterfaceImplementation;
begin
Specify.That(FInterfacedObject).Should.Implement(IInterfaceList);
end;
procedure ObjectSpecification.ShouldEvaluateType;
begin
Specify.That(FInterfacedObject).Should.Be.OfType(TInterfaceList)
end;
procedure ObjectSpecification.ShouldEvaluteSupportedInterfaces;
begin
Specify.That(FInterfacedObject).Should.Support(IInterfaceList);
end;
procedure ObjectSpecification.TearDown;
begin
FInterfacedObject := nil;
end;
{ TPointerSpecBehaviors }
procedure PointerSpecification.SetUp;
begin
GetMem(FPointer, 255);
ContextDescription := 'When a pointer = allocated memory';
end;
procedure PointerSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure PointerSpecification.ShouldEvaluateAssignment;
begin
Specify.That(FPointer).Should.Not_.Be.Nil_;
Specify.That(FPointer).Should.Be.Assigned;
FreeMem(FPointer, 255);
FPointer := nil;
Specify.That(FPointer).Should.Be.Nil_;
Specify.That(FPointer).Should.Not_.Be.Assigned;
end;
procedure PointerSpecification.TearDown;
begin
if Assigned(FPointer) then
FreeMem(FPointer, 255);
end;
{ TInterfaceSpecBehaviors }
procedure InterfaceSpecification.ShouldEvaluateAssignment;
begin
Specify.That(FInterface).Should.Be.Assigned;
Specify.That(FInterface).Should.Not_.Be.Nil_;
FInterface := nil;
Specify.That(FInterface).Should.Not_.Be.Assigned;
Specify.That(FInterface).Should.Be.Nil_;
end;
procedure InterfaceSpecification.ShouldEvaluateImplementingObject;
begin
Specify.That(FInterface).Should.Be.ImplementedBy(TInterfaceList);
end;
procedure InterfaceSpecification.ShouldEvaluateSupportedInterfaces;
begin
Specify.That(FInterface).Should.Support(IInterfaceList);
end;
procedure InterfaceSpecification.ShouldHaveSpecs;
begin
Specify.That(True, 'I''ve got specs').Should.Equal(True);
end;
procedure InterfaceSpecification.SetUp;
begin
FInterface := TInterfaceList.Create;
ContextDescription := 'When an interface = IInterfaceList';
end;
procedure InterfaceSpecification.TearDown;
begin
FInterface := nil;
end;
{ AutoDoc }
procedure AutoDoc.SetUp;
begin
inherited;
FAutoDoc := TBaseAutoDoc.Create(Self);
FAutoDoc.Enabled := True;
end;
procedure AutoDoc.ShouldDocumentSpecNames;
var
SpecDoc: string;
begin
SpecDoc := FAutoDoc.BeginSpec('AutoDoc', 'ShouldDoSomething');
Specify.That(SpecDoc, 'SpecDoc').Should.Equal('AutoDoc - Should do something');
end;
procedure AutoDoc.ShouldDocumentSpecs;
var
SpecDoc: string;
begin
ContextDescription := 'With IAutoDoc';
SpecDoc := FAutoDoc.DocSpec('Specify.That(SpecDoc).Should.Not.Be.Empty');
Specify.That(SpecDoc, 'SpecDoc').Should.Equal(' With IAutoDoc, Specify.That(SpecDoc).Should.Not.Be.Empty');
end;
procedure AutoDoc.ShouldHaveSpecs;
begin
Specify.That(True, 'Got specs').Should.Be.True;
end;
procedure AutoDoc.ShouldNotOutputAnythingWhenDisabled;
var
SpecDoc: string;
begin
FAutoDoc.Enabled := False;
SpecDoc := FAutoDoc.BeginSpec('AutoDoc', 'DontOutputThis');
Specify.That(SpecDoc, 'SpecDoc').Should.Be.Empty;
SpecDoc := FAutoDoc.DocSpec('Don''t output this');
Specify.That(SpecDoc, 'SpecDoc').Should.Be.Empty;
end;
procedure AutoDoc.TearDown;
begin
FAutoDoc := nil;
inherited;
end;
initialization
RegisterSpec(AutoDoc.Suite);
RegisterSpec(Context.Suite);
RegisterSpec(IntegerSpecification.Suite);
RegisterSpec(BooleanSpecification.Suite);
RegisterSpec(FloatSpecification.Suite);
RegisterSpec(StringSpecification.Suite);
RegisterSpec(DateTimeSpecification.Suite);
RegisterSpec(ClassSpecification.Suite);
RegisterSpec(ObjectSpecification.Suite);
RegisterSpec(PointerSpecification.Suite);
RegisterSpec(InterfaceSpecification.Suite);
end.
|
unit SHChangeNotify ;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$IFNDEF VER80} {$IFNDEF VER90} {$IFNDEF VER93}
{$DEFINE Delphi3orHigher}
{$ENDIF} {$ENDIF} {$ENDIF}
//*************************************************************
//*************************************************************
// TSHChangeNotify component by Elliott Shevin shevine@aol.com
// vers. 3.0, October 2000
//
// See the README.TXT file for revision history.
//
//*
//* I owe this component to James Holderness, who described the
//* use of the undocumented Windows API calls it depends upon,
//* and Brad Martinez, who coded a similar function in Visual
//* Basic. I quote here from Brad's expression of gratitude to
//* James:
//* Interpretation of the shell's undocumented functions
//* SHChangeNotifyRegister (ordinal 2) and SHChangeNotifyDeregister
//* (ordinal 4) would not have been possible without the
//* assistance of James Holderness. For a complete (and probably
//* more accurate) overview of shell change notifcations,
//* please refer to James' "Shell Notifications" page at
//* http://www.geocities.com/SiliconValley/4942/
//*
//* This component will let you know when selected events
//* occur in the Windows shell, such as files and folders
//* being renamed, added, or deleted. (Moving an item yields
//* the same results as renaming it.) For the complete list
//* of events the component can trap, see Win32 Programmer's
//* reference description of the SHChangeNotify API call.
//*
//* Properties:
//* MessageNo: the Windows message number which will be used to signal
//* a trapped event. The default is WM_USER (1024); you may
//* set it to some other value if you're using WM_USER for
//* any other purpose.
//* TextCase: tcAsIs (default), tcLowercase, or tcUppercase, determines
//* whether and how the Path parameters passed to your event
//* handlers are case-converted.
//* HardDriveOnly: when set to True, the component monitors only local
//* hard drive partitions; when set to False, monitors the
//* entire file system.
//*
//* Methods:
//* Execute: Begin monitoring the selected shell events.
//* Stop: Stop monitoring.
//*
//* Events:
//* The component has an event corresponding to each event it can
//* trap, e.g. OnCreate, OnMediaInsert, etc.
//* Each event handler is passed either three or four parameters--
//* Sender=this component.
//* Flags=the value indentifying the event that triggered the handler,
//* from the constants in the SHChangeNotify help. This parameter
//* allows multiple events to share handlers and still distinguish
//* the reason the handler was triggered.
//* Path1, Path2: strings which are the paths affected by the shell
//* event. Whether both are passed depends on whether the second
//* is needed to describe the event. For example, OnDelete gives
//* only the name of the file (including path) that was deleted;
//* but OnRenameFolder gives the original folder name in Path1
//* and the new name in Path2.
//* In some cases, such as OnAssocChanged, neither Path parameter
//* means anything, and in other cases, I guessed, but we always
//* pass at least one.
//* Each time an event property is changed, the component is reset to
//* trap only those events for which handlers are assigned. So assigning
//* an event handler suffices to indicate your intention to trap the
//* corresponding shell event.
//*
//* There is one more event: OnEndSessionQuery, which has the same
//* parameters as the standard Delphi OnCloseQuery (and can in fact
//* be your OnCloseQuery handler). This component must shut down its
//* interception of shell events when system shutdown is begun, lest
//* the system fail to shut down at the user's request.
//*
//* Setting CanEndSession (same as CanClose) to FALSE in an
//* OnEndSessionQuery will stop the process of shutting down
//* Windows. You would only need this if you need to keep the user
//* from ending his Windows session while your program is running.
//*
//* I'd be honored to hear what you think of this component.
//* You can write me at shevine@aol.com.
//*************************************************************
//*************************************************************
interface
uses
Windows,
// LCLIntf, LCLType, LMessages,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
{$IFNDEF Delphi3orHigher}
OLE2,
{$ELSE}
ActiveX,
ComObj,
{$ENDIF}
ShlObj ;
const
SHCNF_ACCEPT_INTERRUPTS = $0001 ;
SHCNF_ACCEPT_NON_INTERRUPTS = $0002 ;
SHCNF_NO_PROXY = $8000 ;
type
NOTIFYREGISTER = record
pidlPath : PItemIDList ;
bWatchSubtree : boolean ;
end ;
type
PNOTIFYREGISTER = ^NOTIFYREGISTER ;
type
TTextCase = ( tcAsIs, tcUppercase, tcLowercase ) ;
type
TOneParmEvent = procedure( Sender : TObject ; Flags : cardinal ; Path1 : string ) of object ;
TTwoParmEvent = procedure( Sender : TObject ; Flags : cardinal ; Path1, Path2 : string ) of object ;
TEndSessionQueryEvent = procedure( Sender : TObject ; var CanEndSession : boolean ) of object ;
function SHChangeNotifyRegister( hWnd : hWnd ; dwFlags : integer ; wEventMask : cardinal ; uMsg : UINT ;
cItems : integer ; lpItems : PNOTIFYREGISTER ) : hWnd ; stdcall ;
function SHChangeNotifyDeregister( hWnd : hWnd ) : boolean ; stdcall ;
function SHILCreateFromPath( Path : Pointer ; PIDL : PItemIDList ; var Attributes : ULONG ) : HResult ; stdcall ;
type
TSHChangeNotify = class( TComponent )
private
fTextCase : TTextCase ;
fHardDriveOnly : boolean ;
NotifyCount : integer ;
NotifyHandle : hWnd ;
NotifyArray : array [ 1 .. 26 ] of NOTIFYREGISTER ;
AllocInterface : IMalloc ;
PrevMsg : integer ;
prevpath1 : string ;
prevpath2 : string ;
fMessageNo : integer ;
fAssocChanged : TTwoParmEvent ;
fAttributes : TOneParmEvent ;
fCreate : TOneParmEvent ;
fDelete : TOneParmEvent ;
fDriveAdd : TOneParmEvent ;
fDriveAddGUI : TOneParmEvent ;
fDriveRemoved : TOneParmEvent ;
fMediaInserted : TOneParmEvent ;
fMediaRemoved : TOneParmEvent ;
fMkDir : TOneParmEvent ;
fNetShare : TOneParmEvent ;
fNetUnshare : TOneParmEvent ;
fRenameFolder : TTwoParmEvent ;
fRenameItem : TTwoParmEvent ;
fRmDir : TOneParmEvent ;
fServerDisconnect : TOneParmEvent ;
fUpdateDir : TOneParmEvent ;
fUpdateImage : TOneParmEvent ;
fUpdateItem : TOneParmEvent ;
fEndSessionQuery : TEndSessionQueryEvent ;
OwnerWindowProc : TWndMethod ;
procedure SetMessageNo( value : integer ) ;
procedure WndProc( var msg : TMessage ) ;
protected
procedure QueryEndSession( var msg : TMessage ) ;
public
constructor Create( AOwner : TComponent ) ; override ;
destructor Destroy ; override ;
procedure Execute ;
procedure Stop ;
published
property MessageNo : integer read fMessageNo write SetMessageNo default WM_USER ;
property TextCase : TTextCase read fTextCase write fTextCase default tcAsIs ;
property HardDriveOnly : boolean read fHardDriveOnly write fHardDriveOnly default True ;
property OnAssocChanged : TTwoParmEvent read fAssocChanged write fAssocChanged ;
property OnAttributes : TOneParmEvent read fAttributes write fAttributes ;
property OnCreate : TOneParmEvent read fCreate write fCreate ;
property OnDelete : TOneParmEvent read fDelete write fDelete ;
property OnDriveAdd : TOneParmEvent read fDriveAdd write fDriveAdd ;
property OnDriveAddGUI : TOneParmEvent read fDriveAddGUI write fDriveAddGUI ;
property OnDriveRemoved : TOneParmEvent read fDriveRemoved write fDriveRemoved ;
property OnMediaInserted : TOneParmEvent read fMediaInserted write fMediaInserted ;
property OnMediaRemoved : TOneParmEvent read fMediaRemoved write fMediaRemoved ;
property OnMkDir : TOneParmEvent read fMkDir write fMkDir ;
property OnNetShare : TOneParmEvent read fNetShare write fNetShare ;
property OnNetUnshare : TOneParmEvent read fNetUnshare write fNetUnshare ;
property OnRenameFolder : TTwoParmEvent read fRenameFolder write fRenameFolder ;
property OnRenameItem : TTwoParmEvent read fRenameItem write fRenameItem ;
property OnRmDir : TOneParmEvent read fRmDir write fRmDir ;
property OnServerDisconnect : TOneParmEvent read fServerDisconnect write fServerDisconnect ;
property OnUpdateDir : TOneParmEvent read fUpdateDir write fUpdateDir ;
property OnUpdateImage : TOneParmEvent read fUpdateImage write fUpdateImage ;
property OnUpdateItem : TOneParmEvent read fUpdateItem write fUpdateItem ;
property OnEndSessionQuery : TEndSessionQueryEvent read fEndSessionQuery write fEndSessionQuery ;
{ Published declarations }
end ;
procedure register ;
implementation
const
Shell32DLL = 'shell32.dll' ;
function SHChangeNotifyRegister ; external Shell32DLL index 2 ;
function SHChangeNotifyDeregister ; external Shell32DLL index 4 ;
function SHILCreateFromPath ; external Shell32DLL index 28 ;
procedure register ;
begin
RegisterComponents( 'Custom', [ TSHChangeNotify ] ) ;
end ;
// Set defaults, and ensure NotifyHandle is zero.
constructor TSHChangeNotify.Create( AOwner : TComponent ) ;
begin
inherited Create( AOwner ) ;
fTextCase := tcAsIs ;
fHardDriveOnly := True ;
fAssocChanged := nil ;
fAttributes := nil ;
fCreate := nil ;
fDelete := nil ;
fDriveAdd := nil ;
fDriveAddGUI := nil ;
fDriveRemoved := nil ;
fMediaInserted := nil ;
fMediaRemoved := nil ;
fMkDir := nil ;
fNetShare := nil ;
fNetUnshare := nil ;
fRenameFolder := nil ;
fRenameItem := nil ;
fRmDir := nil ;
fServerDisconnect := nil ;
fUpdateDir := nil ;
fUpdateImage := nil ;
fUpdateItem := nil ;
fEndSessionQuery := nil ;
MessageNo := WM_USER ;
// If designing, dodge the code that implements messag interception.
if csDesigning in ComponentState then
exit ;
// Substitute our window proc for our owner's window proc.
if (Owner is TWinControl) then begin
OwnerWindowProc := ( Owner as TWinControl ).WindowProc ;
(Owner as TWinControl ).WindowProc := WndProc;
end
else begin
OwnerWindowProc := ( Application.MainForm as TWinControl ).WindowProc ;
( Application.MainForm as TWinControl ).WindowProc := WndProc
end;
// Get the IMAlloc interface so we can free PIDLs.
SHGetMalloc( AllocInterface ) ;
end ;
procedure TSHChangeNotify.SetMessageNo( value : integer ) ;
begin
if ( value >= WM_USER ) then
fMessageNo := value
else
raise Exception.Create( 'MessageNo must be greater than or equal to ' + inttostr( WM_USER ) ) ;
end ;
// Execute unregisters any current notification and registers a new one.
procedure TSHChangeNotify.Execute ;
var
EventMask : integer ;
driveletter : string ;
i : integer ;
PIDL : PItemIDList ;
Attributes : ULONG ;
NotifyPtr : PNOTIFYREGISTER ;
begin
NotifyCount := 0 ;
if csDesigning in ComponentState then
exit ;
Stop ; // Unregister the current notification, if any.
EventMask := 0 ;
if assigned( fAssocChanged ) then
EventMask := ( EventMask or SHCNE_ASSOCCHANGED ) ;
if assigned( fAttributes ) then
EventMask := ( EventMask or SHCNE_ATTRIBUTES ) ;
if assigned( fCreate ) then
EventMask := ( EventMask or SHCNE_CREATE ) ;
if assigned( fDelete ) then
EventMask := ( EventMask or SHCNE_DELETE ) ;
if assigned( fDriveAdd ) then
EventMask := ( EventMask or SHCNE_DRIVEADD ) ;
if assigned( fDriveAddGUI ) then
EventMask := ( EventMask or SHCNE_DRIVEADDGUI ) ;
if assigned( fDriveRemoved ) then
EventMask := ( EventMask or SHCNE_DRIVEREMOVED ) ;
if assigned( fMediaInserted ) then
EventMask := ( EventMask or SHCNE_MEDIAINSERTED ) ;
if assigned( fMediaRemoved ) then
EventMask := ( EventMask or SHCNE_MEDIAREMOVED ) ;
if assigned( fMkDir ) then
EventMask := ( EventMask or SHCNE_MKDIR ) ;
if assigned( fNetShare ) then
EventMask := ( EventMask or SHCNE_NETSHARE ) ;
if assigned( fNetUnshare ) then
EventMask := ( EventMask or SHCNE_NETUNSHARE ) ;
if assigned( fRenameFolder ) then
EventMask := ( EventMask or SHCNE_RENAMEFOLDER ) ;
if assigned( fRenameItem ) then
EventMask := ( EventMask or SHCNE_RENAMEITEM ) ;
if assigned( fRmDir ) then
EventMask := ( EventMask or SHCNE_RMDIR ) ;
if assigned( fServerDisconnect ) then
EventMask := ( EventMask or SHCNE_SERVERDISCONNECT ) ;
if assigned( fUpdateDir ) then
EventMask := ( EventMask or SHCNE_UPDATEDIR ) ;
if assigned( fUpdateImage ) then
EventMask := ( EventMask or SHCNE_UPDATEIMAGE ) ;
if assigned( fUpdateItem ) then
EventMask := ( EventMask or SHCNE_UPDATEITEM ) ;
if EventMask = 0 // If there's no event mask
then
exit ; // then there's no need to set an event.
// If the user requests watches on hard drives only, cycle through
// the list of drive letters and add a NotifyList element for each.
// Otherwise, just set the first element to watch the entire file
// system.
if fHardDriveOnly then
for i := ord( 'A' ) to ord( 'Z' ) do begin
driveletter := char( i ) + ':\' ;
if GetDriveType( pchar( driveletter ) ) = DRIVE_FIXED then begin
inc( NotifyCount ) ;
with NotifyArray[ NotifyCount ] do begin
SHILCreateFromPath( pchar( driveletter ), addr( PIDL ), Attributes ) ;
pidlPath := PIDL ;
bWatchSubtree := True ;
end ;
end ;
end
// If the caller requests the entire file system be watched,
// prepare the first NotifyElement accordingly.
else begin
NotifyCount := 1 ;
with NotifyArray[ 1 ] do begin
pidlPath := nil ;
bWatchSubtree := True ;
end ;
end ;
NotifyPtr := addr( NotifyArray ) ;
NotifyHandle := SHChangeNotifyRegister( ( Owner as TWinControl ).Handle,
SHCNF_ACCEPT_INTERRUPTS + SHCNF_ACCEPT_NON_INTERRUPTS, EventMask, fMessageNo, NotifyCount, NotifyPtr ) ;
if NotifyHandle = 0 then begin
Stop ;
raise Exception.Create( 'Could not register SHChangeNotify' ) ;
end ;
end ;
// This procedure unregisters the Change Notification
procedure TSHChangeNotify.Stop ;
var
// NotifyHandle : hWnd ;
i : integer ;
PIDL : PItemIDList ;
begin
if csDesigning in ComponentState then
exit ;
// Deregister the shell notification.
if NotifyCount > 0 then
SHChangeNotifyDeregister( NotifyHandle ) ;
// Free the PIDLs in NotifyArray.
for i := 1 to NotifyCount do begin
PIDL := NotifyArray[ i ].pidlPath ;
if AllocInterface.DidAlloc( PIDL ) = 1 then
AllocInterface.Free( PIDL ) ;
end ;
NotifyCount := 0 ;
end ;
// This is the procedure that is called when a change notification occurs.
// It interprets the two PIDLs passed to it, and calls the appropriate
// event handler, according to what kind of event occurred.
procedure TSHChangeNotify.WndProc( var msg : TMessage ) ;
type
TPIDLLIST = record
pidlist : array [ 1 .. 2 ] of PItemIDList ;
end ;
PIDARRAY = ^TPIDLLIST ;
var
Path1 : string ;
Path2 : string ;
ptr : PIDARRAY ;
p1, p2 : PItemIDList ;
repeated : boolean ;
p : integer ;
event : longint ;
parmcount : byte ;
OneParmEvent : TOneParmEvent ;
TwoParmEvent : TTwoParmEvent ;
// The internal function ParsePidl returns the string corresponding
// to a PIDL.
function ParsePidl( PIDL : PItemIDList ) : string ;
begin
SetLength( result, MAX_PATH ) ;
if not SHGetPathFromIDList( PIDL, pchar( result ) ) then
result := '' ;
end ;
// The actual message handler starts here.
begin
if msg.msg = WM_QUERYENDSESSION then
QueryEndSession( msg ) ;
if msg.msg = fMessageNo then begin
OneParmEvent := nil ;
TwoParmEvent := nil ;
event := msg.LParam and ( $7FFFFFFF ) ;
case event of
SHCNE_ASSOCCHANGED :
TwoParmEvent := fAssocChanged ;
SHCNE_ATTRIBUTES :
OneParmEvent := fAttributes ;
SHCNE_CREATE :
OneParmEvent := fCreate ;
SHCNE_DELETE :
OneParmEvent := fDelete ;
SHCNE_DRIVEADD :
OneParmEvent := fDriveAdd ;
SHCNE_DRIVEADDGUI :
OneParmEvent := fDriveAddGUI ;
SHCNE_DRIVEREMOVED :
OneParmEvent := fDriveRemoved ;
SHCNE_MEDIAINSERTED :
OneParmEvent := fMediaInserted ;
SHCNE_MEDIAREMOVED :
OneParmEvent := fMediaRemoved ;
SHCNE_MKDIR :
OneParmEvent := fMkDir ;
SHCNE_NETSHARE :
OneParmEvent := fNetShare ;
SHCNE_NETUNSHARE :
OneParmEvent := fNetUnshare ;
SHCNE_RENAMEFOLDER :
TwoParmEvent := fRenameFolder ;
SHCNE_RENAMEITEM :
TwoParmEvent := fRenameItem ;
SHCNE_RMDIR :
OneParmEvent := fRmDir ;
SHCNE_SERVERDISCONNECT :
OneParmEvent := fServerDisconnect ;
SHCNE_UPDATEDIR :
OneParmEvent := fUpdateDir ;
SHCNE_UPDATEIMAGE :
OneParmEvent := fUpdateImage ;
SHCNE_UPDATEITEM :
OneParmEvent := fUpdateItem ;
else
begin
OneParmEvent := nil ; // Unknown event;
TwoParmEvent := nil ;
end ;
end ;
if ( assigned( OneParmEvent ) ) or ( assigned( TwoParmEvent ) ) then begin
// Assign a pointer to the array of PIDLs sent
// with the message.
ptr := PIDARRAY( msg.wParam ) ;
// Parse the two PIDLs.
p1 := ptr^.pidlist[ 1 ] ;
try
SetLength( Path1, MAX_PATH ) ;
Path1 := ParsePidl( p1 ) ;
p := pos( #00, Path1 ) ;
if p > 0 then
SetLength( Path1, p - 1 ) ;
except
Path1 := '' ;
end ;
p2 := ptr^.pidlist[ 2 ] ;
try
SetLength( Path2, MAX_PATH ) ;
Path2 := ParsePidl( p2 ) ;
p := pos( #00, Path2 ) ;
if p > 0 then
SetLength( Path2, p - 1 ) ;
except
Path2 := '' ;
end ;
// If this message is the same as the last one (which happens
// a lot), bail out.
try
repeated := ( PrevMsg = event ) and ( uppercase( prevpath1 ) = uppercase( Path1 ) ) and
( uppercase( prevpath2 ) = uppercase( Path2 ) ) except repeated := false ;
end ;
// Save the elements of this message for comparison next time.
PrevMsg := event ;
prevpath1 := Path1 ;
prevpath2 := Path2 ;
// Convert the case of Path1 and Path2 if desired.
case fTextCase of
tcUppercase : begin
Path1 := uppercase( Path1 ) ;
Path2 := uppercase( Path2 ) ;
end ;
tcLowercase : begin
Path1 := lowercase( Path1 ) ;
Path2 := lowercase( Path2 ) ;
end ;
end ;
// Call the event handler according to the number
// of paths we will pass to it.
if not repeated then begin
case event of
SHCNE_ASSOCCHANGED, SHCNE_RENAMEFOLDER, SHCNE_RENAMEITEM :
parmcount := 2 ;
else
parmcount := 1 ;
end ;
if parmcount = 1 then
OneParmEvent( self, event, Path1 )
else
TwoParmEvent( self, event, Path1, Path2 ) ;
end ;
end ; // if assigned(OneParmEvent)...
end ; // if Msg.Msg = fMessageNo...
// Call the original message handler.
OwnerWindowProc( msg ) ;
end ;
procedure TSHChangeNotify.QueryEndSession( var msg : TMessage ) ;
var
CanEndSession : boolean ;
begin
CanEndSession := True ;
if assigned( fEndSessionQuery ) then
fEndSessionQuery( self, CanEndSession ) ;
if CanEndSession then begin
Stop ;
msg.result := 1 ;
end
else
msg.result := 0 ;
end ;
destructor TSHChangeNotify.Destroy ;
begin
if not( csDesigning in ComponentState ) then begin
if (Owner is TWinControl) then begin
if assigned( Owner ) then ( Owner as TWinControl ).WindowProc := OwnerWindowProc ;
end
else begin
if assigned( Application.MainForm ) then ( Application.MainForm as TWinControl ).WindowProc := OwnerWindowProc ;
end;
Stop ;
end ;
inherited ;
end ;
end.
|
//------------------------------------------------------------------------------
//
// Voxelizer
// Copyright (C) 2021 by Jim Valavanis
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
// DESCRIPTION:
// Export Sprite Form
//
//------------------------------------------------------------------------------
// Site : https://sourceforge.net/projects/voxelizer/
//------------------------------------------------------------------------------
unit frm_exportsprite;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, vxl_soft3d, models, ComCtrls;
type
TExportSpriteForm = class(TForm)
Label1: TLabel;
FileNameEdit: TEdit;
SelectFileButton: TSpeedButton;
GeneralGroupBox: TGroupBox;
Label2: TLabel;
SpritePrefixButton: TSpeedButton;
PrefixEdit: TEdit;
PatchRadioGroup: TRadioGroup;
PreviewGroupBox: TGroupBox;
Panel3: TPanel;
PaintBox1: TPaintBox;
Panel4: TPanel;
ZoomInSpeedButton: TSpeedButton;
ZoomOutSpeedButton: TSpeedButton;
HourglassLabel: TLabel;
Panel1: TPanel;
Panel2: TPanel;
Button1: TButton;
Button2: TButton;
SaveDialog1: TSaveDialog;
ZoomTrackBar: TTrackBar;
RotateTrackBar: TTrackBar;
Theta2IncButton1: TSpeedButton;
Theta2DecButton1: TSpeedButton;
ScriptParametersGroupBox: TGroupBox;
ScriptRadioGroup: TRadioGroup;
Label3: TLabel;
ActorNameEdit: TEdit;
Label4: TLabel;
EditorNumberEdit: TEdit;
Label5: TLabel;
Label6: TLabel;
RadiusEdit: TEdit;
HeightLabel: TLabel;
HeightEdit: TEdit;
Timer1: TTimer;
VoxelGroupBox: TGroupBox;
GenerateVoxelCheckBox: TCheckBox;
voxRadioButton64x64: TRadioButton;
voxRadioButton128x128: TRadioButton;
voxRadioButton256x256: TRadioButton;
SolidCheckBox: TCheckBox;
AutoVoxSizeRadioButton: TRadioButton;
RotationsRadioGroup: TRadioGroup;
procedure SpritePrefixButtonClick(Sender: TObject);
procedure SelectFileButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FileNameEditChange(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure ZoomInSpeedButtonClick(Sender: TObject);
procedure ZoomOutSpeedButtonClick(Sender: TObject);
procedure ZoomTrackBarChange(Sender: TObject);
procedure RotateTrackBarChange(Sender: TObject);
procedure Theta2IncButton1Click(Sender: TObject);
procedure Theta2DecButton1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure CheckNumericEdit(Sender: TObject; var Key: Char);
procedure ScriptRadioGroupClick(Sender: TObject);
procedure GenerateVoxelCheckBoxClick(Sender: TObject);
procedure voxRadioButton64x64Click(Sender: TObject);
procedure voxRadioButton128x128Click(Sender: TObject);
procedure voxRadioButton256x256Click(Sender: TObject);
procedure AutoVoxSizeRadioButtonClick(Sender: TObject);
private
{ Private declarations }
needs3dupdate: boolean;
buffer: TBitmap;
device: device_t;
fdevicewidth, fdeviceheight: integer;
fviewdist, ftheta, ftheta2: float;
procedure RenderFaces(const mVertCount, mFaceCount: integer;
const mVert: array of fvec5_t; const mFace: array of ivec3_t; const tex: TBitmap);
procedure DoUpdate3d;
procedure UpdateControls;
function CheckOKtoGO: boolean;
protected
function IsWAD: boolean;
function voxelscale: single;
function md2scale: single;
procedure DoExportSpriteWAD;
procedure DoExportSpritePK3;
public
{ Public declarations }
model: model_t;
modeltex: TBitmap;
procedure PrepareTextures;
procedure DoExportSprite;
end;
implementation
{$R *.dfm}
uses
Math,
vxl_defs,
vxl_utils,
vxl_wadwriter,
vxl_doompatch,
vxl_palettes,
vxl_voxels,
vxl_voxelexport,
vxl_pk3writer,
pngimage,
frm_spriteprefix;
const
MINVIEWDIST = 1.0;
MAXVIEWDIST = 16.0;
procedure TExportSpriteForm.SpritePrefixButtonClick(Sender: TObject);
var
s: string;
begin
s := PrefixEdit.Text;
if GetSpritePrefix(s) then
PrefixEdit.Text := s;
end;
procedure TExportSpriteForm.SelectFileButtonClick(Sender: TObject);
begin
if SaveDialog1.Execute then
begin
FileNameEdit.Text := SaveDialog1.FileName;
Button1.Enabled := True;
end;
end;
procedure TExportSpriteForm.FormCreate(Sender: TObject);
var
i: integer;
begin
DoubleBuffered := True;
for i := 0 to ComponentCount - 1 do
if Components[i].InheritsFrom(TWinControl) then
(Components[i] as TWinControl).DoubleBuffered := True;
fdevicewidth := 256;
fdeviceheight := 510;
device_init(@device, fdevicewidth, fdeviceheight);
buffer := TBitmap.Create;
buffer.Width := fdevicewidth;
buffer.Height := fdeviceheight;
buffer.PixelFormat := pf32bit;
needs3dupdate := True;
modeltex := TBitmap.Create;
modeltex.Width := 256;
modeltex.Height := 256;
modeltex.PixelFormat := pf32bit;
fviewdist := opt_viewdist / OPT_TO_FLOAT;
if fviewdist < MINVIEWDIST then
fviewdist := MINVIEWDIST
else if fviewdist > MAXVIEWDIST then
fviewdist := MAXVIEWDIST;
ftheta := opt_theta1 / OPT_TO_FLOAT;
if ftheta < 0.0 then
ftheta := 0.0
else if ftheta > 2 * PI then
ftheta := 2 * PI;
ftheta2 := opt_theta2 / OPT_TO_FLOAT;
if ftheta2 < 0.0 then
ftheta2 := 0.0
else if ftheta2 > PI / 8 then
ftheta2 := PI / 8;
if opt_spritepal in [0..4] then
PatchRadioGroup.ItemIndex := opt_spritepal;
if opt_spritescript in [0..2] then
ScriptRadioGroup.ItemIndex := opt_spritescript;
GenerateVoxelCheckBox.Checked := opt_dospritevox = 1;
voxRadioButton64x64.Checked := opt_spritevox = 64;
voxRadioButton128x128.Checked := opt_spritevox = 128;
voxRadioButton256x256.Checked := opt_spritevox = 256;
UpdateControls;
end;
procedure TExportSpriteForm.FormDestroy(Sender: TObject);
begin
device_destroy(@device);
modeltex.Free;
buffer.Free;
opt_viewdist := Round(fviewdist * OPT_TO_FLOAT);
opt_theta1 := Round(ftheta * OPT_TO_FLOAT);
opt_theta2 := Round(ftheta2 * OPT_TO_FLOAT);
opt_spritepal := PatchRadioGroup.ItemIndex;
opt_spritescript := ScriptRadioGroup.ItemIndex;
if GenerateVoxelCheckBox.Checked then
opt_dospritevox := 1
else
opt_dospritevox := 0;
if voxRadioButton64x64.Checked then
opt_spritevox := 64
else if voxRadioButton128x128.Checked then
opt_spritevox := 128
else if voxRadioButton256x256.Checked then
opt_spritevox := 256;
end;
procedure TExportSpriteForm.FileNameEditChange(Sender: TObject);
begin
if Trim(FileNameEdit.Text) = '' then
Button1.Enabled := False;
end;
procedure TExportSpriteForm.RenderFaces(const mVertCount, mFaceCount: integer;
const mVert: array of fvec5_t; const mFace: array of ivec3_t; const tex: TBitmap);
var
v1, v2, v3: vertex_t;
i: integer;
procedure _make_vertex(const r: integer; const p: Pvertex_t);
begin
p.pos.x := mVert[r].x;
p.pos.y := mVert[r].z;
p.pos.z := mVert[r].y;
p.pos.w := 1.0;
p.tc.u := mVert[r].u;
p.tc.v := mVert[r].v;
p.color.r := 1.0;
p.color.g := 1.0;
p.color.b := 1.0;
p.rhw := 1.0;
end;
begin
device_set_texture(@device, tex);
for i := 0 to mFaceCount - 1 do
begin
_make_vertex(mFace[i].x, @v1);
_make_vertex(mFace[i].y, @v2);
_make_vertex(mFace[i].z, @v3);
device_draw_primitive(@device, @v1, @v2, @v3);
end;
end;
procedure TExportSpriteForm.DoUpdate3d;
var
c, m, m2: matrix_t;
begin
device_clear(@device);
camera_at_zero(@device, fviewdist, 0.5, 0);
matrix_set_rotate(@m, 0.0, 0.0, 1.0, ftheta);
matrix_set_rotate(@m2, 0.0, 1.0, 0.0, ftheta2);
matrix_mul(@c, @m, @m2);
device.transform.world := c;
transform_update(@device.transform);
device.render_state := RENDER_STATE_TEXTURE_SOLID;
RenderFaces(model.mVertCount, model.mFaceCount, model.mVert, model.mFace, modeltex);
buffer.Canvas.StretchDraw(Rect(0, 0, buffer.Width, buffer.Height), device.bframebuffer);
needs3dupdate := False;
end;
procedure TExportSpriteForm.PaintBox1Paint(Sender: TObject);
begin
if needs3dupdate then
DoUpdate3d;
PaintBox1.Canvas.Draw(0, 0, buffer);
end;
procedure TExportSpriteForm.ZoomInSpeedButtonClick(Sender: TObject);
begin
if fviewdist > MINVIEWDIST then
begin
fviewdist := fviewdist - 0.5;
if fviewdist < MINVIEWDIST then
fviewdist := MINVIEWDIST;
needs3dupdate := True;
UpdateControls;
PaintBox1.Invalidate;
end;
end;
procedure TExportSpriteForm.ZoomOutSpeedButtonClick(Sender: TObject);
begin
if fviewdist < MAXVIEWDIST then
begin
fviewdist := fviewdist + 0.5;
if fviewdist > MAXVIEWDIST then
fviewdist := MAXVIEWDIST;
needs3dupdate := True;
UpdateControls;
PaintBox1.Invalidate;
end;
end;
procedure TExportSpriteForm.UpdateControls;
begin
ZoomTrackBar.Position := GetIntegerInRange(Round(fviewdist * 10), ZoomTrackBar.Min, ZoomTrackBar.Max);
RotateTrackBar.Position := GetIntegerInRange(Round(ftheta / (2 * pi) * RotateTrackBar.Max), RotateTrackBar.Min, RotateTrackBar.Max);
voxRadioButton64x64.Visible := GenerateVoxelCheckBox.Checked;
voxRadioButton128x128.Visible := GenerateVoxelCheckBox.Checked;
voxRadioButton256x256.Visible := GenerateVoxelCheckBox.Checked;
AutoVoxSizeRadioButton.Visible := GenerateVoxelCheckBox.Checked;
end;
procedure TExportSpriteForm.ZoomTrackBarChange(Sender: TObject);
begin
fviewdist := ZoomTrackBar.Position / 10;
needs3dupdate := True;
PaintBox1.Invalidate;
end;
procedure TExportSpriteForm.RotateTrackBarChange(Sender: TObject);
begin
ftheta := RotateTrackBar.Position / RotateTrackBar.Max * 2 * PI;
needs3dupdate := True;
PaintBox1.Invalidate;
end;
procedure TExportSpriteForm.Theta2IncButton1Click(Sender: TObject);
begin
if ftheta2 < PI / 8 then
begin
ftheta2 := ftheta2 + PI / 32;
if ftheta2 > PI / 8 then
ftheta2 := PI / 8;
needs3dupdate := True;
UpdateControls;
PaintBox1.Invalidate;
end;
end;
procedure TExportSpriteForm.Theta2DecButton1Click(Sender: TObject);
begin
if ftheta2 > 0.0 then
begin
ftheta2 := ftheta2 - PI / 32;
if ftheta2 < 0.0 then
ftheta2 := 0.0;
needs3dupdate := True;
UpdateControls;
PaintBox1.Invalidate;
end;
end;
function TExportSpriteForm.CheckOKtoGO: boolean;
var
s: string;
begin
if Trim(FileNameEdit.Text) = '' then
begin
Result := False;
Exit;
end;
if Length(Trim(PrefixEdit.Text)) <> 5 then
begin
Result := False;
Exit;
end;
s := Trim(PrefixEdit.Text);
if Pos(s[5], 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\[]') = 0 then
begin
Result := False;
Exit;
end;
if Pos(' ', s) > 0 then
begin
Result := False;
Exit;
end;
if Length(Trim(ActorNameEdit.Text)) = 0 then
begin
Result := False;
Exit;
end;
Result := True;
end;
procedure TExportSpriteForm.Timer1Timer(Sender: TObject);
begin
Button1.Enabled := CheckOKtoGO;
end;
procedure TExportSpriteForm.CheckNumericEdit(Sender: TObject;
var Key: Char);
begin
if not (Key in [#8, '0'..'9']) then
begin
Key := #0;
Exit;
end;
end;
procedure TExportSpriteForm.ScriptRadioGroupClick(Sender: TObject);
begin
ScriptParametersGroupBox.Visible := ScriptRadioGroup.ItemIndex <> 2;
VoxelGroupBox.Visible := ScriptRadioGroup.ItemIndex = 0;
end;
procedure TExportSpriteForm.PrepareTextures;
var
y: integer;
x: integer;
ln: PIUINT32Array;
r, g, b: byte;
begin
modeltex.PixelFormat := pf32bit;
for y := 0 to modeltex.Height - 1 do
begin
ln := modeltex.ScanLine[y];
for x := 0 to modeltex.Width - 1 do
begin
r := GetRValue(ln[x]);
g := GetGValue(ln[x]);
b := GetBValue(ln[x]);
if r < 16 then
r := 16;
if g < 16 then
g := 16;
if b < 16 then
b := 16;
ln[x] := RGB(r, g, b);
end;
end;
end;
function TExportSpriteForm.IsWAD: boolean;
begin
Result := UpperCase(ExtractFileExt(FileNameEdit.Text)) = '.WAD';
end;
procedure TExportSpriteForm.DoExportSprite;
begin
if IsWAD then
DoExportSpriteWAD
else
DoExportSpritePK3;
end;
function TExportSpriteForm.voxelscale: single;
var
maxscoord: single;
voxsize, w, h: integer;
definitionsize: integer;
maxradius: single;
begin
maxscoord := model.maxcoord;
maxradius := model.maxdiameter / 2;
w := StrToIntDef(RadiusEdit.Text, 64);
h := StrToIntDef(HeightEdit.Text, 128);
if w > h then
definitionsize := w
else
definitionsize := h;
if voxRadioButton64x64.Checked then
voxsize := 64
else if voxRadioButton128x128.Checked then
voxsize := 128
else if voxRadioButton256x256.Checked then
voxsize := 256
else
begin
w := 2 * StrToIntDef(RadiusEdit.Text, 64);
h := StrToIntDef(HeightEdit.Text, 128);
if w > h then
voxsize := w
else
voxsize := h;
if voxsize > 256 then
voxsize := 256;
end;
// Result := definitionsize / voxsize * maxradius;
Result := definitionsize / voxsize * maxscoord / maxradius;
end;
function TExportSpriteForm.md2scale: single;
var
maxcoord: single;
w, h: integer;
definitionsize: integer;
begin
maxcoord := model.maxcoord;
w := StrToIntDef(RadiusEdit.Text, 64);
h := StrToIntDef(HeightEdit.Text, 128);
if w > h then
definitionsize := w
else
definitionsize := h;
Result := definitionsize / 1024 * maxcoord;
end;
const
ROTATIONTRANSLATIONS: array[1..3] of array [0..32] of integer = (
( 0, 1, 2, 3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1),
( 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1),
( 0, 16, 8, 17, 1, 18, 9, 19, 2, 20, 10, 21, 3, 22, 11, 23, 4, 24, 12, 25, 5, 26, 13, 27, 6, 28, 14, 29, 7, 30, 15, 31, -1)
);
ROTATIONCHARS = '123456789ABCDEFGHIJKLMNOPQRSTUVW';
ROTATIONNUM: array[1..3] of integer = (8, 16, 32);
procedure TExportSpriteForm.DoExportSpriteWAD;
var
wad: TWADWriter;
script: TStringList;
name: string;
stmp: string;
i: integer;
ms: TMemoryStream;
b: TBitmap;
vox: voxelbuffer_p;
voxsize: integer;
w, h: integer;
pk3entry: string;
rot: integer;
oldtheta: float;
rotchars: PIntegerArray;
begin
Screen.Cursor := crHourGlass;
wad := TWADWriter.Create;
try
script := TStringList.Create;
try
if ScriptRadioGroup.ItemIndex <> 2 then
begin
stmp := Trim(ActorNameEdit.Text);
name := '';
for i := 1 to Length(stmp) do
if stmp[i] <> ' ' then
name := name + stmp[i];
script.Add('ACTOR ' + stmp + ' ' + EditorNumberEdit.Text);
script.Add('{');
script.Add(' Health 10000');
script.Add(' Radius ' + RadiusEdit.Text);
script.Add(' Height ' + HeightEdit.Text);
script.Add(' Mass 100000');
if SolidCheckBox.Checked then
script.Add(' +SOLID');
script.Add(' States');
script.Add(' {');
script.Add(' Spawn:');
stmp := PrefixEdit.Text;
script.Add(' ' + stmp[1] + stmp[2] + stmp[3] + stmp[4] + ' ' + stmp[5] + ' -1');
script.Add(' }');
script.Add('}');
if ScriptRadioGroup.ItemIndex = 0 then
wad.AddStringList('ACTORDEF', script)
else
wad.AddStringList('DECORATE', script);
end;
finally
script.Free;
end;
wad.AddSeparator('S_START');
b := TBitmap.Create;
try
b.Width := 256;
b.Height := 255;
b.PixelFormat := pf32bit;
if RotationsRadioGroup.ItemIndex = 0 then
begin
b.Canvas.Draw(0, 0, buffer);
for i := 0 to 255 do
b.Canvas.Pixels[i, 0] := RGB(0, 0, 0);
case PatchRadioGroup.ItemIndex of
0: ms := BmpAsPatch(b, @DoomPaletteRaw);
1: ms := BmpAsPatch(b, @HereticPaletteRaw);
2: ms := BmpAsPatch(b, @HexenPaletteRaw);
3: ms := BmpAsPatch(b, @StrifePaletteRaw);
else
ms := BmpAsPatch(b, @RadixPaletteRaw);
end;
wad.AddData(PrefixEdit.Text + '0', ms.Memory, ms.Size);
ms.Free;
end
else
begin
rotchars := @ROTATIONTRANSLATIONS[RotationsRadioGroup.ItemIndex];
oldtheta := ftheta;
for rot := 0 to ROTATIONNUM[RotationsRadioGroup.ItemIndex] - 1 do
begin
DoUpdate3d;
b.Canvas.Draw(0, 0, buffer);
for i := 0 to 255 do
b.Canvas.Pixels[i, 0] := RGB(0, 0, 0);
case PatchRadioGroup.ItemIndex of
0: ms := BmpAsPatch(b, @DoomPaletteRaw);
1: ms := BmpAsPatch(b, @HereticPaletteRaw);
2: ms := BmpAsPatch(b, @HexenPaletteRaw);
3: ms := BmpAsPatch(b, @StrifePaletteRaw);
else
ms := BmpAsPatch(b, @RadixPaletteRaw);
end;
wad.AddData(PrefixEdit.Text + ROTATIONCHARS[rotchars[rot] + 1], ms.Memory, ms.Size);
ms.Free;
ftheta := ftheta + 2 * pi / ROTATIONNUM[RotationsRadioGroup.ItemIndex];
end;
ftheta := oldtheta;
needs3dupdate := True;
end;
finally
b.Free;
end;
wad.AddSeparator('S_END');
if ScriptRadioGroup.ItemIndex = 0 then
begin
pk3entry := '';
if GenerateVoxelCheckBox.Checked then
begin
GetMem(vox, SizeOf(voxelbuffer_t));
if voxRadioButton64x64.Checked then
voxsize := 64
else if voxRadioButton128x128.Checked then
voxsize := 128
else if voxRadioButton256x256.Checked then
voxsize := 256
else
begin
w := 2 * StrToIntDef(RadiusEdit.Text, 64);
h := StrToIntDef(HeightEdit.Text, 128);
if w > h then
voxsize := w
else
voxsize := h;
if voxsize > 256 then
voxsize := 256;
end;
DT_CreateVoxelFromModel(model, vox, voxsize, modeltex);
if ScriptRadioGroup.ItemIndex = 0 then
begin
VXE_ExportVoxelToDDVOX(vox, voxsize, 'vxtmp');
wad.AddFile(PrefixEdit.Text + 'VOX', 'vxtmp');
DeleteFile('vxtmp');
pk3entry := pk3entry + PrefixEdit.Text + 'VOX=' + PrefixEdit.Text + '.DDVOX'#13#10;
wad.AddString('VOXELDEF', 'voxeldef ' + PrefixEdit.Text + '.ddvox ' + Format('scale %1.5f', [voxelscale]) + ' replace sprite ' + PrefixEdit.Text);
end
else
begin
wad.AddSeparator('VX_START');
if voxsize = 256 then
voxsize := 254;
case PatchRadioGroup.ItemIndex of
0: VXE_ExportVoxelToSlab6VOX(vox, voxsize, @DoomPaletteRaw, 'vxtmp');
1: VXE_ExportVoxelToSlab6VOX(vox, voxsize, @HereticPaletteRaw, 'vxtmp');
2: VXE_ExportVoxelToSlab6VOX(vox, voxsize, @HexenPaletteRaw, 'vxtmp');
3: VXE_ExportVoxelToSlab6VOX(vox, voxsize, @StrifePaletteRaw, 'vxtmp');
else
VXE_ExportVoxelToSlab6VOX(vox, voxsize, @RadixPaletteRaw, 'vxtmp');
end;
wad.AddFile(PrefixEdit.Text, 'vxtmp');
DeleteFile('vxtmp');
wad.AddSeparator('VX_END');
// wad.AddString('VOXELDEF', PrefixEdit.Text + '="' + PrefixEdit.Text + '.vox"{'#13#10'}');
end;
FreeMem(vox, SizeOf(voxelbuffer_t));
end;
if pk3entry <> '' then
wad.AddString('PK3ENTRY', pk3entry);
end;
BackupFile(FileNameEdit.Text);
wad.SaveToFile(FileNameEdit.Text);
finally
wad.Free;
end;
Screen.Cursor := crDefault;
end;
procedure TExportSpriteForm.DoExportSpritePK3;
var
pk3: TPK3Writer;
wad: TWADWriter;
script: TStringList;
name: string;
stmp: string;
i: integer;
ms: TMemoryStream;
b: TBitmap;
vox: voxelbuffer_p;
voxsize: integer;
w, h: integer;
rot: integer;
oldtheta: float;
rotchars: PIntegerArray;
begin
Screen.Cursor := crHourGlass;
pk3 := TPK3Writer.Create;
try
script := TStringList.Create;
try
if ScriptRadioGroup.ItemIndex <> 2 then
begin
stmp := Trim(ActorNameEdit.Text);
name := '';
for i := 1 to Length(stmp) do
if stmp[i] <> ' ' then
name := name + stmp[i];
script.Add('ACTOR ' + stmp + ' ' + EditorNumberEdit.Text);
script.Add('{');
script.Add(' Health 100');
script.Add(' Radius ' + RadiusEdit.Text);
script.Add(' Height ' + HeightEdit.Text);
script.Add(' Mass 100');
if SolidCheckBox.Checked then
script.Add(' +SOLID');
script.Add(' States');
script.Add(' {');
script.Add(' Spawn:');
stmp := PrefixEdit.Text;
script.Add(' ' + stmp[1] + stmp[2] + stmp[3] + stmp[4] + ' ' + stmp[5] + ' -1');
script.Add(' }');
script.Add('}');
if ScriptRadioGroup.ItemIndex = 0 then
AddStringDataToPK3(pk3, 'ACTORDEF.txt', script.Text)
else
AddStringDataToPK3(pk3, 'DECORATE.txt', script.Text);
end;
finally
script.Free;
end;
wad := TWADWriter.Create;
try
wad.AddSeparator('S_START');
b := TBitmap.Create;
try
b.Width := 256;
b.Height := 255;
b.PixelFormat := pf32bit;
if RotationsRadioGroup.ItemIndex = 0 then
begin
b.Canvas.Draw(0, 0, buffer);
for i := 0 to 255 do
b.Canvas.Pixels[i, 0] := RGB(0, 0, 0);
case PatchRadioGroup.ItemIndex of
0: ms := BmpAsPatch(b, @DoomPaletteRaw);
1: ms := BmpAsPatch(b, @HereticPaletteRaw);
2: ms := BmpAsPatch(b, @HexenPaletteRaw);
3: ms := BmpAsPatch(b, @StrifePaletteRaw);
else
ms := BmpAsPatch(b, @RadixPaletteRaw);
end;
wad.AddData(PrefixEdit.Text + '0', ms.Memory, ms.Size);
ms.Free;
end
else
begin
rotchars := @ROTATIONTRANSLATIONS[RotationsRadioGroup.ItemIndex];
oldtheta := ftheta;
for rot := 0 to ROTATIONNUM[RotationsRadioGroup.ItemIndex] - 1 do
begin
DoUpdate3d;
b.Canvas.Draw(0, 0, buffer);
for i := 0 to 255 do
b.Canvas.Pixels[i, 0] := RGB(0, 0, 0);
case PatchRadioGroup.ItemIndex of
0: ms := BmpAsPatch(b, @DoomPaletteRaw);
1: ms := BmpAsPatch(b, @HereticPaletteRaw);
2: ms := BmpAsPatch(b, @HexenPaletteRaw);
3: ms := BmpAsPatch(b, @StrifePaletteRaw);
else
ms := BmpAsPatch(b, @RadixPaletteRaw);
end;
wad.AddData(PrefixEdit.Text + ROTATIONCHARS[rotchars[rot] + 1], ms.Memory, ms.Size);
ms.Free;
ftheta := ftheta + 2 * pi / ROTATIONNUM[RotationsRadioGroup.ItemIndex];
end;
ftheta := oldtheta;
needs3dupdate := True;
end;
finally
b.Free;
end;
wad.AddSeparator('S_END');
ms := TMemoryStream.Create;
try
wad.SaveToStream(ms);
AddBinaryDataToPK3(pk3, PrefixEdit.Text + '.wad', ms.Memory, ms.Size);
finally
ms.Free;
end;
finally
wad.Free;
end;
if ScriptRadioGroup.ItemIndex = 0 then
begin
if GenerateVoxelCheckBox.Checked then
begin
GetMem(vox, SizeOf(voxelbuffer_t));
if voxRadioButton64x64.Checked then
voxsize := 64
else if voxRadioButton128x128.Checked then
voxsize := 128
else if voxRadioButton256x256.Checked then
voxsize := 256
else
begin
w := 2 * StrToIntDef(RadiusEdit.Text, 64);
h := StrToIntDef(HeightEdit.Text, 128);
if w > h then
voxsize := w
else
voxsize := h;
if voxsize > 256 then
voxsize := 256;
end;
DT_CreateVoxelFromModel(model, vox, voxsize, modeltex);
VXE_ExportVoxelToDDVOX(vox, voxsize, 'vxtmp');
AddFileToPK3(pk3, 'VOXELS\' + PrefixEdit.Text + '.ddvox', 'vxtmp');
DeleteFile('vxtmp');
AddStringDataToPK3(pk3, 'VOXELS\VOXELDEF.txt', 'voxeldef ' + PrefixEdit.Text + '.ddvox ' + Format('scale %1.5f', [voxelscale]) + ' replace sprite ' + PrefixEdit.Text);
FreeMem(vox, SizeOf(voxelbuffer_t));
end;
end;
BackupFile(FileNameEdit.Text);
pk3.SaveToFile(FileNameEdit.Text);
finally
pk3.Free;
end;
Screen.Cursor := crDefault;
end;
procedure TExportSpriteForm.GenerateVoxelCheckBoxClick(Sender: TObject);
begin
voxRadioButton64x64.Visible := GenerateVoxelCheckBox.Checked;
voxRadioButton128x128.Visible := GenerateVoxelCheckBox.Checked;
voxRadioButton256x256.Visible := GenerateVoxelCheckBox.Checked;
AutoVoxSizeRadioButton.Visible := GenerateVoxelCheckBox.Checked;
end;
procedure TExportSpriteForm.voxRadioButton64x64Click(Sender: TObject);
begin
voxRadioButton64x64.Checked := True;
voxRadioButton128x128.Checked := False;
voxRadioButton256x256.Checked := False;
AutoVoxSizeRadioButton.Checked := False;
end;
procedure TExportSpriteForm.voxRadioButton128x128Click(Sender: TObject);
begin
voxRadioButton64x64.Checked := False;
voxRadioButton128x128.Checked := True;
voxRadioButton256x256.Checked := False;
AutoVoxSizeRadioButton.Checked := False;
end;
procedure TExportSpriteForm.voxRadioButton256x256Click(Sender: TObject);
begin
voxRadioButton64x64.Checked := False;
voxRadioButton128x128.Checked := False;
voxRadioButton256x256.Checked := True;
AutoVoxSizeRadioButton.Checked := False;
end;
procedure TExportSpriteForm.AutoVoxSizeRadioButtonClick(Sender: TObject);
begin
voxRadioButton64x64.Checked := False;
voxRadioButton128x128.Checked := False;
voxRadioButton256x256.Checked := False;
AutoVoxSizeRadioButton.Checked := True;
end;
end.
|
unit ranges;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
{$ModeSwitch typehelpers}
interface
uses
SysUtils, Generics.Collections;
const
RangeEnd = SizeInt.MaxValue;
RangeBegin = 0;
type
EOutOfRangeException = class(Exception);
EInvalidRangeException = class(Exception);
{ TRange }
TRange = record
public type
TSizeIntArray = array of SizeInt;
TSizeIntList = specialize TList<SizeInt>;
private
FStart: SizeInt;
FStop: SizeInt;
FStep: SizeInt;
FInitialStep: Boolean;
function GetElement(AIndex: SizeInt): SizeInt;
public
function Start: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Stop: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Step: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Count: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function MoveNext: Boolean;
property Current: SizeInt read FStart;
constructor Create(const AStart: SizeInt; const AStop: SizeInt; const AStep: SizeInt = 1);
function GetEnumerator: TRange; {$IFDEF INLINING}inline;{$ENDIF}
function ToArray: TSizeIntArray;
function FillList(const AList: TSizeIntList): SizeInt;
function ToList: TSizeIntList;
function SubRange(AStart: SizeInt; AStop: SizeInt = RangeEnd;
AStep: SizeInt = 1): TRange;
function SubRange(constref ARange: TRange): TRange; {$IFDEF INLINING}inline;{$ENDIF}
property Elements[const AIndex: SizeInt]: SizeInt read GetElement; default;
end;
{ TArrayRange }
generic TArrayRange<T> = record
public type
TArrayType = array of T;
PArrayType = ^TArrayType;
TSpecializedArrayRange = specialize TArrayRange<T>;
{ TArrayHelper }
//TArrayHelper = type helper for TArrayType
//function Range(AStart: SizeInt= RangeBegin; AStop: SizeInt = RangeEnd;
// AStep: SizeInt = 1): TSpecializedArrayRange; {$IFDEF INLINING}inline;{$ENDIF}
//function Range(constref ARange: TRange): TSpecializedArrayRange; {$IFDEF INLINING}inline;{$ENDIF}
//end;
private
FInternalRange: TRange;
FArray: PArrayType;
function GetCurrent: T; {$IFDEF INLINING}inline;{$ENDIF}
function GetElement(const AIndex: SizeInt): T; {$IFDEF INLINING}inline;{$ENDIF}
public
function Start: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Stop: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Step: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Count: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function MoveNext: Boolean; {$IFDEF INLINING}inline;{$ENDIF}
property Current: T read GetCurrent;
constructor Create(constref AArray: TArrayType; AStart: SizeInt = RangeBegin;
AStop: SizeInt = RangeEnd; const AStep: SizeInt = 1);
constructor Create(constref AArray: TArrayType; constref ARange: TRange);
function GetEnumerator: TSpecializedArrayRange; {$IFDEF INLINING}inline;{$ENDIF}
function Copy: TArrayType;
function SubRange(AStart: SizeInt; AStop: SizeInt = RangeEnd;
AStep: SizeInt = 1): TSpecializedArrayRange;
function SubRange(constref ARange: TRange): TSpecializedArrayRange;
property Elements[const AIndex: SizeInt]: T read GetElement; default;
class operator :=(constref AArray: TArrayType): TSpecializedArrayRange;
end;
{ TListRange }
generic TListRange<T> = record
public type
TListType = specialize TList<T>;
TSpecializedListRange = specialize TListRange<T>;
{ TListHelper }
//TListHelper = class Helper for TListType
//function Range(AStart: SizeInt= RangeBegin; AStop: SizeInt = RangeEnd;
// AStep: SizeInt = 1): TSpecializedListRange; {$IFDEF INLINING}inline;{$ENDIF}
//function Range(constref ARange: TRange): TSpecializedListRange; {$IFDEF INLINING}inline;{$ENDIF}
//end;
private
FInternalRange: TRange;
FList: TListType;
function GetCurrent: T; {$IFDEF INLINING}inline;{$ENDIF}
function GetElement(const AIndex: SizeInt): T; {$IFDEF INLINING}inline;{$ENDIF}
public
function Start: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Stop: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Step: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function Count: SizeInt; {$IFDEF INLINING}inline;{$ENDIF}
function MoveNext: Boolean; {$IFDEF INLINING}inline;{$ENDIF}
property Current: T read GetCurrent;
constructor Create(const AList: TListType; AStart: SizeInt = RangeBegin;
AStop: SizeInt = RangeEnd; const AStep: SizeInt = 1);
constructor Create(const AList: TListType; constref ARange: TRange);
function GetEnumerator: TSpecializedListRange; {$IFDEF INLINING}inline;{$ENDIF}
function FillList(const AList: TListType): SizeInt;
function Copy: TListType;
function SubRange(AStart: SizeInt; AStop: SizeInt = RangeEnd;
AStep: SizeInt = 1): TSpecializedListRange;
function SubRange(constref ARange: TRange): TSpecializedListRange;
property Elements[const AIndex: SizeInt]: T read GetElement; default;
class operator:=(const AList: TListType): TSpecializedListRange;
end;
function Range(const Start: SizeInt; const Stop: SizeInt; const Step: SizeInt = 1): TRange; {$IFDEF INLINING}inline;{$ENDIF}
implementation
function Range(const Start: SizeInt; const Stop: SizeInt; const Step: SizeInt
): TRange;
begin
Result := TRange.Create(Start, Stop, Step);
end;
{ TListRange.TListHelper }
//function TListRange.TListHelper.Range(AStart: SizeInt; AStop: SizeInt;
// AStep: SizeInt): TSpecializedListRange;
//begin
// Result := TSpecializedListRange(self, AStart, AStop, AStep);
//end;
//
//function TListRange.TListHelper.Range(constref ARange: TRange
// ): TSpecializedListRange;
//begin
// Result := TSpecializedListRange(self, ARange);
//end;
//{ TArrayRange.TArrayHelper }
//
//function TArrayRange.TArrayHelper.Range(AStart: SizeInt; AStop: SizeInt;
// AStep: SizeInt): TSpecializedArrayRange;
//begin
// Result := TSpecializedArrayRange.Create(self, AStart, AStop, AStep);
//end;
//
//function TArrayRange.TArrayHelper.Range(constref ARange: TRange
// ): TSpecializedArrayRange;
//begin
// Result := TSpecializedArrayRange.Create(self, ARange);
//end;
{ TListRange }
function TListRange.GetCurrent: T;
begin
Result := FList[FInternalRange.Start];
end;
function TListRange.GetElement(const AIndex: SizeInt): T;
begin
Result := FList[FInternalRange[AIndex]];
end;
function TListRange.Start: SizeInt;
begin
Result := FInternalRange.Start;
end;
function TListRange.Stop: SizeInt;
begin
Result := FInternalRange.Stop;
end;
function TListRange.Step: SizeInt;
begin
Result := FInternalRange.Step;
end;
function TListRange.Count: SizeInt;
begin
Result := FInternalRange.Count;
end;
function TListRange.MoveNext: Boolean;
begin
Result := FInternalRange.MoveNext;
end;
constructor TListRange.Create(const AList: TListType; AStart: SizeInt;
AStop: SizeInt; const AStep: SizeInt);
begin
if AStop > AList.Count then
AStop := AList.Count;
if AStart > AList.Count then
AStart := AList.Count;
while AStop < 0 do
AStop += AList.Count;
while AStart < 0 do
AStart += AList.Count;
FInternalRange := Range(AStart, AStop, AStep);
FList := AList;
end;
constructor TListRange.Create(const AList: TListType; constref ARange: TRange);
begin
Create(AList, ARange.Start, ARange.Stop, ARange.Step);
end;
function TListRange.GetEnumerator: TSpecializedListRange;
begin
Result.FList := FList;
Result.FInternalRange := FInternalRange.GetEnumerator;
end;
function TListRange.FillList(const AList: TListType): SizeInt;
var
elem: T;
begin
Result := 0;
for elem in self do
begin
AList.Add(elem);
Inc(Result);
end;
end;
function TListRange.Copy: TListType;
begin
Result := TListType.Create;
FillList(Result);
end;
function TListRange.SubRange(AStart: SizeInt; AStop: SizeInt; AStep: SizeInt
): TSpecializedListRange;
begin
Result.FInternalRange := FInternalRange.SubRange(AStart, AStop, AStep);
Result.FList := FList;
end;
function TListRange.SubRange(constref ARange: TRange): TSpecializedListRange;
begin
Result := SubRange(ARange.Start, ARange.Stop, ARange.Step);
end;
class operator TListRange.:=(const AList: TListType): TSpecializedListRange;
begin
Result := TSpecializedListRange.Create(AList);
end;
{ TArrayRange }
function TArrayRange.GetCurrent: T;
begin
Result := FArray^[FInternalRange.Current];
end;
function TArrayRange.GetElement(const AIndex: SizeInt): T;
begin
Result := FArray^[FInternalRange[AIndex]];
end;
function TArrayRange.Start: SizeInt;
begin
Result := FInternalRange.Start;
end;
function TArrayRange.Stop: SizeInt;
begin
Result := FInternalRange.Stop;
end;
function TArrayRange.Step: SizeInt;
begin
Result := FInternalRange.Step;
end;
function TArrayRange.Count: SizeInt;
begin
Result := FInternalRange.Count;
end;
function TArrayRange.MoveNext: Boolean;
begin
Result := FInternalRange.MoveNext;
end;
constructor TArrayRange.Create(constref AArray: TArrayType;
AStart: SizeInt; AStop: SizeInt; const AStep: SizeInt);
begin
if AStop > Length(AArray) then
AStop := Length(AArray);
if AStart > Length(AArray) then
AStart := Length(AArray);
while AStop < 0 do
AStop += Length(AArray);
while AStart < 0 do
AStart += Length(AArray);
FInternalRange := Range(AStart, AStop, AStep);
FArray := @AArray;
end;
constructor TArrayRange.Create(constref AArray: TArrayType; constref ARange: TRange
);
begin
Create(AArray, ARange.Start, ARange.Stop, ARange.Step);
end;
function TArrayRange.GetEnumerator: TSpecializedArrayRange;
begin
Result.FArray := FArray;
Result.FInternalRange := FInternalRange.GetEnumerator;
end;
function TArrayRange.Copy: TArrayType;
var
i: SizeInt;
begin
Result := nil;
SetLength(Result, FInternalRange.Count);
for i:=0 to Length(Result) -1 do
Result[i] := GetElement(i);
end;
function TArrayRange.SubRange(AStart: SizeInt; AStop: SizeInt; AStep: SizeInt
): TSpecializedArrayRange;
begin
Result.FInternalRange := FInternalRange.SubRange(AStart, AStop, AStep);
Result.FArray := FArray;
end;
function TArrayRange.SubRange(constref ARange: TRange): TSpecializedArrayRange;
begin
Result := SubRange(ARange.Start, ARange.Stop, ARange.Step);
end;
class operator TArrayRange.:=(constref AArray: TArrayType
): TSpecializedArrayRange;
begin
Result := TSpecializedArrayRange.Create(AArray);
end;
{ TRange }
function TRange.Count: SizeInt;
begin
Result := (FStop - FStart) div FStep
end;
function TRange.GetElement(AIndex: SizeInt): SizeInt;
begin
while AIndex < 0 do
AIndex += Count;
if AIndex >= Count then
raise EOutOfRangeException.CreateFmt('Element %d not in range', [AIndex]);
Result := FStart + FStep * AIndex;
end;
function TRange.Start: SizeInt;
begin
Result := FStart;
end;
function TRange.Stop: SizeInt;
begin
Result := FStop;
end;
function TRange.Step: SizeInt;
begin
Result := FStep;
end;
function TRange.MoveNext: Boolean;
begin
Result := Count > 1;
if Result then
if FInitialStep then
FInitialStep := False
else
Inc(Fstart, FStep);
end;
constructor TRange.Create(const AStart: SizeInt; const AStop: SizeInt;
const AStep: SizeInt);
begin
if AStep = 0 then
raise EInvalidRangeException.Create('Step size can''t be 0');
if ((AStep < 0) and (AStart < AStop)) or ((AStep > 0) and (AStart > AStop)) then
FStart := AStop
else
FStart := AStart;
FStop := AStop;
FStep := AStep;
end;
function TRange.GetEnumerator: TRange;
begin
Result := self;
Result.FInitialStep := True;
end;
function TRange.ToArray: TSizeIntArray;
var
i: SizeInt;
begin
Result := nil;
SetLength(Result, Count);
for i := 0 to Length(Result) - 1 do
Result[i] := FStart + i * FStep;
end;
function TRange.FillList(const AList: TSizeIntList): SizeInt;
var
elem: SizeInt;
begin
Result := 0;
for elem in self do
begin
AList.Add(elem);
Inc(Result);
end;
end;
function TRange.ToList: TSizeIntList;
begin
Result := TSizeIntList.Create;
FillList(Result);
end;
function TRange.SubRange(AStart: SizeInt; AStop: SizeInt; AStep: SizeInt
): TRange;
begin
if Count = 0 then
begin
AStart := 0;
AStop := 0;
end;
if AStart > Count then
AStart := Count;
While AStart < 0 do
AStart += Count;
if AStop > Count then
AStop := Count;
While AStop < 0 do
AStop += Count;
Result := Range(Start + AStart, AStop + Start, AStep * Step);
end;
function TRange.SubRange(constref ARange: TRange): TRange;
begin
Result := SubRange(ARange.Start, ARange.Stop, ARange.Step);
end;
end.
|
unit Calculadora.Subtrair;
interface
uses Calculadora.Interfaces, Calculadora.Helpers, System.SysUtils,
Calculadora.Operacoes, System.Generics.Collections;
type
TSubtrair = class sealed(TOperacoes)
constructor Create(var Value: TList<double>);
destructor Destroy; override;
class function New(var Value: TList<double>): iOperacoes;
function Executar: String; override;
end;
implementation
{ TSubtrair }
constructor TSubtrair.Create(var Value: TList<double>);
begin
FLista := Value
end;
destructor TSubtrair.Destroy;
begin
inherited;
end;
function TSubtrair.Executar: String;
var
I: Integer;
begin
Result := FLista[0].ToString;
for I := 1 to FLista.Count - 1 do
Result := (Result.ToDouble - FLista[I]).ToString;
inherited;
end;
class function TSubtrair.New(var Value: TList<double>): iOperacoes;
begin
Result := Self.Create(Value);
end;
end.
|
unit BaseActions;
interface
uses ActnList, BaseObjects, Classes, SysUtils;
type
TBaseAction = class(TAction)
private
FLastCollection: TIDObjects;
FCanUndo: boolean;
FDestroyObject: boolean;
FDestroyCollection: boolean;
FLastObjectCopy: TIDObject;
protected
FLastObject: TIDObject;
procedure AssignTo(Dest: TPersistent); override;
public
// последние над которыми проводились операции
property LastObject: TIDObject read FLastObject;
property LastObjectCopy: TIDObject read FLastObjectCopy;
property LastCollection: TIDObjects read FLastCollection write FLastCollection;
// методы выполнения с контекстом и без
function Execute: boolean; overload; override;
function Execute(ABaseObject: TIDObject): boolean; reintroduce; overload; virtual;
function Execute(ABaseCollection: TIDObjects): boolean; reintroduce; overload; virtual;
function Execute(ASQL: string): boolean; reintroduce; overload; virtual;
// может быть откат или нет
property CanUndo: boolean read FCanUndo write FCanUndo;
// удалять ли последнюю коллекцию или объъект при уничтожении команды
property DestroyCollection: boolean read FDestroyCollection write FDestroyCollection;
property DestroyObject: boolean read FDestroyObject write FDestroyObject;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TBaseActionClass = class of TBaseAction;
TBaseActionList = class(TActionList)
private
function GetActions(const Index: integer): TBaseAction;
function GetActionByClassType(AClass: TBAseActionClass): TBaseAction;
public
property ActionByClassType[AClass: TBAseActionClass]: TBaseAction read GetActionByClassType;
property Items[const Index: integer]: TBaseAction read GetActions;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses Math;
function TBaseAction.Execute: boolean;
begin
inherited Execute;
Result := true;
end;
function TBaseAction.Execute(ABaseObject: TIDObject): boolean;
begin
FLastObject := ABaseObject;
if Assigned(FLastObjectCopy) then FreeAndNil(FLastObjectCopy);
if Assigned(ABaseObject) then
begin
FLastObjectCopy := TIDObjectClass(ABaseObject.ClassType).Create(nil);
FLastObjectCopy.Assign(ABaseObject);
end;
Result := true;
//Result := Execute;
end;
constructor TBaseAction.Create(AOwner: TComponent);
begin
inherited;
FLastObjectCopy := nil;
// это перенастраивается в потомках
// коллекции унеичтожаем по умолчанию
DestroyCollection := true;
// объекты оставляем
DestroyObject := false;
// всегда разрешено
DisableIfNoHandler := false;
end;
destructor TBaseAction.Destroy;
begin
// LastObject и LastCollection создаются илм ассоциируются с какими-то глобальными переменными -
// в конструкторах потомков, а уничтодаются - здесь
if DestroyCollection then
try
if Assigned(LastCollection) then LastCollection.Free;
LastCollection := nil;
except
end;
if DestroyObject then
try
if Assigned(LastObject) then LastObject.Free;
except
end;
inherited;
end;
function TBaseAction.Execute(ABaseCollection: TIDObjects): boolean;
begin
FLastCollection := ABaseCollection;
Result := Execute;
end;
function TBaseAction.Execute(ASQL: string): boolean;
begin
Result := inherited Execute;
end;
procedure TBaseAction.AssignTo(Dest: TPersistent);
var ba: TBaseAction;
begin
inherited;
ba := Dest as TBaseAction;
ba.DestroyCollection := false;
ba.DestroyObject := false;
ba.FLastCollection := LastCollection;
ba.FLastObject := LastObject;
ba.CanUndo := false;
end;
{ TBaseActionList }
constructor TBaseActionList.Create(AOwner: TComponent);
begin
inherited;
end;
function TBaseActionList.GetActionByClassType(
AClass: TBAseActionClass): TBaseAction;
var i: integer;
begin
Result := nil;
for i := 0 to ActionCount - 1 do
if Actions[i].ClassType = AClass then
begin
Result := Actions[i] as TBaseAction;
break;
end;
if not Assigned(Result) then
begin
for i := 0 to ActionCount - 1 do
if Actions[i] is AClass then
begin
Result := Actions[i] as TBaseAction;
break;
end;
end;
if not Assigned(Result) then
begin
Result := AClass.Create(Self);
Result.ActionList := Self;
end;
end;
function TBaseActionList.GetActions(const Index: integer): TBaseAction;
begin
result := inherited Actions[Index] as TBaseAction;
end;
end.
|
unit CoreMechanicalStatePoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, CoreMechanicalState;
type
TCoreMechanicalStateDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;override;
constructor Create; override;
end;
TSlottingCoreMechanicalStateDataPoster = class(TImplementedDataPoster)
private
FAllMechanicalStates: TCoreMechanicalStates;
public
property AllMechanicalStates: TCoreMechanicalStates read FAllMechanicalStates write FAllMechanicalStates;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;override;
constructor Create; override;
end;
implementation
uses Facade, SysUtils, Variants;
{ TCoreMechanicalStateDataPoster }
constructor TCoreMechanicalStateDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'TBL_CORE_MECHANICAL_STATE_DICT';
KeyFieldNames := 'Core_Mechanical_State_ID';
FieldNames := 'Core_Mechanical_State_ID, vch_Core_Mech_State_Name, vch_Mech_State_Short_Name, num_Is_Visible';
AccessoryFieldNames := 'Core_Mechanical_State_ID, vch_Core_Mech_State_Name, vch_Mech_State_Short_Name, num_Is_Visible';;
AutoFillDates := false;
Sort := 'vch_Core_Mech_State_Name';
end;
function TCoreMechanicalStateDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TCoreMechanicalStateDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
s: TCoreMechanicalState;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
s := AObjects.Add as TCoreMechanicalState;
s.ID := ds.FieldByName('Core_Mechanical_State_ID').AsInteger;
s.Name := trim(ds.FieldByName('vch_Core_Mech_State_Name').AsString);
s.ShortName := trim(ds.FieldByName('vch_Mech_State_Short_Name').AsString);
s.IsVisible := (ds.FieldByName('num_Is_Visible').AsInteger > 0);
ds.Next;
end;
ds.First;
end;
end;
function TCoreMechanicalStateDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
s: TCoreMechanicalState;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
s := AObject as TCoreMechanicalState;
ds.FieldByName('Core_Mechanical_State_ID').AsInteger := s.ID;
ds.FieldByName('vch_Core_Mech_State_Name').AsString := trim(s.Name);
ds.FieldByName('vch_Mech_State_Short_Name').AsString := trim(s.ShortName);
ds.FieldByName('num_Is_Visible').AsInteger := ord(s.IsVisible);
ds.Post;
if s.ID = 0 then
s.ID := ds.FieldByName('Core_Mechanical_State_ID').AsInteger;
end;
{ TSlottingCoreMechanicalStateDataPoster }
constructor TSlottingCoreMechanicalStateDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_SLOTTING_MECH_STATE';
KeyFieldNames := 'CORE_MECHANICAL_STATE_ID; SLOTTING_UIN';
FieldNames := 'SLOTTING_UIN, CORE_MECHANICAL_STATE_ID';
AccessoryFieldNames := 'SLOTTING_UIN, CORE_MECHANICAL_STATE_ID';
AutoFillDates := false;
Sort := '';
end;
function TSlottingCoreMechanicalStateDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
cms: TSlottingCoreMechanicalState;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
try
// находим строку соответствующую ключу
//ds.Refresh;
ds.First;
cms := AObject as TSlottingCoreMechanicalState;
if ds.Locate(ds.KeyFieldNames, VarArrayOf([cms.MechanicalState.ID, AObject.Owner.ID]),[]) then
ds.Delete
except
Result := -1;
end;
end;
function TSlottingCoreMechanicalStateDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TCoreMechanicalState;
s: TSlottingCoreMechanicalState;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AllMechanicalStates.ItemsByID[ds.FieldByName('CORE_MECHANICAL_STATE_ID').AsInteger] as TCoreMechanicalState;
if Assigned(o) then
begin
s := AObjects.Add as TSlottingCoreMechanicalState;
s.MechanicalState := o;
s.ID := o.ID;
end;
ds.Next;
end;
ds.First;
end;
end;
function TSlottingCoreMechanicalStateDataPoster.PostToDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
var ds: TDataSet;
s: TSlottingCoreMechanicalState;
begin
s := AObject as TSlottingCoreMechanicalState;
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([s.MechanicalState.ID, s.Collection.Owner.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('Core_Mechanical_State_ID').AsInteger := s.MechanicalState.ID;
ds.FieldByName('SLOTTING_UIN').AsInteger := s.Collection.Owner.ID;
ds.Post;
end;
end.
|
unit VisibleDSA.AlgoVisualizer;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Graphics,
Forms,
BGRACanvas2D,
VisibleDSA.AlgoVisHelper,
VisibleDSA.FractalData;
type
TAlgoVisualizer = class(TObject)
private
_data: TFractalData;
_times: integer;
_isForward: boolean;
procedure __setData;
procedure __formShow(Sender: TObject);
public
constructor Create(form: TForm);
destructor Destroy; override;
procedure Paint(canvas: TBGRACanvas2D);
procedure Run;
end;
implementation
uses
Math,
VisibleDSA.AlgoForm;
var
vis: TAlgoVisualizer;
{ TAlgoVisualizer }
constructor TAlgoVisualizer.Create(form: TForm);
var
depth, w, h: integer;
begin
vis := self;
_isForward := true;
depth := 6;
_times := 1;
w := 3 ** depth;
h := 3 ** depth;
form.ClientWidth := w;
form.ClientHeight := h;
form.Caption := 'Fractal Visualizer --- ' + Format('W: %d, H: %d', [w, h]);
form.OnShow := @__formShow;
_data := TFractalData.Create(0);
end;
destructor TAlgoVisualizer.Destroy;
begin
FreeAndNil(_data);
inherited Destroy;
end;
procedure TAlgoVisualizer.Paint(canvas: TBGRACanvas2D);
const
OFFSET: array[0..4] of array[0..1] of integer = (
(0, 0),
(2, 0),
(1, 1),
(0, 2),
(2, 2));
procedure __drawFractal__(x, y, w, h, depth: integer);
var
h_3, w_3, i: integer;
begin
if depth = _data.Depth then
begin
TAlgoVisHelper.SetFill(CL_INDIGO);
TAlgoVisHelper.FillRectangle(canvas, x, y, w, h);
Exit;
end;
if (w <= 1) or (h <= 1) then
begin
TAlgoVisHelper.SetFill(CL_INDIGO);
TAlgoVisHelper.FillRectangle(canvas, x, y, Max(w, 1), Max(h, 1));
Exit;
end;
w_3 := w div 3;
h_3 := h div 3;
for i := 0 to High(OFFSET) do
begin
__drawFractal__(x + OFFSET[i, 0] * w_3, y + OFFSET[i, 1] * h_3, w_3, h_3, depth + 1);
end;
end;
begin
__drawFractal__(0, 0, canvas.Width, canvas.Height, 0);
end;
procedure TAlgoVisualizer.Run;
begin
while true do
begin
_data.Depth := _times;
__setData;
if _isForward then
begin
_times += 1;
if _times >= 7 then
_isForward := not _isForward;
end
else
begin
_times -= 1;
if _times < 1 then
_isForward := not _isForward;
end;
end;
end;
procedure TAlgoVisualizer.__formShow(Sender: TObject);
procedure __threadExecute__;
begin
vis.Run;
end;
var
thread: TThread;
begin
thread := TThread.CreateAnonymousThread(TProcedure(@__threadExecute__));
thread.FreeOnTerminate := true;
thread.Start;
end;
procedure TAlgoVisualizer.__setData;
begin
TAlgoVisHelper.Pause(100);
AlgoForm.BGRAVirtualScreen.DiscardBitmap;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
}
unit ormbr.utils;
interface
uses
Rtti,
Classes,
SysUtils,
StrUtils,
Variants,
Generics.Collections;
type
TStrArray = array of String;
PIInterface = ^IInterface;
IUtilSingleton = interface
['{D41BA6C1-EFDB-4C58-937A-59B864A8F0F4}']
function DateTimeToIso8601(const AValue: TDateTime): string;
function Iso8601ToDateTime(const AValue: string): TDateTime;
function ParseCommandNoSQL(const ASubStr, ACommandText: string;
const ADefault: String = ''): string;
end;
TUtilSingleton = class sealed(TInterfacedObject, IUtilSingleton)
private
class var
FInstance: IUtilSingleton;
private
constructor CreatePrivate;
protected
constructor Create;
public
{ Public declarations }
class function GetInstance: IUtilSingleton;
function DateTimeToIso8601(const AValue: TDateTime): string;
function Iso8601ToDateTime(const AValue: string): TDateTime;
function ParseCommandNoSQL(const ASubStr, ASQL: string;
const ADefault: String): string;
function IfThen<T>(ACondition: Boolean; ATrue: T; AFalse: T): T;
procedure SetWeak(AInterfaceField: PIInterface; const AValue: IInterface);
end;
implementation
{ TUtilSingleton }
procedure TUtilSingleton.SetWeak(AInterfaceField: PIInterface; const AValue: IInterface);
begin
PPointer(AInterfaceField)^ := Pointer(AValue);
end;
constructor TUtilSingleton.Create;
begin
raise Exception.Create('Para usar o IUtilSingleton use o método TUtilSingleton.GetInstance()');
end;
constructor TUtilSingleton.CreatePrivate;
begin
inherited;
end;
/// <summary>
/// YYYY-MM-DD Thh:mm:ss or YYYY-MM-DDThh:mm:ss
/// </summary>
function TUtilSingleton.DateTimeToIso8601(const AValue: TDateTime): string;
begin
if AValue = 0 then
Result := ''
else
if Frac(AValue) = 0 then
Result := FormatDateTime('yyyy"-"mm"-"dd', AValue)
else
if Trunc(AValue) = 0 then
Result := FormatDateTime('"T"hh":"nn":"ss', AValue)
else
Result := FormatDateTime('yyyy"-"mm"-"dd"T"hh":"nn":"ss', AValue);
end;
class function TUtilSingleton.GetInstance: IUtilSingleton;
begin
if not Assigned(FInstance) then
FInstance := TUtilSingleton.CreatePrivate;
Result := FInstance;
end;
function TUtilSingleton.IfThen<T>(ACondition: Boolean; ATrue, AFalse: T): T;
begin
Result := AFalse;
if ACondition then
Result := ATrue;
end;
function TUtilSingleton.Iso8601ToDateTime(const AValue: string): TDateTime;
var
Y, M, D, HH, MI, SS: Cardinal;
begin
// YYYY-MM-DD Thh:mm:ss or YYYY-MM-DDThh:mm:ss
// 1234567890 123456789 1234567890123456789
Result := StrToDateTimeDef(AValue, 0);
case Length(AValue) of
9:
if (AValue[1] = 'T') and (AValue[4] = ':') and (AValue[7] = ':') then
begin
HH := Ord(AValue[2]) * 10 + Ord(AValue[3]) - (48 + 480);
MI := Ord(AValue[5]) * 10 + Ord(AValue[6]) - (48 + 480);
SS := Ord(AValue[8]) * 10 + Ord(AValue[9]) - (48 + 480);
if (HH < 24) and (MI < 60) and (SS < 60) then
Result := EncodeTime(HH, MI, SS, 0);
end;
10:
if (AValue[5] = AValue[8]) and (Ord(AValue[8]) in [Ord('-'), Ord('/')]) then
begin
Y := Ord(AValue[1]) * 1000 + Ord(AValue[2]) * 100 + Ord(AValue[3]) * 10 + Ord(AValue[4]) - (48 + 480 + 4800 + 48000);
M := Ord(AValue[6]) * 10 + Ord(AValue[7]) - (48 + 480);
D := Ord(AValue[9]) * 10 + Ord(AValue[10]) - (48 + 480);
if (Y <= 9999) and ((M - 1) < 12) and ((D - 1) < 31) then
Result := EncodeDate(Y, M, D);
end;
19,24:
if (AValue[5] = AValue[8]) and
(Ord(AValue[8]) in [Ord('-'), Ord('/')]) and
(Ord(AValue[11]) in [Ord(' '), Ord('T')]) and
(AValue[14] = ':') and
(AValue[17] = ':') then
begin
Y := Ord(AValue[1]) * 1000 + Ord(AValue[2]) * 100 + Ord(AValue[3]) * 10 + Ord(AValue[4]) - (48 + 480 + 4800 + 48000);
M := Ord(AValue[6]) * 10 + Ord(AValue[7]) - (48 + 480);
D := Ord(AValue[9]) * 10 + Ord(AValue[10]) - (48 + 480);
HH := Ord(AValue[12]) * 10 + Ord(AValue[13]) - (48 + 480);
MI := Ord(AValue[15]) * 10 + Ord(AValue[16]) - (48 + 480);
SS := Ord(AValue[18]) * 10 + Ord(AValue[19]) - (48 + 480);
if (Y <= 9999) and ((M - 1) < 12) and ((D - 1) < 31) and (HH < 24) and (MI < 60) and (SS < 60) then
Result := EncodeDate(Y, M, D) + EncodeTime(HH, MI, SS, 0);
end;
end;
end;
function TUtilSingleton.ParseCommandNoSQL(const ASubStr, ASQL: string;
const ADefault: String): string;
var
LFor: Integer;
LPosI: Integer;
LPosF: Integer;
begin
Result := '';
LPosI := Pos(ASubStr + '=', ASQL);
try
if LPosI > 0 then
begin
LPosI := LPosI + Length(ASubStr);
for LFor := LPosI to Length(ASQL) do
begin
case ASQL[LFor] of
'=': LPosI := LFor;
'&': begin
if (not MatchText(ASubStr, ['values','json'])) then
Break;
end;
end;
// if (ASQL[LFor] = '=') then
// LPosI := LFor
// else
// if (ASQL[LFor] = ',') and
// (not MatchText(ASubStr, ['values','json'])) then
// Break;
end;
LPosF := LFor - LPosI;
Result := Copy(ASQL, LPosI+1, LPosF-1);
end;
finally
if (Result = '') and (ADefault <> '') then
Result := ADefault
end;
end;
end.
|
unit FMX.DCLabel;
interface
uses
System.Classes, System.UITypes, System.Types, System.Rtti,
FMX.Controls, FMX.StdCtrls, FMX.Types, FMX.Platform, FMX.Objects,
uDCObjects,
aOPCLookupList,
FMX.DCText;
type
//TaCustomOPCLabel = class(TTextControl)
TaCustomOPCLabel = class(TaDCText)
private
FAutoSize: Boolean;
FIsPressed: Boolean;
FLookupList: TaOPCLookupList;
FShowError: boolean;
FDisplayFormat: string;
FTrim: boolean;
procedure SetAutoSize(const Value: Boolean);
procedure FitSize;
procedure SetDisplayFormat(const Value: string);
procedure SetLookupList(const Value: TaOPCLookupList);
procedure SetShowError(const Value: boolean);
procedure SetTrim(const Value: boolean);
protected
procedure ApplyStyle; override;
procedure SetText(const Value: string); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure DefineProperties(Filer: TFiler); override;
function GetDefaultSize: TSizeF; override;
procedure Resize; override;
function GetDefaultStyleLookupName: string; override;
procedure ChangeData(Sender:TObject);override;
public
constructor Create(AOwner: TComponent); override;
{ triggers }
property IsPressed: Boolean read FIsPressed;
published
property LookupList : TaOPCLookupList read FLookupList write SetLookupList;
property DisplayFormat : string read FDisplayFormat write SetDisplayFormat;
property StairsOptions default [soIncrease, soDecrease];
property Trim:boolean read FTrim write SetTrim default False;
property ShowError: boolean read FShowError write SetShowError default True;
property Action;
property Align;
property Anchors;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property AutoTranslate default True;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
//property DesignVisible default True;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Font;
property FontColor;
property StyledSettings;
property Locked default False;
property Height;
property HelpContext;
property HelpKeyword;
property HelpType;
property HitTest default False;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property StyleLookup;
property Text;
property TextAlign;
property TouchTargetExpansion;
property VertTextAlign;
property Visible default True;
property Width;
property WordWrap default True;
property Trimming default TTextTrimming.None;
{events}
property OnApplyStyleLookup;
{Drag and Drop events}
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
{Keyboard events}
property OnKeyDown;
property OnKeyUp;
{Mouse events}
property OnCanFocus;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnResize;
end;
TaOPCLabel = class(TaCustomOPCLabel)
end;
// TaOPCLabelTest = class(TLabel)
// end;
implementation
uses
aOPCUtils,
System.SysUtils;
{ TLabel }
procedure TaCustomOPCLabel.ChangeData(Sender: TObject);
var
aValue: Extended;
Precision: Integer;
i: Integer;
aValueStr: string;
begin
if (ErrorCode <> 0) and FShowError then
Text := ErrorString
else
begin
if LookupList = nil then
begin
try
if Value = '' then
Exit;
aValue := StrToFloat(Value); //TryStrToFloat(Value); //StrToFloat(Value, OpcFS);
// нужно ли отсекать, а не округлять
if Trim then
begin
Precision := 1;
i := pos('.',DisplayFormat);
if i>0 then
begin
inc(i);
while i<=Length(DisplayFormat) do
begin
if CharInSet(DisplayFormat[i], ['0','#']) then
Precision := Precision * 10;
inc(i);
end;
end;
aValue := Trunc(aValue*Precision) / Precision;
end;
Text := FormatValue(aValue, DisplayFormat);
except
Text := Value
end;
end
else
begin
// пытаемся найти соответствие нашему значению и форматируем его
// если не находим, то возвращаем числовое значение
LookupList.Lookup(Value,aValueStr);
if DisplayFormat <> '' then
Text := Format(DisplayFormat,[aValueStr])
else
Text := aValueStr
end;
end;
inherited;
end;
constructor TaCustomOPCLabel.Create(AOwner: TComponent);
var
DefaultValueService: IInterface;
TrimmingDefault: TValue;
begin
inherited;
AutoTranslate := True;
if (csDesigning in ComponentState)
and SupportsPlatformService(IFMXDefaultPropertyValueService, DefaultValueService) then
begin
TrimmingDefault := IFMXDefaultPropertyValueService(DefaultValueService).GetDefaultPropertyValue(Self.ClassName, 'trimming');
if not TrimmingDefault.IsEmpty then
Trimming := TrimmingDefault.AsType<TTextTrimming>;
end;
WordWrap := True;
HitTest := False;
SetAcceptsControls(False);
end;
procedure TaCustomOPCLabel.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('TabOrder', IgnoreIntegerValue, nil, False);
end;
function TaCustomOPCLabel.GetDefaultSize: TSizeF;
var
DefMetricsSrv: IFMXDefaultMetricsService;
begin
// if SupportsPlatformService(IFMXDefaultMetricsService, IInterface(DefMetricsSrv)) and DefMetricsSrv.SupportsDefaultSize(ckLabel) then
// Result := TSizeF.Create(DefMetricsSrv.GetDefaultSize(ckLabel).Width, DefMetricsSrv.GetDefaultSize(ckLabel).Height)
// else
Result := TSizeF.Create(120, 17);
end;
function TaCustomOPCLabel.GetDefaultStyleLookupName: string;
begin
Result := 'Labelstyle';
end;
procedure TaCustomOPCLabel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
if Button = TMouseButton.mbLeft then
begin
FIsPressed := True;
StartTriggerAnimation(Self, 'IsPressed');
ApplyTriggerEffect(Self, 'IsPressed');
end;
end;
procedure TaCustomOPCLabel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
if (Button = TMouseButton.mbLeft) and (FIsPressed) then
begin
FIsPressed := False;
StartTriggerAnimation(Self, 'IsPressed');
ApplyTriggerEffect(Self, 'IsPressed');
end;
end;
procedure TaCustomOPCLabel.Resize;
begin
inherited;
if FAutoSize then
FitSize;
end;
procedure TaCustomOPCLabel.FitSize;
begin
if not (csLoading in ComponentState) then
WordWrap := False;
ApplyStyle;
end;
procedure TaCustomOPCLabel.ApplyStyle;
var
TextObj: TText;
S: TAlignLayout;
begin
inherited;
if AutoSize and (Text <> '') then
begin
if Assigned(TextObject) and (TextObject is TText) then
begin
TextObj := TText(TextObject);
S := TextObj.Align;
TextObj.Align := TAlignLayout.None;
TextObj.AutoSize := True;
Width := TextObj.Width;
Height := TextObj.Height;
TextObj.AutoSize := False;
TextObj.Align := S;
end;
end;
end;
procedure TaCustomOPCLabel.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
if FAutoSize then
FitSize;
end;
end;
procedure TaCustomOPCLabel.SetDisplayFormat(const Value: string);
begin
FDisplayFormat := Value;
ChangeData(self);
end;
procedure TaCustomOPCLabel.SetLookupList(const Value: TaOPCLookupList);
begin
FLookupList := Value;
if Value <> nil then
Value.FreeNotification(Self);
ChangeData(self);
end;
procedure TaCustomOPCLabel.SetShowError(const Value: boolean);
begin
FShowError := Value;
ChangeData(self);
end;
procedure TaCustomOPCLabel.SetText(const Value: string);
begin
if Value <> Text then
begin
inherited;
if FAutoSize then
ApplyStyle;
end
else
inherited;
end;
procedure TaCustomOPCLabel.SetTrim(const Value: boolean);
begin
FTrim := Value;
ChangeData(self);
end;
initialization
RegisterFmxClasses([TaCustomOPCLabel]);
end.
|
unit utils;
interface
uses Windows, ExtCtrls, Controls, Graphics, Forms, SysUtils, Registry, IniFiles,
ShlObj;
function getTownName(strName: string):string;
procedure setBtnOnForm(const Image: TImage; ImageList: TImageList; value: integer);
procedure FMouseDown(Image: TImage; ImageList: TImageList; value: integer);
procedure FMouseLeave(fromForm: TForm; Image: TImage; ImageList: TImageList; value: integer);
procedure FMouseMove(fromForm: TForm; Image: TImage; ImageList: TImageList; value: integer);
procedure FMouseUp(Image: TImage; ImageList: TImageList; value: integer);
function addPlus(t: integer): string;
procedure Autorun();
function StrToAscii(S:String):String;
function LocalTimeToUTC(AValue: TDateTime): TDateTime;
function HTTPEncode(const AStr: String): String;
function url_encode(const url:string):string;
function Convert(s:string):string;
function GetSpecialPath(CSIDL: word): string;
procedure setStrToIni(section, key, value: string);
function getStrFromIni(section, key, default: string): string;
implementation
uses main, options, main_class;
function getTownName(strName: string):string;
var p: integer;
begin
p := Pos(' (', strName)-1;
strName := Copy(strName, 1, p);
Result := strName;
end;
procedure setBtnOnForm(const Image: TImage; ImageList: TImageList; value: integer);
var B: TBitMap;
begin
B := TBitMap.Create;
B.Width := Image.Width;
B.Height := Image.Height;
ImageList.GetBitmap(value,B);
Image.Picture.Bitmap.Assign(B);
B.Free;
Image.Refresh;
end;
////////////////////////////////////////////////////////////////////////////////
procedure FMouseDown(Image: TImage; ImageList: TImageList; value: integer);
begin
setBtnOnForm(Image, ImageList, value);
end;
procedure FMouseLeave(fromForm: TForm; Image: TImage; ImageList: TImageList; value: integer);
begin
fromForm.cursor := crDefault;
setBtnOnForm(Image, ImageList, value);
end;
procedure FMouseMove(fromForm: TForm; Image: TImage; ImageList: TImageList; value: integer);
begin
fromForm.cursor := crHandPoint;
setBtnOnForm(Image, ImageList, value);
end;
procedure FMouseUp(Image: TImage; ImageList: TImageList; value: integer);
begin
setBtnOnForm(Image, ImageList, value);
end;
////////////////////////////////////////////////////////////////////////////////
function addPlus(t: integer): string;
begin
Result := intToStr(t);
if t>0 then Result := '+'+intToStr(t);
end;
procedure Autorun();
var Reg:TRegistry;
ini: TiniFile;
begin
ini := TIniFile.Create(GetSpecialPath(CSIDL_APPDATA)+'/Meteonova.Tray/'+iniFile);
if ini.ReadInteger('config', 'autorun', 1) = 1 then
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Run', false);
Reg.WriteString('MeteonovaTray', Application.ExeName);
Reg.Free;
end
else
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',false);
Reg.DeleteValue('MeteonovaTray');
Reg.Free;
end;
ini.Free;
end;
function StrToAscii(S:String):String;
var I,X:Integer;
RS:String;
CurChar:String;
begin
Result := '';
IF Length(S)=0 then Exit;
X:=1;
FOR I:=1 TO Length(S) Do
begin
CurChar :='#'+Inttostr(Ord(S[I]));
Insert (CurChar, RS, X);
X := X + Length(CurChar);
end;
Result := RS;
end;
function LocalTimeToUTC(AValue: TDateTime): TDateTime;
var
ST1, ST2: TSystemTime;
TZ: TTimeZoneInformation;
begin
GetTimeZoneInformation(TZ);
TZ.Bias := -TZ.Bias;
TZ.StandardBias := -TZ.StandardBias;
TZ.DaylightBias := -TZ.DaylightBias;
DateTimeToSystemTime(AValue, ST1);
SystemTimeToTzSpecificLocalTime(@TZ, ST1, ST2);
Result := SystemTimeToDateTime(ST2);
end;
function HTTPEncode(const AStr: String): String;
// The NoConversion set contains characters as specificed in RFC 1738 and
// should not be modified unless the standard changes.
const
NoConversion = ['A'..'Z','a'..'z','*','@','.','_','-',
'0'..'9','$','!','''','(',')'];
var
Sp, Rp: PChar;
begin
SetLength(Result, Length(AStr) * 3);
Sp := PChar(AStr);
Rp := PChar(Result);
while Sp^ <>#0 do
begin
if Sp^ in NoConversion then
Rp^ := Sp^
else
if Sp^ = ' ' then
Rp^ := '+'
else
begin
FormatBuf(Rp^, 3, '%%%.2x', 6, [Ord(Sp^)]);
Inc(Rp,2);
end;
Inc(Rp);
Inc(Sp);
end;
SetLength(Result, Rp - PChar(Result));
end;
function url_encode(const url:string):string;
var
i: integer;
begin
result:='';
for i:=1 to length(url) do begin
case url[i] of
'a'..'z','A'..'Z','0'..'9','/','.','&','-'
(* maybe some more are allowed *)
: result:=result+ url[i];
else result:=result+'%'+uppercase(inttohex(ord(url[i]),2));
end;
end;
end;
function Convert(s:string):string;
var j: Integer;
const
rus='ÀÁÂÃÄŨÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÜÛÚÝÞßàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ';
web='%Ñ0%C1%C2%C3%C4%C5%A8%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DC%DB%DA%DD%DE%DF%E0%E1%E2%E3%E4%E5%B8%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FC%FB%FA%FD%FE%FF';
begin
for j := 1 to Length(s) do
if (pos(s[j],rus)>0) then begin
result:=result+copy(web,3*(pos(s[j],rus)-1)+1,3);
end
else result:=result+s[j];
end;
function GetSpecialPath(CSIDL: word): string;
var s: string;
begin
SetLength(s, MAX_PATH);
if not SHGetSpecialFolderPath(0, PChar(s), CSIDL, true)
then s := GetSpecialPath(CSIDL_APPDATA);
result := PChar(s);
end;
function getStrFromIni(section, key, default: string): string;
var ini: TIniFile;
begin
ini := TIniFile.Create(GetSpecialPath(CSIDL_APPDATA)+'/Meteonova.Tray/'+iniFile);
Result := ini.ReadString(section, key, default);
if Result = default then
setStrToIni(section, key, default);
ini.Free;
end;
procedure setStrToIni(section, key, value: string);
var ini: TIniFile;
error: Integer;
begin
{$IOChecks off}
if not DirectoryExists(GetSpecialPath(CSIDL_APPDATA)+'\Meteonova.Tray') then
MkDir(GetSpecialPath(CSIDL_APPDATA)+'\Meteonova.Tray');
error := IOResult;
if error = 0 then
begin
ini := TIniFile.Create(GetSpecialPath(CSIDL_APPDATA)+'\Meteonova.Tray\'+iniFile);
try
ini.WriteString(section, key, value);
finally
ini.Free;
end;
end;
end;
end.
|
unit HJYServices;
interface
uses SysUtils, Classes, Windows, HJYFactoryIntfs;
type
THJYService = Class(TObject, IInterface)
private
FRefCount: Integer;
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
end;
function HJYService: IInterface;
implementation
uses HJYFactoryManagers;
var
FHJYService: IInterface;
function HJYService: IInterface;
begin
if not Assigned(FHJYService) then
FHJYService := THJYService.Create;
Result := FHJYService;
end;
{ THJYService }
function THJYService._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount);
end;
function THJYService._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
end;
function THJYService.QueryInterface(const IID: TGUID; out Obj): HResult;
var
lvFactory: THJYFactory;
begin
Result := E_NOINTERFACE;
if Self.GetInterface(IID, Obj) then
Result := S_OK
else
begin
lvFactory := FactoryManager.FindFactory(IID);
if Assigned(lvFactory) then
begin
lvFactory.CreateInstance(IID, Obj);
Result := S_OK;
end;
end;
end;
initialization
FHJYService := nil;
finalization
FHJYService := nil;
end.
|
unit hmt_parser;
{$mode objfpc}{$H+}
interface
uses
sysutils, Classes,
rs_image;
type
THmtMaterial = record
type_: shortint;
tex_index: shortint;
unknown_float1, unknown_float2: single;
zero: integer;
hex_a: integer;
name: array[0..15] of byte;
end;
THmtTexture = record
data_offset: integer;
palette_offset: integer;
name_offset: integer;
width, height: word;
name: array[0..15] of byte;
name_string: string;
image: TRSImage;
end;
THmtFile = record
material_count: integer;
texture_offset: integer;
texture_count: integer;
materials: array of THmtMaterial;
textures: array of THmtTexture;
end;
function ParseHmtFile(const fname: string): THmtFile;
//**************************************************************************************************
implementation
function NameToString(name: array of byte): string;
var
i: Integer;
begin
result := '';
for i := 0 to length(name) - 1 do begin
if name[i] = 0 then break;
result += char( name[i] );
end;
end;
procedure ReadTexture(var tex: THmtTexture; var f: TMemoryStream);
const
ImageDescription: array[0..5] of TImageDescription = (
(palette_entries: 16; sample_bits: 4),
(palette_entries: 256; sample_bits: 8),
(palette_entries: 0; sample_bits: 16),
(palette_entries: 0; sample_bits: 32),
(palette_entries: 0; sample_bits: 4),
(palette_entries: 0; sample_bits: 16)
);
var
image: TRSImage;
buf: array[0..27] of byte;
description: TImageDescription;
bpp: byte;
color_rgba: integer;
pos: int64;
begin
tex.data_offset := f.ReadDWord;
f.ReadBuffer(buf, 28);
tex.palette_offset := f.ReadDWord;
tex.name_offset := f.ReadDWord;
tex.width := f.ReadWord;
tex.height := f.ReadWord;
f.ReadByte; //0x01
bpp := f.ReadByte;
image.type_ := f.ReadByte;
f.ReadByte;
color_rgba := f.ReadDWord;
pos := f.Position;
f.Seek(tex.name_offset, TSeekOrigin.soBeginning);
f.ReadBuffer(tex.name, 16);
tex.name_string := NameToString(tex.name);
f.Seek(pos, TSeekOrigin.soBeginning);
description := ImageDescription[image.type_];
image.sampleBits := description.sample_bits;
image.paletteEntries := description.palette_entries;
image.width := tex.width;
image.height := tex.height;
writeln('name: ', tex.name_string);
writeln('size: ', tex.width, 'x', tex.height);
writeln('subtype: ', image.type_, ' bpp: ', bpp);
writeln('sample bits: ', image.sampleBits);
writeln('palette offset: ', tex.palette_offset);
writeln('data offset: ', tex.data_offset);
if tex.palette_offset > 0 then begin
writeln('palette entries: ', image.paletteEntries);
f.Seek(tex.palette_offset, TSeekOrigin.soBeginning);
LoadPalette(image, f);
end;
f.Seek(tex.data_offset, TSeekOrigin.soBeginning);
LoadSamples(image, f);
DecodePixels(image);
f.Seek(pos, TSeekOrigin.soBeginning);
writeln;
tex.image := image;
end;
procedure ReadMaterial(var mat: THmtMaterial; var f: TMemoryStream);
begin
mat.type_ := f.ReadWord;
mat.tex_index := f.ReadWord;
mat.unknown_float1 := f.ReadDWord;
mat.unknown_float2 := f.ReadDWord;
mat.zero := f.ReadDWord;
mat.hex_a := f.ReadDWord;
f.ReadBuffer(mat.name, 16);
writeln(NameToString(mat.name));
if (mat.zero <> 0) or (mat.hex_a <> $A) then
writeln('unusual file');
writeln(' type1: ', mat.type_);
writeln(' type2: ', mat.tex_index);
end;
function ParseHmtFile(const fname: string): THmtFile;
var
f: TMemoryStream;
hmt: THmtFile;
i: Integer;
begin
f := TMemoryStream.Create;
f.LoadFromFile(fname);
//read main info
hmt.material_count := f.ReadDWord;
hmt.texture_offset := f.ReadDWord;
f.Seek(hmt.texture_offset, TSeekOrigin.soBeginning);
hmt.texture_count := f.ReadDWord;
f.Seek(8, TSeekOrigin.soBeginning);
//read materials
writeln('materials: ', hmt.material_count);
SetLength(hmt.materials, hmt.material_count);
for i := 0 to hmt.material_count - 1 do begin
ReadMaterial(hmt.materials[i], f);
end;
if hmt.texture_count = 0 then begin
result := hmt;
f.Free;
exit;
end;
//read textures
writeln('textures: ', hmt.texture_count);
f.Seek(hmt.texture_offset + 4, TSeekOrigin.soBeginning);
SetLength(hmt.textures, hmt.texture_count);
for i := 0 to hmt.texture_count - 1 do begin
ReadTexture(hmt.textures[i], f);
end;
f.Free;
result := hmt;
end;
end.
|
unit MBRTUMasterDispatcherFunc;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils,
MBRTUMasterDispatcherTypes;
function IsValidCRC(var APacket : TMBPacket; APacketLen : Word) : Boolean;
function GetPortAdapterIDStr(APortParam : TMBDispPortParam) : String;
function IsEqualPortInfo(AOld : TMBDispPortParam; ANew : TMBDispPortParam) : Boolean;
implementation
uses CRC16Func, COMPortParamTypes;
function IsValidCRC(var APacket: TMBPacket; APacketLen: Word): Boolean;
begin
Result := GetCRC16(@APacket[0],APacketLen) = 0;
end;
function GetPortAdapterIDStr(APortParam: TMBDispPortParam): String;
var TempPrefix : String;
begin
{$IFDEF WINDOWS}
TempPrefix := cCOMPrefixWindows;
{$ENDIF}
{$IFDEF UNIX}
TempPrefix := cCOMPrefixLinux;
{$ENDIF}
if APortParam.PortPrefix <> '' then TempPrefix := APortParam.PortPrefix;
Result := Format('%s%d',[TempPrefix,APortParam.PortNum]);
end;
function IsEqualPortInfo(AOld: TMBDispPortParam; ANew: TMBDispPortParam): Boolean;
begin
Result := (AOld.Parity = ANew.Parity) and
(AOld.StopBits = ANew.StopBits) and
(AOld.DataBits = ANew.DataBits) and
(AOld.BaudRate = ANew.BaudRate) and
SameText(AOld.PortPrefix, ANew.PortPrefix) and
(AOld.PortNum = ANew.PortNum);
end;
end.
|
unit uSpringTestCaseHelper;
interface
uses
TestFramework;
type
TSpringTestCaseHelper = class helper for TTestCase
protected // note this cannot be strict protected, as a TTestCase descendant cannot use it
procedure TestInterfaceImplementedByClass(const FInterface: IInterface;
const ClassType: TClass; const InstanceDescription: string); virtual;
procedure TestInterfaceNotImplementedByClass(const FInterface: IInterface; const ClassType: TClass; const
InstanceDescription: string); virtual;
end;
implementation
uses
SysUtils,
Spring;
procedure TSpringTestCaseHelper.TestInterfaceImplementedByClass(const FInterface
: IInterface; const ClassType: TClass; const InstanceDescription: string);
var
Instance: TObject;
begin
// as of Delphi 2010, you can cast back from an interface to the implementing class;
// see http://stackoverflow.com/questions/4138211/how-to-cast-a-interface-to-a-object-in-delphi/11167316#11167316
Instance := FInterface as TObject;
Check(Instance.InheritsFrom(ClassType),
Format('%s class "%s" does not inherit from "%s".', [InstanceDescription,
GetQualifiedClassName(Instance), GetQualifiedClassName(ClassType)]));
end;
procedure TSpringTestCaseHelper.TestInterfaceNotImplementedByClass(const FInterface: IInterface; const ClassType:
TClass; const InstanceDescription: string);
var
Instance: TObject;
begin
// as of Delphi 2010, you can cast back from an interface to the implementing class;
// see http://stackoverflow.com/questions/4138211/how-to-cast-a-interface-to-a-object-in-delphi/11167316#11167316
Instance := FInterface as TObject;
Check(Instance.InheritsFrom(ClassType),
Format('%s class "%s" does inherit from "%s", but should not.', [InstanceDescription,
GetQualifiedClassName(Instance), GetQualifiedClassName(ClassType)]));
end;
end.
|
unit RTF_EdytorUlicy;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls, JvUIB, JvUIBLib;
type
TFrmEdytorUlicy = class(TForm)
GbxDaneOgolne: TGroupBox;
EdtNazwa: TEdit;
LblNazwa: TLabel;
EdtPoczatek: TEdit;
LblPoczatek: TLabel;
EdtKoniec: TEdit;
LblKoniec: TLabel;
GbxPostoje: TGroupBox;
BtnOK: TButton;
BtnAnuluj: TButton;
LbxAvailablePostoje: TListBox;
LbxSelectedPostoje: TListBox;
BtnAdd: TBitBtn;
BtnRemove: TBitBtn;
BtnMoveUp: TBitBtn;
BtnMoveDown: TBitBtn;
LblAvailablePostoje: TLabel;
LblAssignedPostoje: TLabel;
TmrUpdateButtons: TTimer;
CbxObszar: TComboBox;
LblObszar: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure EdtPoczatekKeyPress(Sender: TObject; var Key: Char);
procedure BtnAddClick(Sender: TObject);
procedure BtnRemoveClick(Sender: TObject);
procedure BtnMoveUpClick(Sender: TObject);
procedure BtnMoveDownClick(Sender: TObject);
procedure TmrUpdateButtonsTimer(Sender: TObject);
procedure LbxAvailablePostojeDblClick(Sender: TObject);
procedure LbxSelectedPostojeDblClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FId: Integer;
FObszarId: Integer;
procedure DisplayObszary;
procedure DisplayAssignedPostoje;
procedure DisplayAvailablePostoje;
procedure ClearAssignedPostoje;
procedure ClearAvailablePostoje;
public
{ Public declarations }
procedure SetData(Fields: TSQLResult);
end;
implementation
uses
Math, RT_Tools, RT_SQL;
{$R *.DFM}
type
TPostoj = class (TObject)
Id: Integer;
Nazwa: String;
constructor Create(AId: Integer; ANazwa: String);
end;
constructor TPostoj.Create(AId: Integer; ANazwa: String);
begin
inherited Create;
Id := AId;
Nazwa := ANazwa;
end;
{ TFrmEdytorUlicy }
{ Private declarations }
procedure TFrmEdytorUlicy.DisplayObszary;
var
Index: Integer;
begin
with TSQL.Instance.CreateQuery do
try
SQL.Text := 'SELECT ID,NAZWA FROM OBSZAR';
Open;
while not Eof do
begin
Index := CbxObszar.Items.AddObject(Fields.ByNameAsString['NAZWA'], Pointer(Fields.ByNameAsInteger['ID']));
if Fields.ByNameAsInteger['ID'] = FObszarId then
CbxObszar.ItemIndex := Index;
Next;
end;
finally
Free;
end;
end;
procedure TFrmEdytorUlicy.DisplayAssignedPostoje;
begin
with TSQL.Instance.CreateQuery do
try
SQL.Text := Format('SELECT * FROM POSTOJ WHERE ID NOT IN (SELECT POSTOJID FROM POSTOJNAULICY WHERE POSTOJNAULICY.ULICAID = %d)', [
FId
]);
Open;
while not Eof do
begin
LbxAvailablePostoje.AddItem(Fields.ByNameAsString['NAZWA'], TPostoj.Create(Fields.ByNameAsInteger['ID'], Fields.ByNameAsString['NAZWA']));
Next;
end;
finally
Free;
end;
end;
procedure TFrmEdytorUlicy.DisplayAvailablePostoje;
begin
with TSQL.Instance.CreateQuery do
try
SQL.Text := Format('SELECT POSTOJ.ID, POSTOJ.NAZWA FROM POSTOJNAULICY INNER JOIN POSTOJ ON (POSTOJNAULICY.POSTOJID = POSTOJ.ID) WHERE POSTOJNAULICY.ULICAID = %d ORDER BY POSTOJNAULICY.INDEKS', [
FId
]);
Open;
while not Eof do
begin
LbxSelectedPostoje.AddItem(Fields.ByNameAsString['NAZWA'], TPostoj.Create(Fields.ByNameAsInteger['ID'], Fields.ByNameAsString['NAZWA']));
Next;
end;
finally
Free;
end;
end;
procedure TFrmEdytorUlicy.ClearAssignedPostoje;
var
I: Integer;
begin
for I := 0 to LbxAvailablePostoje.Count - 1 do
LbxAvailablePostoje.Items.Objects[I].Free;
end;
procedure TFrmEdytorUlicy.ClearAvailablePostoje;
var
I: Integer;
begin
for I := 0 to LbxSelectedPostoje.Count - 1 do
LbxSelectedPostoje.Items.Objects[I].Free;
end;
{ Public declarations }
procedure TFrmEdytorUlicy.SetData(Fields: TSQLResult);
begin
FId := Fields.ByNameAsInteger['ID'];
FObszarId := Fields.ByNameAsInteger['OBSZARID'];
EdtNazwa.Text := Fields.ByNameAsString['NAZWA'];
EdtPoczatek.Text := Fields.ByNameAsString['POCZATEK'];
EdtKoniec.Text := Fields.ByNameAsString['KONIEC'];
end;
{ Event handlers }
procedure TFrmEdytorUlicy.FormCreate(Sender: TObject);
begin
//
end;
procedure TFrmEdytorUlicy.FormDestroy(Sender: TObject);
begin
ClearAssignedPostoje;
ClearAvailablePostoje;
end;
procedure TFrmEdytorUlicy.FormShow(Sender: TObject);
begin
DisplayObszary;
DisplayAssignedPostoje;
DisplayAvailablePostoje;
end;
procedure TFrmEdytorUlicy.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
I1, I2{, J1, J2}: Integer;
I: Integer;
begin
if ModalResult = mrCancel then
Exit;
if EdtNazwa.Text = '' then
begin
EdtNazwa.SetFocus;
ShowError('Należy podać nazwę ulicy');
CanClose := False;
Exit;
end;
if EdtPoczatek.Text = '' then
begin
EdtPoczatek.SetFocus;
ShowError('Należy podać numer początkowy, którego dotyczy wpis ulicy');
CanClose := False;
Exit;
end;
I1 := StrtoInt(EdtPoczatek.Text);
if EdtKoniec.Text <> '' then
begin
I2 := StrtoInt(EdtKoniec.Text);
if I1 > I2 then
begin
EdtKoniec.SetFocus;
ShowError('Podany zakres, którego dotyczy wpis ulicy jest niepoprawny');
CanClose := False;
Exit;
end;
end;
// else
// I2 := MaxInt;
if LbxSelectedPostoje.Count = 0 then
begin
CanClose := False;
ShowError('Należy przypisać chociaż jeden postój do danego wpisu ulicy');
Exit;
end;
if CbxObszar.ItemIndex = -1 then
begin
CbxObszar.SetFocus;
ShowError('Należy wybrać obszar do danego wpisu ulicy');
CanClose := False;
Exit;
end;
with TSQL.Instance.CreateQuery do
try
SQL.Text := Format('EXECUTE PROCEDURE UPDATE_ULICA %d,%s,%s,%s,%d;', [
FId,
QuotedStr(EdtNazwa.Text),
QuotedStr(EdtPoczatek.Text),
QuotedStr(EdtKoniec.Text),
Integer(CbxObszar.Items.Objects[CbxObszar.ItemIndex])
]);
Execute;
FId := Fields.ByNameAsInteger['NEW_ID'];
SQL.Text := Format('DELETE FROM POSTOJNAULICY WHERE ULICAID=%d', [
FId
]);
Execute;
for I := 0 to LbxSelectedPostoje.Count - 1 do
begin
SQL.Text := FORMAT('EXECUTE PROCEDURE ADD_POSTOJ_DO_ULICY %d,%d;', [
TPostoj(LbxSelectedPostoje.Items.Objects[I]).Id,
FId
]);
Execute;
end;
Transaction.Commit;
finally
Free;
end;
// for I := 0 to TDatabase.Instance.Streets.Count - 1 do
// begin
// Street := TDatabase.Instance.Streets[I];
// if (Data <> Street) and AnsiSameText(Street.Name, EdtNazwa.Text) then
// begin
// J1 := StrToInt(Street.Start);
// if Street.Stop <> '' then
// J2 := StrToInt(Street.Stop)
// else
// J2 := MaxInt;
// if ((I1 >= J1) and (I1 <= J2)) or ((I2 >= J1) and (I2 <= J2)) then
// begin
// if (J1 = 1) and (J2 = MaxInt) then
// EdtNazwa.SetFocus
// else
// EdtPoczatek.SetFocus;
// ShowError('Podany zakres, którego dotyczy wpis ulicy koliduje z innym wpisem o tej samej nazwie');
// CanClose := False;
// Exit;
// end;
// end;
// end;
end;
procedure TFrmEdytorUlicy.EdtPoczatekKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', #8]) then Key := #0;
end;
procedure TFrmEdytorUlicy.BtnAddClick(Sender: TObject);
begin
with LbxAvailablePostoje do
begin
LbxSelectedPostoje.AddItem(Items[ItemIndex], Items.Objects[ItemIndex]);
Items.Delete(ItemIndex);
end;
end;
procedure TFrmEdytorUlicy.BtnRemoveClick(Sender: TObject);
begin
with LbxSelectedPostoje do
begin
LbxAvailablePostoje.AddItem(Items[ItemIndex], Items.Objects[ItemIndex]);
Items.Delete(ItemIndex);
end;
end;
procedure TFrmEdytorUlicy.BtnMoveUpClick(Sender: TObject);
var
NewIndex: Integer;
begin
with LbxSelectedPostoje do
begin
NewIndex := ItemIndex - 1;
Items.Move(ItemIndex, NewIndex);
ItemIndex := NewIndex;
end;
end;
procedure TFrmEdytorUlicy.BtnMoveDownClick(Sender: TObject);
var
NewIndex: Integer;
begin
with LbxSelectedPostoje do
begin
NewIndex := ItemIndex + 1;
Items.Move(ItemIndex, ItemIndex + 1);
ItemIndex := NewIndex;
end;
end;
procedure TFrmEdytorUlicy.TmrUpdateButtonsTimer(Sender: TObject);
begin
BtnAdd.Enabled := LbxAvailablePostoje.ItemIndex <> -1;
BtnRemove.Enabled := LbxSelectedPostoje.ItemIndex <> -1;
BtnMoveUp.Enabled := LbxSelectedPostoje.ItemIndex > 0;
BtnMoveDown.Enabled := (LbxSelectedPostoje.ItemIndex <> -1) and (LbxSelectedPostoje.ItemIndex < LbxSelectedPostoje.Count - 1);
end;
procedure TFrmEdytorUlicy.LbxAvailablePostojeDblClick(Sender: TObject);
var
Index: Integer;
begin
with LbxAvailablePostoje do
begin
Index := ItemAtPos(ScreenToClient(Mouse.CursorPos), True);
if Index <> -1 then
begin
LbxSelectedPostoje.AddItem(Items[ItemIndex], Items.Objects[ItemIndex]);
Items.Delete(ItemIndex);
end;
end;
end;
procedure TFrmEdytorUlicy.LbxSelectedPostojeDblClick(Sender: TObject);
var
Index: Integer;
begin
with LbxSelectedPostoje do
begin
Index := ItemAtPos(ScreenToClient(Mouse.CursorPos), True);
if Index <> -1 then
begin
LbxAvailablePostoje.AddItem(Items[ItemIndex], Items.Objects[ItemIndex]);
Items.Delete(ItemIndex);
end;
end;
end;
procedure TFrmEdytorUlicy.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
function IsUpperCase(S: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 1 to Length(S) do
if not (S[I] in [' ', '0'..'9']) then
begin
Result := UpCase(S[I]) = S[I];
Break;
end;
end;
begin
if Key = VK_F9 then
begin
if IsUpperCase(EdtNazwa.Text) then
EdtNazwa.Text := LowerCase(EdtNazwa.Text)
else
EdtNazwa.Text := UpperCase(EdtNazwa.Text);
end;
end;
end.
|
unit Iocp.Queue;
interface
uses
Classes, SyncObjs;
type
{
*** 指针队列 ***
}
TIocpPointerQueue = class
private
FQueue: TList;
protected
function GetCount: Integer; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function Push(P: Pointer): Boolean; virtual;
function Pop(out P: Pointer): Boolean; virtual;
procedure Clear; virtual;
property Count: Integer read GetCount;
end;
{
*** 带锁的指针队列 ***
}
TIocpQueue = class(TIocpPointerQueue)
private
FLocker: TCriticalSection;
protected
function GetCount: Integer; override;
public
constructor Create; override;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function Push(P: Pointer): Boolean; override;
function Pop(out P: Pointer): Boolean; override;
procedure Clear; override;
end;
{
*** 文本队列 ***
}
TTextQueue = class(TIocpQueue)
public
destructor Destroy; override;
function Push(S: AnsiString): Boolean; reintroduce;
function Pop(out S: AnsiString): Boolean; reintroduce;
end;
implementation
{ TIocpPointerQueue }
procedure TIocpPointerQueue.Clear;
begin
FQueue.Clear;
end;
constructor TIocpPointerQueue.Create;
begin
FQueue := TList.Create;
end;
destructor TIocpPointerQueue.Destroy;
begin
FQueue.Free;
inherited Destroy;
end;
function TIocpPointerQueue.GetCount: Integer;
begin
Result := FQueue.Count;
end;
function TIocpPointerQueue.Pop(out P: Pointer): Boolean;
begin
if (FQueue.Count <= 0) then
begin
Result := False;
Exit;
end;
P := FQueue[FQueue.Count - 1];
FQueue.Delete(FQueue.Count - 1);
Result := True;
end;
function TIocpPointerQueue.Push(P: Pointer): Boolean;
begin
FQueue.Add(P);
Result := True;
end;
{ TIocpQueue }
constructor TIocpQueue.Create;
begin
inherited Create;
FLocker := TCriticalSection.Create;
end;
destructor TIocpQueue.Destroy;
begin
FLocker.Free;
inherited Destroy;
end;
procedure TIocpQueue.Clear;
begin
try
Lock;
inherited Clear;
finally
Unlock;
end;
end;
function TIocpQueue.GetCount: Integer;
begin
try
Lock;
Result := inherited GetCount;
finally
Unlock;
end;
end;
procedure TIocpQueue.Lock;
begin
FLocker.Enter;
end;
function TIocpQueue.Pop(out P: Pointer): Boolean;
begin
try
Lock;
Result := inherited Pop(P);
finally
Unlock;
end;
end;
function TIocpQueue.Push(P: Pointer): Boolean;
begin
try
Lock;
Result := inherited Push(P);
finally
Unlock;
end;
end;
procedure TIocpQueue.Unlock;
begin
FLocker.Leave;
end;
{ TTextQueue }
destructor TTextQueue.Destroy;
var
S: AnsiString;
begin
while Pop(S) do;
inherited Destroy;
end;
function TTextQueue.Pop(out S: AnsiString): Boolean;
var
ps: PAnsiString;
begin
Result := inherited Pop(Pointer(ps));
if not Result then Exit;
S := ps^;
System.Dispose(ps);
end;
function TTextQueue.Push(S: AnsiString): Boolean;
var
ps: PAnsiString;
begin
System.New(ps);
ps^ := S;
Result := inherited Push(ps);
end;
end.
|
unit Parameters;
interface
uses
System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Ora, Grids, ValEdit, ActnList, Vcl.ExtCtrls, BCDialogs.Dlg;
type
TValueListEditor = class(ValEdit.TValueListEditor)
public
property InplaceEditor; // change this property to public
end;
TParametersDialog = class(TDialog)
CancelButton: TButton;
OKButton: TButton;
Panel1: TPanel;
Panel2: TPanel;
Separator1Panel: TPanel;
ValueListEditor: TValueListEditor;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Formshow(Sender: TObject);
procedure ValueListEditorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FOraQuery: TOraQuery;
FOraSQL: TOraSQL;
public
{ Public declarations }
ValuesList: TValueListEditor; { Save param values }
function Open(OraQuery: TOraQuery): Boolean; overload;
function Open(OraSQL: TOraSQL): Boolean; overload;
end;
function ParametersDialog: TParametersDialog;
implementation
{$R *.dfm}
Uses
DB, BCCommon.StyleUtils, BCCommon.StringUtils;
var
FParametersDialog: TParametersDialog;
function ParametersDialog: TParametersDialog;
begin
if not Assigned(FParametersDialog) then
Application.CreateForm(TParametersDialog, FParametersDialog);
Result := FParametersDialog;
SetStyledFormSize(Result);
end;
procedure TParametersDialog.FormCreate(Sender: TObject);
begin
ValuesList := TValueListEditor.Create(nil);
ValuesList.Strings.Clear;
end;
procedure TParametersDialog.FormDestroy(Sender: TObject);
begin
ValuesList.Free;
FParametersDialog := nil;
end;
procedure TParametersDialog.Formshow(Sender: TObject);
begin
with ValueListEditor do
begin
Col := 1;
Row := 1;
SetFocus;
EditorMode := True;
InplaceEditor.SelectAll; // Trick to get the focus in to a first cell!
end;
end;
function TParametersDialog.Open(OraQuery: TOraQuery): Boolean;
var
i, j: Integer;
Rslt: Integer;
KeyName, KeyValue: string;
begin
FOraQuery := OraQuery;
ValueListEditor.Strings.Clear;
for i := 0 to OraQuery.ParamCount - 1 do
ValueListEditor.InsertRow(OraQuery.Params[i].Name, DecryptString(ValuesList.Values[EncryptString(OraQuery.Params[i].Name)]), True);
Rslt := ShowModal;
for i := 0 to OraQuery.ParamCount - 1 do
OraQuery.Params[i].Value := ValueListEditor.Values[OraQuery.Params[i].Name];
for i := 0 to OraQuery.ParamCount - 1 do
begin
KeyName := EncryptString(OraQuery.Params[i].Name);
KeyValue := EncryptString(OraQuery.Params[i].Value);
ValuesList.FindRow(KeyName, j);
if j <> -1 then
ValuesList.Values[KeyName] := KeyValue
else
ValuesList.InsertRow(KeyName, KeyValue, True)
end;
Result := Rslt = mrOk;
end;
function TParametersDialog.Open(OraSQL: TOraSQL): Boolean;
var
i, j: Integer;
Rslt: Integer;
KeyName, KeyValue: string;
begin
FOraSQL := OraSQL;
ValueListEditor.Strings.Clear;
for i := 0 to OraSQL.ParamCount - 1 do
ValueListEditor.InsertRow(OraSQL.Params[i].Name, DecryptString(ValuesList.Values[EncryptString(OraSQL.Params[i].Name)]), True);
Rslt := ShowModal;
for i := 0 to OraSQL.ParamCount - 1 do
OraSQL.Params[i].Value := ValueListEditor.Values[OraSQL.Params[i].Name];
for i := 0 to OraSQL.ParamCount - 1 do
begin
KeyName := EncryptString(OraSQL.Params[i].Name);
KeyValue := EncryptString(OraSQL.Params[i].Value);
ValuesList.FindRow(KeyName, j);
if j <> -1 then
ValuesList.Values[KeyName] := KeyValue
else
ValuesList.InsertRow(KeyName, KeyValue, True)
end;
Result := Rslt = mrOk;
end;
procedure TParametersDialog.ValueListEditorKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = 13) or (Key = 9) then
begin
if ValueListEditor.Row < Pred(ValueListEditor.RowCount) then
ValueListEditor.Row := ValueListEditor.Row + 1
else
if Key = 9 then { tab goes around }
ValueListEditor.Row := 1
else
if Key = 13 then { enter executes }
OKButton.Click;
end;
end;
end.
|
// Copyright 2018 The Casbin Authors. All Rights Reserved.
//
// 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 Tests.Effect;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TTestEffect = class(TObject)
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure testSomeAllow;
[Test]
procedure testNotSomeDeny;
[Test]
procedure testSomeAllowANDNotDeny;
[Test]
procedure testPriorityORDeny;
[Test]
procedure testUnknown;
[Test]
procedure testEmptyEffects;
end;
implementation
uses
Casbin.Effect.Types, Casbin.Effect, System.SysUtils;
procedure TTestEffect.Setup;
begin
end;
procedure TTestEffect.TearDown;
begin
end;
procedure TTestEffect.testEmptyEffects;
begin
Assert.AreEqual(true, mergeEffects(ecNotSomeDeny, []));
end;
procedure TTestEffect.testNotSomeDeny;
var
effects: TEffectArray;
begin
SetLength(effects, 3);
//Not Some Deny
effects[0]:=erAllow;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(True, mergeEffects(ecNotSomeDeny, effects), '1');
effects[0]:=erDeny;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(False, mergeEffects(ecNotSomeDeny, effects), '2');
end;
procedure TTestEffect.testPriorityORDeny;
var
effects: TEffectArray;
begin
SetLength(effects, 3);
effects[0]:=erAllow;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(true, mergeEffects(ecPriorityORDeny, effects), '1');
effects[0]:=erIndeterminate;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(True, mergeEffects(ecPriorityORDeny, effects), '2');
effects[0]:=erIndeterminate;
effects[1]:=erAllow;
effects[2]:=erDeny;
Assert.AreEqual(True, mergeEffects(ecPriorityORDeny, effects), '3');
effects[0]:=erIndeterminate;
effects[1]:=erDeny;
effects[2]:=erAllow;
Assert.AreEqual(False, mergeEffects(ecPriorityORDeny, effects), '4');
effects[0]:=erAllow;
effects[1]:=erDeny;
effects[2]:=erAllow;
Assert.AreEqual(true, mergeEffects(ecPriorityORDeny, effects), '5');
effects[0]:=erDeny;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(false, mergeEffects(ecPriorityORDeny, effects), '6');
end;
procedure TTestEffect.testSomeAllow;
var
effects: TEffectArray;
begin
SetLength(effects, 3);
effects[0]:=erAllow;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(True, mergeEffects(ecSomeAllow, effects), '1');
effects[0]:=erDeny;
effects[1]:=erDeny;
effects[2]:=erDeny;
Assert.AreEqual(False, mergeEffects(ecSomeAllow, effects), '2');
effects[0]:=erAllow;
effects[1]:=erDeny;
effects[2]:=erDeny;
Assert.AreEqual(True, mergeEffects(ecSomeAllow, effects), '3');
effects[0]:=erIndeterminate;
effects[1]:=erDeny;
effects[2]:=erDeny;
Assert.AreEqual(false, mergeEffects(ecSomeAllow, effects), '4');
end;
procedure TTestEffect.testSomeAllowANDNotDeny;
var
effects: TEffectArray;
begin
SetLength(effects, 3);
effects[0]:=erIndeterminate;
effects[1]:=erIndeterminate;
effects[2]:=erIndeterminate;
Assert.AreEqual(False, mergeEffects(ecSomeAllowANDNotDeny, effects), '1');
effects[0]:=erAllow;
effects[1]:=erIndeterminate;
effects[2]:=erIndeterminate;
Assert.AreEqual(true, mergeEffects(ecSomeAllowANDNotDeny, effects), '2');
effects[0]:=erAllow;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(true, mergeEffects(ecSomeAllowANDNotDeny, effects), '3');
effects[0]:=erDeny;
effects[1]:=erAllow;
effects[2]:=erAllow;
Assert.AreEqual(False, mergeEffects(ecSomeAllowANDNotDeny, effects), '4');
end;
procedure TTestEffect.testUnknown;
var
proc: TProc;
begin
proc:=procedure
begin
mergeEffects(ecUnknown, []);
end;
Assert.WillRaise(proc);
end;
initialization
TDUnitX.RegisterTestFixture(TTestEffect);
end.
|
unit UUtilsJSON;
interface
uses
Data.DBXJSON, System.JSON, Types, Classes;
type
TJSONPersistent = class(TObject)
protected
function GetAsJSon: string;
procedure SetAsJSon(const Value: string);
function GetAsJSonObject: TJSONObject; virtual;
procedure SetAsJSonObject(const Value: TJSONObject); virtual;
public
constructor CreateAsJSON(strJSON: String); overload; virtual;
property AsJSon: string read GetAsJSon write SetAsJSon;
property AsJSonObject: TJSONObject read GetAsJSonObject write SetAsJSonObject;
end;
function GetAsObject(json: TJSONObject; strName: string): TJSONObject;
function GetAsArray(json: TJSONObject; strName: string): TJSONArray;
function GetAsString(json: TJSONObject; strName: string; strDefault: string = ''): string;
function GetAsDouble(json: TJSONObject; strName: string; dblDefault: Double = 0): Double; overload;
function GetAsInteger(json: TJSONObject; strName: string; iDefault: integer = 0): integer; overload;
function GetAsBoolean(json: TJSONObject; strName: string): boolean;
function GetAsRect(json: TJSONObject; strName: string): TRect;
procedure GetAsStringList(json: TJSONObject; strName: string; list: TStringList);
function CreateBoolPair(strName: string; blnValue: boolean): TJSONPair;
function CreateRectPair(strName: string; rect: TRect): TJSONPair;
function CreateStringListPair(strName: string; list: TStringList): TJSONPair;
function EscapeString(const AValue: string): string;
implementation
uses
SysUtils;
function GetAsObject(json: TJSONObject; strName: string): TJSONObject;
var
oPair: TJSONPair;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := nil;
oPair := json.Get(strName);
if Assigned(oPair) then begin
Result:= oPair.JsonValue as TJSONObject;
end;
end;
function GetAsArray(json: TJSONObject; strName: string): TJSONArray;
var
oPair: TJSONPair;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := nil;
oPair := json.Get(strName);
if Assigned(oPair) then begin
Result:= oPair.JsonValue as TJSONArray;
end;
end;
function GetAsString(json: TJSONObject; strName, strDefault: string): string;
var
oPair: TJSONPair;
oString: TJSONString;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := strDefault;
oPair := json.Get(strName);
if Assigned(oPair) then begin
oString := oPair.JsonValue as TJSONString;
if Assigned(oString) then begin
Result := oString.Value;
end;
end;
end;
function GetAsDouble(json: TJSONObject; strName: string; dblDefault: Double): Double;
var
oPair: TJSONPair;
oNumber: TJSONNumber;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := dblDefault;
oPair := json.Get(strName);
if Assigned(oPair) then begin
oNumber := oPair.JsonValue as TJSONNumber;
if Assigned(oNumber) then begin
Result := oNumber.AsDouble;
end;
end;
end;
function GetAsInteger(json: TJSONObject; strName: string; iDefault: integer): integer;
var
oPair: TJSONPair;
oNumber: TJSONNumber;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := iDefault;
oPair := json.Get(strName);
if Assigned(oPair) then begin
oNumber := oPair.JsonValue as TJSONNumber;
if Assigned(oNumber) then begin
Result := oNumber.AsInt64;
end;
end;
end;
function GetAsBoolean(json: TJSONObject; strName: string): boolean;
var
oPair: TJSONPair;
begin
assert(Assigned(json), 'json parameter not assigned');
Result := False;
oPair := json.Get(strName);
if Assigned(oPair) then begin
Result := oPair.JsonValue is TJSONTrue;
end;
end;
function CreateBoolPair(strName: string; blnValue: boolean): TJSONPair;
begin
if blnValue then
Result := TJSONPair.Create(strName, TJSONTrue.Create)
else
Result := TJSONPair.Create(strName, TJSONFalse.Create);
end;
function GetAsRect(json: TJSONObject; strName: string): TRect;
var
oPair: TJSONPair;
oRectObject: TJSONObject;
begin
assert(Assigned(json), 'json parameter not assigned');
oPair := json.Get(strName);
if Assigned(oPair) then begin
oRectObject := oPair.JsonValue as TJSONObject;
Result.Left := GetAsInteger(oRectObject, 'Left', 0);
Result.Top := GetAsInteger(oRectObject, 'Top', 0);
Result.Right := GetAsInteger(oRectObject, 'Right', 0);
Result.Bottom := GetAsInteger(oRectObject, 'Bottom', 0);
end else begin
Result := Rect(0,0,0,0);
end;
end;
function CreateRectPair(strName: string; rect: TRect): TJSONPair;
var
oRectObject: TJSONObject;
begin
oRectObject := TJSONObject.Create;
oRectObject.AddPair('Left', TJSONNumber.Create(rect.Left));
oRectObject.AddPair('Top', TJSONNumber.Create(rect.Top));
oRectObject.AddPair('Right', TJSONNumber.Create(rect.Right));
oRectObject.AddPair('Bottom', TJSONNumber.Create(rect.Bottom));
Result := TJSONPair.Create(strName, oRectObject);
end;
procedure GetAsStringList(json: TJSONObject; strName: string; list: TStringList);
var
oPair: TJSONPair;
oListArray: TJSONArray;
i: integer;
begin
assert(Assigned(json), 'json parameter not assigned');
list.Clear;
oPair := json.Get(strName);
if Assigned(oPair) then begin
oListArray := oPair.JsonValue as TJSONArray;
for i := 0 to oListArray.Size -1 do begin
list.Add(oListArray.Get(i).Value);
end;
end;
end;
function CreateStringListPair(strName: string; list: TStringList): TJSONPair;
var
oListArray: TJSONArray;
i: Integer;
begin
oListArray := TJSONArray.Create;
for i := 0 to list.Count -1 do begin
oListArray.AddElement( TJSONString.Create( EscapeString(list[i])) );
end;
Result := TJSONPair.Create(strName, oListArray);
end;
{ TJSONPersistent }
constructor TJSONPersistent.CreateAsJSON(strJSON: String);
begin
Create;
AsJSon := strJSON;
end;
function TJSONPersistent.GetAsJSon: string;
var
oJsonObject: TJSONObject;
begin
oJsonObject := GetAsJSonObject;
try
Result := oJsonObject.ToString();
finally
oJsonObject.Free;
end;
end;
function TJSONPersistent.GetAsJSonObject: TJSONObject;
begin
Result := TJSONObject.Create;
end;
procedure TJSONPersistent.SetAsJSon(const Value: string);
var
oJsonObject: TJSONObject;
begin
oJsonObject := TJSONObject.ParseJSONValue(Value) as TJSONObject;
try
SetAsJSonObject(oJsonObject);
finally
oJsonObject.Free;
end;
end;
procedure TJSONPersistent.SetAsJSonObject(const Value: TJSONObject);
begin
//
end;
function EscapeString(const AValue: string): string;
const
ESCAPE = '\';
// QUOTATION_MARK = '"';
REVERSE_SOLIDUS = '\';
SOLIDUS = '/';
BACKSPACE = #8;
FORM_FEED = #12;
NEW_LINE = #10;
CARRIAGE_RETURN = #13;
HORIZONTAL_TAB = #9;
var
AChar: Char;
begin
Result := '';
for AChar in AValue do
begin
case AChar of
// !! Double quote (") is handled by TJSONString
// QUOTATION_MARK: Result := Result + ESCAPE + QUOTATION_MARK;
REVERSE_SOLIDUS: Result := Result + ESCAPE + REVERSE_SOLIDUS;
SOLIDUS: Result := Result + ESCAPE + SOLIDUS;
BACKSPACE: Result := Result + ESCAPE + 'b';
FORM_FEED: Result := Result + ESCAPE + 'f';
NEW_LINE: Result := Result + ESCAPE + 'n';
CARRIAGE_RETURN: Result := Result + ESCAPE + 'r';
HORIZONTAL_TAB: Result := Result + ESCAPE + 't';
else
begin
if (Integer(AChar) < 32) or (Integer(AChar) > 126) then
Result := Result + ESCAPE + 'u' + IntToHex(Integer(AChar), 4)
else
Result := Result + AChar;
end;
end;
end;
end;
end.
|
{------------------------------------
功能说明:系统通知相关接口
创建日期:2011/07/16
作者:wzw
版权:wzw
-------------------------------------}
unit NotifyServiceIntf;
{$weakpackageunit on}
interface
type
INotify = interface
['{9D0B21A1-CCA0-422F-B11B-4650B506A573}']
procedure Notify(Flags: Integer; Intf: IInterface; Param: Integer);
end;
TSysNotifyEvent = procedure(Flags: Integer; Intf: IInterface; Param: Integer) of object;
INotifyService = interface
['{F347E481-F6C3-48DA-BDD5-9452C69FCE30}']
procedure SendNotify(Flags: Integer; Intf: IInterface; Param: Integer);
procedure RegisterNotify(Notify: INotify);
procedure UnRegisterNotify(Notify: INotify);
procedure RegisterNotifyEx(Flags: Integer; Notify: INotify);
procedure UnRegisterNotifyEx(Notify: INotify);
procedure RegisterNotifyEvent(NotifyEvent: TSysNotifyEvent);
procedure UnRegisterNotifyEvent(NotifyEvent: TSysNotifyEvent);
procedure RegisterNotifyEventEx(Flags: Integer; NotifyEvent: TSysNotifyEvent);
procedure UnRegisterNotifyEventEx(NotifyEvent: TSysNotifyEvent);
end;
implementation
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [SINTEGRA_60M]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 1.0
*******************************************************************************}
unit Sintegra60mVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils,
Sintegra60aVO;
type
[TEntity]
[TTable('ECF_SINTEGRA_60M')]
TSintegra60mVO = class(TVO)
private
FID: Integer;
FDATA_EMISSAO: TDateTime;
FNUMERO_SERIE_ECF: String;
FNUMERO_EQUIPAMENTO: Integer;
FMODELO_DOCUMENTO_FISCAL: String;
FCOO_INICIAL: Integer;
FCOO_FINAL: Integer;
FCRZ: Integer;
FCRO: Integer;
FVALOR_VENDA_BRUTA: Extended;
FVALOR_GRANDE_TOTAL: Extended;
FNOME_CAIXA: String;
FID_GERADO_CAIXA: Integer;
FDATA_SINCRONIZACAO: TDateTime;
FHORA_SINCRONIZACAO: String;
FListaSintegra60aVO: TObjectList<TSintegra60aVO>;
public
constructor Create; override;
destructor Destroy; override;
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('DATA_EMISSAO', 'Data Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO;
[TColumn('NUMERO_SERIE_ECF', 'Numero Serie Ecf', 160, [ldGrid, ldLookup, ldCombobox], False)]
property NumeroSerieEcf: String read FNUMERO_SERIE_ECF write FNUMERO_SERIE_ECF;
[TColumn('NUMERO_EQUIPAMENTO', 'Numero Equipamento', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property NumeroEquipamento: Integer read FNUMERO_EQUIPAMENTO write FNUMERO_EQUIPAMENTO;
[TColumn('MODELO_DOCUMENTO_FISCAL', 'Modelo Documento Fiscal', 16, [ldGrid, ldLookup, ldCombobox], False)]
property ModeloDocumentoFiscal: String read FMODELO_DOCUMENTO_FISCAL write FMODELO_DOCUMENTO_FISCAL;
[TColumn('COO_INICIAL', 'Coo Inicial', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CooInicial: Integer read FCOO_INICIAL write FCOO_INICIAL;
[TColumn('COO_FINAL', 'Coo Final', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CooFinal: Integer read FCOO_FINAL write FCOO_FINAL;
[TColumn('CRZ', 'Crz', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Crz: Integer read FCRZ write FCRZ;
[TColumn('CRO', 'Cro', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Cro: Integer read FCRO write FCRO;
[TColumn('VALOR_VENDA_BRUTA', 'Valor Venda Bruta', 128, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorVendaBruta: Extended read FVALOR_VENDA_BRUTA write FVALOR_VENDA_BRUTA;
[TColumn('VALOR_GRANDE_TOTAL', 'Valor Grande Total', 128, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorGrandeTotal: Extended read FVALOR_GRANDE_TOTAL write FVALOR_GRANDE_TOTAL;
[TColumn('NOME_CAIXA', 'Nome Caixa', 64, [ldGrid, ldLookup, ldCombobox], False)]
property NomeCaixa: String read FNOME_CAIXA write FNOME_CAIXA;
[TColumn('ID_GERADO_CAIXA', 'Id Gerado Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)]
property IdGeradoCaixa: Integer read FID_GERADO_CAIXA write FID_GERADO_CAIXA;
[TColumn('DATA_SINCRONIZACAO', 'Data Sinronizacao', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataSincronizacao: TDateTime read FDATA_SINCRONIZACAO write FDATA_SINCRONIZACAO;
[TColumn('HORA_SINCRONIZACAO', 'Hora Sincronizacao', 64, [ldGrid, ldLookup, ldCombobox], False)]
property HoraSincronizacao: String read FHORA_SINCRONIZACAO write FHORA_SINCRONIZACAO;
[TManyValuedAssociation('ID_SINTEGRA_60M', 'ID')]
property ListaSintegra60aVO: TObjectList<TSintegra60aVO> read FListaSintegra60aVO write FListaSintegra60aVO;
end;
implementation
constructor TSintegra60mVO.Create;
begin
inherited;
FListaSintegra60aVO := TObjectList<TSintegra60aVO>.Create;
end;
destructor TSintegra60mVO.Destroy;
begin
FreeAndNil(FListaSintegra60aVO);
inherited;
end;
initialization
Classes.RegisterClass(TSintegra60mVO);
finalization
Classes.UnRegisterClass(TSintegra60mVO);
end.
|
unit teste.classes.pedido;
interface
uses
Windows,
System.classes,
System.Generics.Collections,
System.SysUtils;
type
TpedidoItem = class
Private
Fcodigo: integer;
FcodigoProduto: integer;
FdescricaoProduto: string;
Fquantidade: integer;
FvalorUnitario: double;
FvalorTotal: double;
function getValorTotal: double;
public
published
Property Codigo: integer read Fcodigo write Fcodigo;
Property CodigoProduto: integer read FcodigoProduto write FcodigoProduto;
Property DescricaoProduto: string read FdescricaoProduto
write FdescricaoProduto;
Property Quantidade: integer read Fquantidade write Fquantidade;
Property ValorUnitario: double read FvalorUnitario write FvalorUnitario;
Property ValorTotal: double read getValorTotal write FvalorTotal;
end;
TpedidoItens = TObjectList<TpedidoItem>;
type
TpedidoClass = class
private
Fcodigo: integer;
Fdata: Tdatetime;
FclienteCodigo: integer;
FclienteNome: string;
Ftotal: double;
Fitens: TpedidoItens;
public
constructor create(numero: integer);
procedure excluir;
procedure gravar;
procedure limpar;
function getTotal: double;
function Listapedidos(filtro: string): olevariant;
published
Property Codigo: integer read Fcodigo write Fcodigo;
Property Data: Tdatetime read Fdata write Fdata;
Property ClienteCodigo: integer read FclienteCodigo write FclienteCodigo;
Property ClienteNome: string read FclienteNome write FclienteNome;
Property Total: double read getTotal write Ftotal;
Property Itens: TpedidoItens read Fitens write Fitens;
end;
implementation
uses
teste.dao.pedido;
{ Tpedido }
constructor TpedidoClass.create(numero: integer);
begin
Fitens := TpedidoItens.create(false);
if numero > 0 then
begin
Fcodigo := numero;
TdaoPedido.getPedido(self);
end;
end;
{ ----------------------------------------------------------------------------- }
{ TpedidoIten }
function TpedidoItem.getValorTotal: double;
begin
result := 0;
if (Quantidade > 0) and (ValorUnitario > 0) then
result := Quantidade * ValorUnitario
end;
{ ----------------------------------------------------------------------------- }
procedure TpedidoClass.excluir;
begin
if TdaoPedido.deletePedido(self) then
begin
limpar;
end;
end;
{ ----------------------------------------------------------------------------- }
function TpedidoClass.getTotal: double;
var
ototal: double;
i: integer;
begin
ototal := 0;
for i := 0 to Itens.Count - 1 do
begin
ototal := ototal + Itens[i].ValorTotal;
end;
Ftotal := ototal;
result := ototal;
end;
procedure TpedidoClass.gravar;
begin
TdaoPedido.setPedido(self);
end;
procedure TpedidoClass.limpar;
begin
Fcodigo := 0;
Fdata := 0;
FclienteCodigo := 0;
ClienteNome := '';
Ftotal := 0;
Fitens.Clear;
end;
function TpedidoClass.Listapedidos(filtro: string): olevariant;
begin
result := TdaoPedido.listarPedidos(filtro);
end;
{ ----------------------------------------------------------------------------- }
end.
|
unit untTokenHelper;
interface
uses
System.JSON, System.NetEncoding, System.Hash, System.SysUtils;
const
TheKey = '{1017CD6D-2CCC-4F71-882B-A0448F432DC1}';
function GetTokenFromData(Data: string; SecretKey: string): string;
function GetDataFromToken(Token: string; SecretKey: string): string;
implementation
function GetTokenFromData(Data: string; SecretKey: string): string;
var
EncodedData : string;
EncodedDataHash : string;
CustomEncoder : TBase64Encoding;
begin
CustomEncoder := TBase64Encoding.Create(0);
EncodedData := CustomEncoder.Encode(Data);
EncodedDataHash := THashSHA2.GetHMAC(EncodedData, SecretKey);
Result := EncodedData + '.' + EncodedDataHash;
end;
function GetDataFromToken(Token: string; SecretKey: string): string;
var
EncodedData : string;
EncodedDataHash : string;
CheckDataHash : string;
CustomEncoder : TBase64Encoding;
begin
CustomEncoder := TBase64Encoding.Create(0);
EncodedData := Copy(Token, 1, Pos('.', Token) - 1);
EncodedData := StringReplace(EncodedData, '%3D', '=', [rfReplaceAll]);
EncodedDataHash := Copy(Token, Pos('.', Token) + 1, Length(Token)- (Pos('.', Token)));
CheckDataHash := THashSHA2.GetHMAC(EncodedData, SecretKey);
if CheckDataHash <> EncodedDataHash then
Result := 'Invalid token'
else
Result := CustomEncoder.Decode(EncodedData);
end;
end.
|
unit UReconfList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UEmbedForm, StdCtrls, ExtCtrls, ComCtrls, Grids, tc;
type
TFReconfList = class(TEmbedForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Panel2: TPanel;
Header: THeaderControl;
Grid: TStringGrid;
StatusBar1: TStatusBar;
procedure HeaderSectionResize(HeaderControl: THeaderControl;
Section: THeaderSection);
procedure FormActivate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
Model : TModel;
procedure Load;
function Change(Item : RItem) : boolean;
end;
var
FReconfList: TFReconfList;
implementation
uses URParams, UModel;
{$R *.DFM}
procedure TFReconfList.HeaderSectionResize(
HeaderControl: THeaderControl; Section: THeaderSection);
begin
if Section.Index = 0 then
Grid.ColWidths[Section.Index] := Section.Width - 4
else
Grid.ColWidths[Section.Index] := Section.Width;
end;
procedure TFReconfList.FormActivate(Sender: TObject);
begin
Grid.ColWidths[0] := Header.Sections[0].Width - 4;
Grid.ColWidths[1] := Header.Sections[1].Width;
Grid.ColWidths[2] := Header.Sections[2].Width;
Grid.ColWidths[3] := Header.Sections[3].Width;
Load;
end;
procedure TFReconfList.Button1Click(Sender: TObject);
var
Item : RItem;
begin
Item := RItem.Create(Model.ReconfList);
if not Change(Item) then exit;
Model.ReconfList.Append(Item);
Load;
end;
procedure TFReconfList.Button3Click(Sender: TObject);
begin
if Model.ReconfList.Count < 1 then
begin
MessageDlg('В списке перенастройки отсутствуют объекты!', mtError, [mbOk], 0);
exit;
end;
if MessageDlg('Удалить выделенный элемент?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then exit;
Model.ReconfList.Delete(grid.Row);
Load;
end;
procedure TFReconfList.Load;
var
i : integer;
id : Integer;
begin
StatusBar1.SimpleText := format('Критерий оптимизации: %d', [Round(FModel.ModelCopy.OptimKoef / 1000)]);
Model.ReconfList.SortAll;
for i := 0 to grid.RowCount do
begin
grid.cells[0, i] := '';
grid.cells[1, i] := '';
grid.cells[2, i] := '';
grid.cells[3, i] := '';
end;
grid.RowCount := Model.ReconfList.Count;
With Model.ReconfList do
for i := Low(List) to High(List) do
with (List[i] as RItem) do
begin
id := Model.Lines.FindByNumber(rLine);
if id <> -1 then
grid.cells[0, i] := Model.Lines.List[id].Name
else
grid.cells[0, i] := NoLink;
grid.cells[1, i] := ShortTime2Works(rTime);
id := Model.Materials.FindByNumber(rFrom);
if id <> -1 then
grid.cells[2, i] := Model.Materials.List[id].Name
else
grid.cells[2, i] := NoLink;
id := Model.Materials.FindByNumber(rTo);
if id <> -1 then
grid.cells[3, i] := Model.Materials.List[id].Name
else
grid.cells[3, i] := NoLink;
end;
end;
function TFReconfList.Change(Item: RItem) : boolean;
begin
FRParams.Item := Item;
FRParams.Model := Model;
FRParams.ShowModal;
result := (FRParams.ModalResult = mrOk)
end;
procedure TFReconfList.Button2Click(Sender: TObject);
begin
if Model.ReconfList.Count < 1 then
begin
MessageDlg('В списке перенастройки отсутствуют объекты!', mtError, [mbOk], 0);
exit;
end;
Change(Model.ReconfList.List[grid.row] as RItem);
Load;
end;
end.
|
unit Grijjy.FaceDetection.iOS;
{< Face Detection for iOS. }
interface
uses
iOSapi.CoreImage,
FMX.Graphics,
Grijjy.FaceDetection;
type
{ IgoFaceDetector implementation }
TgoFaceDetectorImplementation = class(TInterfacedObject, IgoFaceDetector)
private
FMaxFaces: Integer;
FContext: CIContext;
FDetector: CIDetector;
protected
{ IgoFaceDetector }
function DetectFaces(const ABitmap: TBitmap): TArray<TgoFace>;
public
constructor Create(const AAccuracy: TgoFaceDetectionAccuracy;
const AMaxFaces: Integer);
destructor Destroy; override;
end;
implementation
uses
System.Types,
System.Math,
iOSapi.Foundation;
{ These APIs are missing from iOSapi.CoreImage: }
function CIDetectorAccuracyLow: Pointer;
begin
Result := Pointer(CocoaPointerConst(libCoreImage, 'CIDetectorAccuracyLow')^);
end;
function CIDetectorAccuracyHigh: Pointer;
begin
Result := Pointer(CocoaPointerConst(libCoreImage, 'CIDetectorAccuracyLow')^);
end;
function CIDetectorAccuracy: Pointer;
begin
Result := Pointer(CocoaPointerConst(libCoreImage, 'CIDetectorAccuracy')^);
end;
function CIDetectorTypeFace: NSString;
begin
Result := CocoaNSStringConst(libCoreImage, 'CIDetectorTypeFace');
end;
function kCIFormatBGRA8: CIFormat;
begin
Result := PInteger(CocoaPointerConst(libCoreImage, 'kCIFormatBGRA8'))^;
end;
{ TgoFaceDetectorImplementation }
constructor TgoFaceDetectorImplementation.Create(
const AAccuracy: TgoFaceDetectionAccuracy; const AMaxFaces: Integer);
var
Options: NSDictionary;
Value: Pointer;
begin
inherited Create;
FMaxFaces := AMaxFaces;
{ Create a CoreImage context. This is required by the CIFaceDetector class. }
FContext := TCIContext.Wrap(TCIContext.OCClass.contextWithOptions(nil));
{ We need to make sure the context stays alive for the duration of this
object. So retain it. (We will release it in the destructor). }
FContext.retain;
{ Create an options dictionary with a single option:
the face detection accuracy. }
if (AAccuracy = TgoFaceDetectionAccuracy.Low) then
Value := CIDetectorAccuracyLow
else
Value := CIDetectorAccuracyHigh;
Options := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject(
Value, CIDetectorAccuracy));
{ Create a face detector using the context and options we just created. }
FDetector := TCIDetector.Wrap(TCIDetector.OCClass.detectorOfType(
CIDetectorTypeFace, FContext, Options));
{ Like the context, we need to keep the detector alive. }
FDetector.retain;
end;
destructor TgoFaceDetectorImplementation.Destroy;
begin
{ We retained the detector and context in the constructor, so we need to
release it here. }
if Assigned(FDetector) then
FDetector.release;
if Assigned(FContext) then
FContext.release;
inherited;
end;
function TgoFaceDetectorImplementation.DetectFaces(
const ABitmap: TBitmap): TArray<TgoFace>;
var
SrcData: TBitmapData;
Data: NSData;
Size: NSSize;
Image: CIImage;
Format: CIFormat;
Features: NSArray;
I, Count: Integer;
SrcFeature: CIFaceFeature;
DstFace: TgoFace;
R: NSRect;
P: NSPoint;
begin
Assert(Assigned(ABitmap));
{ Create a CIImage with the contents of our FireMonkey bitmap.
First, we need to create a NSData object with the raw bitmap data of the
FireMonkey bitmap. }
if (not ABitmap.Map(TMapAccess.Read, SrcData)) then
Exit(nil);
try
Data := TNSData.Wrap(TNSData.OCClass.dataWithBytes(SrcData.Data,
SrcData.Width * SrcData.Height * SrcData.BytesPerPixel));
finally
ABitmap.Unmap(SrcData);
end;
{ Now we can create a CIImage using this data.
We create it in BGRA8 format to match the format in the FireMonkey bitmap. }
Size.width := ABitmap.Width;
Size.height := ABitmap.Height;
Format := kCIFormatBGRA8;
Image := TCIImage.Wrap(TCIImage.OCClass.imageWithBitmapData(Data,
ABitmap.Width * 4, Size, Format, nil));
{ Pass the image to the face detector. }
Features := FDetector.featuresInImage(Image, nil);
if (Features = nil) then
Exit(nil);
{ Convert the CIFaceFeature objects to TgoFace records. }
Count := Min(Features.count, FMaxFaces);
SetLength(Result, Count);
for I := 0 to Count - 1 do
begin
{ Extract the face feature from the array. }
SrcFeature := TCIFaceFeature.Wrap(Features.objectAtIndex(I));
{ Calculate the face bounds.
NOTE: Images on iOS are upside-down }
R := SrcFeature.bounds;
DstFace.Bounds.Left := R.origin.x;
DstFace.Bounds.Top := ABitmap.Height - R.origin.y - R.size.height;
DstFace.Bounds.Width := R.size.width;
DstFace.Bounds.Height := R.size.height;
{ Convert the left eye position, again taking into account the image
is upside-down. }
if (SrcFeature.hasLeftEyePosition) then
begin
P := SrcFeature.leftEyePosition;
DstFace.LeftEyePosition := PointF(P.x, ABitmap.Height - P.y);
end
else
DstFace.LeftEyePosition := PointF(0, 0);
{ Convert the right eye position. }
if (SrcFeature.hasRightEyePosition) then
begin
P := SrcFeature.rightEyePosition;
DstFace.RightEyePosition := PointF(P.x, ABitmap.Height - P.y);
end
else
DstFace.RightEyePosition := PointF(0, 0);
{ Calculate the distance between the eyes manually. }
DstFace.EyesDistance := DstFace.LeftEyePosition.Distance(DstFace.RightEyePosition);
Result[I] := DstFace;
end;
end;
end.
|
(**
* $Id: dco.rpc.RPCException.pas 840 2014-05-24 06:04:58Z QXu $
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific language governing rights and limitations under the License.
*)
unit dco.rpc.RPCException;
interface
uses
System.SysUtils,
dco.rpc.ErrorObject,
dco.rpc.Identifier;
type
/// <summary>Thrown when a RPC message is perceived to be invalid.</summary>
ERPCException = class(Exception)
private
FError: TErrorObject;
FId: TIdentifier;
public
property Error: TErrorObject read FError;
property Id: TIdentifier read FId;
public
constructor Create(const Error: TErrorObject; const Id: TIdentifier);
end;
implementation
constructor ERPCException.Create(const Error: TErrorObject; const Id: TIdentifier);
begin
FError := Error;
FId := Id;
if (FId.Value = nil) then
inherited Create(FError.ToString)
else
inherited Create(Format('%s (id=%s)', [FError.ToString, FId.ToString]));
end;
end.
|
unit ShaleVolumeForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TShaleVolume_Form = class(TForm)
RadioGroup1: TRadioGroup;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
GroupBox3: TGroupBox;
Label1: TLabel;
Label2: TLabel;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
Edit3: TEdit;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure RadioButton2Click(Sender: TObject);
procedure RadioButton1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ShaleVolume_Form: TShaleVolume_Form;
implementation
uses Main_Form, SelectLog;
{$R *.dfm}
procedure TShaleVolume_Form.Button1Click(Sender: TObject);
var
Error_Code:integer;
Temp_Value:Single;
begin
with MainForm do
begin
Operation_Canceled:=False;
Value_Is_Constant[1]:=RadioButton1.Checked;
if Value_Is_Constant[1] then
begin
Val(Edit3.Text, Temp_Value, Error_Code);
if Error_Code=0 then
Constant_Value[1]:=Temp_Value
else
begin
MessageDlg('Please enter a valid number for gamma-ray index!', mtError, [mbOk], 0);
Exit;
end;
GRI_Track_Number:=-1;
end;
Shale_Volume_Method:=RadioGroup1.ItemIndex;
end;
Close;
end;
procedure TShaleVolume_Form.Button2Click(Sender: TObject);
begin
MainForm.Operation_Canceled:=True;
Close;
end;
procedure TShaleVolume_Form.Button3Click(Sender: TObject);
begin
Select_Log:=TSelect_Log.Create(Self);
Select_Log.ShowModal;
MainForm.GRI_Track_Number:=Select_Log.Selected_Track_Number;
if Select_Log.Selected_Track_Number<>-1 then
begin
MainForm.GRI_Track_Number:=Select_Log.Selected_Track_Number;
Label2.Caption:=MainForm.Charts[MainForm.GRI_Track_Number].Title.Text.Text;
end;
Select_Log.Free;
end;
procedure TShaleVolume_Form.RadioButton2Click(Sender: TObject);
begin
Edit3.Enabled:=RadioButton1.Checked;
Edit3.Color:=clBtnFace;
Button3.Enabled:=RadioButton2.Checked;
if MainForm.GRI_Track_Number<>-1 then
begin
Label2.Caption:=MainForm.Charts[MainForm.GRI_Track_Number].Title.Text.Text;
end;
end;
procedure TShaleVolume_Form.RadioButton1Click(Sender: TObject);
begin
Edit3.Enabled:=RadioButton1.Checked;
Edit3.Color:=clWindow;
Button3.Enabled:=RadioButton2.Checked;
Label2.Caption:='NONE';
Edit3.SetFocus;
end;
procedure TShaleVolume_Form.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose:=True;
with MainForm do
begin
if (not(Operation_Canceled))and(GRI_Track_Number=-1)and(not(Value_Is_Constant[1])) then
begin
CanClose:=False;
MessageDlg('Please select a track for gamma-ray index!', mtWarning,[mbOk],0);
Exit;
end;
end;
end;
end.
|
(*
@abstract(Contient des classes génériques pour manipuler des
tableaux "Array" a travers un pointeur.)
Contient des classes pour manipuler des tableaux 1D de type Byte, Integer, Single et Double. @br
Contient des classes pour manipuler des tableaux 2D de type Byte, Integer, Single et Double.
-------------------------------------------------------------------------------------------------------------
@created(24/02/2019)
@author(J.Delauney (BeanzMaster))
@bold(Historique) : @br
@unorderedList(
@item(Creation : 24/02/2019)
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes :)@br
-------------------------------------------------------------------------------------------------------------
@bold(Dependances) : BZSceneStrConsts, BZLogger si DEBUGLOG est activé @br
-------------------------------------------------------------------------------------------------------------
@bold(Credits :)@br
@unorderedList(
@item(J.Delauney (BeanzMaster))
)
-------------------------------------------------------------------------------------------------------------
@bold(LICENCE) : MPL / LGPL @br
------------------------------------------------------------------------------------------------------------- *)
unit BZArrayClasses;
//==============================================================================
{$mode objfpc}{$H+}
// Options de débogage pour que les logs soient fonctionnels, nous devons définir
// les options de compilations dans les unités des paquets. Car les options relatif à
// un projet ne sont pas propagé dans les unités d'un paquet.
{.$DEFINE DEBUG}
{.$DEFINE DEBUGLOG}
//{$i ..\bzscene_options.inc} // L'inclusion de ce fichier provoque une erreur de compilation avec cette unité ?????
//==============================================================================
interface
uses
Classes, SysUtils;
//==============================================================================
const
{ Granularité de croissance minimum d'un tableau }
cDefaultListGrowthDelta = 16;
{ Lorsque la liste est plus petite que cInsertionSort_CutOff, nous utilisons InsertionSort au lieu d'appeler
tout autre algorithme de tri, de manière récursive.
8 et 64 semblent être les limites inférieures et supérieures où les performances se dégradent, donc
quelque chose entre 16 et 48 donne probablement les meilleures performances
D'après mes tests 42 est une bonne valeur médiane. }
cInsertionSort_CutOff = 42;
{ Lorsque la liste est plus petite que cQuickSort_CutOff, nous utilisons l'algorithme QuickSort au lieu de DualQuickSort }
cQuickSort_CutOff = 500;
type
{ Déclaration pour définir un tableau dynamique de single }
TBZDynSingleArray = Array of Single;
{ Déclaration pour définir un tableau dynamique de single }
TBZDynIntegerArray = Array of Integer;
{ Déclaration pour définir un tableau dynamique de single }
TBZDynByteArray = Array of Byte;
{ Ordre de trie Ascendant ou descendant }
TBZSortOrder = (soAscending, soDescending);
{ Classe de base générique pour gérer un tableau de n'importe quel type, tableau statique et pointeur.
Fournis quelques fonctions utiles et communes ajouter, supprimer, accès aux données.
Prend également en charge l'accès en mode LIFO (Stack) }
generic TBZBaseArray<T> = Class
private
//F: boolean;
FTagString : string;
type
PT = ^ T;
TArr = array of T;
//PArr = ^TArr;
procedure SetCount(AValue : Int64);
protected
{$CODEALIGN RECORDMIN=16}
FData: TArr; //Le pointeur de liste de base (non typé)
{$CODEALIGN RECORDMIN=4}
FCapacity:Int64;
FDataSize:Int64;
FItemSize:Int64; // Doit être défini dans les sous-classes
FGrowthDelta: Integer;
FParentData: Pointer;
FHandle: Int64;
FRevision: LongWord;
FCount: Int64;
FPosition: Int64;
FFirstDone: Boolean;
Function GetData: Pointer; inline;
Function GetDataArray: TArr; inline;
function GetValue(Position: Int64): T;
procedure SetValue(Position : Int64; const AValue : T);
function GetMutable(Position: Int64): PT;
procedure IncreaseCapacity;
procedure SetCapacity(NewCapacity: Int64); virtual;
function CompareValue(Const {%H-}elem1, {%H-}elem2) : Integer; virtual;
procedure AnyQuickSort( idxL, idxH : Integer; Dir : TBZSortOrder); //CompareValue: TBZArraySortCompareValue); //var SwapBuf : pByte);
procedure AnyInsertionSort(idxL, idxH : Integer; Dir : TBZSortOrder); //CompareValue: TBZArraySortCompareValue);
procedure AnyMergeSort(idxL, idxH : Integer; Dir : TBZSortOrder; Stride : Longint; var SwapBuf : PT); //CompareValue: TBZArraySortCompareValue; var SwapBuf : PT);
procedure AnyDualPivotQuickSort(idxL, idxH : Integer; Dir : TBZSortOrder); // CompareValue : TBZArraySortCompareValue);
public
{ Creation d'un nouveau tableau vide}
constructor Create; //override;
{ Creation d'un nouveau tableau de "Reserved" éléments }
constructor Create(Reserved: Int64); overload;
{ Créer un nouveau tableau avec un nombre d'éléments Réservés et un propriétaire }
constructor CreateParented(AParentData: Pointer; Reserved: Int64); overload;
{ Libère et détruit le tableau }
destructor Destroy; override;
{ Renvoie la taille totale du tableau }
function DataSize: Int64; // size of the list
{ Renvoie la taille d'un élément }
function ItemSize: Longint;
{ Ajoute un nouvel élément }
function Add(const Value: T):Int64;
{ Ajoute un nouvel élément si celui-ci n'es pas déja présent dans le tableau. Retourne -1 si l'élément n'est pas ajouté }
function AddNoDup(const Value: T):Int64;
{ Insert un nouvel élément à la position "Position" }
procedure Insert(Position: Int64; const Value: T);
{ Efface un élément à la position "Position" }
procedure Delete(Position : Int64);
{ Echange la posiotion des éléments "Index1" et "Index2" }
procedure Exchange(index1, index2: Int64);
{ Inverse le tableau }
procedure Reverse; inline;
//procedure AddNulls(nbVals: Cardinal); inline;
//procedure InsertNulls(Position : Int64; nbVals: Cardinal); inline;
{ Vide la liste sans altérer la capacité. }
procedure Flush;
{ Vide la liste et libère les éléments }
procedure Clear;
{ Ajoute un nouvel élément en haut tableau }
procedure Push(const Value: T);
{ Récupère l'élément en haut du tableau }
function Pop: T;
{ Retourne le premier élément du tableau }
function First: T;
{ Retourne le dernier élément du tableau }
function Last: T;
{ Renvoie l'élément suivant du tableau, relatif à la position actuelle }
function Next: T;
{ Renvoie l'élément précédent du tableau, relatif à la position actuelle }
function Prev: T;
{ Renvoie l'élément actuel du tableau, relatif à la position actuelle }
function Current : T;
{ Déplacer la position actuelle dans le tableau à la prochaine }
function MoveNext:Boolean;
{ Déplacer la position actuelle dans le tableau à la précédente }
function MovePrev:Boolean;
{ Déplacer la position actuelle dans le tableau vers le premier élément }
function MoveFirst:Boolean;
{ Déplacer la position actuelle dans le tableau vers le dernier élément }
function MoveLast:Boolean;
{ Renvoie la position actuelle dans le tableau }
function GetPosition : Int64;
{ Se placer à la postion "Pos" en fonction de StartAt@br
@param(Valeurs possible pour StartAt :@br
@unorderedlist(
@item( 0 = Depuis le début (defaut) )
@item( 1 = Depuis la position actuelle)
@item( 2 = En partant de la fin)
)}
function Seek(const pos : Int64; const StartAt : Byte = 0) : boolean;
{ Se placer à n'importe quelle position dans le tableau (equivalent a seek(position, 0)}
function MoveTo(Position:Int64) : Boolean;
{ Vérifie si la fin du tableau est atteinte}
function IsEndOfArray : Boolean;
{ Retourne l'index de l'élément "SearchItem". Dans le cas ou celui n'existe pas retourne -1 }
function IndexOf(SearchItem : T): Integer;
{ Renvoie l'élélement suivant de l'élément "anItem", Si l'élément n'existe pas le premier élément du tableau est retourné }
function GetNextFrom(anItem : T) : T;
// Array Rasterizer
// function Scan(CallBack):Boolean;
// function ScanNext(CallBack):Boolean;
// function ScanPrev(CallBack):Boolean;
// function ScanMany(nbItem,CallBack):Boolean;
// function ScanTo(Position,CallBack):Boolean;
// function ScanAll(CallBack):Boolean;
// function ScanRange(From, To, CallBack):Boolean;
// Array Utils
// function CompareItems(Index1, index2, CompareValue): Integer; virtual;
{ Trie le tableaux par ordre croissant ou décroissant.
L'algorithme de tri utilisé dépend du nombre d'éléments en fonction des constantes cInsertion_CutOff et cQuickSort_CutOff. @br
Si la liste à un nombre d'éléments inférieur à 42 le tri par insertion est utilisé. @br
Si la liste à un nombre d'éléments inférieur ou égale à 500 le tri rapide "QuickSort" est utilisé. @br
Si non, c'est le tri rapide à double pivot "DualPivotQuickSort" qui est utilisé. }
procedure Sort(Const Direction : TBZSortOrder = soAscending); virtual;
{ Trie le tableau avec l'algorithme de trie rapide "QuickSort" version "Stable" }
procedure QuickSort(Const Direction : TBZSortOrder = soAscending); virtual;
{ Trie le tableau avec l'algorithme de trie rapide à double pivot version "Stable", c'est l'algorithme utilisé par défaut par la méthode Sort }
procedure DualQuickSort(Const Direction : TBZSortOrder = soAscending); virtual;
{ Trie le tableau avec l'algorithme de fusion : MergeSort version "Stable". Un peu moins rapide que le quicksort. }
procedure MergeSort(Const Direction : TBZSortOrder = soAscending); virtual;
{ Trie le tableau avec l'algorithme d'insertion }
procedure InsertionSort(Const Direction : TBZSortOrder = soAscending); virtual;
{ Mélange les éléments du tableau aléatoirement. Il vous faudra appeler la méthode Randomize en premier }
procedure Shuffle;
// procedure Merge(AnotherArray: TBZBaseArray<T>);
// function Clone : TBZBaseArray<T>;
// function Extract(From, Nb : Int64): TBZBaseArray<T>;
// Extra funcs for management
// function InsertItemsAt(Pos:Int64; AnArray : TBZBaseArray<T>):Boolean;
// function InsertItemsAtEnd
// function InsertItemsAtFirst
// procedure DeleteItems(Index: Int64r; nbVals: Cardinal); inline;
{ Nombre d'éléments dans la liste. Lors de l'attribution d'un nombre, les éléments ajoutés sont réinitialisés à zéro. }
property Count: Int64 read FCount write SetCount;
{ Capacité du tableau actuel. Non persistant. }
property Capacity: Int64 read FCapacity write SetCapacity;
{ Granularité de croissance. Pas persistant. }
property GrowthDelta: Integer read FGrowthDelta write FGrowthDelta;
{ Augmenter de un après chaque changement de contenu. }
property Revision: LongWord read FRevision write FRevision;
{ Renvoie le propriétaire s'il existe }
property ParentData : Pointer read FParentData;
{ Renvoie le tableau sous forme de pointeur }
property Data : Pointer read GetData;
property DataArray : TArr read GetDataArray;
{ Renvoie le handle du tableau }
property Handle : Int64 read FHandle;
{ Accès aux éléments du tableau }
property Items[i : Int64]: T read getValue write SetValue;// default;
{ Accès à l'élément dans le tableau en tant que pointeur générique }
property Mutable[i : Int64]: PT read getMutable;
{ Tag utilisateur }
property TagString: string read FTagString write FTagString;
end;
{ Extension de TBZBaseArray générique pour la gestion de tableaux de 2 dimensions.
Attention avec des enregistrements, cette clsse peux retourné des index faux. Et je ne sais pas pourquoi !}
generic TBZBaseArrayMap2D<T> = class(specialize TBZBaseArray<T>)
private
function GetValue2D(x, y : Int64): T;
procedure SetValue2D(x, y : Int64; AValue: T);
protected
FRows, FCols : Int64;
public
{ Creation d'un nouveau tableau vide de "Rows" lignes et "Cols" colonnes }
constructor Create(Cols, Rows: Int64); overload;
{ Créer un nouveau tableau avec un nombre d'éléments Réservés de "Rows" lignes et "Cols" colonnes et des données propriétaires }
constructor CreateParented(AParentData: Pointer; Rows, Cols: Int64); overload;
{ Déplacer la position actuelle dans le tableau vers "Row", "Position" }
function MoveTo(Row : Integer; Position : Integer) : Boolean; overload;
{ Accès aux éléments du tableau }
property Items[x,y : Int64]: T read GetValue2D write SetValue2D;
{ Retourne le nombre de ligne du tableau }
property RowCount : Int64 read FRows;
{ Retourne le nombre de colonne du tableau }
property ColCount : Int64 read FCols;
end;
//generic TBZBaseArrayMap3D<T> = class(specialize TBZBaseArray<T>)
//private
// function GetValue3D(x, y, z : Int64): T;
// procedure SetValue3D(x, y, z : Int64; AValue: T);
//published
//public
// constructor Create(Rows, Cols, DCols : Int64); overload;
// constructor CreateParented(AParentData: Pointer; Rows, Cols, DCols: Int64); overload;
// property Items[x,y,z : Int64]: T read GetValue3D write SetValue3D;
//end;
//
//generic TBZBaseArrayMap4D<T> = class(specialize TBZBaseArray<T>)
//private
// function GetValue4D(x, y, z, w : Int64): T;
// procedure SetValue4D(x, y, z, w : Int64; AValue: T);
//published
//public
// constructor Create(Rows, Cols, DCols, TCols: Int64); overload;
// constructor CreateParented(AParentData: Pointer; Rows, Cols, DCols, TCols: Int64); overload;
// property Items[x,y,z,w : Int64]: T read GetValue4D write SetValue4D;
//end;
Type
{ Tableau générique de type Byte à une Dimension }
generic TBZArrayByte<T> = class(specialize TBZBaseArray<T>);
{ Tableau générique de type Integer à une Dimension }
generic TBZArrayInt<T> = class(specialize TBZBaseArray<T>);
{ Tableau générique de type Virgule flottante à une Dimension }
generic TBZArrayFloat<T> = class(specialize TBZBaseArray<T>);
{ Tableau générique de type Byte à deux Dimensions }
generic TBZArrayMap2DByte<T> = class(specialize TBZBaseArrayMap2D<T>);
{ Tableau générique de type Integer à deux Dimensions }
generic TBZArrayMap2DInt<T> = class(specialize TBZBaseArrayMap2D<T>);
{ Tableau générique de type Virgule flottante à deux Dimensions }
generic TBZArrayMap2DFloat<T> = class(specialize TBZBaseArrayMap2D<T>);
{ Liste spécialisée dans le stockage de type Byte }
TBZByteList = class(specialize TBZArrayByte<Byte>)
protected
function CompareValue(Const elem1, elem2) : Integer; override;
end;
{ Liste spécialisée dans le stockage de type Integer }
TBZIntegerList = class(specialize TBZArrayInt<Integer>)
protected
function CompareValue(Const elem1, elem2) : Integer; override;
end;
{ Liste spécialisée dans le stockage de type Single }
TBZSingleList = class(specialize TBZArrayFloat<Single>)
protected
function CompareValue(Const elem1, elem2) : Integer; override;
end;
{ Liste spécialisée dans le stockage de type Double }
TBZDoubleList = class(specialize TBZArrayFloat<Double>)
protected
function CompareValue(Const elem1, elem2) : Integer; override;
end;
{ Liste spécialisée à deux dimension dans le stockage de type Byte }
TBZByte2DMap = class(specialize TBZArrayMap2DByte<Byte>);
{ Liste spécialisée à deux dimension dans le stockage de type Integer }
TBZInteger2DMap = class(specialize TBZArrayMap2DInt<Integer>);
{ Liste spécialisée à deux dimension dans le stockage de type Single }
TBZSingle2DMap = class(specialize TBZArrayMap2DFloat<Single>);
{ Liste spécialisée à deux dimension dans le stockage de type Double }
TBZDouble2DMap = class(specialize TBZArrayMap2DFloat<Double>);
//==============================================================================
implementation
//==============================================================================
{$IFDEF DEBUG}
uses
BZSceneStrConsts
{$IFDEF DEBUGLOG}
,BZLogger, BZTypesHelpers
{$ENDIF}
;
{$ENDIF}
{%region%=====[ TBZBaseArray ]=================================================}
constructor TBZBaseArray.Create;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Create');
{$ENDIF}
{$ENDIF}
inherited Create;
FCapacity:=0;
// FItemSize:=Sizeof(T); // Must be defined in subclasses ????
FGrowthDelta:= cDefaultListGrowthDelta;
FParentData:=nil;
FHandle:=0;
//FIsDirty:=false;
FRevision:=0;
FCount:=0;
FPosition:=0;
FFirstDone:=false;
end;
constructor TBZBaseArray.Create(Reserved : Int64);
begin
Create;
FDataSize:=Reserved;//*ItemSize;
SetCapacity(Reserved);
//SetCount(Reserved);
end;
constructor TBZBaseArray.CreateParented(AParentData : Pointer; Reserved : Int64);
begin
Create(Reserved);
FParentData := AParentData;
end;
destructor TBZBaseArray.Destroy;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Destroy');
{$ENDIF}
{$ENDIF}
Clear;
//SetLength(FData, 0);
FData := nil;
inherited Destroy;
end;
procedure TBZBaseArray.SetCount(AValue : Int64);
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.SetCount');
GlobalLogger.LogStatus('>>> AValue = ' + AValue.ToString);
{$ENDIF}
Assert(AValue >= 0);
{$endif}
if FCount = AValue then Exit;
if AValue> FCapacity then SetCapacity(AValue);
FCount := AValue;
Inc(FRevision);
end;
Function TBZBaseArray.GetData : Pointer;
begin
Result := @FData;
end;
Function TBZBaseArray.GetDataArray : TArr;
begin
Result := FData;
end;
function TBZBaseArray.GetValue(Position : Int64) : T;
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.GetValue');
GlobalLogger.LogStatus('>>> Position = ' + Position.ToString);
if (position > FCount) and (position < 0) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert((position < FCount) and (position>=0), rsIndexOutOfRange);
{$endif}
Result := FData[Position];
end;
procedure TBZBaseArray.SetValue(Position : Int64; const AValue : T);
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.SetValue');
GlobalLogger.LogStatus('>>> Position = ' + Position.ToString);
if (position > FCount) and (position < 0) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert((position < FCount) and (position>=0), rsIndexOutOfRange);
{$endif}
//if FData[Position] = AValue then exit;
if Position >= FCapacity then IncreaseCapacity;
FData[Position] := AValue;
end;
function TBZBaseArray.GetMutable(Position : Int64) : PT;
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.GetMutable');
GlobalLogger.LogStatus('>>> Position = ' + Position.ToString);
if (position > FCount) and (position < 0) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert((position < FCount) and (position>=0), rsIndexOutOfRange);
{$endif}
Result := @FData[Position];
end;
procedure TBZBaseArray.IncreaseCapacity;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.IncreaseCapacity');
GlobalLogger.LogStatus('>>>> FCapacity = '+ FCapacity.ToString);
GlobalLogger.LogStatus('>>>> FCount = '+ FCount.ToString);
{$ENDIF}
{$ENDIF}
if FCapacity=0 then SetCapacity(1)
else
begin
if FCount >= FCapacity then SetCapacity(FCapacity+FGrowthDelta);
end;
end;
procedure TBZBaseArray.SetCapacity(NewCapacity : Int64);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.SetCapacity');
GlobalLogger.LogStatus('>>>> NewCapacity = '+ NewCapacity.ToString);
{$ENDIF}
{$ENDIF}
if FCapacity = newCapacity then exit;
//if FCount < FCapacity then exit;
FCapacity := newCapacity;
SetLength(FData, FCapacity);
Inc(FRevision);
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogStatus('>>>> Revision = ' + FRevision.ToString + ' Capacity = ' + FCapacity.ToString);
{$ENDIF}
{$ENDIF}
end;
function TBZBaseArray.CompareValue(Const elem1, elem2) : Integer;
begin
result := 0;
end;
function TBZBaseArray.DataSize : Int64;
begin
Result := FCount * ItemSize; //FDataSize;
end;
function TBZBaseArray.ItemSize : Longint;
begin
Result := Sizeof(T); //FItemSize;
end;
function TBZBaseArray.Add(const Value : T) : Int64;
begin
Result := FCount;
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Add');
{$ENDIF}
{$ENDIF}
if Result >= FCapacity then IncreaseCapacity;
FData[Result] := Value;
Inc(FCount);
end;
function TBZBaseArray.AddNoDup(const Value : T) : Int64;
Var
pos : Integer;
isNew : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.AddNoDup');
{$ENDIF}
{$ENDIF}
Result := -1;
pos := 0;
isNew := True;
while ((pos < FCount) and (isNew = true)) do
begin
if FData[pos] = Value then isNew := False;
inc(pos);
end;
if IsNew then
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogHint('>>>> New value');
{$ENDIF}
{$ENDIF}
Result := FCount;
if Result >= FCapacity then IncreaseCapacity;
FData[Result] := Value;
Inc(FCount);
end;
end;
procedure TBZBaseArray.Insert(Position : Int64; const Value : T);
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Insert');
GlobalLogger.LogStatus('>>> Position = ' + Position.ToString);
if (position >= FCount) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert(Position < FCount);
{$endif}
if FCount = FCapacity then IncreaseCapacity;
if Position < FCount then
System.Move(FData[Position], FData[Position + 1], (FCount - Position) * ItemSize);
FData[Position] := Value;
Inc(FCount);
end;
procedure TBZBaseArray.Delete(Position : Int64);
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Delete');
GlobalLogger.LogStatus('>>> Position = ' + Position.ToString);
if (position > FCount - 1) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert(Position < FCount-1);
{$endif}
if (Position < (FCount - 1)) then
begin
Dec(FCount);
System.Move(FData[(Position + 1)], FData[Position], (FCount - Position) * ItemSize);
end
else Dec(FCount);
Inc(FRevision);
end;
procedure TBZBaseArray.Exchange(index1, index2 : Int64);
var
temp : T;
begin
{$ifdef DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Exchange');
GlobalLogger.LogStatus('>>> Index 1 = ' + Index1.ToString);
GlobalLogger.LogStatus('>>> Index 2 = ' + Index2.ToString);
if (Index1 > FCount - 1) or (Index2 > FCount - 1) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert((Index1 < FCount) and (Index2 < FCount));
{$endif}
if Index1 = Index2 then Exit;
temp := FData[index1];
FData[index1] := FData[index2];
FData[index2] := temp;
Inc(FRevision);
end;
procedure TBZBaseArray.Reverse;
var
s, e: Integer;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Reverse');
{$ENDIF}
{$ENDIF}
s := 0;
e := FCount - 1;
while s < e do
begin
Exchange(s, e);
Inc(s);
Dec(e);
end;
Inc(FRevision);
end;
//procedure TBZBaseArray.AddNulls(nbVals : Cardinal);
//begin
//
//end;
//
//procedure TBZBaseArray.InsertNulls(Position : Int64; nbVals : Cardinal);
//begin
//
//end;
procedure TBZBaseArray.Flush;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Flush');
{$ENDIF}
{$ENDIF}
SetCount(0);
end;
procedure TBZBaseArray.Clear;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Clear');
{$ENDIF}
{$ENDIF}
SetCount(0);
SetCapacity(0);
end;
//procedure TBZBaseArray.AdjustCapacityToAtLeast(const size: Integer);
//begin
// if FCapacity < Size then SetCapacity(size);
//end;
procedure TBZBaseArray.Push(const Value : T);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Push');
{$ENDIF}
{$ENDIF}
Add(Value);
end;
function TBZBaseArray.Pop : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Pop');
{$ENDIF}
{$ENDIF}
Result := FData[FCount-1];
Delete(FCount-1);
end;
function TBZBaseArray.First : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.First');
{$ENDIF}
{$ENDIF}
Result := FData[0];
end;
function TBZBaseArray.Last : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Last');
{$ENDIF}
{$ENDIF}
Result := Pop;
end;
function TBZBaseArray.Next : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Next');
{$ENDIF}
{$ENDIF}
if (FPosition < FCount) then //Inc(FPosition);
Result := FData[FPosition + 1]
else Result := FData[FPosition];
end;
function TBZBaseArray.Prev : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Prev');
{$ENDIF}
{$ENDIF}
if (FPosition > 0) then //Dec(FPosition);
Result := FData[FPosition - 1]
else Result := FData[FPosition];
end;
function TBZBaseArray.Current : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Current');
{$ENDIF}
{$ENDIF}
Result := FData[FPosition];
end;
function TBZBaseArray.MoveNext : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MoveNext');
{$ENDIF}
{$ENDIF}
Result := false;
if (FPosition >= FCount-1) then exit;
Result := True;
Inc(FPosition);
end;
function TBZBaseArray.MovePrev : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MovePrev');
{$ENDIF}
{$ENDIF}
Result := false;
if (FPosition <= 0 ) then exit;
Result := True;
Dec(FPosition);
end;
function TBZBaseArray.MoveFirst : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MoveFirst');
if FCount <= 0 then GlobalLogger.LogError(rsListOrArrayIsEmpty);
{$ENDIF}
Assert(FCount>0);
{$ENDIF}
result := true;
FPosition := 0;
end;
function TBZBaseArray.MoveLast : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MoveLast');
if FCount <= 0 then GlobalLogger.LogError(rsListOrArrayIsEmpty);
{$ENDIF}
Assert(FCount>0);
{$ENDIF}
result := true;
FPosition := FCount-1;
end;
function TBZBaseArray.GetPosition : Int64;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.GetPosition');
GlobalLogger.LogStatus('>>> Position = ' + FPosition.ToString);
{$ENDIF}
{$ENDIF}
Result := FPosition;
end;
function TBZBaseArray.Seek(const pos : Int64; const StartAt : Byte=0) : boolean;
var
newpos : Int64;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Seek');
GlobalLogger.LogStatus('>>> Position = ' + Pos.ToString);
if (pos> FCount - 1) then GlobalLogger.LogError(rsIndexOutOfRange);
{$ENDIF}
Assert(Pos < FCount);
{$ENDIF}
result := true;
Case StartAt of
0: newpos := Pos; // From Beginning
1:
begin
newpos := (FPosition-1) + Pos; // From Current positon
if newpos >= FCount then
begin
//newpos := FCount-1;
result := false;
end;
end;
2:
begin
newpos := (FCount-1) - Pos; // From End;
if newpos=0 then
begin
//newpos := 0;
result := false;
end;
end;
else newpos := pos;
end;
if result then FPosition := newpos;
end;
function TBZBaseArray.MoveTo(Position:Int64) : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MoveTo');
{$ENDIF}
{$ENDIF}
result:= Self.Seek(Position, 0);
end;
function TBZBaseArray.IsEndOfArray : Boolean;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.IsEndOfArray');
GlobalLogger.LogStatus('>>> Position = ' + FPosition.ToString);
GlobalLogger.LogStatus('>>> Count = ' + FCount.ToString);
{$ENDIF}
{$ENDIF}
result := (FPosition >= FCount);
end;
function TBZBaseArray.IndexOf(SearchItem : T) : Integer;
var
i: Integer;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.IndexOf');
{$ENDIF}
{$ENDIF}
if FCount <= 0 then Result := -1
else
begin
Result := -1;
for i := 0 to FCount - 1 do
if FData[i] = SearchItem then
begin
Result := i;
Exit;
end;
end;
end;
function TBZBaseArray.GetNextFrom(anItem : T) : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.GetNextFrom');
{$ENDIF}
{$ENDIF}
if FCount <= 0 then exit;
Result := FData[((Self.indexOf(anItem) + 1) mod Self.Count)];
end;
{ Le "Dual Pivot QuickSort" est plus légèrement plus rapide que le QuickSort classique (dans la majorité des cas).
Sur la papier, le DualPivotQuickSort à 1.9nlnn+O(n) comparaisons, ce qui est 5% de moins que les comparaisons 2nlnn+O(n) de l'algorithme Quicksort classique à pivot unique.
Cependant, il a besoin de 0.6nlnn+O(n) échanges de valeurs alors qu'avec le Quicksort classique il en faut 1/3nlnn+O(n).
Il existe une version en Java optimisée de cet algorithmequi donne de meilleurs résultats, mais celle-ci est complexe à mettre en place
cf : http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/DualPivotQuicksort.java }
procedure TBZBaseArray.AnyDualPivotQuickSort(idxL, idxH : Integer; Dir : TBZSortOrder);
var
idx, lpi, rpi : Integer;
nb, li, hi : Integer;
SwapTemp, p, q, ak : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.AnyDualPivotQuickSort');
GlobalLogger.LogStatus('>>> idxL = ' + idxL.ToString);
GlobalLogger.LogStatus('>>> idxH = ' + idxH.ToString);
{$ENDIF}
{$ENDIF}
if (idxH <= idxL) then Exit;
nb := idxH - idxL;
if nb < cInsertionSort_CutOff then
begin
AnyInsertionSort(idxL, idxH, Dir);
Exit;
end;
//else if nb <= cQuickSort_CutOff then
//begin
// AnyQuickSort(idxL, idxH, Dir);
// Exit;
//end;
li := idxL;
hi := idxH;
// Debut de la partition
if Dir = soAscending then
begin
if (CompareValue(FData[hi], FData[li]) < 0) then
begin
SwapTemp := FData[li];
FData[li] := FData[hi];
FData[hi] := SwapTemp;
end;
end
else
begin
if (CompareValue(FData[hi], FData[li]) > 0) then
begin
SwapTemp := FData[li];
FData[li] := FData[hi];
FData[hi] := SwapTemp;
end;
end;
p := FData[li];
q := FData[hi];
lpi := li + 1;
rpi := hi - 1;
idx := lpi;
if Dir = soAscending then
begin
While (idx <= rpi) do
begin
ak := FData[idx];
if (CompareValue(ak, p) < 0) then
begin
FData[idx] := FData[lpi];
FData[lpi] := ak;
inc(lpi);
end
else if (CompareValue(ak, q) >= 0) then
begin
While ((CompareValue(FData[rpi], q) > 0) and (idx < rpi)) do Dec(rpi);
FData[idx] := FData[rpi];
FData[rpi] := ak;
dec(rpi);
if (CompareValue(ak, p) < 0) then
begin
FData[idx] := FData[lpi];
FData[lpi] := ak;
inc(lpi);
end;
end;
inc(idx);
end;
end
else
begin
While (idx <= rpi) do
begin
ak := FData[idx];
if (CompareValue(ak, p) > 0) then
begin
FData[idx] := FData[lpi];
FData[lpi] := ak;
inc(lpi);
end
else if (CompareValue(ak, q) <= 0) then
begin
While ((CompareValue(FData[rpi], q) < 0) and (idx < rpi)) do Dec(rpi);
FData[idx] := FData[rpi];
FData[rpi] := ak;
dec(rpi);
if (CompareValue(ak, p) > 0) then
begin
FData[idx] := FData[lpi];
FData[lpi] := ak;
inc(lpi);
end;
end;
inc(idx);
end;
end;
Dec(lpi);
Inc(rpi);
SwapTemp := FData[lpi];
FData[lpi] := FData[li];
FData[li] := SwapTemp;
SwapTemp := FData[rpi];
FData[rpi] := FData[hi];
FData[hi] := SwapTemp;
// Fin de la partition
AnyDualPivotQuickSort(li,lpi - 1, Dir);
if DIr = soAscending then
begin
if (CompareValue(FData[lpi], FData[rpi]) < 0) then AnyDualPivotQuickSort(lpi + 1, rpi - 1, Dir);
end
else
begin
if (CompareValue(FData[lpi], FData[rpi]) > 0) then AnyDualPivotQuickSort(lpi + 1, rpi - 1, Dir);
end;
AnyDualPivotQuickSort(rpi + 1, hi, Dir);
end;
procedure TBZBaseArray.AnyQuickSort(idxL, idxH : Integer; Dir : TBZSortOrder);
var
li, hi : Integer;
TP : Integer;
mi : Integer;
SwapBuf : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.AnyQuickSort');
GlobalLogger.LogStatus('>>> idxL = ' + idxL.ToString);
GlobalLogger.LogStatus('>>> idxH = ' + idxH.ToString);
{$ENDIF}
{$ENDIF}
if (idxL >= idxH) then exit;
if (idxH - idxL) < cInsertionSort_CutOff then
begin
AnyInsertionSort(IdxL, idxH, Dir);//, CompareValue);
Exit;
end;
if idxL<>0 then mi := (idxL + idxH) div 2
else mi := (((idxL+1) + idxH) div 2) - 1;
li := idxL;
hi := idxH;
SwapBuf := FData[li];
FData[li] := FData[mi];
FData[mi] := SwapBuf;
TP := idxL;
inc(li);
if dir = soAscending then
begin
repeat
if (CompareValue( FData[li], FData[idxL] ) < 0) then
begin
inc(TP);
SwapBuf := FData[TP];
FData[TP] := FData[li];
FData[li] := SwapBuf;
end;
inc(li);
until li>hi;
end
else
begin
repeat
if (CompareValue( FData[li], FData[idxL] ) > 0) then
begin
inc(TP);
SwapBuf := FData[TP];
FData[TP] := FData[li];
FData[li] := SwapBuf;
end;
inc(li);
until li>hi;
end;
SwapBuf := FData[idxL];
FData[idxL] := FData[TP];
FData[TP] := SwapBuf;
AnyQuickSort(idxL, TP-1, Dir);//, CompareValue);
AnyQuickSort(TP+1, idxH, Dir);//, CompareValue);
end;
procedure TBZBaseArray.AnyInsertionSort(idxL, idxH : Integer; Dir : TBZSortOrder);
var
ps, cs : Integer;
li,hi : Integer;
SwapBuf : T;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.AnyInsertionSort');
GlobalLogger.LogStatus('>>> idxL = ' + idxL.ToString);
GlobalLogger.LogStatus('>>> idxH = ' + idxH.ToString);
{$ENDIF}
{$ENDIF}
if FCount<2 then exit;
if FCount = 2 then
begin
if (CompareValue(FData[1], FData[0]) < 0) then
begin
If Dir = soAscending then
begin
SwapBuf := FData[0];
FData[0] := FData[1];
FData[1] := SwapBuf;
Exit;
end
else
begin
Exit;
end;
end;
end;
li :=idxL + 1;
hi :=idxH;
Repeat
SwapBuf := FData[li]; //Move(pb[ls], SwapBuf^, Stride);
ps := li;
cs := ps - 1;
If Dir = soAscending then
begin
While (ps >= 1) and (CompareValue(SwapBuf, FData[cs]) < 0) do
begin
FData[ps] := FData[cs];
dec(ps);
dec(cs);
end;
end
else
begin
While (ps >= 1) and (CompareValue(SwapBuf, FData[cs]) > 0) do
begin
FData[ps] := FData[cs];
dec(ps);
dec(cs);
end;
end;
FData[ps] := SwapBuf;
inc(li);
until li > hi;
end;
{ Merge sort : Adapté de : http://alexandrecmachado.blogspot.com/2015/03/merge-sort-for-delphi-revisited.html
L'algorithme de tri par fusion est STABLE
"et cette implémentation fonctionne encore mieux que l'algorithme de tri rapide standard (QuickSort) (~ 10% plus rapide dans la plupart des cas)"
Soit disant l'auteur originel du code mais dans tous mes test celui-ci est toujours resté moins permorfant que le quicksort. }
procedure TBZBaseArray.AnyMergeSort(idxL, idxH : Integer; Dir : TBZSortOrder; Stride : Longint; var SwapBuf : PT);
var
li,hi : Integer;
mi : Integer;
FirstCount: Integer;
i, j: Integer;
ToInx: Integer;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.AnyMergeSort');
GlobalLogger.LogStatus('>>> idxL = ' + idxL.ToString);
GlobalLogger.LogStatus('>>> idxH = ' + idxH.ToString);
{$ENDIF}
{$ENDIF}
li := idxL;
hi := idxH;
// Point pivot milieu
if li<>0 then mi := (li + hi) div 2
else mi := (((li+1) + hi) div 2) - 1;
// Trie la 1ère moitié de la liste, soit avec un tri par fusion, soit,
// s'il y a assez peu d'éléments, avec un tri par insertion
if (li < mi) then
begin
if (mi - li) < cInsertionSort_CutOff then
begin
AnyInsertionSort(li, mi, Dir);//, CompareValue);
end
else
begin
AnyMergeSort(li, mi, Dir, Stride, SwapBuf); //, CompareValue
end;
end;
// Trie la 2e moitié de la liste
if (mi < hi) then
begin
if (hi - mi) < cInsertionSort_CutOff then
begin
AnyInsertionSort(mi, hi, Dir);//, CompareValue);
end
else
begin
AnyMergeSort(mi, hi, Dir, Stride, SwapBuf); //, CompareValue
end;
end;
// Copier la première moitié de la liste dans notre liste temporaire
FirstCount := (mi - li);
Move(FData[li], SwapBuf^, FirstCount * Stride);
// configure les index: i est l'index de la liste temporaire (c'est-à-dire la
// première moitié de la liste), j est l'indice de la seconde moitié de la
// liste, ToInx est l'index dans la fusion où les éléments seront copiés
i := 0;
j := mi + 1;
ToInx := li;
// maintenant on fusionne les deux listes
// On répète jusqu'à ce que l'une des listes soit vide...
while (i < FirstCount) and (j <= hi) do
begin
// calcule le plus petit élément à partir des éléments suivants dans les deux listes et le recopie.
// Et incrémente l'index pertinent.
if Dir = soAscending then
begin
if (CompareValue(SwapBuf[i], FData[j]) < 0) then
begin
FData[ToInx] := SwapBuf[i];
inc(i);
end
else
begin
FData[ToInx] := FData[j];
inc(j);
end;
end
else
begin
if (CompareValue(SwapBuf[i], FData[j]) > 0) then
begin
FData[ToInx] := SwapBuf[i];
inc(i);
end
else
begin
FData[ToInx] := FData[j];
inc(j);
end;
end;
// il y a un élément de plus dans la liste fusionnée
inc(ToInx);
end;
// s'il y a d'autres éléments dans la première liste, on les recopie.
if (i < FirstCount) then
begin
Move(Swapbuf[i], FData[ToInx], (FirstCount - i) * Stride);
end;
// S'il y a d'autres éléments dans la deuxième liste, ils sont déjà en place et nous avons terminé.
// S'il n'y en a pas, nous avons également fini.
end;
procedure TBZBaseArray.Sort(Const Direction : TBZSortOrder);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Sort');
{$ENDIF}
{$ENDIF}
if FCount<2 then exit;
if FCount < cInsertionSort_CutOff then AnyInsertionSort(0, FCount-1, Direction)
else if FCount <= cQuickSort_CutOff then AnyQuickSort(0, FCount-1, Direction)
else AnyDualPivotQuickSort(0, FCount-1, Direction);
end;
procedure TBZBaseArray.QuickSort(Const Direction : TBZSortOrder);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.QuickSort');
{$ENDIF}
{$ENDIF}
if FCount<2 then exit;
AnyQuickSort(0, FCount-1, Direction);
end;
procedure TBZBaseArray.DualQuickSort(Const Direction : TBZSortOrder);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.DualQuickSort');
{$ENDIF}
{$ENDIF}
if FCount<2 then exit;
AnyDualPivotQuickSort(0, FCount-1, Direction);
end;
procedure TBZBaseArray.MergeSort(Const Direction : TBZSortOrder);
var
SwapBuf : PT;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.MergeSort');
{$ENDIF}
{$ENDIF}
if FCount<2 then exit;
SwapBuf := nil;
GetMem(SwapBuf, (FCount * Sizeof(T)));
AnyMergeSort(0, FCount-1, Direction, Sizeof(T), SwapBuf);
FreeMem(SwapBuf);
end;
procedure TBZBaseArray.InsertionSort(Const Direction : TBZSortOrder);
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.InsertionSort');
{$ENDIF}
{$ENDIF}
AnyInsertionSort(0, FCount-1, Direction);
end;
procedure TBZBaseArray.Shuffle;
Var
SwapBuffer : T;
I, K, RandIdx : Integer;
begin
{$IFDEF DEBUG}
{$IFDEF DEBUGLOG}
GlobalLogger.LogNotice('>>> TBZBaseArray.Shuffle');
{$ENDIF}
{$ENDIF}
K := FCount - 1;
for i := 1 to K do
begin
RandIdx := random(K - I + 1) + I; // Distribution uniforme
SwapBuffer := FData[RandIdx];
FData[RandIdx] := FData[I];
FData[I] := SwapBuffer;
end;
end;
{%endregion%}
{%region%=====[ TBZBaseArrayMap2D ]============================================}
function TBZBaseArrayMap2D.GetValue2D(x, y : Int64) : T;
var
pos : Int64;
begin
{$ifdef DEBUG}
assert((x<FCols) and (y<FRows));
{$endif}
//GlobalLogger.LogStatus('x,y : '+Inttostr(x)+', '+Inttostr(y));
//GlobalLogger.LogStatus('Set to : '+Inttostr(x)+', '+Inttostr(y));
pos := (y*FCols+x);
//GlobalLogger.LogStatus('Get at : '+Inttostr(pos));
Result := FData[pos];
end;
procedure TBZBaseArrayMap2D.SetValue2D(x, y : Int64; AValue : T);
var
pos : Int64;
begin
{$ifdef DEBUG}
assert((x<FCols) and (y<FRows));
{$endif}
pos := (y*FCols+x);
{$ifdef DEBUG}
//GlobalLogger.LogStatus('NbRows, NbCols : '+Inttostr(FRows)+', '+Inttostr(FCols));
//GlobalLogger.LogStatus('Set to : '+Inttostr(x)+', '+Inttostr(y));
//GlobalLogger.LogStatus('Set at : '+Inttostr(pos));
{$endif}
//if FData[pos] = AValue then exit;
FData[pos] := AValue;
end;
constructor TBZBaseArrayMap2D.Create(Cols, Rows : Int64);
begin
Inherited Create(Rows*Cols);
FRows := Rows;
FCols := Cols;
end;
constructor TBZBaseArrayMap2D.CreateParented(AParentData : Pointer; Rows, Cols : Int64);
begin
Inherited CreateParented(AParentData, Rows*Cols);
end;
function TBZBaseArrayMap2D.MoveTo(Row : Integer; Position : Integer) : Boolean;
var
pos : Int64;
begin
pos := (Row*FCols+Position);
result := Inherited MoveTo(Pos);
end;
{%endregion%}
{%region%=====[ TBZDoubleList ]================================================}
function TBZDoubleList.CompareValue(Const elem1, elem2) : Integer;
var
i1 : Double absolute elem1;
i2 : Double absolute elem2;
begin
if i1 = i2 then Result:=0
else if i1 < i2 then Result:=-1
else Result:=1;
end;
{%endregion%}
{%region%=====[ TBZSingleList ]================================================}
function TBZSingleList.CompareValue(Const elem1, elem2) : Integer;
var
i1 : Single absolute elem1;
i2 : Single absolute elem2;
begin
if i1 = i2 then Result:=0
else if i1 < i2 then Result:=-1
else Result:=1;
end;
{%endregion%}
{%region%=====[ TBZByteList ]==================================================}
function TBZByteList.CompareValue(Const elem1, elem2) : Integer;
var
i1 : Byte absolute elem1;
i2 : Byte absolute elem2;
begin
if i1 = i2 then Result:=0
else if i1 < i2 then Result:=-1
else Result:=1;
end;
{%endregion%}
{%region%=====[ TBZIntegerList ]===============================================}
function TBZIntegerList.CompareValue(Const elem1, elem2) : Integer;
var
i1 : integer absolute elem1;
i2 : integer absolute elem2;
begin
if i1 = i2 then Result:=0
else if i1 < i2 then Result:=-1
else Result:=1;
end;
{%endregion%}
//==============================================================================
end.
|
unit fRelatorioBasico;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, fBasico, System.Actions, Vcl.ActnList,
Vcl.StdCtrls, Vcl.ExtCtrls, dmuPrincipal, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
dxSkinBlack, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, dmuLookup, Data.DB, uClientDataSet,
uTypes, cxCheckBox, dmuRelatorio, cxGroupBox, dxCheckGroupBox,
uControleAcesso, ppComm, ppRelatv, ppProd, ppClass, ppReport, cxDateUtils,
Vcl.ComCtrls, dxCore, cxCalendar, ppParameter, ppCTCtrl, ppCtrls,
cxImageComboBox;
type
TfrmRelatorioBasico = class(TfrmBasico)
pnBotoes: TPanel;
pnConfiguracoes: TPanel;
btnGerarRelatorio: TButton;
ActionList: TActionList;
Ac_GerarRelatorio: TAction;
dsOrganizacao: TDataSource;
pnOrganizacao: TPanel;
lb2: TLabel;
cbOrganizacao: TcxLookupComboBox;
chkTodasOrganizacoes: TcxCheckBox;
procedure FormCreate(Sender: TObject);
procedure Ac_GerarRelatorioExecute(Sender: TObject);
procedure chkTodasOrganizacoesPropertiesEditValueChanged(Sender: TObject);
private
protected
dmLookup: TdmLookup;
dmRelatorio: TdmRelatorio;
procedure pprValidarPermissao(ipAcao: TAcaoTela; ipPermissao: string);
function fprExtrairValor(ipChkTodos: TcxCheckBox; ipLookup: TcxCustomEdit; ipMsgErro: string): Integer;
// function fprExtrairValor(ipChkTodos: TcxCheckBox; ipLookup: TcxImageComboBox; ipMsgErro: string): Integer; overload;
function fprGetPermissao: String; virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
end;
var
frmRelatorioBasico: TfrmRelatorioBasico;
implementation
{$R *.dfm}
procedure TfrmRelatorioBasico.pprValidarPermissao(ipAcao: TAcaoTela; ipPermissao: string);
begin
if not TInfoLogin.fpuGetInstance.Usuario.fpuValidarPermissao(ipAcao, ipPermissao) then
raise Exception.Create('Operação não permitida.' + slineBreak + 'O usuário logado não possui a ação de ' +
AcaoTelaDescricao[ipAcao].ToUpper + ' para a permissão ' + TModulos.fpuGetInstance.fpuGetDescricao(ipPermissao).ToUpper);
end;
function TfrmRelatorioBasico.fprExtrairValor(ipChkTodos: TcxCheckBox; ipLookup: TcxCustomEdit; ipMsgErro: string): Integer;
begin
Result := 0;
if Assigned(ipLookup.Parent) and (ipLookup.Parent is TdxCheckGroupBox) and (not TdxCheckGroupBox(ipLookup.Parent).CheckBox.Checked) then
Result := -1
else if not ipChkTodos.Checked then
begin
if VarIsNull(ipLookup.EditValue) then
raise Exception.Create(ipMsgErro);
Result := ipLookup.EditValue;
end;
end;
procedure TfrmRelatorioBasico.Ac_GerarRelatorioExecute(Sender: TObject);
begin
inherited;
if VarIsNull(cbOrganizacao.EditValue) then
raise Exception.Create('Informe para qual organização o relatório está sendo gerado.');
dmLookup.cdslkOrganizacao.Locate(TBancoDados.coId, cbOrganizacao.EditValue, []);
end;
procedure TfrmRelatorioBasico.chkTodasOrganizacoesPropertiesEditValueChanged(
Sender: TObject);
begin
inherited;
cbOrganizacao.Enabled := not chkTodasOrganizacoes.Checked;
end;
constructor TfrmRelatorioBasico.Create(AOwner: TComponent);
begin
inherited;
pprValidarPermissao(atVisualizar, fprGetPermissao);
end;
procedure TfrmRelatorioBasico.FormCreate(Sender: TObject);
begin
dmLookup := TdmLookup.Create(Self);
dmLookup.Name := '';
dmRelatorio := TdmRelatorio.Create(Self);
dmRelatorio.Name := '';
inherited;
dmLookup.cdslkOrganizacao.ppuDataRequest([TParametros.coTodos], ['NAO_IMPORTA']);;
if not dmLookup.cdslkOrganizacao.Eof then
begin
cbOrganizacao.EditValue := dmLookup.cdslkOrganizacaoID.AsInteger;
cbOrganizacao.PostEditValue;
end;
end;
end.
|
unit fmMain;
{
This application checks for an update on the local file system. If an update does not exist, it
launches the target EXE and terminates.
If an update exists on the file system in the path Updates\Pending\[VersionInfo] then this application
applies the update by moving the current files specified in the new manifest into a backup directory
located at Updates\Backup\[VersionInfo], and copying in the new files. When the update is complete
the update directory is moved into the Updates\Applied folder, and the update webservice is called
to signal that the update was applied.
The Program may find multiple updates on the filesystem. It will choose the next higher version
and apply that update first followed by all remaining updates in order of lowest to highest version
numbers.
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, uPatcher, unApplyUpdate;
type
TfrmMain = class(TForm)
meWhatsNew: TRichEdit;
meProgress: TMemo;
btOK: TButton;
la1: TLabel;
la2: TLabel;
pbProgress: TProgressBar;
procedure btOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FUpdateApplier :ThcUpdateApplier;
FErrorEncountered :boolean;
procedure LaunchEXEAndTerminate;
procedure OnApplyingUpdate(UpdateVersion, WhatsNew: string);
procedure OnUpdateFailure(UpdateVersion, UpdateErrorMessage :string);
procedure OnProgressUpdate(Sender: TObject);
procedure OnPatchProgress(ASender: TObject; const ACurrentPosition,
AMaximumPosition: LongWord; var ACanContinue: LongBool);
public
end;
var
frmMain: TfrmMain;
implementation
uses
CodeSiteLogging
,hcUpdateSettings
,hcVersionList
,ShellAPI
,StrUtils
;
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
var
nIndex,
nSecs :integer;
Param :string;
begin
FErrorEncountered := False;
if ParamCount = 1 then
begin
Param := ParamStr(1);
if StartsText('pause',Param) then
begin
//determine delay time
nIndex := Pos(':',Param);
nSecs := StrToInt(copy(Param,nIndex+1,Length(Param)));
meProgress.Lines.Add(Format('Delaying CheckForUpdates by %d Seconds',[nSecs]));
sleep(nSecs * 1000);
end;
end;
FUpdateApplier := ThcUpdateApplier.Create;
FUpdateApplier.ApplySilentUpdates := False; //launcher provides UI for feedback so ignore silent updates
FUpdateApplier.OnApplyUpdate := OnApplyingUpdate;
FUpdateApplier.OnProgressUpdate := OnProgressUpdate;
FUpdateApplier.OnPatchProgress := OnPatchProgress;
FUpdateApplier.OnApplyUpdateError := OnUpdateFailure;
if FUpdateApplier.CheckForUpdatesAndApply = 0 then //if no updates we're found & applied then
LaunchEXEAndTerminate;
end;
procedure TfrmMain.OnPatchProgress(ASender : TObject;
const ACurrentPosition : LongWord;
const AMaximumPosition : LongWord;
var ACanContinue : LongBool);
begin
if AMaximumPosition <> pbProgress.Max then
pbProgress.Max := AMaximumPosition;
if ACurrentPosition <> pbProgress.Position then
pbProgress.Position := ACurrentPosition;
Forms.Application.ProcessMessages;
end;
procedure TfrmMain.OnProgressUpdate(Sender :TObject);
{
This event is called every time a line is added so just add
the last line to the TMemo and scroll it into view.
}
begin
meProgress.Lines.Add(FUpdateApplier.Progress[FUpdateApplier.Progress.Count - 1]);
SendMessage(meProgress.Handle, EM_SCROLLCARET, 0, 0);
Forms.Application.ProcessMessages;
end;
procedure TfrmMain.OnUpdateFailure(UpdateVersion, UpdateErrorMessage: string);
begin
MessageDlg(Format('An error occurred while applying the %s update. %s may not be usable. We recommend you contact technical support immediately.',[UpdateVersion,AutoUpdateSettings.TargetEXE]),mtError,[mbOK],0);
btOK.Caption := 'Close';
end;
procedure TfrmMain.OnApplyingUpdate(UpdateVersion :string; WhatsNew :string);
var
stringStream :TStringStream;
begin
Caption := Format('Applying Update: %s',[UpdateVersion]);
stringStream := TStringStream.Create(WhatsNew);
try
meWhatsNew.Lines.LoadFromStream(stringStream);
finally
stringStream.Free;
end;
Forms.Application.ProcessMessages;
end;
procedure TfrmMain.btOKClick(Sender: TObject);
begin
LaunchEXEAndTerminate;
end;
procedure TfrmMain.LaunchEXEAndTerminate;
var
FileNameWithPath :string;
begin
FileNameWithPath := IncludeTrailingPathDelimiter(AutoUpdateSettings.AppDir) + AutoUpdateSettings.TargetEXE;
if not FileExists(FileNameWithPath) then
MessageDlg(Format('EXE Specified in INI file does not Exist: '#13#10'''%s''',[FileNameWithPath]),mtWarning,[mbOk],0);
ShellExecute(Handle, 'open', PWideChar(WideString(AutoUpdateSettings.AppDir + AutoUpdateSettings.TargetEXE)), nil, nil, SW_SHOWNORMAL) ;
PostQuitMessage(0);
end;
end.
|
unit SqlMonitor;
interface
uses
Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Memo,
Aurelius.Drivers.Interfaces,
Aurelius.Commands.Listeners;
type
TfrmSqlMonitor = class(TForm, ICommandExecutionListener)
Memo: TMemo;
PanelBottom: TPanel;
btClear: TButton;
btClose: TButton;
procedure btClearClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
class var
FInstance: TFrmSqlMonitor;
procedure ExecutingCommand(SQL: string; Params: TEnumerable<TDBParam>);
public
class function GetInstance: TFrmSqlMonitor;
end;
implementation
uses
DBConnection;
{$R *.fmx}
procedure TfrmSqlMonitor.btClearClick(Sender: TObject);
begin
Memo.Lines.Clear;
end;
procedure TfrmSqlMonitor.btCloseClick(Sender: TObject);
begin
Self.Hide;
end;
procedure TfrmSqlMonitor.ExecutingCommand(SQL: string;
Params: TEnumerable<TDBParam>);
begin
TDBConnection.AddLines(Memo.Lines, SQL, Params);
end;
class function TfrmSqlMonitor.GetInstance: TFrmSqlMonitor;
begin
if FInstance = nil then
FInstance := TFrmSqlMonitor.Create(Application);
Result := FInstance;
end;
end.
|
Unit AdvFiles;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
{$IFDEF MACOS} OSXUtils, {$ELSE} Windows, {$ENDIF} SysUtils, Classes,
FileSupport, StringSupport, MathSupport, ErrorSupport,
AdvStreams, AdvObjects, AdvExceptions;
Type
TAdvFile = Class(TAdvAccessStream)
Private
FStream : TFileStream;
function GetHandle: THandle;
Protected
Function GetPosition : Int64; Override;
Procedure SetPosition(Const Value : Int64); Override;
Function GetSize : Int64; Override;
Procedure SetSize(Const iValue : Int64); Override;
Procedure RaiseError(aException : EAdvExceptionClass; Const sMethod, sMessage : String); Overload; Override;
Function ErrorClass : EAdvExceptionClass; Override;
Public
constructor Create(const AFileName: string; Mode: Word); overload;
Destructor Destroy; override;
function Link : TAdvFile; overload;
Procedure Read(Var aBuffer; iCount : Cardinal); Override;
Procedure Write(Const aBuffer; iCount : Cardinal); Override;
Function Readable : Int64; Override;
Function Writeable : Int64; Override;
property Handle: THandle read GetHandle;
End;
EAdvFile = Class(EAdvStream);
Implementation
{ TAdvFile }
constructor TAdvFile.Create(const AFileName: string; Mode: Word);
begin
inherited create;
FStream := TFileStream.Create(AFileName, mode);
end;
destructor TAdvFile.Destroy;
begin
FStream.Free;
inherited;
end;
function TAdvFile.ErrorClass: EAdvExceptionClass;
begin
Result := EAdvFile;
end;
function TAdvFile.GetHandle: THandle;
begin
result := FStream.Handle;
end;
function TAdvFile.GetPosition: Int64;
begin
result := FStream.Position;
end;
function TAdvFile.GetSize: Int64;
begin
result := FStream.Size;
end;
function TAdvFile.Link: TAdvFile;
begin
result := TAdvFile(Inherited Link);
end;
procedure TAdvFile.RaiseError(aException: EAdvExceptionClass; const sMethod, sMessage: String);
begin
Inherited RaiseError(aException, sMethod, StringFormat('%s: ''%s''', [sMessage, FStream.FileName]));
end;
procedure TAdvFile.Read(var aBuffer; iCount: Cardinal);
begin
if FStream.Read(aBuffer, iCount) < iCount then
RaiseError('Read', 'Unable to read past end of file');
end;
function TAdvFile.Readable: Int64;
begin
result := FStream.Size - FStream.Position;
end;
procedure TAdvFile.SetPosition(const Value: Int64);
begin
FStream.Position := value;
end;
procedure TAdvFile.SetSize(const iValue: Int64);
begin
FStream.Size := iValue;
end;
procedure TAdvFile.Write(const aBuffer; iCount: Cardinal);
begin
If (FStream.Write(aBuffer, iCount) < iCount) Then
RaiseError('Read', 'Unable to write the entire buffer');
end;
function TAdvFile.Writeable: Int64;
begin
result := 0; // ?
end;
end.
|
{ Project : Basic Serial Communication
Component : CPort Library , Freeware
http://sourceforge.net/projects/comport/
Programmer : Mr.Ukrit Tantasutanon
Website : www.micro-research.co.th
}
unit UfrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CPort, Menus, ExtCtrls, ComCtrls;
type
TfrmMain = class(TForm)
ComPort1: TComPort;
edtSendText: TEdit;
MainMenu1: TMainMenu;
Fil1: TMenuItem;
Exit1: TMenuItem;
About1: TMenuItem;
AboutMRT1: TMenuItem;
Panel1: TPanel;
Label1: TLabel;
edtPortNo: TEdit;
btnOpenClose: TButton;
btnExit: TButton;
btnSend: TButton;
StatusBar1: TStatusBar;
memoRxData: TMemo;
Label2: TLabel;
btnClear: TButton;
procedure btnOpenCloseClick(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure AboutMRT1Click(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure ComPort1RxChar(Sender: TObject; Count: Integer);
procedure edtSendTextKeyPress(Sender: TObject; var Key: Char);
procedure btnClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.AboutMRT1Click(Sender: TObject);
begin
ShowMessage('More information for microcontroller product at www.micro-research.co.th');
end;
procedure TfrmMain.btnClearClick(Sender: TObject);
begin
memoRxData.Clear;
end;
procedure TfrmMain.btnExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TfrmMain.btnOpenCloseClick(Sender: TObject);
begin
try
if ComPort1.Connected=false then
begin
edtPortNo.Enabled:=False;
ComPort1.Port:='COM'+edtPortNo.Text;
ComPort1.Connected:=True;
btnOpenClose.Caption:='CLOSE';
edtSendText.Enabled:=True;
btnSend.Enabled:=True;
StatusBar1.Panels[0].Text:='Connected : 9600 bps,N,8,1';
end
else
begin
edtPortNo.Enabled:=True;
ComPort1.Connected:=False;
btnOpenClose.Caption:='OPEN';
edtSendText.Enabled:=False;
btnSend.Enabled:=False;
StatusBar1.Panels[0].Text:='Disconnected';
end;
except
edtPortNo.Enabled:=True;
ComPort1.Connected:=False;
btnOpenClose.Caption:='OPEN';
StatusBar1.Panels[0].Text:='Can not open specific COM port!!!';
end;
end;
procedure TfrmMain.btnSendClick(Sender: TObject);
begin
if ComPort1.Connected then
begin
ComPort1.WriteStr(edtSendText.Text+#13);
end;
end;
procedure TfrmMain.ComPort1RxChar(Sender: TObject; Count: Integer);
var
RxData : string;
begin
ComPort1.ReadStr(RxData,Count);
if RxData[Count]=#13 then
begin
memoRxData.Text:=memoRxData.Text+RxData+#13+#10;
end
else
begin
memoRxData.Text:=memoRxData.Text+RxData;
end;
end;
procedure TfrmMain.edtSendTextKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then
begin
//ShowMessage('OK');
btnSendClick(Self);
end;
end;
procedure TfrmMain.Exit1Click(Sender: TObject);
begin
Application.Terminate;
end;
end.
|
{$J+} {Writable constants}
unit ExMruU;
interface
uses
{$IFDEF WIN32}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, OvcBase, OvcMRU, StdCtrls, OvcState, OvcFiler, OvcStore;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Exit1: TMenuItem;
N1: TMenuItem;
Open1: TMenuItem;
OpenDialog1: TOpenDialog;
Memo1: TMemo;
Reopen1: TMenuItem;
ClearHistoryList1: TMenuItem;
OvcComponentState1: TOvcComponentState;
OvcIniFileStore1: TOvcIniFileStore;
DelphiList: TOvcMenuMRU;
FileMenuList: TOvcMenuMRU;
procedure Open1Click(Sender: TObject);
procedure ClearHistoryList1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure OvcMRUClick(Sender: TObject; const ItemText: String;
var Action: TOvcMRUClickAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Open1Click(Sender: TObject);
begin
{ Show the file open dialog. }
if (OpenDialog1.Execute) then begin
{ Load the file into the Memo. }
Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
{ Add all files to the main MRU list. }
FileMenuList.Add(OpenDialog1.FileName);
{ If a Delphi DPR file was opened, add it to the top }
{ of the split MRU list. }
if UpperCase(ExtractFileExt(OpenDialog1.FileName)) = '.DPR' then begin
DelphiList.AddSplit(OpenDialog1.FileName, apTop);
Reopen1.Enabled := True;
end;
{ If a Delphi PAS file was opened, add it to the bottom }
{ of the split MRU list. }
if UpperCase(ExtractFileExt(OpenDialog1.FileName)) = '.PAS' then begin
DelphiList.AddSplit(OpenDialog1.FileName, apBottom);
Reopen1.Enabled := True;
end;
end;
end;
procedure TForm1.ClearHistoryList1Click(Sender: TObject);
begin
DelphiList.Clear;
FileMenuList.Clear;
Reopen1.Enabled := False;
end;
procedure TForm1.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.OvcMRUClick(Sender: TObject; const ItemText: String;
var Action: TOvcMRUClickAction);
begin
{ A MRU menu item was clicked. Open the file in the Memo. }
Memo1.Lines.LoadFromFile(ItemText);
end;
end.
|
unit dbf_reg;
{===============================================================================
|| TDbf Component || http://tdbf.netfirms.com ||
===============================================================================}
(*
tDBF is supplied as is. The author disclaims all warranties,
expressed or implied, including, without limitation, the warranties of
merchantability and of fitness for any purpose. The author assumes no
liability for damages, direct or consequential, which may result from the
use of MyDBF.
You are allowed to use this component in any project free of charge.
You are
NOT allowed to claim that you have created this component. You are
NOT allowed to copy this component's code into your own component and
claim that the code is your idea.
*)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db,DsgnIntf,ExptIntf,
Dbf,
UDbfPagedFile, UDbfFile, UDbfIndex, UDbfMemo,
UDbfCursor, UDbfEngine, UDbfFieldDef,UDbfCommon
;
{$i _dbfCommon.inc}
//====================================================================
// Delphi is a bit to permissive for me, I mean protected doesn't work within
// one unit. So i decided that convention:
// private member begins by '_'
// It's forbidden to access any '_something' except from the class where it
// is defined. To check that, I just have to look for '._' anywhere in the code.
//====================================================================
procedure Register;
implementation
//==========================================================
//============ DESIGNONLY =================================
//==========================================================
//==========================================================
//============ TTableNameProperty
//==========================================================
type
TTableNameProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
procedure TTableNameProperty.Edit; {override;}
var
FileOpen: TOpenDialog;
Dbf: TDbf;
begin
FileOpen := TOpenDialog.Create(Application);
try
with fileopen do begin
Dbf:=GetComponent(0) as TDbf;
FileOpen.InitialDir:=Dbf.AbsolutePath;
Filename := GetValue;
Filter := 'Dbf table|*.dbf';
if Execute then begin
SetValue(Filename);
end;
end;
finally
Fileopen.free;
end;
end;
function TTableNameProperty.GetAttributes: TPropertyAttributes; {override;}
begin
Result := [paDialog, paRevertable];
end;
//==========================================================
//============ TIndexFileNameProperty
//==========================================================
type
TIndexFileNameProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
procedure TIndexFileNameProperty.Edit; {override;}
var
FileOpen: TOpenDialog;
IndexDef: TDbfIndexDef;
Indexes: TDbfIndexCollection;
Dbf:TDbf;
begin
FileOpen := TOpenDialog.Create(Application);
try
with fileopen do begin
IndexDef:=GetComponent(0) as TDbfIndexDef;
Indexes:=TDbfIndexCollection(IndexDef.Collection);
Dbf:=TDbf(Indexes._Owner);
FileOpen.InitialDir := Dbf.AbsolutePath;
Filename := GetValue;
Filter := 'Simple index (ndx)|*.ndx|Multiple index (mdx)|*.mdx';
if Execute then begin
SetValue(ExtractFileName(Filename));
end;
end;
finally
Fileopen.free;
end;
end;
function TIndexFileNameProperty.GetAttributes: TPropertyAttributes; {override;}
begin
Result := [paDialog, paRevertable];
end;
//==========================================================
//============ TSortFieldProperty
//==========================================================
type
TSortFieldProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
function TSortFieldProperty.GetAttributes: TPropertyAttributes; {override;}
begin
Result := [paValueList, paSortList, paRevertable];
end;
procedure TSortFieldProperty.GetValues(Proc: TGetStrProc);
var
IndexDef: TDbfIndexDef;
Indexes: TDbfIndexCollection;
Dbf:TDbf;
i:integer;
begin
IndexDef:=GetComponent(0) as TDbfIndexDef;
Indexes:=TDbfIndexCollection(IndexDef.Collection);
Dbf:=TDbf(Indexes._Owner);
for i:=0 to Dbf.FieldCount-1 do begin
Proc(Dbf.Fields[i].FieldName);
end;
end;
//==========================================================
//============ TIndexNameProperty
//==========================================================
type
TIndexNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
function GetValue: string; override;
end;
function TIndexNameProperty.GetAttributes: TPropertyAttributes; {override;}
begin
Result := [paValueList, paRevertable];
end;
procedure TIndexNameProperty.GetValues(Proc: TGetStrProc);
var
Dbf:TDbf;
i:integer;
begin
Dbf:=GetComponent(0) as TDbf;
for i:=0 to Dbf.Indexes.Count-1 do begin
Proc(Dbf.Indexes[i].IndexFile);
end;
end;
procedure TIndexNameProperty.SetValue(const Value: string); {override}
var
Dbf:TDbf;
begin
Dbf:=GetComponent(0) as TDbf;
Dbf.Indexname:=Value;
end;
function TIndexNameProperty.GetValue: string; {override;}
var
Dbf:TDbf;
begin
Dbf:=GetComponent(0) as TDbf;
Result:=Dbf.Indexname;
end;
//==========================================================
//============ TVersionProperty
//==========================================================
type
TVersionProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
procedure TVersionProperty.Edit; {override;}
var
Dbf: TDbf;
begin
Dbf:=GetComponent(0) as TDbf;
ShowMessage(
DBf.Version + ' : a dBase component'+#13+
'for Delphi and c++ builder with no BDE.'+#13+
#13 +
'To get the latest version, please visit'+#13+
'the website : http://tdbf.netfirms.com');
end;
function TVersionProperty.GetAttributes: TPropertyAttributes; {override;}
begin
Result := [paDialog, paReadOnly, paRevertable];
end;
//==========================================================
//============ TNativeFieldTypeProperty
//==========================================================
type
TNativeFieldTypeProperty = class(TCharProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
procedure TNativeFieldTypeProperty.SetValue(const Value: string);
var
L: Longint;
begin
if Length(Value) = 0 then L := 0 else
if Value[1] = '#' then L := StrToInt(Copy(Value, 2, Maxint))
else L := Ord(Value[1]);
SetOrdValue(L);
end;
function TNativeFieldTypeProperty.GetAttributes: TPropertyAttributes; {override;}
begin
result:=[paRevertable,paValueList];
end;
procedure TNativeFieldTypeProperty.GetValues(Proc: TGetStrProc);
begin
Proc('C Character');
Proc('N Numeric');
Proc('D Date');
Proc('L Logical');
Proc('M Memo');
Proc('B Blob');
Proc('F Float');
Proc('O Double');
Proc('I Integer');
Proc('G Graphic');
Proc('+ AutoIncrement');
Proc('@ DateTime');
end;
//==========================================================
//============ initialization
//==========================================================
procedure Register;
begin
RegisterComponents('Goodies', [TDbf]);
RegisterPropertyEditor(TypeInfo(string), TDbf, 'TableName', TTableNameProperty);
RegisterPropertyEditor(TypeInfo(string), TDbf, 'Version', TVersionProperty);
RegisterPropertyEditor(TypeInfo(string), TDbf, 'IndexFile', TIndexNameProperty);
RegisterPropertyEditor(TypeInfo(string), TDbfIndexDef, 'IndexFile', TIndexFileNameProperty);
RegisterPropertyEditor(TypeInfo(string), TDbfIndexDef, 'SortField', TSortFieldProperty);
RegisterPropertyEditor(TypeInfo(char), TDbfFieldDef, 'NativeFieldType', TNativeFieldTypeProperty);
end;
initialization
_DbfExePath:=ExtractFilePath(ToolServices.GetProjectName);
finalization
end.
|
unit ManutencaoVeiculos;
interface
type
TManutencaoVeiculos = class
private
var
FID: Integer;
FVeiculo: Integer;
FItem: Integer;
FDataManuencao: System.TDate;
FKmManutencao: Double;
FDataPrevisao: System.TDate;
FKmPrevisao: Double;
FValor: Double;
FDataLiberacao: System.TDate;
FSituacao: Integer;
FObs: String;
FLog: String;
public
property ID: Integer read FID write FID;
property Veiculo: Integer read FVeiculo write FVeiculo;
property Item: Integer read FItem write FItem;
property DataManutencao: System.TDate read FDataManuencao write FDataManuencao;
property KMManutencao: Double read FKmManutencao write FKmManutencao;
property DataPrevisao: System.TDate read FDataPrevisao write FDataPrevisao;
property KMPrevisao: Double read FKmPrevisao write FKmPrevisao;
property Valor: Double read FValor write FValor;
property DataLiberacao: System.TDate read FDataLiberacao write FDataLiberacao;
property Situacao: Integer read FSituacao write FSituacao;
property Obs: String read FObs write FObs;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create(pFID: Integer; pFVeiculo: Integer; pFItem: Integer; pFDataManuencao: System.TDate; pFKmManutencao: Double;
pFDataPrevisao: System.TDate; pFKmPrevisao: Double; pFValor: Double; pFDataLiberacao: System.TDate;
pFSituacao: Integer; pFObs: String; pFLog: String); overload;
end;
implementation
constructor TManutencaoVeiculos.Create;
begin
inherited Create;
end;
constructor TManutencaoVeiculos.Create(pFID: Integer; pFVeiculo: Integer; pFItem: Integer; pFDataManuencao: System.TDate;
pFKmManutencao: Double; pFDataPrevisao: System.TDate; pFKmPrevisao: Double; pFValor: Double;
pFDataLiberacao: System.TDate; pFSituacao: Integer; pFObs: String; pFLog: String);
begin
FID := pFID;
FVeiculo := pFVeiculo;
FItem := pFItem;
FDataManuencao := pFDataManuencao;
FKmManutencao := pFKmManutencao;
FDataPrevisao := pFDataPrevisao;
FKmPrevisao := pFKmPrevisao;
FValor := pFValor;
FDataLiberacao := pFDataLiberacao;
FSituacao := pFSituacao;
FObs := pFObs;
FLog := pFLog;
end;
end.
|
{------------------------------------
功能说明:接口说明服务
创建日期:2010/06/07
作者:WZW
版权:WZW
-------------------------------------}
unit uSvcInfoObj;
interface
uses sysUtils, Classes, SysFactory, SvcInfoIntf;
type
TSvcInfoObj = class(TInterfacedObject, ISvcInfoEx, ISvcInfo)
private
protected
{ISvcInfo}
function GetModuleName: String;
function GetTitle: String;
function GetVersion: String;
function GetComments: String;
{ISvcInfoEx}
procedure GetSvcInfo(Intf: ISvcInfoGetter);
public
end;
implementation
uses SysFactoryMgr, FactoryIntf;
{procedure Create_SvcInfoObj(out anInstance: IInterface);
begin
anInstance:=TSvcInfoObj.Create;
end;}
{ TSvcInfoObj }
function TSvcInfoObj.GetComments: String;
begin
Result := '用于获取当前系统所有接口信息';
end;
function TSvcInfoObj.GetModuleName: String;
begin
Result := ExtractFileName(SysUtils.GetModuleName(HInstance));
end;
function TSvcInfoObj.GetTitle: String;
begin
Result := '接口说明服务(ISvcInfoEx)';
end;
function TSvcInfoObj.GetVersion: String;
begin
Result := '20100607.001';
end;
procedure TSvcInfoObj.GetSvcInfo(Intf: ISvcInfoGetter);
var i: integer;
aFactory: TFactory;
SvcInfoEx: ISvcInfoEx;
begin
if Intf = nil then
exit;
for i := 0 to FactoryManager.FactoryList.Count - 1 do
begin
aFactory := FactoryManager.FactoryList.Items[i];
if aFactory.GetInterface(ISvcInfoEx, SvcInfoEx) then
SvcInfoEx.GetSvcInfo(Intf);
end;
end;
initialization
//TIntfFactory.Create(ISvcInfoEx,@Create_SvcInfoObj);
finalization
end. |
unit frmUndoExample;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Spring.Collections, uPointCommand, uPointInterfaces;
type
TUndoExampleForm = class(TForm)
Panel1: TPanel;
btnUndo: TButton;
btnClear: TButton;
PaintBox1: TPaintBox;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure btnUndoClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
private
{ Private declarations }
FDots: IStack<IPointCommand>;
procedure UpdateLabel;
public
{ Public declarations }
end;
var
UndoExampleForm: TUndoExampleForm;
implementation
{$R *.dfm}
procedure TUndoExampleForm.btnClearClick(Sender: TObject);
begin
if FDots.Count > 0 then
begin
repeat
FDots.Pop.Undo;
until FDots.Count <= 0;
end;
UpdateLabel;
end;
procedure TUndoExampleForm.btnUndoClick(Sender: TObject);
begin
if FDots.Count > 0 then
begin
FDots.Pop.Undo;
end;
PaintBox1.Invalidate;
UpdateLabel;
end;
procedure TUndoExampleForm.FormCreate(Sender: TObject);
begin
FDots := TCollections.CreateStack<IPointCommand>;
end;
procedure TUndoExampleForm.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
LCommand: IPointCommand;
begin
LCommand := TPointPlacerCommand.Create(PaintBox1.Canvas, TPoint.Create(X, Y));
LCommand.Execute;
FDots.Push(LCommand);
UpdateLabel;
end;
procedure TUndoExampleForm.PaintBox1Paint(Sender: TObject);
var
LDot: IPointCommand;
begin
for LDot in FDots do
begin
LDot.Execute;
end;
end;
procedure TUndoExampleForm.UpdateLabel;
begin
Label1.Caption := 'Number of Dots: ' + FDots.Count.ToString();
end;
end.
|
{
功能: 视频连接
}
unit VideoSlideDecoder;
interface
uses
Windows, VideoSlideParams, DecoderParam;
type
HVIDEODECODER = pointer;
// 创建SlideShow视频解码器
// HVIDEODECODER __stdcall SDVideoCreate(const VideoSlideParam* pParam);
function SDVideoCreate(const pParam : PVideoProcessParam) : HVIDEODECODER; stdcall;
// 销毁SlideShow视频解码器
// void __stdcall SDVideoDestroy(HVIDEODECODER hVideo);
procedure SDVideoDestroy(hVideo : HVIDEODECODER); stdcall;
// 置入一个视频频源及其处理参数(含剪裁、亮度对比度调节、特效设置等),多次调用即可置入多个视频源
// BOOL __stdcall SDAddVideoSource(HVIDEODECODER hVideo, const wchar_t* szSrcVideoFile, const VideoProcessParam* pParam);
function SDAddVideoSource(hVideo : HVIDEODECODER; const szSrcVideoFile : PWideChar; const pParam : PVideoProcessParam) : BOOL; stdcall;
implementation
const
DLLNAME = 'WS_SlideDecoder.dll';
function SDVideoCreate ; external DLLNAME Name 'SDVideoCreate';
procedure SDVideoDestroy ; external DLLNAME Name 'SDVideoDestroy';
function SDAddVideoSource ; external DLLNAME Name 'SDAddVideoSource';
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [PONTO_FECHAMENTO_JORNADA]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PontoFechamentoJornadaController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti,
Atributos, VO, Generics.Collections, PontoFechamentoJornadaVO;
type
TPontoFechamentoJornadaController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TPontoFechamentoJornadaVO>;
class function ConsultaObjeto(pFiltro: String): TPontoFechamentoJornadaVO;
class procedure Insere(pObjeto: TPontoFechamentoJornadaVO);
class function Altera(pObjeto: TPontoFechamentoJornadaVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses UDataModule, T2TiORM;
class procedure TPontoFechamentoJornadaController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TPontoFechamentoJornadaVO>;
ConsultaSQL: String;
begin
try
/// EXERCICIO: Crie uma view no banco de dados para substituir a consulta abaixo.
ConsultaSQL :=
'SELECT PFJ.*, C.PIS_NUMERO, P.NOME AS NOME_COLABORADOR, '+
'PCJ.CODIGO AS CODIGO_CLASSIFICACAO, PCJ.NOME AS NOME_CLASSIFICACAO '+
'FROM PONTO_FECHAMENTO_JORNADA PFJ '+
'INNER JOIN COLABORADOR C ON (PFJ.ID_COLABORADOR = C.ID) '+
'INNER JOIN PESSOA P ON (C.ID_PESSOA = P.ID) '+
'INNER JOIN PONTO_CLASSIFICACAO_JORNADA PCJ ON (PFJ.ID_PONTO_CLASSIFICACAO_JORNADA = PCJ.ID)';
Retorno := TT2TiORM.Consultar<TPontoFechamentoJornadaVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TPontoFechamentoJornadaVO>(Retorno);
finally
end;
end;
class function TPontoFechamentoJornadaController.ConsultaLista(pFiltro: String): TObjectList<TPontoFechamentoJornadaVO>;
begin
try
Result := TT2TiORM.Consultar<TPontoFechamentoJornadaVO>(pFiltro, '-1', True);
finally
end;
end;
class function TPontoFechamentoJornadaController.ConsultaObjeto(pFiltro: String): TPontoFechamentoJornadaVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TPontoFechamentoJornadaVO>(pFiltro, True);
finally
end;
end;
class procedure TPontoFechamentoJornadaController.Insere(pObjeto: TPontoFechamentoJornadaVO);
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPontoFechamentoJornadaController.Altera(pObjeto: TPontoFechamentoJornadaVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TPontoFechamentoJornadaController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TPontoFechamentoJornadaVO;
begin
try
ObjetoLocal := TPontoFechamentoJornadaVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPontoFechamentoJornadaController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TPontoFechamentoJornadaController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TPontoFechamentoJornadaController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TPontoFechamentoJornadaVO>(TObjectList<TPontoFechamentoJornadaVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TPontoFechamentoJornadaController);
finalization
Classes.UnRegisterClass(TPontoFechamentoJornadaController);
end.
|
unit LogViewerTestApplication;
interface
uses
SysUtils,
Forms,
UFileNameCycler,
PlainLogManager,
FileLogWriter,
ConsoleLogWriter,
DefaultLogEntity,
EmptyLogEntity,
GlobalLogManagerUnit;
type
TLVTApplication = class
public const
LogSubFolder = 'Log';
LogFileCount = 10;
protected
fLog: TEmptyLog;
procedure StartupLog;
procedure StartupConsoleLog;
procedure StartupFileLog;
function GetLogDirectory: string;
procedure ShutdownLog;
public
property Log: TEmptyLog read fLog;
procedure Run;
end;
implementation
procedure TLVTApplication.StartupLog;
begin
GlobalLogManager := TPlainLogManager.Create;
StartupConsoleLog;
fLog := TLog.Create(GlobalLogManager, 'Application');
StartupFileLog;
end;
procedure TLVTApplication.StartupConsoleLog;
var
w: TConsoleLogWriter;
begin
w := TConsoleLogWriter.Create;
GlobalLogManager.AddWriter(w);
end;
procedure TLVTApplication.StartupFileLog;
var
w: TFileLogWriter;
begin
w := TFileLogWriter.Create;
if not DirectoryExists(GetLogDirectory) then
ForceDirectories(GetLogDirectory);
w.FilePath := CycleFileName(IncludeTrailingPathDelimiter(GetLogDirectory) + 'logFile',
LogFileCount, '.text');
Log.Write('Log file: ' + w.FilePath);
GlobalLogManager.AddWriter(w);
end;
function TLVTApplication.GetLogDirectory: string;
begin
result := ExtractFilePath(Application.ExeName) + LogSubFolder;
end;
procedure TLVTApplication.ShutdownLog;
begin
FreeAndNil(fLog);
FreeAndNil(GlobalLogManager);
end;
procedure TLVTApplication.Run;
begin
StartupLog;
ShutdownLog;
end;
end.
|
{
Perk Tree Visual User Interface v1.2
created by matortheeternal
** Description **
Apply this script to an AVIF record which contains a perk tree, e.g.
AVTwoHanded, AVAlchemy, AVDestruction, etc. You will get a window
with yellow nodes arranged like the perk tree. You can edit this
tree and save it using this Visual User Interface.
** Tutorial **
- Viewing perks: Hover your mouse over a perk node to get a hint menu
which says what perk that node corresponds to.
- Selecting perks: Double click a perk node to select it. Once
selected the perk node will turn green.
- Showing the grid: Click the "Show Grid" button to show the grid
behind the perk tree. Click it again to hide the grid.
- Showing connections: Click "Show Connections" to show connections
between perks. Click it again to hide them.
- Adding perks: Click the "Add Perk" button to create a new perk node.
- Removing perks: After selecting a perk you can remove it by clicking
the Remove Perk button.
- Creating connections: Starting with no perks selected, click the
Create Connection button. Select the first perk and click the button
again (it should say "Perk 1"), then select the second perk and click
the button again (it should say "Perk 2").
- Removing connections: Starting with no perks selected, click the
Remove Connection button. Select the first perk and click the button
again (it should say "Perk 1"), then select the second perk and click
the button again (it should say "Perk 2").
- Snap to grid: If you wish you can snap all perk positions to the grid.
This will affect all of the loaded perks, so it is recommend that you
don't do so unless you plan on saving grid positions only. Click the
button again to allow for free movement of perks.
- Enable movement: You can disable/enable perk movement using the button
"Disable Movement"/"Enable Movement". This is handy if you want to
make or delete connections without accidentally moving perks slightly.
- Maximum x-grid: To increase/decrease space on the x-axis, you can change
the number in the edit box by the "Maximum x-grid" label. This must be
an integer value greater than or equal to 6 and less than or equal to 14.
- Setting perks: Select a perk and then choose a new perk from the drop down
menu to set it to your choice.
- Moving perks: Click and drag a perk node to move it.
- Saving: When you exit the window a save dialog will prompt you if you
want to save your changes. If you want to save adjusted positions of
pre-existing perks make sure you check "Save Offset Positions". If you
want to save new grid positions for the perks check "Save Grid
Positions". If you want to save changes to connections between perks
check "Save Connections". New perks will be saved unless you click
Cancel.
** Grid Scale **
You can adjust the grid scale a few lines down in the constants section.
This is the length of a grid unit in pixels. 60 is the safest value to
avoid perk tree clipping. You can increase it to 70-90 for most trees
though, to allow for greater resolution when editing. If you open a
perk tree and notice a perk is off the window, close the UI immediately
and don't save anything from the save window.
}
unit PerkTreeUI;
uses mteFunctions;
const
ColorTransparent = $000001; // transparent color for overlay
gridScale = 70; // size of a grid square
var
Form1, Form2: TForm1;
nodeList: TList;
i, j, k, cv, nct, cct, xOffset, yOffset, xSave, ySave: integer;
slPerks, slBethesdaFiles: TStringList;
background, yPog, gPog: TPicture;
proceed, ShowConnections, ShowGrid, SnapToGrid, SecondPerk, MouseDown,
DisableMovement, bethFile: boolean;
nodeArray: Array[0..100] of TImage;
connectionsArray: Array[0..1,0..100] of TImage;
ActivePerk, Perk1, Perk2: TImage;
LogFile: text;
Button1, Button2, Button3, Button4, Button5, Button6, Button7,
Button8, Button9, Button10: TButton;
ComboBox1: TComboBox;
Edit1: TEdit;
Image1, Image2, mImage: TImage;
Label1, Label2: TLabel;
CheckBox1, CheckBox2, CheckBox3: TCheckBox;
Panel1: TPanel;
StartingPerk, perktree, group, element, f: IInterface;
//=========================================================================
// Make nodes on top procedure
procedure Form1.MakeNodesOnTop;
begin
for i := 0 to nct - 1 do begin
nodeArray[i].Visible := false;
nodeArray[i].Visible := true;
end;
end;
//=========================================================================
// Draw grid procedure
procedure Form1.DrawGrid;
begin
Image1.Canvas.Pen.Width := 1;
Image1.Canvas.Pen.Style := psSolid;
// vertical lines
for i := 1 to 50 do begin
Image1.Canvas.Pen.Color := $00FFFFFF;
cv := gridScale*i;
if (cv = gridScale) or (cv = gridScale*13) then
Image1.Canvas.Pen.Color := $00FF4444;
if (Image1.Width <= cv) then Break;
Image1.Canvas.MoveTo(cv, Image1.Height);
Image1.Canvas.LineTo(cv, 0);
end;
// horizontal lines
for i := 1 to 20 do begin
Image1.Canvas.Pen.Color := $00FFFFFF;
cv := Image1.Height - gridScale*i;
if (cv = Image1.Height - 5*gridScale) then
Image1.Canvas.Pen.Color := $00FF4444;
if (cv = Image1.Height - gridScale) then
Image1.Canvas.Pen.Color := $00FF4444;
if (0 > cv) then Break;
Image1.Canvas.MoveTo(0, cv);
Image1.Canvas.LineTo(Image1.Width, cv);
end;
MakeNodesOnTop;
end;
//=========================================================================
// Draw Connections procedure
procedure Form1.DrawConnections;
var
sImg, eImg: TImage;
begin
Image2.Canvas.Pen.Color := $00FFF6C0;
Image2.Canvas.Pen.Style := psSolid;
Image2.Canvas.Pen.Width := 1;
for i := 0 to cct - 1 do begin
sImg := ConnectionsArray[0,i];
eImg := ConnectionsArray[1,i];
Image2.Canvas.MoveTo(sImg.Left - 5, sImg.Top - 5);
Image2.Canvas.LineTo(eImg.Left - 5, eImg.Top - 5);
end;
MakeNodesOnTop;
end;
//=========================================================================
// Redraw background procedure
procedure Form1.RedrawBackground;
begin
Image2.Canvas.Brush.Color := ColorTransparent;
Image2.Canvas.FillRect(Rect(0, 0, Image2.Width, Image2.Height));
end;
//=========================================================================
// Redraw all procedure
procedure Form1.Redraw;
begin
RedrawBackground;
if ShowConnections then DrawConnections;
end;
//=========================================================================
// Enable/Disable Movement button
procedure Form1.Button8Click(Sender: TObject);
begin
if not DisableMovement then begin
Button8.Caption := 'Enable Movement';
DisableMovement := true;
end
else begin
Button8.Caption := 'Disable Movement';
DisableMovement := false;
end;
end;
//=========================================================================
// Remove Connection button
procedure Form1.Button7Click(Sender: TObject);
begin
if not SecondPerk then begin
if Assigned(ActivePerk) then begin
Perk1 := ActivePerk;
SecondPerk := true;
Button6.Enabled := false;
Button5.Enabled := false;
Button7.Caption := 'Perk 2';
end
else begin
Button6.Enabled := false;
Button5.Enabled := false;
Button7.Caption := 'Perk 1';
end;
end
else begin
if Assigned(ActivePerk) then begin
if not (ActivePerk = Perk1) then begin
Perk2 := ActivePerk;
for i := 0 to cct - 1 do begin
if (ConnectionsArray[0,i] = Perk1) and (ConnectionsArray[1,i] = Perk2)
or (ConnectionsArray[0,i] = Perk2) and (ConnectionsArray[1,i] = Perk1)
then begin
for j := i to cct - 2 do begin
ConnectionsArray[0,j] := ConnectionsArray[0,j+1];
ConnectionsArray[1,j] := ConnectionsArray[1,j+1];
end;
ConnectionsArray[0,cct] := nil;
ConnectionsArray[1,cct] := nil;
cct := cct - 1;
end;
end;
// cleaning up
SecondPerk := false;
Perk1 := nil;
Perk2 := nil;
Redraw;
Button5.Enabled := true;
if cct <= 100 then Button6.Enabled := true;
Button7.Caption := 'Remove Connection';
end;
end;
end;
end;
//=========================================================================
// Create Connection button
procedure Form1.Button6Click(Sender: TObject);
begin
if not SecondPerk then begin
if Assigned(ActivePerk) then begin
Perk1 := ActivePerk;
SecondPerk := true;
Button7.Enabled := false;
Button5.Enabled := false;
Button6.Caption := 'Perk 2';
end
else begin
Button7.Enabled := false;
Button5.Enabled := false;
Button6.Caption := 'Perk 1';
end;
end
else begin
if Assigned(ActivePerk) then begin
if not (ActivePerk = Perk1) then begin
Perk2 := ActivePerk;
ConnectionsArray[0,cct] := Perk1;
ConnectionsArray[1,cct] := Perk2;
Inc(cct);
if cct >= 100 then Button6.Enabled := false;
// cleaning up
SecondPerk := false;
Perk1 := nil;
Perk2 := nil;
Redraw;
Button7.Enabled := true;
Button5.Enabled := true;
Button6.Caption := 'Create Connection';
end;
end;
end;
end;
//=========================================================================
// Remove Perk Button
procedure Form1.Button5Click(Sender: TObject);
var
perkIndex: integer;
begin
// remove the perk
if Assigned(ActivePerk) then begin
for i := 0 to cct - 1 do begin
if (ConnectionsArray[0,i] = ActivePerk)
or (ConnectionsArray[1,i] = ActivePerk) then begin
for j := i to cct - 2 do begin
ConnectionsArray[0,j] := ConnectionsArray[0,j+1];
ConnectionsArray[1,j] := ConnectionsArray[1,j+1];
end;
ConnectionsArray[0,cct] := nil;
ConnectionsArray[1,cct] := nil;
cct := cct - 1;
end;
end;
for i := 0 to nct - 1 do begin
if nodeArray[i] = ActivePerk then begin
perkIndex := i;
Break;
end;
end;
TImage(NodeArray[perkIndex]).Free;
for i := perkIndex to nct - 2 do begin
nodeArray[i] := nodeArray[i+1];
end;
nodeArray[nct] := nil;
nct := nct - 1;
if nct < 100 then Button4.Enabled := true;
ActivePerk := nil;
Redraw;
Button5.Enabled := false;
ComboBox1.Enabled := false;
end;
end;
//=========================================================================
// Assign perk to ComboBox1.Text
procedure Form1.ComboBox1Change(Sender: TObject);
begin
if Assigned(ActivePerk) then
ActivePerk.Hint := ComboBox1.Text;
end;
//=========================================================================
// Defocus selection when clicking background
procedure Form1.Image1Click(Sender: TObject);
begin
if Assigned(ActivePerk) then
ActivePerk.Picture := yPog;
ActivePerk := nil;
Button5.Enabled := false;
ComboBox1.Enabled := false;
end;
//=========================================================================
// Round Node Position procedure
procedure Form1.RoundNodePosition(nImage: TImage);
var
lm, tm, cTop, cLeft: integer;
begin
//left position
cLeft := nImage.Left - 6;
lm := cLeft mod gridScale;
if (lm >= gridScale div 2) then begin
nImage.Left := ((cLeft div gridScale) + 1)*gridScale + 5;
end
else begin
nImage.Left := (cLeft div gridScale)*gridScale + 5;
end;
//top position
cTop := Image1.Height - nImage.Top - 6;
tm := cTop mod gridScale;
if (tm >= gridScale div 2) then begin
nImage.Top := Image1.Height - ((cTop div gridScale) + 1)*gridScale + 5;
end
else begin
nImage.Top := Image1.Height - (cTop div gridScale)*gridScale + 5;
end;
end;
//=========================================================================
// Snap Nodes To Grid procedure
procedure Form1.SnapNodesToGrid;
begin
for i := 0 to nct - 1 do begin
RoundNodePosition(nodeArray[i]);
end;
Redraw;
end;
//=========================================================================
// NodeMouseDown: start tracking node to mouse position
procedure Form1.NodeMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if DisableMovement then exit;
MouseDown := true;
mImage := TImage(Sender);
xOffset := mImage.Left - 5;
yOffset := mImage.Top - 5;
end;
//=========================================================================
// NodeMouseMove: track node to mouse position
procedure Form1.NodeMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
dX, dY: integer;
begin
if not MouseDown then Exit;
mImage.Left := xOffset + X;
xOffset := mImage.Left - 5;
mImage.Top := yOffset + Y;
yOffset := mImage.Top - 5;
if ShowConnections then begin
RedrawBackground;
DrawConnections;
end;
end;
//=========================================================================
// NodeMouseUp: Stop moving node
procedure TForm1.NodeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
MouseDown := false;
Redraw;
if SnapToGrid then
SnapNodesToGrid;
end;
//=========================================================================
// Remove Perk Button
procedure Form1.NodeSelected(Sender: TObject);
begin
if Assigned(ActivePerk) then
ActivePerk.Picture := yPog;
ActivePerk := TImage(Sender);
TImage(Sender).Picture := gPog;
ComboBox1.Enabled := true;
ComboBox1.Text := ActivePerk.Hint;
if (Button6.Caption = 'Create Connection')
and (Button7.Caption = 'Remove Connection') then
Button5.Enabled := true;
end;
//=========================================================================
// Add Perk button
procedure Form1.Button4Click(Sender: TObject);
begin
nodeArray[nct] := TImage.Create(Panel1);
nodeArray[nct].Parent := Panel1;
nodeArray[nct].Picture := yPog;
nodeArray[nct].Top := Image1.Height - gridScale + 5;
nodeArray[nct].Left := gridScale + 5;
nodeArray[nct].ParentShowHint := false;
nodeArray[nct].Hint := 'NULL - Null Reference [00000000]';
nodeArray[nct].Proportional := true;
nodeArray[nct].ShowHint := true;
nodeArray[nct].Transparent := true;
nodeArray[nct].Height := 12;
nodeArray[nct].Width := 12;
nodeArray[nct].OnMouseDown := NodeMouseDown;
nodeArray[nct].OnMouseMove := NodeMouseMove;
nodeArray[nct].OnMouseUp := NodeMouseUp;
nodeArray[nct].OnDblClick := NodeSelected;
Inc(nct);
if nct = 100 then Button4.Enabled := false;
//Redraw;
end;
//=========================================================================
// Snap/Free from Grid button
procedure Form1.Button3Click(Sender: TObject);
begin
if SnapToGrid then begin
SnapToGrid := false;
Button3.Caption := 'Snap to Grid';
end
else begin
SnapToGrid := true;
Button3.Caption := 'Free from Grid';
SnapNodesToGrid;
end;
end;
//=========================================================================
// Show/Hide Grid Lines button
procedure Form1.Button2Click(Sender: TObject);
begin
if ShowGrid then begin
ShowGrid := false;
Button2.Caption := 'Show Grid Lines';
Image1.Picture := background;
end
else begin
ShowGrid := true;
Button2.Caption := 'Hide Grid Lines';
DrawGrid;
end;
end;
//=========================================================================
// Show/Hide Connections button
procedure Form1.Button1Click(Sender: TObject);
begin
if ShowConnections then begin
ShowConnections := false;
Button1.Caption := 'Show Connections';
RedrawBackground;
end
else begin
ShowConnections := true;
Button1.Caption := 'Hide Connections';
DrawConnections;
end;
end;
//=========================================================================
// Scale window to Edit1
procedure Form1.Edit1Change(Sender: TObject);
begin
proceed := false;
try
StrToInt(Edit1.Text);
proceed := true;
Except on Exception do
exit;
end;
if proceed then begin
for i := 0 to nct - 1 do begin
if (nodeArray[i].Left > (StrToInt(Edit1.Text) * gridScale)) then
proceed := false;
end;
end;
if proceed and (StrToInt(Edit1.Text) < 15) and (StrToInt(Edit1.Text) > 4) then begin
Image1.Width := StrToInt(Edit1.Text) * gridScale;
Image2.Width := Image1.Width;
Image2.Picture.Bitmap.Width := Image1.Width;
Panel1.Width := Image1.Width + 20;
if 64 + Panel1.Width < 644 then
Form1.Width := 644
else
Form1.Width := 64 + Panel1.Width;
Image1.Picture := background;
if ShowGrid then DrawGrid;
Redraw;
end;
end;
//=========================================================================
// LoadPerkTree procedure
procedure Form1.LoadPerkTree(sp: IInterface);
var
perk, tree, connections: IInterface;
perkName: string;
xGrid, yGrid, maxGrid, xPos, yPos, index: Integer;
hnam, vnam: real;
begin
AddMessage('GridScale = '+IntToStr(gridScale));
maxGrid := 0;
tree := ElementByPath(sp, 'Perk Tree');
for i := 1 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, i);
xGrid := geev(perk, 'XNAM');
if (xGrid > maxGrid) then maxGrid := xGrid;
end;
for i := 1 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, i);
perkName := geev(perk, 'PNAM');
xGrid := maxGrid - genv(perk, 'XNAM');
yGrid := genv(perk, 'YNAM');
hnam := genv(perk, 'HNAM');
vnam := genv(perk, 'VNAM');
xPos := Round(hnam * gridScale);
yPos := Round(vnam * gridScale);
AddMessage(perkName + ' :: ('+IntToStr(xGrid)+'.'+IntToStr(xPos)+', '+IntToStr(yGrid)+'.'+IntToStr(yPos)+')');
// create perk with loaded attributes
Button4.Click;
nodeArray[nct - 1].Hint := perkName;
nodeArray[nct - 1].Tag := geev(perk, 'INAM');
nodeArray[nct - 1].Left := (xGrid + 1) * gridScale - xPos;
nodeArray[nct - 1].Top := Image1.Height - gridScale - (yGrid * gridScale) - yPos;
end;
for i := 1 to ElementCount(ElementByPath(sp, 'Perk Tree')) - 1 do begin
perk := ElementByIndex(tree, i);
connections := ElementByPath(perk, 'Connections');
for j := 0 to ElementCount(connections) - 1 do begin
for k := 0 to nct - 1 do begin
if SameText(nodeArray[k].Tag, IntToStr(GetEditValue(ElementByIndex(connections, j)))) then begin
ConnectionsArray[0,cct] := TImage(nodeArray[i - 1]);
ConnectionsArray[1,cct] := TImage(nodeArray[k]);
Inc(cct);
end;
end;
end;
end;
Edit1.Text := IntToStr(maxGrid + 3);
Edit1Change(nil);
Button1Click(nil);
Button8Click(nil);
end;
//=========================================================================
// SavePerkTree procedure
procedure Form1.SavePerkTree(sp: IInterface; saveGrid: boolean;
savePositions: boolean; saveConnections: boolean);
var
perk, tree, connections, connection: IInterface;
maxGrid, oXg, oYg, xGrid, yGrid, xPos, yPos, xChange, yChange,
maxIndex: integer;
index0, index1: string;
xOld, yOld, xNew, yNew, xDiff, yDiff, minRes: real;
begin
maxGrid := 0;
maxIndex := 0;
tree := ElementByPath(sp, 'Perk Tree');
// calculate maxIndex for new perk creation
for i := 0 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, i);
j := StrToInt(geev(perk, 'INAM'));
if (j > maxIndex) then maxIndex := j;
end;
// calculate maxGrid for reflection (perk trees are stored backwards)
for i := 0 to nct - 1 do begin
xGrid := Round((nodeArray[i].Left)/(gridScale));
if (xGrid > 0) then xGrid := xGrid - 1;
if xGrid > maxgrid then maxGrid := xGrid;
end;
// save values
for i := 0 to nct - 1 do begin
// calculate values to be saved for perk
xGrid := Round((nodeArray[i].Left)/(gridScale));
oXg := xGrid;
if (xGrid > 0) then xGrid := xGrid - 1;
xPos := (oXg * gridScale) - nodeArray[i].Left;
xGrid := maxGrid - xGrid;
yGrid := Round((Image1.Height - nodeArray[i].Top)/(gridScale));
oYg := yGrid;
if (yGrid > 0) then yGrid := yGrid - 1;
if (yGrid > 4) then yGrid := 4;
if (oYg > 5) then oYg := 5;
yPos := Image1.Height - nodeArray[i].Top - (oYg * gridScale);
// either create new node in perk tree, or use existing one
if i + 2 > ElementCount(tree) then begin
perk := ElementAssign(tree, HighInteger, ElementByIndex(tree, 0), False);
seev(perk, 'PNAM', nodeArray[i].Hint);
seev(perk, 'FNAM', '01 00 00 00');
seev(perk, 'INAM', maxIndex + 1);
nodeArray[i].Tag := IntToStr(maxIndex + 1);
seev(perk, 'XNAM', xGrid);
seev(perk, 'YNAM', yGrid);
seev(perk, 'HNAM', FloatToStr(xPos/gridScale));
seev(perk, 'VNAM', FloatToStr(yPos/gridScale));
seev(perk, 'SNAM', Name(sp));
Inc(maxIndex);
Continue;
end
else begin
// try to find a matching perk in the tree
for j := 1 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, j);
if SameText(geev(perk, 'PNAM'), nodeArray[i].Hint) then
Break;
// if no matching perk found, use perk at nodeArray index
if j = ElementCount(tree) - 1 then
perk := ElementByIndex(tree, i);
end;
end;
// save values
seev(perk, 'PNAM', nodeArray[i].Hint);
// if positions are the same as current values within resolution error,
// don't save them
xOld := StrToFloat(geev(perk, 'XNAM')) + StrToFloat(geev(perk, 'HNAM'));
yOld := StrToFloat(geev(perk, 'YNAM')) + StrToFloat(geev(perk, 'VNAM'));
xNew := xGrid + xPos/gridScale;
yNew := yGrid + yPos/gridScale;
xDiff := xOld - xNew;
yDiff := yOld - yNew;
minRes := 1/gridScale;
// save grid and positions
if saveGrid and savePositions then begin
if abs(xDiff) > minRes then begin
seev(perk, 'XNAM', xGrid);
seev(perk, 'HNAM', FloatToStr(xPos/gridScale));
end;
if abs(yDiff) > minRes then begin
seev(perk, 'YNAM', yGrid);
seev(perk, 'VNAM', FloatToStr(yPos/gridScale));
end;
end
else if saveGrid then begin
if abs(xDiff) > minRes then begin
xChange := geev(perk, 'XNAM') - xGrid;
seev(perk, 'XNAM', xGrid);
if xChange <> 0 then
seev(perk, 'HNAM', StrToFloat(geev(perk, 'HNAM')) + xChange);
end;
if abs(yDiff) > minRes then begin
yChange := geev(perk, 'YNAM') - yGrid;
seev(perk, 'YNAM', yGrid);
if yChange <> 0 then
seev(perk, 'VNAM', StrToFloat(geev(perk, 'VNAM')) + yChange);
end;
end
else if savePositions then begin
if abs(xDiff) > minRes then begin
xChange := geev(perk, 'XNAM') - xGrid;
seev(perk, 'HNAM', FloatToStr(xPos/gridScale - xChange));
end;
if abs(yDiff) > minRes then begin
yChange := geev(perk, 'YNAM') - yGrid;
seev(perk, 'VNAM', FloatToStr(yPos/gridScale - yChange));
end;
end;
end;
// save connections
if saveConnections then begin
// create new connections
for i := 0 to cct - 1 do begin
for j := 1 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, j);
if geev(perk, 'PNAM') = connectionsArray[0,i].Hint then begin
connections := ElementByPath(perk, 'Connections');
if not Assigned(connections) then begin
ElementAssign(perk, 7, nil, False);
connections := ElementByPath(perk, 'Connections');
end;
for k := 0 to ElementCount(connections) - 1 do begin
connection := ElementByIndex(connections, k);
if SameText(IntToStr(GetEditValue(connection)), IntToStr(connectionsArray[1,i].Tag)) then
Break;
if (k = ElementCount(connections) - 1) then begin
connection := ElementAssign(connections, HighInteger, nil, False);
SetEditValue(connection, IntToStr(connectionsArray[1,i].Tag));
end;
end;
end;
end;
end;
// delete nonexistent connections
for i := 1 to ElementCount(tree) - 1 do begin
perk := ElementByIndex(tree, i);
connections := ElementByPath(perk, 'Connections');
if not Assigned(connections) then Continue;
for j := ElementCount(connections) - 1 downto 0 do begin
connection := ElementByIndex(connections, j);
index0 := IntToStr(geev(perk, 'INAM'));
index1 := IntToStr(GetEditValue(connection));
for k := 0 to cct - 1 do begin
if SameText(IntToStr(connectionsArray[0,k].Tag), index0) and SameText(IntToStr(connectionsArray[1,k].Tag), index1) then
Break;
if k = cct - 1 then
Remove(connection);
end;
end;
end;
end;
end;
//=========================================================================
// SaveDialog for saving the perk tree
procedure SaveDialog(sp: IInterface);
var
b1, b2, b3: boolean;
begin
Form2 := TForm.Create(nil);
try
Form2.Height := 200;
Form2.Width := 310;
Form2.Position := poScreenCenter;
Form2.Caption := 'Save Perk Tree?';
// set Label2 properties
Label2 := TLabel.Create(Form2);
Label2.Parent := Form2;
Label2.Left := 8;
Label2.Height := 31;
Label2.Top := 8;
Label2.Width := 194;
Label2.Caption := 'Select the options you want to use to save the perk tree'#13'you made below:';
// set CheckBox1 properties
CheckBox1 := TCheckBox.Create(Form2);
CheckBox1.Parent := Form2;
CheckBox1.Left := 16;
CheckBox1.Top := Label2.Top + Label2.Height + 8;
CheckBox1.Width := 120;
CheckBox1.Caption := ' Save Grid Positions';
//CheckBox1.State := cbChecked;
CheckBox1.TabOrder := 0;
// set CheckBox2 properties
CheckBox2 := TCheckBox.Create(Form2);
CheckBox2.Parent := Form2;
CheckBox2.Left := 16;
CheckBox2.Top := CheckBox1.Top + CheckBox1.Height + 4;
CheckBox2.Width := 130;
CheckBox2.Caption := ' Save Offset Positions';
//CheckBox2.State := cbChecked;
CheckBox2.TabOrder := 1;
// set CheckBox3 properties
CheckBox3 := TCheckBox.Create(Form2);
CheckBox3.Parent := Form2;
CheckBox3.Left := 16;
CheckBox3.Top := CheckBox2.Top + CheckBox2.Height + 4;
CheckBox3.Width := 110;
CheckBox3.Caption := ' Save Connections';
CheckBox3.TabOrder := 2;
// set Button9 properties
Button9 := TButton.Create(Form2);
Button9.Parent := Form2;
Button9.Height := 25;
Button9.Top := CheckBox3.Top + CheckBox3.Height + 16;
Button9.Width := 100;
Button9.Left := Form2.Width div 2 - Button9.Width - 8;
Button9.Caption := 'OK';
Button9.ModalResult := mrOk;
Button9.TabOrder := 3;
// set Button10 properties
Button10 := TButton.Create(Form2);
Button10.Parent := Form2;
Button10.Height := 25;
Button10.Top := Button9.Top;
Button10.Left := Button9.Left + Button9.Width + 8;
Button10.Width := 100;
Button10.Caption := 'Cancel';
Button10.ModalResult := mrCancel;
Button10.TabOrder := 4;
if Form2.ShowModal = mrOk then begin
if CheckBox1.State = cbChecked then b1 := true;
if CheckBox2.State = cbChecked then b2 := true;
if CheckBox3.State = cbChecked then b3 := true;
SavePerkTree(sp, b1, b2, b3);
end;
Finally
Form2.free;
end;
end;
//=========================================================================
// Create the UI Form
procedure OptionsForm(sp: IInterface);
begin
Form1 := TForm.Create(nil);
try
// set Form1 properties
Form1.Height := 716;
Form1.Width := 1064;
Form1.Position := poScreenCenter;
Form1.Caption := 'Perk Tree UI';
Form1.ClientHeight := 716;
Form1.ClientWidth := 1064;
// set Panel1 properties
Panel1 := TPanel.Create(Form1);
Panel1.Parent := Form1;
Panel1.Left := 16;
Panel1.Height := 580;
Panel1.Top := 16;
Panel1.Width := 1000;
Panel1.Caption := 'Panel1';
Panel1.ClientHeight := 580;
Panel1.ClientWidth := 1000;
Panel1.Color := clSilver;
Panel1.ParentColor := False;
Panel1.TabOrder := 0;
// set Image1 properties
Image1 := TImage.Create(Panel1);
Image1.Parent := Panel1;
Image1.Picture := background;
Image1.Left := 10;
Image1.Height := 560;
Image1.Top := 10;
Image1.Width := 980;
Image1.OnClick := Image1Click;
// set Image2 properties
Image2 := TImage.Create(Panel1);
Image2.Parent := Panel1;
Image2.Left := 10;
Image2.Height := 560;
Image2.Top := 10;
Image2.Width := 980;
Image2.Transparent := true;
Image2.Picture.Bitmap.TransparentColor := ColorTransparent;
Image2.Picture.Bitmap.Width := Image2.Width;
Image2.Picture.Bitmap.Height := Image2.Height;
Image2.OnClick := Image1Click;
RedrawBackground;
// set Button1 properties
Button1 := TButton.Create(Form1);
Button1.Parent := Form1;
Button1.Left := Panel1.Left;
Button1.Height := 25;
Button1.Top := Panel1.Top + Panel1.Height + 8;
Button1.Width := 128;
Button1.Caption := 'Show Connections';
Button1.OnClick := Button1Click;
Button1.TabOrder := 1;
// set Button2 properties
Button2 := TButton.Create(Form1);
Button2.Parent := Form1;
Button2.Left := Panel1.Left;
Button2.Height := 25;
Button2.Top := Button1.Top + Button1.Height + 5;
Button2.Width := 128;
Button2.Caption := 'Show Grid Lines';
Button2.OnClick := Button2Click;
Button2.ParentFont := False;
Button2.TabOrder := 2;
// set Button4 properties
Button4 := TButton.Create(Form1);
Button4.Parent := Form1;
Button4.Left := Button2.Left + Button2.Width + 8;
Button4.Height := 25;
Button4.Top := Button1.Top;
Button4.Width := 128;
Button4.Caption := 'Add Perk';
Button4.OnClick := Button4Click;
Button4.TabOrder := 4;
// set Button5 properties
Button5 := TButton.Create(Form1);
Button5.Parent := Form1;
Button5.Left := Button4.Left;
Button5.Height := 25;
Button5.Top := Button2.Top;
Button5.Width := 128;
Button5.Caption := 'Remove Perk';
Button5.Enabled := False;
Button5.OnClick := Button5Click;
Button5.TabOrder := 5;
// set Button6 properties
Button6 := TButton.Create(Form1);
Button6.Parent := Form1;
Button6.Left := Button5.Left + Button5.Width + 8;
Button6.Height := 25;
Button6.Top := Button1.Top;
Button6.Width := 128;
Button6.Caption := 'Create Connection';
Button6.OnClick := Button6Click;
Button6.TabOrder := 6;
// set Button7 properties
Button7 := TButton.Create(Form1);
Button7.Parent := Form1;
Button7.Left := Button6.Left;
Button7.Height := 25;
Button7.Top := Button2.Top;
Button7.Width := 128;
Button7.Caption := 'Remove Connection';
Button7.OnClick := Button7Click;
Button7.TabOrder := 7;
// set Button3 properties
Button3 := TButton.Create(Form1);
Button3.Parent := Form1;
Button3.Left := Button7.Left + Button7.Width + 8;
Button3.Height := 25;
Button3.Top := Button1.Top;
Button3.Width := 128;
Button3.Caption := 'Snap to Grid';
Button3.OnClick := Button3Click;
Button3.TabOrder := 3;
// set Button8 properties
Button8 := TButton.Create(Form1);
Button8.Parent := Form1;
Button8.Left := Button3.Left;
Button8.Height := 25;
Button8.Top := Button2.Top;
Button8.Width := 128;
Button8.Caption := 'Disable Movement';
Button8.OnClick := Button8Click;
Button8.TabOrder := 8;
// set Label1 properties
Label1 := TLabel.Create(Form1);
Label1.Parent := Form1;
Label1.Left := Panel1.Left;
Label1.Height := 16;
Label1.Top := Button2.Top + Button2.Height + 20;
Label1.Width := 92;
Label1.Caption := 'Maximum x-grid:';
// set Edit1 properties
Edit1 := TEdit.Create(Form1);
Edit1.Parent := Form1;
Edit1.Left := Label1.Left + Label1.Width + 8;
Edit1.Height := 23;
Edit1.Top := Label1.Top - 7;
Edit1.Width := 39;
Edit1.OnChange := Edit1Change;
Edit1.TabOrder := 10;
Edit1.Text := '14';
// set ComboBox1 properties
ComboBox1 := TComboBox.Create(Form1);
ComboBox1.Parent := Form1;
ComboBox1.Left := Edit1.Left + Edit1.Width + 16;
ComboBox1.Height := 23;
ComboBox1.Top := Edit1.Top;
ComboBox1.Width := 384;
ComboBox1.ItemHeight := 15;
ComboBox1.OnChange := ComboBox1Change;
ComboBox1.TabOrder := 11;
ComboBox1.Items.Text := slPerks.Text;
ComboBox1.Text := 'Choose Perk Here';
ComboBox1.Enabled := False;
if Assigned(sp) then
LoadPerkTree(sp);
if Form1.ShowModal = mrOk then begin
//stuff
end;
finally
if Assigned(sp) then
SaveDialog(sp);
Form1.Free;
end;
end;
//=========================================================================
// Initialize variables, pictures, and stringlists
function Initialize: Integer;
begin
// initialize array count variables
nct := 0;
cct := 0;
// load pictures
yPog := TPicture.Create;
yPog.LoadFromFile(ProgramPath + 'Edit Scripts\PerkTreeUI\Yellow_pog.png');
gPog := TPicture.Create;
gPog.LoadFromFile(ProgramPath + 'Edit Scripts\PerkTreeUI\Green_pog.png');
background := TPicture.Create;
background.LoadFromFile(ProgramPath + 'Edit Scripts\PerkTreeUI\starfield.bmp');
// create stringlists
slPerks := TStringList.Create;
slPerks.Sorted := true;
slBethesdaFiles := TStringList.Create;
// bethesda files
slBethesdaFiles.Add('Skyrim.esm');
slBethesdaFiles.Add('Update.esm');
slBethesdaFiles.Add('Dawnguard.esm');
slBethesdaFiles.Add('Hearthfires.esm');
slBethesdaFiles.Add('Dragonborn.esm');
slBethesdaFiles.Add('Skyrim.Hardcoded.keep.this.with.the.exe.and.otherwise.ignore.it.I.really.mean.it.dat');
// load perks stringlist
slPerks.AddObject('NULL - Null Reference [00000000]', TObject('00000000'));
for i := 0 to FileCount - 1 do begin
f := FileByIndex(i);
group := GroupBySignature(f, 'PERK');
for j := 0 to ElementCount(group) - 1 do begin
element := ElementByIndex(group, j);
slPerks.AddObject(Name(element), TObject(FormID(element)));
end;
end;
end;
//=========================================================================
// Process selected records for a suitable AVIF record with perk tree
function Process(e: IInterface): integer;
begin
if Signature(e) <> 'AVIF' then
exit;
if Assigned(StartingPerk) then
exit;
if slBethesdaFiles.IndexOf(GetFileName(GetFile(e))) > -1 then begin
bethfile := true;
exit;
end;
perktree := ElementByPath(e, 'Perk Tree');
if Assigned(perktree) then
StartingPerk := e;
end;
//=========================================================================
// Open UI
function Finalize: integer;
begin
if bethfile then begin
AddMessage(' You can''t edit perk trees in Bethesda master files.');
AddMessage(' Copy the AVIF record as override to a new file to edit it.');
exit;
end;
OptionsForm(StartingPerk);
background.Free;
gPog.Free;
yPog.Free;
slPerks.Free;
end;
end.
|
unit uRevision;
interface
uses
Classes,
SysUtils,
Contnrs,
DateUtils;
type
TRevision = class
private
FDateRevision: TDate;
FTauxRevision: Real;
function GetStrDate: string;
public
constructor Create(aDateRevision: TDate; aTauxRevision: Real);
property DateRevision: TDate Read FDateRevision write FDateRevision;
property TauxRevision: Real Read FTauxRevision write FTauxRevision;
property StrDateRevision: string read GetStrDate;
end;
TMensualite = class
private
FDateDu : TDate;
FDateAu : TDate;
FLoyerPrincipal: Real;
function GetDateDebut: string;
function GetDateFin: string;
function GetLoyerPrincipal: string;
public
constructor Create(aDateDu: TDate; aDateAu: TDate;
aLoyerPrincipale: Real);
property DateDu: TDate read FDateDu write FDateDu;
property DateAu: TDate read FDateAu write FDateAu;
property LoyerPrincipal: Real read FLoyerPrincipal write FLoyerPrincipal;
property strLoyerPrincipal: string read GetLoyerPrincipal;
property strDateDebut: string read GetDateDebut;
property strDateFin: string read GetDateFin;
end;
TListeRevision = class(TObjectList)
private
function GetItem(Index: Integer): TRevision;
procedure SetItem(Index: Integer; const Value: TRevision);
public
constructor Create(AOwner: TComponent);
function Add(AObject: TRevision): Integer;
procedure Insert(Index: Integer; AObject: TRevision);
property Items[Index: Integer]: TRevision read GetItem
write SetItem; default;
procedure CreerPeriodeRevisions;
function GetLoyer(aDatePeriode: TDate;
aDateReference: TDate;
aLoyerReference: Real): Real;
end;
TListeMensualite = class(TObjectList)
private
FListeRevision: TListeRevision;
FLoyerActuel : Real;
FDateDebut : TDate;
FDateFin : TDate;
function GetItem(Index: Integer): TMensualite;
procedure SetItem(Index: Integer; const Value: TMensualite);
public
constructor Create(); overload;
constructor Create(aLoyerActuel: Real;
aDateDebut: TDate;
aDateFin: TDate); overload;
destructor Destroy;
function Add(AObject: TMensualite): Integer;
procedure Insert(Index: Integer; AObject: TMensualite);
property Items[Index: Integer]: TMensualite read GetItem
write SetItem; default;
property LoyerActuel: Real read FLoyerActuel write FLoyerActuel;
property DateDebut: TDate read FDateDebut write FDateDebut;
property DateFin: TDate read FDateFin write FDateFin;
function Calculer: TListeMensualite;
end;
implementation
{ TRevision }
constructor TRevision.Create(aDateRevision: TDate; aTauxRevision: Real);
begin
FDateRevision := aDateRevision;
FTauxRevision := aTauxRevision;
end;
function TRevision.GetStrDate: string;
begin
Result := FormatDateTime('dd/MM/yyyy', DateRevision);
end;
{ TListeRevision }
constructor TListeRevision.Create(AOwner: TComponent);
begin
CreerPeriodeRevisions;
end;
procedure TListeRevision.CreerPeriodeRevisions;
begin
// Borne Inférieure
Self.Add(TRevision.Create(EncodeDate(1962, 7, 5), 0));
Self.Add(TRevision.Create(EncodeDate(1995, 4, 1), 10));
Self.Add(TRevision.Create(EncodeDate(1995, 12, 1), 10));
Self.Add(TRevision.Create(EncodeDate(1996, 6, 1), 10));
Self.Add(TRevision.Create(EncodeDate(1997, 3, 1), 20));
Self.Add(TRevision.Create(EncodeDate(1997, 11, 1), 15));
Self.Add(TRevision.Create(EncodeDate(1998, 8, 1), 20));
// Borne Supérieure jusqu'à ce jour
Self.Add(TRevision.Create(Date, 0));
end;
function TListeRevision.GetLoyer(aDatePeriode, aDateReference: TDate;
aLoyerReference: Real): Real;
var
DerniereDate: TDate;
I : Integer;
begin
for I := Self.Count - 1 downto 1 do
begin
aLoyerReference := aLoyerReference * (1 - (Self[I].TauxRevision / 100));
Result := aLoyerReference;
if DateInRange(aDatePeriode, Self[I - 1].FDateRevision,
Self[I].FDateRevision) then
Break;
end;
end;
function TListeRevision.GetItem(Index: Integer): TRevision;
begin
Result := TRevision(inherited GetItem(index));
end;
function TListeRevision.Add(AObject: TRevision): Integer;
begin
Result := inherited Add(AObject);
end;
procedure TListeRevision.Insert(Index: Integer; AObject: TRevision);
begin
inherited Insert(index, AObject);
end;
procedure TListeRevision.SetItem(Index: Integer; const Value: TRevision);
begin
inherited SetItem(index, Value);
end;
{ TMensualite }
constructor TMensualite.Create(aDateDu, aDateAu: TDate;
aLoyerPrincipale: Real);
begin
FDateDu := StartOfTheMonth(aDateDu);
FDateAu := EndOfTheMonth(aDateAu);
FLoyerPrincipal := aLoyerPrincipale;
end;
function TMensualite.GetDateDebut: string;
begin
Result := FormatDateTime('dd/MM/yyyy', FDateDu);
end;
function TMensualite.GetDateFin: string;
begin
Result := FormatDateTime('dd/MM/yyyy', FDateAu);
end;
function TMensualite.GetLoyerPrincipal: string;
begin
Result := FormatFloat('#,##0.00', FLoyerPrincipal);
end;
{ TListeMensualite }
function TListeMensualite.Add(AObject: TMensualite): Integer;
begin
Result := inherited Add(AObject);
end;
function TListeMensualite.Calculer: TListeMensualite;
var
NbrMois : Integer;
I : Integer;
Mensualite : TMensualite;
DateMensualite : TDate;
LoyerMensualite: Real;
begin
DateMensualite := DateFin;
NbrMois := MonthsBetween(DateFin, DateDebut) + 1;
for I := 0 to NbrMois do
begin
LoyerMensualite := FListeRevision.GetLoyer(IncMonth(DateDebut, I),
DateMensualite,
LoyerActuel);
Mensualite := TMensualite.Create(IncMonth(DateDebut, I),
IncMonth(DateDebut, I), LoyerMensualite);
Self.Add(Mensualite);
end;
Result := Self;
end;
constructor TListeMensualite.Create;
begin
FListeRevision := TListeRevision.Create(nil);
end;
constructor TListeMensualite.Create(aLoyerActuel: Real;
aDateDebut: TDate;
aDateFin: TDate);
begin
FListeRevision := TListeRevision.Create(nil);
FLoyerActuel := aLoyerActuel;
FDateDebut := aDateDebut;
FDateFin := aDateFin;
Calculer;
end;
destructor TListeMensualite.Destroy;
begin
FListeRevision.Free;
end;
function TListeMensualite.GetItem(Index: Integer): TMensualite;
begin
Result := TMensualite(inherited GetItem(Index));
end;
procedure TListeMensualite.Insert(Index: Integer; AObject: TMensualite);
begin
inherited Insert(Index, AObject);
end;
procedure TListeMensualite.SetItem(Index: Integer; const Value: TMensualite);
begin
inherited SetItem(Index, Value);
end;
end.
|
unit model.Loja;
interface
uses
UConstantes,
app.Funcoes,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants;
type
TLoja = class(TObject)
private
aID : TGUID;
aCodigo : Currency;
aNome ,
aFantasia,
aCpfCnpj : String;
procedure SetNome(Value : String);
procedure SetFantasia(Value : String);
procedure SetCpfCnpj(Value : String);
function GetTipo : TTipoLoja;
function GetCpfCnpj : String;
public
constructor Create; overload;
property ID : TGUID read aID write aID;
property Codigo : Currency read aCodigo write aCodigo;
property Tipo : TTipoLoja read GetTipo;
property Nome : String read aNome write SetNome;
property Fantasia : String read aFantasia write SetFantasia;
property CpfCnpj : String read GetCpfCnpj write aCpfCnpj;
procedure NewID;
function ToString : String; override;
end;
TLOjas = Array of TLoja;
implementation
{ TLoja }
constructor TLoja.Create;
begin
inherited Create;
aId := GUID_NULL;
aCodigo := 0;
aNome := EmptyStr;
aFantasia := EmptyStr;
aCpfCnpj := EmptyStr;
end;
function TLoja.GetCpfCnpj: String;
begin
Result := aCpfCnpj;
end;
function TLoja.GetTipo: TTipoLoja;
begin
if StrIsCNPJ(aCpfCnpj) then
Result := TTipoCliente.tcPessoaJuridica
else
Result := TTipoCliente.tcPessoaFisica;
end;
procedure TLoja.NewID;
var
aGuid : TGUID;
begin
CreateGUID(aGuid);
aId := aGuid;
end;
procedure TLoja.SetCpfCnpj(Value: String);
var
aStr : String;
begin
aStr := SomenteNumero(AnsiLowerCase(Trim(Value)));
if StrIsCPF(aStr) then
aCpfCnpj := FormatarTexto('999.999.999-99;0', aStr)
else
if StrIsCNPJ(aStr) then
aCpfCnpj := FormatarTexto('99.999.999/9999-99;0', aStr)
else
aCpfCnpj := EmptyStr;
end;
procedure TLoja.SetFantasia(Value: String);
begin
aFantasia := Trim(Value);
end;
procedure TLoja.SetNome(Value: String);
begin
aNome := Trim(Value);
end;
function TLoja.ToString: String;
begin
Result := aFantasia + ' (' + aCpfCnpj + ')';
end;
end.
|
unit uCalculatorTests;
interface
uses
uCalculator
, DUnitX.TestFramework
;
type
[TestFixture]
TCalculatorTests = class
private
Expected, Actual: integer;
Calculator: TCalculator;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestSimpleAddition;
[Test]
procedure TestAddingZero;
[Test]
procedure TestAddingTwoNegativeNumbers;
end;
implementation
{ TCalculatorTests }
procedure TCalculatorTests.Setup;
begin
Calculator := TCalculator.Create;
end;
procedure TCalculatorTests.TearDown;
begin
Calculator.Free;
end;
procedure TCalculatorTests.TestSimpleAddition;
begin
Expected := 4;
Actual := Calculator.Add(2, 2);
Assert.AreEqual(Expected, Actual, 'The calculator thinks that 2 + 2 is not 4!');
end;
procedure TCalculatorTests.TestAddingTwoNegativeNumbers;
begin
Expected := -4;
Actual := Calculator.Add(-2, -2);
Assert.AreEqual(Expected, Actual, 'The Add function failed to realize that -2 + -2 is -4');
end;
procedure TCalculatorTests.TestAddingZero;
begin
Expected := 4;
Actual := Calculator.Add(4, 0);
Assert.AreEqual(Expected, Actual, 'The calculator thinks that 4 + 0 is not 4!');
end;
initialization
TDUnitX.RegisterTestFixture(TCalculatorTests);
end.
|
(*
Copyright 2016 Michael Justin
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 LazLoggerTests;
interface
uses
{$IFDEF FPC}
fpcunit,testregistry
{$ELSE}
TestFramework
{$ENDIF};
type
{ TLazLoggerTests }
TLazLoggerTests = class(TTestCase)
published
procedure CreateLogger;
procedure TestDebug;
procedure TestInfo;
procedure TestWriteFile;
end;
implementation
uses
djLogAPI, LazLoggerLogger,
LazLogger,
SysUtils;
{ TLazLoggerTests }
procedure TLazLoggerTests.CreateLogger;
var
LoggerFactory: ILoggerFactory;
Logger: ILogger;
begin
LoggerFactory := TLazLoggerFactory.Create;
Logger := LoggerFactory.GetLogger('lazlogger1');
CheckEquals('lazlogger1', Logger.Name);
end;
procedure TLazLoggerTests.TestDebug;
var
LoggerFactory: ILoggerFactory;
Logger: ILogger;
E: EAbort;
begin
LoggerFactory := TLazLoggerFactory.Create;
Logger := LoggerFactory.GetLogger('lazlogger2');
Logger.Debug('log4d msg');
Logger.Debug('log4d msg', ['a', 2, Date]);
E := EAbort.Create('example');
Logger.Debug('log4d msg', E);
E.Free;
end;
procedure TLazLoggerTests.TestInfo;
var
LoggerFactory: ILoggerFactory;
Logger: ILogger;
E: EAbort;
begin
LoggerFactory := TLazLoggerFactory.Create;
Logger := LoggerFactory.GetLogger('lazlogger3');
Logger.Info('simple msg');
Logger.Info('simple msg', ['a', 2, Date]);
E := EAbort.Create('simple example exception');
Logger.Info('simple msg', E);
E.Free;
end;
procedure TLazLoggerTests.TestWriteFile;
var
LoggerFactory: ILoggerFactory;
Logger: ILogger;
begin
LoggerFactory := TLazLoggerFactory.Create;
Logger := LoggerFactory.GetLogger('lazlogger4');
DebugLogger.LogName := 'lazlogger.log';
Logger.Info('logged to lazlogger.log');
end;
end.
|
Unit Soundex;
INTERFACE
Const
{ Signatures des fichiers RIFF/WAVE }
RiffSignature='RIFF';
WaveSignature='WAVE';
FmtSignature='fmt ';
DataSignature='data';
Type
RiffFile=Record
rID:Array [0..3]of Char; { 0 … 3: Toujours "RIFF"}
rLen:LongInt; { 4 … 7: Taille des donn‚es}
wID:Array [0..3]of Char; { 8 … 11: Toujours "WAVE"}
fID:Array [0..3]of Char; { 9 … 15: Toujours "fmt "}
fLen:LongInt; { 16 … 19: Taille des donn‚es dans le format }
wFormatTag:Word; { 20 … 21: *}
nChannels:Word; { 22 … 23: Nombre de canal}
nSamplesPerSec:Word; { 24 … 25: Fr‚quence d'un "Sample"}
nAvgBytesPerSec:Word; { 26 … 27: **}
nBlockAlign:Word; { 28 … 29: ***}
FormatSpecific:Word; { 30 … 31: Format specifique … la r‚gion de donn‚e}
Dummy:LongInt; { 32 … 35 }
dID:Array[0..3]of Char; { 36 … 39: Toujours "data"}
dLen:LongInt; { 40 … 43: Taille des donn‚es}
dData:Pointer; { 44 … 47: Forme de donn‚e Wave actuel}
End;
Const
{Signature d'un fichier VOC de ®Creative Labs¯ }
VocSign='Creative Voice File'+#$1A;
Type
{Entˆte d'un fichier de format VOC de ®Creative Labs¯ }
VocHeader=Record
Sign:Array[0..19]of Char; { 0 … 19: Signature }
SampOff:Word; { 20 … 21 }
VersLo:Byte; { 22 }
VersHi:Byte; { 23 }
{IdentCode:Word; { 24 … 25 }
End;
VoiceBlock=Record
IdentCode:Byte; { 0: Code d'identification }
LongLo:Word; { 1 … 2: Longueur de "Sample" }
LongHi:Byte; { 3: Longueur de "Sample"}
X:Record Case Byte Of
1:(TimeConstant:Byte; { 4: Temps = 256 - 1000000 / "Sample" }
PackType:Byte); { 5: Type de packet: }
{ 0 = 8 bits sans packet }
{ 1 = 4 bits en packet }
{ 2 = 2,6 bits en packet }
{ 3 = 2 bits en packet}
2:(W:Word); { 4 … 5 }
End;
End;
IMPLEMENTATION
END. |
unit uWeatherData;
interface
uses uObserverPatternInterfaces
, Generics.Collections
;
type
TWeatherStation = class(TInterfacedObject, ISubject)
private
FTemperature: integer;
FHumidity: integer;
FPressure: double;
FObserverList: TList<IObserver>;
function GetTemperature: integer;
function GetHumidity: integer;
function GetPressure: double;
public
constructor Create;
destructor Destroy; override;
procedure SetWeatherInformation(aTemperature: integer; aHumidity: integer; aPressure: double);
procedure RegisterObserver(aObserver: IObserver);
procedure RemoveObserver(aObserver: IObserver);
procedure NotifyObservers;
procedure MeasurementsChanged;
property Temperature: integer read GetTemperature;
property Humidity: integer read GetHumidity;
property Pressure: double read GetPressure;
end;
implementation
{ TWeatherData }
constructor TWeatherStation.Create;
begin
inherited Create;
FObserverList := TList<IObserver>.Create;
end;
destructor TWeatherStation.Destroy;
begin
FObserverList.Free;
inherited;
end;
function TWeatherStation.GetHumidity: integer;
begin
Result := FHumidity;
end;
function TWeatherStation.GetPressure: double;
begin
Result := FPressure;
end;
function TWeatherStation.GetTemperature: integer;
begin
Result := FTemperature;
end;
procedure TWeatherStation.MeasurementsChanged;
begin
NotifyObservers;
end;
procedure TWeatherStation.NotifyObservers;
var
Observer: IObserver;
begin
for Observer in FObserverList do
begin
Observer.Update(Temperature, Humidity, Pressure);
end;
end;
procedure TWeatherStation.RegisterObserver(aObserver: IObserver);
begin
FObserverList.Add(aObserver);
end;
procedure TWeatherStation.RemoveObserver(aObserver: IObserver);
begin
FObserverList.Remove(aObserver);
end;
procedure TWeatherStation.SetWeatherInformation(aTemperature, aHumidity: integer; aPressure: double);
begin
FTemperature := aTemperature;
FHumidity := aHumidity;
FPressure := aPressure;
MeasurementsChanged;
end;
end.
|
unit WebSocket;
interface
type
HCkBinData = Pointer;
HCkRest = Pointer;
HCkString = Pointer;
HCkStringBuilder = Pointer;
HCkWebSocket = Pointer;
HCkTask = Pointer;
function CkWebSocket_Create: HCkWebSocket; stdcall;
procedure CkWebSocket_Dispose(handle: HCkWebSocket); stdcall;
function CkWebSocket_getCloseAutoRespond(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_putCloseAutoRespond(objHandle: HCkWebSocket; newPropVal: wordbool); stdcall;
procedure CkWebSocket_getCloseReason(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__closeReason(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_getCloseReceived(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_getCloseStatusCode(objHandle: HCkWebSocket): Integer; stdcall;
procedure CkWebSocket_getDebugLogFilePath(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
procedure CkWebSocket_putDebugLogFilePath(objHandle: HCkWebSocket; newPropVal: PWideChar); stdcall;
function CkWebSocket__debugLogFilePath(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_getFinalFrame(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_getFrameDataLen(objHandle: HCkWebSocket): Integer; stdcall;
procedure CkWebSocket_getFrameOpcode(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__frameOpcode(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_getFrameOpcodeInt(objHandle: HCkWebSocket): Integer; stdcall;
function CkWebSocket_getIdleTimeoutMs(objHandle: HCkWebSocket): Integer; stdcall;
procedure CkWebSocket_putIdleTimeoutMs(objHandle: HCkWebSocket; newPropVal: Integer); stdcall;
function CkWebSocket_getIsConnected(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_getLastErrorHtml(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__lastErrorHtml(objHandle: HCkWebSocket): PWideChar; stdcall;
procedure CkWebSocket_getLastErrorText(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__lastErrorText(objHandle: HCkWebSocket): PWideChar; stdcall;
procedure CkWebSocket_getLastErrorXml(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__lastErrorXml(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_getLastMethodSuccess(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_putLastMethodSuccess(objHandle: HCkWebSocket; newPropVal: wordbool); stdcall;
function CkWebSocket_getNeedSendPong(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_getPingAutoRespond(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_putPingAutoRespond(objHandle: HCkWebSocket; newPropVal: wordbool); stdcall;
function CkWebSocket_getPongAutoConsume(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_putPongAutoConsume(objHandle: HCkWebSocket; newPropVal: wordbool); stdcall;
function CkWebSocket_getPongConsumed(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_getReadFrameFailReason(objHandle: HCkWebSocket): Integer; stdcall;
function CkWebSocket_getVerboseLogging(objHandle: HCkWebSocket): wordbool; stdcall;
procedure CkWebSocket_putVerboseLogging(objHandle: HCkWebSocket; newPropVal: wordbool); stdcall;
procedure CkWebSocket_getVersion(objHandle: HCkWebSocket; outPropVal: HCkString); stdcall;
function CkWebSocket__version(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_AddClientHeaders(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_CloseConnection(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_GetFrameData(objHandle: HCkWebSocket; outStr: HCkString): wordbool; stdcall;
function CkWebSocket__getFrameData(objHandle: HCkWebSocket): PWideChar; stdcall;
function CkWebSocket_GetFrameDataBd(objHandle: HCkWebSocket; binData: HCkBinData): wordbool; stdcall;
function CkWebSocket_GetFrameDataSb(objHandle: HCkWebSocket; sb: HCkStringBuilder): wordbool; stdcall;
function CkWebSocket_PollDataAvailable(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_ReadFrame(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_ReadFrameAsync(objHandle: HCkWebSocket): HCkTask; stdcall;
function CkWebSocket_SaveLastError(objHandle: HCkWebSocket; path: PWideChar): wordbool; stdcall;
function CkWebSocket_SendClose(objHandle: HCkWebSocket; includeStatus: wordbool; statusCode: Integer; reason: PWideChar): wordbool; stdcall;
function CkWebSocket_SendCloseAsync(objHandle: HCkWebSocket; includeStatus: wordbool; statusCode: Integer; reason: PWideChar): HCkTask; stdcall;
function CkWebSocket_SendFrame(objHandle: HCkWebSocket; stringToSend: PWideChar; finalFrame: wordbool): wordbool; stdcall;
function CkWebSocket_SendFrameAsync(objHandle: HCkWebSocket; stringToSend: PWideChar; finalFrame: wordbool): HCkTask; stdcall;
function CkWebSocket_SendFrameBd(objHandle: HCkWebSocket; bdToSend: HCkBinData; finalFrame: wordbool): wordbool; stdcall;
function CkWebSocket_SendFrameBdAsync(objHandle: HCkWebSocket; bdToSend: HCkBinData; finalFrame: wordbool): HCkTask; stdcall;
function CkWebSocket_SendFrameSb(objHandle: HCkWebSocket; sbToSend: HCkStringBuilder; finalFrame: wordbool): wordbool; stdcall;
function CkWebSocket_SendFrameSbAsync(objHandle: HCkWebSocket; sbToSend: HCkStringBuilder; finalFrame: wordbool): HCkTask; stdcall;
function CkWebSocket_SendPing(objHandle: HCkWebSocket; pingData: PWideChar): wordbool; stdcall;
function CkWebSocket_SendPingAsync(objHandle: HCkWebSocket; pingData: PWideChar): HCkTask; stdcall;
function CkWebSocket_SendPong(objHandle: HCkWebSocket): wordbool; stdcall;
function CkWebSocket_SendPongAsync(objHandle: HCkWebSocket): HCkTask; stdcall;
function CkWebSocket_UseConnection(objHandle: HCkWebSocket; connection: HCkRest): wordbool; stdcall;
function CkWebSocket_ValidateServerHandshake(objHandle: HCkWebSocket): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkWebSocket_Create; external DLLName;
procedure CkWebSocket_Dispose; external DLLName;
function CkWebSocket_getCloseAutoRespond; external DLLName;
procedure CkWebSocket_putCloseAutoRespond; external DLLName;
procedure CkWebSocket_getCloseReason; external DLLName;
function CkWebSocket__closeReason; external DLLName;
function CkWebSocket_getCloseReceived; external DLLName;
function CkWebSocket_getCloseStatusCode; external DLLName;
procedure CkWebSocket_getDebugLogFilePath; external DLLName;
procedure CkWebSocket_putDebugLogFilePath; external DLLName;
function CkWebSocket__debugLogFilePath; external DLLName;
function CkWebSocket_getFinalFrame; external DLLName;
function CkWebSocket_getFrameDataLen; external DLLName;
procedure CkWebSocket_getFrameOpcode; external DLLName;
function CkWebSocket__frameOpcode; external DLLName;
function CkWebSocket_getFrameOpcodeInt; external DLLName;
function CkWebSocket_getIdleTimeoutMs; external DLLName;
procedure CkWebSocket_putIdleTimeoutMs; external DLLName;
function CkWebSocket_getIsConnected; external DLLName;
procedure CkWebSocket_getLastErrorHtml; external DLLName;
function CkWebSocket__lastErrorHtml; external DLLName;
procedure CkWebSocket_getLastErrorText; external DLLName;
function CkWebSocket__lastErrorText; external DLLName;
procedure CkWebSocket_getLastErrorXml; external DLLName;
function CkWebSocket__lastErrorXml; external DLLName;
function CkWebSocket_getLastMethodSuccess; external DLLName;
procedure CkWebSocket_putLastMethodSuccess; external DLLName;
function CkWebSocket_getNeedSendPong; external DLLName;
function CkWebSocket_getPingAutoRespond; external DLLName;
procedure CkWebSocket_putPingAutoRespond; external DLLName;
function CkWebSocket_getPongAutoConsume; external DLLName;
procedure CkWebSocket_putPongAutoConsume; external DLLName;
function CkWebSocket_getPongConsumed; external DLLName;
function CkWebSocket_getReadFrameFailReason; external DLLName;
function CkWebSocket_getVerboseLogging; external DLLName;
procedure CkWebSocket_putVerboseLogging; external DLLName;
procedure CkWebSocket_getVersion; external DLLName;
function CkWebSocket__version; external DLLName;
function CkWebSocket_AddClientHeaders; external DLLName;
function CkWebSocket_CloseConnection; external DLLName;
function CkWebSocket_GetFrameData; external DLLName;
function CkWebSocket__getFrameData; external DLLName;
function CkWebSocket_GetFrameDataBd; external DLLName;
function CkWebSocket_GetFrameDataSb; external DLLName;
function CkWebSocket_PollDataAvailable; external DLLName;
function CkWebSocket_ReadFrame; external DLLName;
function CkWebSocket_ReadFrameAsync; external DLLName;
function CkWebSocket_SaveLastError; external DLLName;
function CkWebSocket_SendClose; external DLLName;
function CkWebSocket_SendCloseAsync; external DLLName;
function CkWebSocket_SendFrame; external DLLName;
function CkWebSocket_SendFrameAsync; external DLLName;
function CkWebSocket_SendFrameBd; external DLLName;
function CkWebSocket_SendFrameBdAsync; external DLLName;
function CkWebSocket_SendFrameSb; external DLLName;
function CkWebSocket_SendFrameSbAsync; external DLLName;
function CkWebSocket_SendPing; external DLLName;
function CkWebSocket_SendPingAsync; external DLLName;
function CkWebSocket_SendPong; external DLLName;
function CkWebSocket_SendPongAsync; external DLLName;
function CkWebSocket_UseConnection; external DLLName;
function CkWebSocket_ValidateServerHandshake; external DLLName;
end.
|
unit DCPcast256;
{$MODE Delphi}
interface
uses
Classes, Sysutils, Crypto;
type
TCipherCAST256= class(TCipher)
protected
Kr, Km: array[0..11,0..3] of DWord;
procedure InitKey(const Key; Size: longword); override;
public
destructor Destroy; override;
class function Algorithm: TCipherAlgorithm; override;
class function MaxKeySize: integer; override;
class function SelfTest: boolean; override;
class function BlockSize: Integer; override;
procedure EncryptBlock(const InData; var OutData); override;
procedure DecryptBlock(const InData; var OutData); override;
end;
implementation
{$R-}{$Q-}
{$I DCPcast256.inc}
function LRot32(a, n: dword): dword;
begin
Result:= (a shl n) or (a shr (32-n));
end;
function SwapDword(a: dword): dword;
begin
Result:= ((a and $FF) shl 24) or ((a and $FF00) shl 8) or ((a and $FF0000) shr 8) or ((a and $FF000000) shr 24);
end;
function F1(a,rk,mk: DWord): DWord;
var
t: DWord;
begin
t:= LRot32(mk + a,rk);
Result:= ((S1[t shr 24] xor S2[(t shr 16) and $FF]) - S3[(t shr 8) and $FF]) + S4[t and $FF];
end;
function F2(a,rk,mk: DWord): DWord;
var
t: DWord;
begin
t:= LRot32(mk xor a,rk);
Result:= ((S1[t shr 24] - S2[(t shr 16) and $FF]) + S3[(t shr 8) and $FF]) xor S4[t and $FF];
end;
function F3(a,rk,mk: DWord): DWord;
var
t: DWord;
begin
t:= LRot32(mk - a,rk);
Result:= ((S1[t shr 24] + S2[(t shr 16) and $FF]) xor S3[(t shr 8) and $FF]) - S4[t and $FF];
end;
destructor TCipherCAST256.Destroy;
begin
FillChar(Kr,Sizeof(Kr),$FF);
FillChar(Km,Sizeof(Km),$FF);
inherited Destroy;
end;
class function TCipherCAST256.MaxKeySize: integer;
begin
Result:= 256;
end;
class function TCipherCAST256.BlockSize: Integer;
begin
Result := 128;
end;
class function TCipherCAST256.Algorithm: TCipherAlgorithm;
begin
Result:= caCast256;
end;
class function TCipherCAST256.SelfTest: boolean;
const
Key1: array[0..15] of byte=
($23,$42,$bb,$9e,$fa,$38,$54,$2c,$0a,$f7,$56,$47,$f2,$9f,$61,$5d);
InBlock1: array[0..15] of byte=
($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$0c,$9b,$28,$07);
OutBlock1: array[0..15] of byte=
($96,$3a,$8a,$50,$ce,$b5,$4d,$08,$e0,$de,$e0,$f1,$d0,$41,$3d,$cf);
Key2: array[0..23] of byte=
($23,$42,$bb,$9e,$fa,$38,$54,$2c,$be,$d0,$ac,$83,$94,$0a,$c2,$98,$ba,$c7,$7a,$77,$17,$94,$28,$63);
InBlock2: array[0..15] of byte=
($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$de,$25,$5a,$ff);
OutBlock2: array[0..15] of byte=
($2b,$c1,$92,$9f,$30,$13,$47,$a9,$9d,$3f,$3e,$45,$ad,$34,$01,$e8);
Key3: array[0..31] of byte=
($23,$42,$bb,$9e,$fa,$38,$54,$2c,$be,$d0,$ac,$83,$94,$0a,$c2,$98,$8d,$7c,$47,$ce,$26,$49,$08,$46,$1c,$c1,$b5,$13,$7a,$e6,$b6,$04);
InBlock3: array[0..15] of byte=
($00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$c5,$fc,$eb,$19);
OutBlock3: array[0..15] of byte=
($1e,$2e,$bc,$6c,$9f,$2e,$43,$8e,$1d,$90,$d9,$b9,$c6,$85,$32,$86);
var
Block: array[0..15] of byte;
Cipher: TCipherCAST256;
begin
FillChar(Block, SizeOf(Block), 0);
Cipher:= TCipherCAST256.Create(@Key1,SizeOf(Key1) * 8);
Cipher.EncryptBlock(InBlock1,Block);
Result:= boolean(CompareMem(@Block,@OutBlock1,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock1,16));
Cipher.Free;
Cipher := TCipherCAST256.Create(@Key2,SizeOf(Key2) * 8);
Cipher.EncryptBlock(InBlock2,Block);
Result:= Result and boolean(CompareMem(@Block,@OutBlock2,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock2,16));
Cipher.Free;
Cipher := TCipherCAST256.Create(@Key3,Sizeof(Key3)*8);
Cipher.EncryptBlock(InBlock3,Block);
Result:= Result and boolean(CompareMem(@Block,@OutBlock3,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock3,16));
Cipher.Free;
end;
procedure TCipherCAST256.InitKey(const Key; Size: longword);
var
x: array[0..7] of DWord;
cm, cr: DWord;
i, j: longword;
tr, tm: array[0..7] of DWord;
begin
Size:= Size div 8;
FillChar(x,Sizeof(x),0);
Move(Key,x,Size);
cm:= $5a827999;
cr:= 19;
for i:= 0 to 7 do
x[i]:= (x[i] shl 24) or ((x[i] shl 8) and $FF0000) or ((x[i] shr 8) and $FF00) or (x[i] shr 24);
for i:= 0 to 11 do
begin
for j:= 0 to 7 do
begin
tm[j]:= cm;
Inc(cm,$6ed9eba1);
tr[j]:= cr;
Inc(cr,17);
end;
x[6]:= x[6] xor f1(x[7],tr[0],tm[0]);
x[5]:= x[5] xor f2(x[6],tr[1],tm[1]);
x[4]:= x[4] xor f3(x[5],tr[2],tm[2]);
x[3]:= x[3] xor f1(x[4],tr[3],tm[3]);
x[2]:= x[2] xor f2(x[3],tr[4],tm[4]);
x[1]:= x[1] xor f3(x[2],tr[5],tm[5]);
x[0]:= x[0] xor f1(x[1],tr[6],tm[6]);
x[7]:= x[7] xor f2(x[0],tr[7],tm[7]);
for j:= 0 to 7 do
begin
tm[j]:= cm;
Inc(cm,$6ed9eba1);
tr[j]:= cr;
Inc(cr,17);
end;
x[6]:= x[6] xor f1(x[7],tr[0],tm[0]);
x[5]:= x[5] xor f2(x[6],tr[1],tm[1]);
x[4]:= x[4] xor f3(x[5],tr[2],tm[2]);
x[3]:= x[3] xor f1(x[4],tr[3],tm[3]);
x[2]:= x[2] xor f2(x[3],tr[4],tm[4]);
x[1]:= x[1] xor f3(x[2],tr[5],tm[5]);
x[0]:= x[0] xor f1(x[1],tr[6],tm[6]);
x[7]:= x[7] xor f2(x[0],tr[7],tm[7]);
Kr[i,0]:= x[0] and 31;
Kr[i,1]:= x[2] and 31;
Kr[i,2]:= x[4] and 31;
Kr[i,3]:= x[6] and 31;
Km[i,0]:= x[7];
Km[i,1]:= x[5];
Km[i,2]:= x[3];
Km[i,3]:= x[1];
end;
FillChar(x,Sizeof(x),$FF);
end;
procedure TCipherCAST256.EncryptBlock(const InData; var OutData);
var
A: array[0..3] of DWord;
begin
A[0]:= PDWord(@InData)^;
A[1]:= PDWord(pointer(@InData)+4)^;
A[2]:= PDWord(pointer(@InData)+8)^;
A[3]:= PDWord(pointer(@InData)+12)^;
A[0]:= SwapDWord(A[0]);
A[1]:= SwapDWord(A[1]);
A[2]:= SwapDWord(A[2]);
A[3]:= SwapDWord(A[3]);
A[2]:= A[2] xor f1(A[3],kr[0,0],km[0,0]);
A[1]:= A[1] xor f2(A[2],kr[0,1],km[0,1]);
A[0]:= A[0] xor f3(A[1],kr[0,2],km[0,2]);
A[3]:= A[3] xor f1(A[0],kr[0,3],km[0,3]);
A[2]:= A[2] xor f1(A[3],kr[1,0],km[1,0]);
A[1]:= A[1] xor f2(A[2],kr[1,1],km[1,1]);
A[0]:= A[0] xor f3(A[1],kr[1,2],km[1,2]);
A[3]:= A[3] xor f1(A[0],kr[1,3],km[1,3]);
A[2]:= A[2] xor f1(A[3],kr[2,0],km[2,0]);
A[1]:= A[1] xor f2(A[2],kr[2,1],km[2,1]);
A[0]:= A[0] xor f3(A[1],kr[2,2],km[2,2]);
A[3]:= A[3] xor f1(A[0],kr[2,3],km[2,3]);
A[2]:= A[2] xor f1(A[3],kr[3,0],km[3,0]);
A[1]:= A[1] xor f2(A[2],kr[3,1],km[3,1]);
A[0]:= A[0] xor f3(A[1],kr[3,2],km[3,2]);
A[3]:= A[3] xor f1(A[0],kr[3,3],km[3,3]);
A[2]:= A[2] xor f1(A[3],kr[4,0],km[4,0]);
A[1]:= A[1] xor f2(A[2],kr[4,1],km[4,1]);
A[0]:= A[0] xor f3(A[1],kr[4,2],km[4,2]);
A[3]:= A[3] xor f1(A[0],kr[4,3],km[4,3]);
A[2]:= A[2] xor f1(A[3],kr[5,0],km[5,0]);
A[1]:= A[1] xor f2(A[2],kr[5,1],km[5,1]);
A[0]:= A[0] xor f3(A[1],kr[5,2],km[5,2]);
A[3]:= A[3] xor f1(A[0],kr[5,3],km[5,3]);
A[3]:= A[3] xor f1(A[0],kr[6,3],km[6,3]);
A[0]:= A[0] xor f3(A[1],kr[6,2],km[6,2]);
A[1]:= A[1] xor f2(A[2],kr[6,1],km[6,1]);
A[2]:= A[2] xor f1(A[3],kr[6,0],km[6,0]);
A[3]:= A[3] xor f1(A[0],kr[7,3],km[7,3]);
A[0]:= A[0] xor f3(A[1],kr[7,2],km[7,2]);
A[1]:= A[1] xor f2(A[2],kr[7,1],km[7,1]);
A[2]:= A[2] xor f1(A[3],kr[7,0],km[7,0]);
A[3]:= A[3] xor f1(A[0],kr[8,3],km[8,3]);
A[0]:= A[0] xor f3(A[1],kr[8,2],km[8,2]);
A[1]:= A[1] xor f2(A[2],kr[8,1],km[8,1]);
A[2]:= A[2] xor f1(A[3],kr[8,0],km[8,0]);
A[3]:= A[3] xor f1(A[0],kr[9,3],km[9,3]);
A[0]:= A[0] xor f3(A[1],kr[9,2],km[9,2]);
A[1]:= A[1] xor f2(A[2],kr[9,1],km[9,1]);
A[2]:= A[2] xor f1(A[3],kr[9,0],km[9,0]);
A[3]:= A[3] xor f1(A[0],kr[10,3],km[10,3]);
A[0]:= A[0] xor f3(A[1],kr[10,2],km[10,2]);
A[1]:= A[1] xor f2(A[2],kr[10,1],km[10,1]);
A[2]:= A[2] xor f1(A[3],kr[10,0],km[10,0]);
A[3]:= A[3] xor f1(A[0],kr[11,3],km[11,3]);
A[0]:= A[0] xor f3(A[1],kr[11,2],km[11,2]);
A[1]:= A[1] xor f2(A[2],kr[11,1],km[11,1]);
A[2]:= A[2] xor f1(A[3],kr[11,0],km[11,0]);
A[0]:= SwapDWord(A[0]);
A[1]:= SwapDWord(A[1]);
A[2]:= SwapDWord(A[2]);
A[3]:= SwapDWord(A[3]);
PDWord(@OutData)^:= A[0];
PDWord(pointer(@OutData)+4)^:= A[1];
PDWord(pointer(@OutData)+8)^:= A[2];
PDWord(pointer(@OutData)+12)^:= A[3];
end;
procedure TCipherCAST256.DecryptBlock(const InData; var OutData);
var
A: array[0..3] of DWord;
begin
A[0]:= PDWord(@InData)^;
A[1]:= PDWord(pointer(@InData)+4)^;
A[2]:= PDWord(pointer(@InData)+8)^;
A[3]:= PDWord(pointer(@InData)+12)^;
A[0]:= SwapDWord(A[0]);
A[1]:= SwapDWord(A[1]);
A[2]:= SwapDWord(A[2]);
A[3]:= SwapDWord(A[3]);
A[2]:= A[2] xor f1(A[3],kr[11,0],km[11,0]);
A[1]:= A[1] xor f2(A[2],kr[11,1],km[11,1]);
A[0]:= A[0] xor f3(A[1],kr[11,2],km[11,2]);
A[3]:= A[3] xor f1(A[0],kr[11,3],km[11,3]);
A[2]:= A[2] xor f1(A[3],kr[10,0],km[10,0]);
A[1]:= A[1] xor f2(A[2],kr[10,1],km[10,1]);
A[0]:= A[0] xor f3(A[1],kr[10,2],km[10,2]);
A[3]:= A[3] xor f1(A[0],kr[10,3],km[10,3]);
A[2]:= A[2] xor f1(A[3],kr[9,0],km[9,0]);
A[1]:= A[1] xor f2(A[2],kr[9,1],km[9,1]);
A[0]:= A[0] xor f3(A[1],kr[9,2],km[9,2]);
A[3]:= A[3] xor f1(A[0],kr[9,3],km[9,3]);
A[2]:= A[2] xor f1(A[3],kr[8,0],km[8,0]);
A[1]:= A[1] xor f2(A[2],kr[8,1],km[8,1]);
A[0]:= A[0] xor f3(A[1],kr[8,2],km[8,2]);
A[3]:= A[3] xor f1(A[0],kr[8,3],km[8,3]);
A[2]:= A[2] xor f1(A[3],kr[7,0],km[7,0]);
A[1]:= A[1] xor f2(A[2],kr[7,1],km[7,1]);
A[0]:= A[0] xor f3(A[1],kr[7,2],km[7,2]);
A[3]:= A[3] xor f1(A[0],kr[7,3],km[7,3]);
A[2]:= A[2] xor f1(A[3],kr[6,0],km[6,0]);
A[1]:= A[1] xor f2(A[2],kr[6,1],km[6,1]);
A[0]:= A[0] xor f3(A[1],kr[6,2],km[6,2]);
A[3]:= A[3] xor f1(A[0],kr[6,3],km[6,3]);
A[3]:= A[3] xor f1(A[0],kr[5,3],km[5,3]);
A[0]:= A[0] xor f3(A[1],kr[5,2],km[5,2]);
A[1]:= A[1] xor f2(A[2],kr[5,1],km[5,1]);
A[2]:= A[2] xor f1(A[3],kr[5,0],km[5,0]);
A[3]:= A[3] xor f1(A[0],kr[4,3],km[4,3]);
A[0]:= A[0] xor f3(A[1],kr[4,2],km[4,2]);
A[1]:= A[1] xor f2(A[2],kr[4,1],km[4,1]);
A[2]:= A[2] xor f1(A[3],kr[4,0],km[4,0]);
A[3]:= A[3] xor f1(A[0],kr[3,3],km[3,3]);
A[0]:= A[0] xor f3(A[1],kr[3,2],km[3,2]);
A[1]:= A[1] xor f2(A[2],kr[3,1],km[3,1]);
A[2]:= A[2] xor f1(A[3],kr[3,0],km[3,0]);
A[3]:= A[3] xor f1(A[0],kr[2,3],km[2,3]);
A[0]:= A[0] xor f3(A[1],kr[2,2],km[2,2]);
A[1]:= A[1] xor f2(A[2],kr[2,1],km[2,1]);
A[2]:= A[2] xor f1(A[3],kr[2,0],km[2,0]);
A[3]:= A[3] xor f1(A[0],kr[1,3],km[1,3]);
A[0]:= A[0] xor f3(A[1],kr[1,2],km[1,2]);
A[1]:= A[1] xor f2(A[2],kr[1,1],km[1,1]);
A[2]:= A[2] xor f1(A[3],kr[1,0],km[1,0]);
A[3]:= A[3] xor f1(A[0],kr[0,3],km[0,3]);
A[0]:= A[0] xor f3(A[1],kr[0,2],km[0,2]);
A[1]:= A[1] xor f2(A[2],kr[0,1],km[0,1]);
A[2]:= A[2] xor f1(A[3],kr[0,0],km[0,0]);
A[0]:= SwapDWord(A[0]);
A[1]:= SwapDWord(A[1]);
A[2]:= SwapDWord(A[2]);
A[3]:= SwapDWord(A[3]);
PDWord(@OutData)^:= A[0];
PDWord(pointer(@OutData)+4)^:= A[1];
PDWord(pointer(@OutData)+8)^:= A[2];
PDWord(pointer(@OutData)+12)^:= A[3];
end;
end.
|
{Implementación de Pilas con Arreglos (Implementación en Memoria Continua).}
{Maximiliano Sosa; Ricardo Quesada; Gonzalo J. García}
unit Upilas;
interface
uses Udatos;
const MaxPila = 20;
type
TipoPila = record
cima: 0..MaxPila;
elementos: array[1..MaxPila] of TipoDato;
end;
function PilaVacia(P: TipoPila): boolean;
function PilaLlena(P: TipoPila): boolean;
function Top(P: TipoPila): TipoDato;
procedure CrearPila(var P: TipoPila);
procedure SacarDePila(var P: TipoPila; var x: TipoDato);
procedure PonerEnPila(var P: TipoPila; x: TipoDato);
implementation
procedure CrearPila(var P: TipoPila);
begin
P.cima := 0;
end;
function PilaVacia(P: TipoPila): boolean;
begin
PilaVacia := P.cima = 0;
end;
function PilaLlena(P: TipoPila): boolean;
begin
PilaLlena := P.cima = MaxPila;
end;
function Top(P: TipoPila): TipoDato;
begin
Top := P.elementos[P.cima];
end;
procedure SacarDePila(var P: TipoPila; var x: TipoDato);
begin
x := P.elementos[P.cima];
P.cima := P.cima - 1;
end;
procedure PonerEnPila(var P: TipoPila; x: TipoDato);
begin
P.cima := P.cima + 1;
P.elementos[P.cima] := x;
end;
end.
|
unit TextEditor.Search.Normal;
interface
uses
System.Classes, System.SysUtils, TextEditor.Lines, TextEditor.Search.Base;
type
TTextEditorNormalSearch = class(TTextEditorSearchBase)
strict private
FCount: Integer;
FExtended: Boolean;
FLookAt: Integer;
FOrigin: PChar;
FCasedPattern: string;
FLineBreak: string;
FPatternLength, FPatternLengthSuccessor: Integer;
FRun: PChar;
FShift: array [AnsiChar] of Integer;
FShiftInitialized: Boolean;
FTextLength: Integer;
FTextToSearch: string;
FTheEnd: PChar;
function GetFinished: Boolean;
procedure InitShiftTable;
protected
function GetLength(const AIndex: Integer): Integer; override;
function TestWholeWord: Boolean;
procedure CaseSensitiveChanged; override;
procedure SetPattern(const AValue: string); override;
public
constructor Create(const AExtended: Boolean; const ALineBreak: string);
function SearchAll(const ALines: TTextEditorLines): Integer; override;
function FindFirst(const AText: string): Integer;
function Next: Integer;
property Count: Integer read FCount write FCount;
property Finished: Boolean read GetFinished;
property Pattern read FCasedPattern;
end;
implementation
uses
Winapi.Windows, System.Character, TextEditor.Consts, TextEditor.Language;
constructor TTextEditorNormalSearch.Create(const AExtended: Boolean; const ALineBreak: string);
begin
inherited Create;
FExtended := AExtended;
FLineBreak := ALineBreak;
end;
function TTextEditorNormalSearch.GetFinished: Boolean;
begin
Result := (FRun >= FTheEnd) or (FPatternLength >= FTextLength);
end;
procedure TTextEditorNormalSearch.InitShiftTable;
var
LAnsiChar: AnsiChar;
LIndex: Integer;
begin
FPatternLength := Length(FPattern);
if FPatternLength = 0 then
Status := STextEditorPatternIsEmpty;
FPatternLengthSuccessor := FPatternLength + 1;
FLookAt := 1;
for LAnsiChar := Low(AnsiChar) to High(AnsiChar) do
FShift[LAnsiChar] := FPatternLengthSuccessor;
for LIndex := 1 to FPatternLength do
FShift[AnsiChar(FPattern[LIndex])] := FPatternLengthSuccessor - LIndex;
while FLookAt < FPatternLength do
begin
if FPattern[FPatternLength] = FPattern[FPatternLength - FLookAt] then
Break;
Inc(FLookAt);
end;
FShiftInitialized := True;
end;
function TTextEditorNormalSearch.TestWholeWord: Boolean;
var
LPTest: PChar;
function IsWordBreakChar(AChar: Char): Boolean;
begin
if (AChar < TEXT_EDITOR_EXCLAMATION_MARK) or AChar.IsWhiteSpace then
Result := True
else
if AChar = TEXT_EDITOR_LOW_LINE then
Result := False
else
Result := not AChar.IsLetterOrDigit;
end;
begin
LPTest := FRun - FPatternLength;
Result := ((LPTest < FOrigin) or IsWordBreakChar(LPTest[0])) and ((FRun >= FTheEnd) or IsWordBreakChar(FRun[1]));
end;
function TTextEditorNormalSearch.Next: Integer;
var
LIndex: Integer;
LPValue: PChar;
begin
Result := 0;
Inc(FRun, FPatternLength);
while FRun < FTheEnd do
begin
if FPattern[FPatternLength] <> FRun^ then
Inc(FRun, FShift[AnsiChar((FRun + 1)^)])
else
begin
LPValue := FRun - FPatternLength + 1;
LIndex := 1;
while FPattern[LIndex] = LPValue^ do
begin
if LIndex = FPatternLength then
begin
if WholeWordsOnly then
if not TestWholeWord then
Break;
Inc(FCount);
Result := FRun - FOrigin - FPatternLength + 2;
Exit;
end;
Inc(LIndex);
Inc(LPValue);
end;
Inc(FRun, FLookAt);
if FRun >= FTheEnd then
Break;
Inc(FRun, FShift[AnsiChar(FRun^)] - 1);
end;
end;
end;
procedure TTextEditorNormalSearch.SetPattern(const AValue: string);
var
LValue: string;
begin
LValue := AValue;
if FExtended then
begin
LValue := StringReplace(LValue, '\n', FLineBreak, [rfReplaceAll]);
LValue := StringReplace(LValue, '\t', TEXT_EDITOR_TAB_CHAR, [rfReplaceAll]);
LValue := StringReplace(LValue, '\0', TEXT_EDITOR_SUBSTITUTE_CHAR, [rfReplaceAll]);
end;
if FPattern <> LValue then
begin
FCasedPattern := LValue;
if CaseSensitive then
FPattern := FCasedPattern
else
FPattern := AnsiLowerCase(FCasedPattern);
FShiftInitialized := False;
end;
FCount := 0;
end;
procedure TTextEditorNormalSearch.CaseSensitiveChanged;
begin
if CaseSensitive then
FPattern := FCasedPattern
else
FPattern := AnsiLowerCase(FCasedPattern);
FShiftInitialized := False;
end;
function TTextEditorNormalSearch.SearchAll(const ALines: TTextEditorLines): Integer;
var
LPosition: Integer;
begin
Status := '';
Clear;
LPosition := FindFirst(ALines.Text);
while LPosition > 0 do
begin
FResults.Add(Pointer(LPosition));
LPosition := Next;
end;
Result := FResults.Count;
SetLength(FTextToSearch, 0);
end;
function TTextEditorNormalSearch.FindFirst(const AText: string): Integer;
begin
if not FShiftInitialized then
InitShiftTable;
Result := 0;
FTextLength := Length(AText);
if FTextLength >= FPatternLength then
begin
FTextToSearch := AText;
if not CaseSensitive then
CharLowerBuff(PChar(FTextToSearch), FTextLength);
FOrigin := PChar(FTextToSearch);
FTheEnd := FOrigin + FTextLength;
FRun := FOrigin - 1;
Result := Next;
end;
end;
function TTextEditorNormalSearch.GetLength(const AIndex: Integer): Integer;
begin
Result := FPatternLength;
end;
end.
|
program SubstringEvenChar;
{$MODE OBJFPC}
var
S, sub : String;
function LetterNumber(C : Char) : Integer;
begin
LetterNumber := ord(C) - ord('a') + 1;
end;
function AllCharactersEven(S : String) : Boolean;
var
counts : array [1..26] of Integer;
i, pos : Integer;
begin
for i := 1 to 26 do
counts[i] := 0;
for i := 1 to Length(S) do
begin
pos := LetterNumber(S[i]);
counts[pos] := counts[pos] + 1;
end;
for i := 1 to 26 do
begin
if counts[i] mod 2 <> 0 then
begin
AllCharactersEven := false;
exit;
end;
end;
AllCharactersEven := true;
end;
function CalculateNumberSubstringsWithEven(S : String) : Integer;
var
i, j, len, count : Integer;
begin
count := 0;
len := Length(S);
for i := 1 to len do
begin
j := 1;
for j := 1 to (len - i + 1) do
begin
sub := copy(S, j, i);
if AllCharactersEven(sub) then
begin
count := count + 1;
//writeln(sub);
end;
end;
end;
CalculateNumberSubstringsWithEven := count;
end;
begin
S := 'abbaa';
writeln('Input = ', S);
writeln('Number of Substrings with even characters = ', CalculateNumberSubstringsWithEven(S));
S := 'geeksforgeeks';
writeln('Input = ', S);
writeln('Number of Substrings with even characters = ', CalculateNumberSubstringsWithEven(S));
end. |
// fontes de consulta: http://balaiotecnologico.blogspot.com.br/2009/07/design-patterns-com-delphi-abstract.html
unit AbstractFactory;
interface
uses
Classes,Buttons,StdCtrls,Graphics;
Type
TTipoColor = (tcRed, tcBlue);
TOAbstractFactory = class(TObject)
public
class function GetTipoColor(cTipo:TTipoColor):TOAbstractFactory;
constructor Create;
destructor Destroy; override;
//abstract widget constructors
function CreateSpeedButton(AOwner: TComponent): TSpeedButton; virtual; abstract;
function CreateEdit(AOwner: TComponent): TEdit; virtual; abstract;
function CreateLabel(AOwner: TComponent): TLabel; virtual; abstract;
end;
TORedFactory = class(TOAbstractFactory)
public
//concrete widget constructors
function CreateSpeedButton(AOwner: TComponent): TSpeedButton; override;
function CreateEdit(AOwner: TComponent): TEdit; override;
function CreateLabel(AOwner: TComponent): TLabel; override;
end;
TOBlueFactory = class(TOAbstractFactory)
public
//concrete widget constructors
function CreateSpeedButton(AOwner: TComponent): TSpeedButton; override;
function CreateEdit(AOwner: TComponent): TEdit; override;
function CreateLabel(AOwner: TComponent): TLabel; override;
end;
implementation
{ TOAbstractFactory }
constructor TOAbstractFactory.Create;
begin
inherited;
//
end;
destructor TOAbstractFactory.Destroy;
begin
//
inherited;
end;
class function TOAbstractFactory.GetTipoColor(
cTipo: TTipoColor): TOAbstractFactory;
begin
result := nil;
case cTipo of
tcRed : Result := TORedFactory.Create;
tcBlue : Result := TOBlueFactory.Create;
end;
end;
{ TORedFactory }
function TORedFactory.CreateEdit(AOwner: TComponent): TEdit;
begin
result := TEdit.Create(AOwner);
TEdit(result).color := clRed;
end;
function TORedFactory.CreateLabel(AOwner: TComponent): TLabel;
begin
TLabel(AOwner).Color := clRed;
end;
function TORedFactory.CreateSpeedButton(AOwner: TComponent): TSpeedButton;
begin
TSpeedButton(AOwner).Caption := 'R'+TSpeedButton(AOwner).Caption;
end;
{ TOBlueFactory }
function TOBlueFactory.CreateEdit(AOwner: TComponent): TEdit;
begin
result := TEdit.Create(AOwner);
TEdit(result).color := clBlue;
end;
function TOBlueFactory.CreateLabel(AOwner: TComponent): TLabel;
begin
TLabel(AOwner).Color := clBlue;
end;
function TOBlueFactory.CreateSpeedButton(AOwner: TComponent): TSpeedButton;
begin
TSpeedButton(AOwner).Caption := 'B'+TSpeedButton(AOwner).Caption;
end;
end.
|
{
Visual control displaying a map.
Data for the map (tile images) must be supplied via callbacks.
@seealso OSM.TileStorage
(c) Fr0sT-Brutal https://github.com/Fr0sT-Brutal/Delphi_OSMMap
@author(Fr0sT-Brutal (https://github.com/Fr0sT-Brutal))
}
unit OSM.MapControl;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFDEF FPC}
LCLIntf, LCLType,
{$ENDIF}
{$IFDEF DCC} // Currently VCL only => Windows only
Windows,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, ExtCtrls, Forms,
Math, Types,
OSM.SlippyMapUtils;
const
// Default W and H of cache image in number of tiles.
// Memory occupation of an image:
// (4 bytes per pixel) * `TilesH` * `TilesV` * (65536 pixels in single tile) @br
// For value 8 it counts 16.7 Mb
CacheImageDefTilesH = 8;
CacheImageDefTilesV = 8;
// Default W and H of cache image in pixels
CacheImageDefWidth = CacheImageDefTilesH*TILE_IMAGE_WIDTH;
CacheImageDefHeight = CacheImageDefTilesV*TILE_IMAGE_HEIGHT;
// Margin that is added to cache image to hold view area, in number of tiles
CacheMarginSize = 2;
// Size of margin for labels on map, in pixels
LabelMargin = 2;
type
// Shape of mapmark glyph
TMapMarkGlyphShape = (gshCircle, gshSquare, gshTriangle);
// Visual properties of mapmark's glyph
TMapMarkGlyphStyle = record
Shape: TMapMarkGlyphShape;
Size: Cardinal;
BorderColor: TColor;
BgColor: TColor;
end;
PMapMarkGlyphStyle = ^TMapMarkGlyphStyle;
// Visual properties of mapmark's caption
TMapMarkCaptionStyle = record
Color: TColor;
BgColor: TColor;
DX, DY: Integer;
Transparent: Boolean;
{}//TODO: text position, alignment
end;
PMapMarkCaptionStyle = ^TMapMarkCaptionStyle;
// Flags to indicate which properties must be taken from MapMark object when drawing.
// By default props will use owner's values
TMapMarkCustomProp = (propGlyphStyle, propCaptionStyle, propFont);
TMapMarkCustomProps = set of TMapMarkCustomProp;
// Class representing a single mapmark.
// It is recommended to be created by TMapMarkList.NewItem
TMapMark = class
public
//~ Mapmark data
Coord: TGeoPoint;
Caption: string;
Visible: Boolean;
Data: Pointer;
//~ Visual style
CustomProps: TMapMarkCustomProps;
GlyphStyle: TMapMarkGlyphStyle;
CaptionStyle: TMapMarkCaptionStyle;
CaptionFont: TFont;
destructor Destroy; override;
end;
TMapControl = class;
// Notification of an action over a mapmark in a list
TOnItemNotify = procedure (Sender: TObject; Item: TMapMark; Action: TListNotification) of object;
// List of mapmarks
TMapMarkList = class
strict private
FMap: TMapControl;
FList: TList;
FUpdateCount: Integer;
FOnItemNotify: TOnItemNotify;
public
constructor Create(Map: TMapControl);
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function Get(Index: Integer): TMapMark;
// Find the next map mark that is near specified coordinates.
// @param GeoCoords - coordinates to search
// @param ConsiderMapMarkSize - widen an area to search by mapmark size
// @param(PrevIndex - index of previous found mapmark in the list.
// `-1` (default) will start from the 1st element)
// @returns index of mapmark in the list, `-1` if not found.
//
// Samples:
// 1) Check if there's any map marks at this point:
// ```pascal
// if Find(Point) <> -1 then ...
// ```
// 2) Select all map marks at this point
// ```pascal
// idx := -1;
// repeat
// idx := MapMarks.Find(Point, idx);
// if idx = -1 then Break;
// ... do something with MapMarks[idx] ...
// until False;
// ```
function Find(const GeoCoords: TGeoPoint; ConsiderMapMarkSize: Boolean = True; StartIndex: Integer = -1): Integer; overload;
// The same as above but searches within specified rectangle
function Find(const GeoRect: TGeoRect; ConsiderMapMarkSize: Boolean = True; StartIndex: Integer = -1): Integer; overload;
// Create TMapMark object and initially assign values from owner map's fields
function NewItem: TMapMark;
// Simple method to add a mapmark by coords and caption
function Add(const GeoCoords: TGeoPoint; const Caption: string): TMapMark; overload;
// Add a mapmark with fully customizable properties. `MapMark` should be init-ed by NewItem
function Add(MapMark: TMapMark): TMapMark; overload;
procedure Delete(MapMark: TMapMark);
function Count: Integer;
procedure Clear;
// Assigning a handler for this event allows implementing custom init, disposal
// of allocated memory etc.
property OnItemNotify: TOnItemNotify read FOnItemNotify write FOnItemNotify;
end;
// Options of map control
TMapOption = (moDontDrawCopyright, moDontDrawScale);
TMapOptions = set of TMapOption;
// Mode of handling of plain left mouse button press
TMapMouseMode = (mmDrag, mmSelect);
// Callback to draw an image of a single tile having number (`TileHorzNum`;`TileVertNum`)
// at point `TopLeft` on canvas `Canvas`.
// Callback must set `Handled` to @true, otherwise default actions will be done.
// This type is common for both TMapControl.OnDrawTile and TMapControl.OnDrawTileLoading callbacks.
//
// _Note for TMapControl.OnDrawTile:_@br
// If `Handled` is not set to @true, TMapControl.DrawTileLoading method is called for this tile.
// Usually you have to assign this callback only.
//
// _Note for TMapControl.OnDrawTileLoading:_@br
// The handler is called only for empty tiles allowing a user to draw his own label
TOnDrawTile = procedure (Sender: TMapControl; TileHorzNum, TileVertNum: Cardinal;
const TopLeft: TPoint; Canvas: TCanvas; var Handled: Boolean) of object;
// Callback to custom draw a mapmark. It is called before default drawing.
// If `Handled` is not set to @true, default drawing will be done.
// User could draw a mapmark fully or just change some props and let default
// drawing do its job
TOnDrawMapMark = procedure (Sender: TMapControl; Canvas: TCanvas; const Point: TPoint;
MapMark: TMapMark; var Handled: Boolean) of object;
// Callback to react on selection by mouse
TOnSelectionBox = procedure (Sender: TMapControl; const GeoRect: TGeoRect) of object;
// Control displaying a map or its visible part.
TMapControl = class(TScrollBox)
strict private
FMapSize: TSize; // current map dims in pixels
FCacheImage: TBitmap; // drawn tiles (it could be equal to or larger than view area!)
FCopyright, // lazily created cache images for
FScaleLine: TBitmap; // scale line and copyright
FZoom: Integer; // current zoom; integer for simpler operations
FCacheImageRect: TRect; // position of cache image on map in map coords
FMapOptions: TMapOptions;
FDragPos: TPoint;
FMaxZoom, FMinZoom: TMapZoomLevel; // zoom constraints
FMapMarkList: TMapMarkList;
FSelectionBox: TShape; // much simpler than drawing on canvas, tracking bounds etc.
FSelectionBoxBindPoint: TPoint; // point at which selection starts
FMouseMode: TMapMouseMode;
FOnDrawTile: TOnDrawTile;
FOnDrawTileLoading: TOnDrawTile;
FOnZoomChanged: TNotifyEvent;
FOnDrawMapMark: TOnDrawMapMark;
FOnSelectionBox: TOnSelectionBox;
strict protected
//~ overrides
procedure PaintWindow(DC: HDC); override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override;
procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
//~ main methods
function ViewInCache: Boolean; inline;
procedure UpdateCache;
procedure MoveCache;
function SetCacheDimensions: Boolean;
procedure DrawTileLoading(TileHorzNum, TileVertNum: Cardinal; const TopLeft: TPoint; Canvas: TCanvas);
procedure DrawTile(TileHorzNum, TileVertNum: Cardinal; const TopLeft: TPoint; Canvas: TCanvas);
procedure DrawMapMark(Canvas: TCanvas; MapMark: TMapMark);
//~ getters/setters
procedure SetNWPoint(const MapPt: TPoint); overload;
function GetCenterPoint: TGeoPoint;
procedure SetCenterPoint(const GeoCoords: TGeoPoint);
function GetNWPoint: TGeoPoint;
procedure SetNWPoint(const GeoCoords: TGeoPoint); overload;
procedure SetZoomConstraint(Index: Integer; ZoomConstraint: TMapZoomLevel);
//~ helpers
function ViewAreaRect: TRect;
class procedure DrawCopyright(const Text: string; DestBmp: TBitmap);
class procedure DrawScale(Zoom: TMapZoomLevel; DestBmp: TBitmap);
public
// Default glyph style of mapmarks. New items will be init-ed with this value
MapMarkGlyphStyle: TMapMarkGlyphStyle;
// Default caption style of mapmarks. New items will be init-ed with this value
MapMarkCaptionStyle: TMapMarkCaptionStyle;
// Default font of mapmarks. New items will be init-ed with this value
MapMarkCaptionFont: TFont;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// (Re)draw single tile having numbers `(TileHorzNum;TileVertNum)`
procedure RefreshTile(TileHorzNum, TileVertNum: Cardinal);
// Convert a point from map pixel coords to geo coords
function MapToGeoCoords(const MapPt: TPoint): TGeoPoint; overload;
// Convert a rect from map pixel coords to geo coords
function MapToGeoCoords(const MapRect: TRect): TGeoRect; overload;
// Convert a point from geo coords to map pixel coords
function GeoCoordsToMap(const GeoCoords: TGeoPoint): TPoint; overload;
// Convert a rect from geo coords to map pixel coords
function GeoCoordsToMap(const GeoRect: TGeoRect): TRect; overload;
// Convert a point from view area coords to map coords
function ViewToMap(const ViewPt: TPoint): TPoint; overload;
// Convert a rect from view area coords to map coords
function ViewToMap(const ViewRect: TRect): TRect; overload;
// Convert a point from map coords to view area coords
function MapToView(const MapPt: TPoint): TPoint; overload;
// Convert a rect from map coords to view area coords
function MapToView(const MapRect: TRect): TRect; overload;
// Convert map points to scrollbox inner coordinates (not client!)
function MapToInner(const MapPt: TPoint): TPoint;
// Convert scrollbox inner coordinates (not client!) to map points
function InnerToMap(const Pt: TPoint): TPoint;
// Delta move the view area
procedure ScrollMapBy(DeltaHorz, DeltaVert: Integer);
// Absolutely move the view area
procedure ScrollMapTo(Horz, Vert: Integer);
// Set zoom level to new value and reposition to given point
// @param Value - new zoom value
// @param MapBindPt - point in map coords that must keep its position within view
procedure SetZoom(Value: Integer; const MapBindPt: TPoint); overload;
// Simple zoom change with binding to top-left corner
procedure SetZoom(Value: Integer); overload;
// Zoom to show given region `GeoRect`
procedure ZoomToArea(const GeoRect: TGeoRect);
// Zoom to fill view area as much as possible
procedure ZoomToFit;
//~ properties
// Current zoom level
property Zoom: Integer read FZoom;
// Map options
property MapOptions: TMapOptions read FMapOptions write FMapOptions;
// Point of center of current view area. Set this property to move view
property CenterPoint: TGeoPoint read GetCenterPoint write SetCenterPoint;
// Point of top-left corner of current view area. Set this property to move view
property NWPoint: TGeoPoint read GetNWPoint write SetNWPoint;
// Minimal zoom level. Zoom couldn't be set to a value less than this value
property MinZoom: TMapZoomLevel index 0 read FMinZoom write SetZoomConstraint;
// Maximal zoom level. Zoom couldn't be set to a value greater than this value
property MaxZoom: TMapZoomLevel index 1 read FMaxZoom write SetZoomConstraint;
// List of mapmarks on a map
property MapMarks: TMapMarkList read FMapMarkList;
// Mode of handling left mouse button press
property MouseMode: TMapMouseMode read FMouseMode write FMouseMode;
// View area in map coords
property ViewRect: TRect read ViewAreaRect;
//~ events/callbacks
// Callback is called when map tile must be drawn
property OnDrawTile: TOnDrawTile read FOnDrawTile write FOnDrawTile;
// Callback is called when map tile with loading state must be drawn
property OnDrawTileLoading: TOnDrawTile read FOnDrawTileLoading write FOnDrawTileLoading;
// Callback is called when zoom level is changed
property OnZoomChanged: TNotifyEvent read FOnZoomChanged write FOnZoomChanged;
// Callback is called when mapmark must be drawn
property OnDrawMapMark: TOnDrawMapMark read FOnDrawMapMark write FOnDrawMapMark;
// Callback is called when selection with mouse was made
property OnSelectionBox: TOnSelectionBox read FOnSelectionBox write FOnSelectionBox;
end;
function ToInnerCoords(const StartPt, Pt: TPoint): TPoint; overload; inline;
function ToOuterCoords(const StartPt, Pt: TPoint): TPoint; overload; inline;
function ToInnerCoords(const StartPt: TPoint; const Rect: TRect): TRect; overload; inline;
function ToOuterCoords(const StartPt: TPoint; const Rect: TRect): TRect; overload; inline;
const
// Default style of mapmark glyph.
// TMapControl.MapMarkGlyphStyle is init-ed with this value
DefaultMapMarkGlyphStyle: TMapMarkGlyphStyle = (
Shape: gshCircle;
Size: 20;
BorderColor: clWindowFrame;
BgColor: clSkyBlue;
);
// Default style of mapmark caption.
// TMapControl.MapMarkGlyphStyle is init-ed with this value
DefaultMapMarkCaptionStyle: TMapMarkCaptionStyle = (
Color: clMenuText;
BgColor: clWindow;
DX: 3;
Transparent: True
);
const
S_Lbl_Loading = 'Loading [%d : %d]...';
// @exclude
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('OSM', [TMapControl]);
end;
// *** Utils ***
// Like Client<=>Screen
function ToInnerCoords(const StartPt, Pt: TPoint): TPoint;
begin
Result := Pt.Subtract(StartPt);
end;
function ToInnerCoords(const StartPt: TPoint; const Rect: TRect): TRect;
begin
Result := RectFromPoints(
ToInnerCoords(StartPt, Rect.TopLeft),
ToInnerCoords(StartPt, Rect.BottomRight)
);
end;
function ToOuterCoords(const StartPt, Pt: TPoint): TPoint;
begin
Result := Pt.Add(StartPt);
end;
function ToOuterCoords(const StartPt: TPoint; const Rect: TRect): TRect;
begin
Result := RectFromPoints(
ToOuterCoords(StartPt, Rect.TopLeft),
ToOuterCoords(StartPt, Rect.BottomRight)
);
end;
// Floor value to tile size
function ToTileWidthLesser(Width: Cardinal): Cardinal; inline;
begin
Result := (Width div TILE_IMAGE_WIDTH)*TILE_IMAGE_WIDTH;
end;
function ToTileHeightLesser(Height: Cardinal): Cardinal; inline;
begin
Result := (Height div TILE_IMAGE_HEIGHT)*TILE_IMAGE_HEIGHT;
end;
// Ceil value to tile size
function ToTileWidthGreater(Width: Cardinal): Cardinal; inline;
begin
Result := ToTileWidthLesser(Width);
if Width mod TILE_IMAGE_WIDTH > 0 then
Inc(Result, TILE_IMAGE_WIDTH);
end;
function ToTileHeightGreater(Height: Cardinal): Cardinal; inline;
begin
Result := ToTileHeightLesser(Height);
if Height mod TILE_IMAGE_HEIGHT > 0 then
Inc(Result, TILE_IMAGE_HEIGHT);
end;
// Draw triangle on canvas
procedure Triangle(Canvas: TCanvas; const Rect: TRect);
begin
Canvas.Polygon([
Point(Rect.Left, Rect.Bottom),
Point(Rect.Left + Rect.Width div 2, Rect.Top),
Rect.BottomRight]);
end;
{ TMapMark }
destructor TMapMark.Destroy;
begin
if CaptionFont <> nil then
FreeAndNil(CaptionFont);
end;
{ TMapMarkList }
constructor TMapMarkList.Create(Map: TMapControl);
begin
FMap := Map;
FList := TList.Create;
end;
destructor TMapMarkList.Destroy;
begin
Clear;
FreeAndNil(FList);
inherited;
end;
procedure TMapMarkList.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TMapMarkList.EndUpdate;
begin
if FUpdateCount > 0 then
Dec(FUpdateCount);
if FUpdateCount = 0 then // redraw map view if update is not held back
FMap.Invalidate;
end;
function TMapMarkList.Count: Integer;
begin
Result := FList.Count;
end;
procedure TMapMarkList.Clear;
var i: Integer;
begin
for i := 0 to FList.Count - 1 do
begin
if Assigned(FOnItemNotify) then
FOnItemNotify(Self, FList[i], lnDeleted);
TMapMark(FList[i]).Free;
end;
FList.Clear;
if FUpdateCount = 0 then // redraw map view if update is not held back
FMap.Invalidate;
end;
function TMapMarkList.Get(Index: Integer): TMapMark;
begin
Result := FList[Index];
end;
function TMapMarkList.Find(const GeoCoords: TGeoPoint; ConsiderMapMarkSize: Boolean; StartIndex: Integer): Integer;
var
i: Integer;
MapMark: TMapMark;
begin
if StartIndex = -1 then
StartIndex := 0;
for i := StartIndex to Count - 1 do
begin
MapMark := Get(i);
{}// TODO ConsiderMapMarkSize
if SameValue(GeoCoords.Long, MapMark.Coord.Long) and SameValue(GeoCoords.Lat, MapMark.Coord.Lat) then
Exit(i);
end;
Result := -1;
end;
function TMapMarkList.Find(const GeoRect: TGeoRect; ConsiderMapMarkSize: Boolean; StartIndex: Integer): Integer;
var
i: Integer;
MapMark: TMapMark;
begin
if StartIndex = -1 then
StartIndex := 0
else
Inc(StartIndex);
for i := StartIndex to Count - 1 do
begin
MapMark := Get(i);
{}// TODO ConsiderMapMarkSize
if GeoRect.Contains(MapMark.Coord) then
Exit(i);
end;
Result := -1;
end;
function TMapMarkList.NewItem: TMapMark;
begin
Result := TMapMark.Create;
Result.Visible := True;
Result.GlyphStyle := FMap.MapMarkGlyphStyle;
Result.CaptionStyle := FMap.MapMarkCaptionStyle;
end;
// Add mapmark with specified coords and caption.
function TMapMarkList.Add(const GeoCoords: TGeoPoint; const Caption: string): TMapMark;
var MapMark: TMapMark;
begin
MapMark := NewItem;
MapMark.Coord := GeoCoords;
MapMark.Caption := Caption;
Result := Add(MapMark);
end;
function TMapMarkList.Add(MapMark: TMapMark): TMapMark;
begin
Result := MapMark;
FList.Add(Result);
if Assigned(FOnItemNotify) then
FOnItemNotify(Self, Result, lnAdded);
if FUpdateCount = 0 then // redraw map view if update is not held back
FMap.Invalidate;
end;
procedure TMapMarkList.Delete(MapMark: TMapMark);
var i: Integer;
begin
i := FList.IndexOf(MapMark);
if i <> -1 then
begin
if Assigned(FOnItemNotify) then
FOnItemNotify(Self, MapMark, lnDeleted);
TMapMark(FList[i]).Free;
FList.Delete(i);
end;
if FUpdateCount = 0 then // redraw map view if update is not held back
FMap.Invalidate;
end;
{ TMapControl }
constructor TMapControl.Create(AOwner: TComponent);
begin
inherited;
// Setup Scrollbox's properties
Self.HorzScrollBar.Tracking := True;
Self.VertScrollBar.Tracking := True;
Self.DragCursor := crSizeAll;
Self.AutoScroll := True;
FCacheImage := TBitmap.Create;
FSelectionBox := TShape.Create(Self);
FSelectionBox.Visible := False;
FSelectionBox.Parent := Self;
FSelectionBox.Brush.Style := bsClear;
FSelectionBox.Pen.Mode := pmNot;
FSelectionBox.Pen.Style := psDashDot;
FMapMarkList := TMapMarkList.Create(Self);
FMinZoom := Low(TMapZoomLevel);
FMaxZoom := High(TMapZoomLevel);
MapMarkGlyphStyle := DefaultMapMarkGlyphStyle;
MapMarkCaptionStyle := DefaultMapMarkCaptionStyle;
MapMarkCaptionFont := TFont.Create;
MapMarkCaptionFont.Assign(Self.Font);
// Assign outbound value to ensure the zoom will be changed
FZoom := -1;
SetZoom(Low(TMapZoomLevel));
end;
destructor TMapControl.Destroy;
begin
FreeAndNil(FCacheImage);
FreeAndNil(FCopyright);
FreeAndNil(FScaleLine);
FreeAndNil(FMapMarkList);
FreeAndNil(MapMarkCaptionFont);
inherited;
end;
// *** overrides - events ***
// Main drawing routine
// ! Compiler-specific input !
// DC here varies:
// - Delphi: dimensions of current display res and top-left at viewport's top-left
// - LCL: dimensions somewhat larger than client area and top-left at control top-left
// Canvas.ClipRect helps avoiding defines here
procedure TMapControl.PaintWindow(DC: HDC);
var
ViewRect: TRect;
Canvas: TCanvas;
MapViewGeoRect: TGeoRect;
Idx: Integer;
DCClipRectTopLeft: TPoint;
begin
// if view area lays within cached image, no update required
if not ViewInCache then
begin
MoveCache;
UpdateCache;
end;
// ViewRect is current view area in CacheImage coords
ViewRect := ToInnerCoords(FCacheImageRect.TopLeft, ViewAreaRect);
Canvas := TCanvas.Create; // Prefer canvas methods over bit blitting
try
Canvas.Handle := DC;
// Top-left point of view area in DC coords
DCClipRectTopLeft := Canvas.ClipRect.TopLeft;
// draw cache (map background)
Canvas.CopyRect(
TRect.Create(DCClipRectTopLeft, ViewRect.Width, ViewRect.Height),
FCacheImage.Canvas,
ViewRect
);
// init copyright bitmap if not inited yet and draw it in bottom-right corner
if not (moDontDrawCopyright in FMapOptions) then
begin
if FCopyright = nil then
begin
FCopyright := TBitmap.Create;
FCopyright.Transparent := True;
FCopyright.TransparentColor := clWhite;
DrawCopyright(TilesCopyright, FCopyright);
end;
Canvas.Draw(
DCClipRectTopLeft.X + ViewRect.Width - FCopyright.Width - LabelMargin,
DCClipRectTopLeft.Y + ViewRect.Height - FCopyright.Height - LabelMargin,
FCopyright
);
end;
// scaleline bitmap must've been inited already in SetZoom
// draw it in bottom-left corner
if not (moDontDrawScale in FMapOptions) then
begin
Canvas.Draw(
DCClipRectTopLeft.X + LabelMargin,
DCClipRectTopLeft.Y + ViewRect.Height - FScaleLine.Height - LabelMargin,
FScaleLine
);
end;
// Draw mapmarks
if FMapMarkList.Count > 0 then
begin
idx := -1;
// Determine rect of map in view (map could be smaller than view!)
MapViewGeoRect := MapToGeoCoords(EnsureInMap(FZoom, ViewAreaRect));
// Draw marks within rect
repeat
idx := FMapMarkList.Find(MapViewGeoRect, True, idx);
if idx = -1 then Break;
DrawMapMark(Canvas, FMapMarkList.Get(idx));
until False;
end;
finally
FreeAndNil(Canvas);
end;
end;
// NB: painting on TWinControl is pretty tricky, doing it ordinary way leads
// to weird effects as DC's do not cover whole client area.
// Luckily this could be solved with Invalidate which fully redraws the control
procedure TMapControl.WMHScroll(var Message: TWMHScroll);
begin
Invalidate;
inherited;
end;
procedure TMapControl.WMVScroll(var Message: TWMVScroll);
begin
Invalidate;
inherited;
end;
// ! Only with csCustomPaint ControlState the call chain
// TWinControl.WMPaint > PaintHandler > PaintWindow will be executed.
procedure TMapControl.WMPaint(var Message: TWMPaint);
begin
ControlState := ControlState + [csCustomPaint];
inherited;
ControlState := ControlState - [csCustomPaint];
end;
// Control resized - reposition cache, set new scrollbar props
// Parent's method only calls OnResize
procedure TMapControl.Resize;
begin
if SetCacheDimensions then
UpdateCache;
{$IFDEF FPC}
// ! Compiler-specific !
// LCL has weird scrollbars - they require Page to be set to actual size
Self.HorzScrollBar.Page := Self.ClientWidth;
Self.VertScrollBar.Page := Self.ClientHeight;
{$ENDIF}
Invalidate;
inherited;
end;
// Focus self on mouse press
// Start dragging or selecting on mouse press
procedure TMapControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var MousePos: TPoint;
begin
SetFocus;
// Left button and no shifts only
if (Button = mbLeft) and (Shift = [ssLeft]) then
case MouseMode of
mmDrag:
begin
MousePos := ViewToMap(Point(X, Y));
// Position is inside map and no mapmark below
if InMap(Zoom, MousePos) and (FMapMarkList.Find(MapToGeoCoords(MousePos), True) = -1) then
BeginDrag(False, -1); // < 0 - use the DragThreshold property of the global Mouse variable (c) help
inherited;
end;
mmSelect:
begin
MousePos := ViewToMap(Point(X, Y));
// Position is inside map - start selection
if InMap(Zoom, MousePos) then
begin
FSelectionBoxBindPoint := MapToInner(MousePos);
FSelectionBox.BoundsRect := TRect.Create(FSelectionBoxBindPoint, 0, 0);
FSelectionBox.Visible := True;
end;
inherited;
end;
end; // case
end;
// Resize selection box if active
procedure TMapControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if FSelectionBox.Visible then
begin
// ! Rect here could easily become non-normalized (Top below Bottom, f.ex.) so we normalize it
FSelectionBox.BoundsRect := TRect.Create(FSelectionBoxBindPoint,
MapToInner(EnsureInMap(Zoom, ViewToMap(Point(X, Y)))), True);
Invalidate;
end;
inherited;
end;
procedure TMapControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var GeoRect: TGeoRect;
begin
if FSelectionBox.Visible then
begin
FSelectionBox.Visible := False;
Invalidate;
GeoRect := MapToGeoCoords(
TRect.Create(InnerToMap(FSelectionBox.BoundsRect.TopLeft), FSelectionBox.Width, FSelectionBox.Height)
);
if Assigned(FOnSelectionBox) then
FOnSelectionBox(Self, GeoRect);
end;
inherited;
end;
// Zoom in/out on mouse wheel
// ! Compiler-specific input !
// - Delphi: Mouse position is in screen coords, it could be any point outside the client area!
// - FPC: Mouse position is in client coords
function TMapControl.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean;
begin
inherited;
// Calc mouse pos in client coords
{$IFDEF DCC}
MousePos := ScreenToClient(MousePos);
{$ENDIF}
SetZoom(FZoom + Sign(WheelDelta), EnsureInMap(FZoom, ViewToMap(MousePos)));
Result := True;
end;
// Process dragging
procedure TMapControl.DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
inherited;
Accept := True;
case State of
dsDragEnter: // drag started - save initial drag position
FDragPos := Point(X, Y);
dsDragMove: // dragging - move the map
begin
ScrollMapBy(FDragPos.X - X, FDragPos.Y - Y);
FDragPos := Point(X, Y);
end;
end;
end;
// Cancel selection box on Escape press
procedure TMapControl.KeyDown(var Key: Word; Shift: TShiftState);
begin
if FSelectionBox.Visible then
if (Shift = []) and (Key = VK_ESCAPE) then
begin
FSelectionBox.Visible := False;
Invalidate;
end;
inherited;
end;
// *** new methods ***
procedure TMapControl.SetZoom(Value: Integer; const MapBindPt: TPoint);
var
CurrBindPt, NewViewNW, ViewBindPt: TPoint;
BindCoords: TGeoPoint;
begin
// New value violates contraints - reject it
if not (Value in [FMinZoom..FMaxZoom]) then Exit;
if Value = FZoom then Exit;
// save bind point if zoom is valid (zoom value is used to calc geo coords)
if FZoom in [Low(TMapZoomLevel)..High(TMapZoomLevel)]
then BindCoords := MapToGeoCoords(MapBindPt)
else BindCoords := OSM.SlippyMapUtils.MapToGeoCoords(Low(TMapZoomLevel), Point(0, 0));
ViewBindPt := MapToView(MapBindPt); // save bind point in view coords, we'll reposition to it after zoom
FZoom := Value;
FMapSize := TSize.Create(MapWidth(FZoom), MapHeight(FZoom));
HorzScrollBar.Range := FMapSize.cx;
VertScrollBar.Range := FMapSize.cy;
// init copyright bitmap if not inited yet and draw it
if not (moDontDrawScale in FMapOptions) then
begin
if FScaleLine = nil then
FScaleLine := TBitmap.Create;
DrawScale(FZoom, FScaleLine);
end;
// move viewport
CurrBindPt := GeoCoordsToMap(BindCoords); // bind point in new map coords
NewViewNW := CurrBindPt.Subtract(ViewBindPt); // view's top-left corner in new map coords
SetNWPoint(NewViewNW);
SetCacheDimensions;
if not ViewInCache then
MoveCache;
UpdateCache; // zoom changed - update cache anyway
Refresh;
if Assigned(FOnZoomChanged) then
FOnZoomChanged(Self);
end;
procedure TMapControl.SetZoom(Value: Integer);
begin
SetZoom(Value, Point(0,0));
end;
// Determines cache image size according to control and map size
// Returns true if size was changed
function TMapControl.SetCacheDimensions: Boolean;
var
CtrlSize, CacheSize: TSize;
begin
// dims of view area in pixels rounded to full tiles
CtrlSize.cx := ToTileWidthGreater(ClientWidth);
CtrlSize.cy := ToTileHeightGreater(ClientHeight);
// cache dims = Max(control+margins, Min(map, default+margins))
CacheSize.cx := Min(FMapSize.cx, CacheImageDefWidth + CacheMarginSize*TILE_IMAGE_WIDTH);
CacheSize.cy := Min(FMapSize.cy, CacheImageDefHeight + CacheMarginSize*TILE_IMAGE_HEIGHT);
CacheSize.cx := Max(CacheSize.cx, CtrlSize.cx + CacheMarginSize*TILE_IMAGE_WIDTH);
CacheSize.cy := Max(CacheSize.cy, CtrlSize.cy + CacheMarginSize*TILE_IMAGE_HEIGHT);
Result := (FCacheImageRect.Width <> CacheSize.cx) or (FCacheImageRect.Height <> CacheSize.cy);
if not Result then Exit;
FCacheImageRect.Size := CacheSize;
FCacheImage.SetSize(CacheSize.cx, CacheSize.cy);
end;
function TMapControl.ViewToMap(const ViewPt: TPoint): TPoint;
begin
Result := ToOuterCoords(ViewAreaRect.TopLeft, ViewPt);
end;
function TMapControl.ViewToMap(const ViewRect: TRect): TRect;
begin
Result := ToOuterCoords(ViewAreaRect.TopLeft, ViewRect);
end;
function TMapControl.MapToView(const MapPt: TPoint): TPoint;
begin
Result := ToInnerCoords(ViewAreaRect.TopLeft, MapPt);
end;
function TMapControl.MapToView(const MapRect: TRect): TRect;
begin
Result := ToInnerCoords(ViewAreaRect.TopLeft, MapRect);
end;
// ! Compiler-specific !
// TScrollBox is different in different compilers.
// - FPC considers internal area just as scrollbars' range are set (that is, whole
// scrollable area inside the box).
// - Delphi considers control bounds only (just a visible area)
// So this method converts map points to scrollbox inner coordinates (not client!)
function TMapControl.MapToInner(const MapPt: TPoint): TPoint;
begin
{$IFDEF FPC}
Result := MapPt; // scrollbox coords = absolute coords
{$ENDIF}
{$IFDEF DCC}
Result := MapToView(MapPt); // scrollbox coords = current view coords
{$ENDIF}
end;
function TMapControl.InnerToMap(const Pt: TPoint): TPoint;
begin
{$IFDEF FPC}
Result := Pt; // scrollbox coords = absolute coords
{$ENDIF}
{$IFDEF DCC}
Result := ViewToMap(Pt); // scrollbox coords = current view coords
{$ENDIF}
end;
// View area position and size in map coords
function TMapControl.ViewAreaRect: TRect;
begin
Result := ClientRect;
Result.Offset(Point(HorzScrollBar.Position, VertScrollBar.Position));
end;
// Whether view area is inside cache image
function TMapControl.ViewInCache: Boolean;
begin
Result := FCacheImageRect.Contains(ViewAreaRect);
end;
// Fill the cache image
procedure TMapControl.UpdateCache;
var
CacheHorzCount, CacheVertCount, horz, vert, CacheHorzNum, CacheVertNum: Integer;
begin
// Clear the image
FCacheImage.Canvas.Brush.Color := Self.Color;
FCacheImage.Canvas.FillRect(TRect.Create(Point(0, 0), FCacheImage.Width, FCacheImage.Height));
// Get dimensions of cache
CacheHorzCount := Min(FMapSize.cx - FCacheImageRect.Left, FCacheImageRect.Width) div TILE_IMAGE_WIDTH;
CacheVertCount := Min(FMapSize.cy - FCacheImageRect.Top, FCacheImageRect.Height) div TILE_IMAGE_HEIGHT;
// Get top-left of cache in tiles
CacheHorzNum := FCacheImageRect.Left div TILE_IMAGE_WIDTH;
CacheVertNum := FCacheImageRect.Top div TILE_IMAGE_HEIGHT;
// Draw cache tiles
for horz := 0 to CacheHorzCount - 1 do
for vert := 0 to CacheVertCount - 1 do
DrawTile(CacheHorzNum + horz, CacheVertNum + vert, Point(horz*TILE_IMAGE_WIDTH, vert*TILE_IMAGE_HEIGHT), FCacheImage.Canvas);
end;
// Calc new cache coords to cover current view area
procedure TMapControl.MoveCache;
var
ViewRect: TRect;
MarginH, MarginV: Cardinal;
begin
ViewRect := ViewAreaRect;
// move view rect to the border of tiles (to lesser value)
ViewRect.Left := ToTileWidthLesser(ViewRect.Left);
ViewRect.Top := ToTileHeightLesser(ViewRect.Top);
// resize view rect to the border of tiles (to greater value)
ViewRect.Right := ToTileWidthGreater(ViewRect.Right);
ViewRect.Bottom := ToTileHeightGreater(ViewRect.Bottom);
// reposition new cache rect to cover tile-aligned view area
// calc margins
MarginH := FCacheImageRect.Width - ViewRect.Width;
MarginV := FCacheImageRect.Height - ViewRect.Height;
// margins on the both sides
if MarginH > TILE_IMAGE_WIDTH then
MarginH := MarginH div 2;
if MarginV > TILE_IMAGE_HEIGHT then
MarginV := MarginV div 2;
FCacheImageRect.SetLocation(ViewRect.TopLeft);
FCacheImageRect.TopLeft.Subtract(Point(MarginH, MarginV));
end;
procedure TMapControl.RefreshTile(TileHorzNum, TileVertNum: Cardinal);
var
TileTopLeft: TPoint;
begin
// calc tile rect in map coords
TileTopLeft := Point(TileHorzNum*TILE_IMAGE_WIDTH, TileVertNum*TILE_IMAGE_HEIGHT);
// the tile is not in cache
if not FCacheImageRect.Contains(TileTopLeft) then
Exit;
// convert tile to cache image coords
TileTopLeft.SetLocation(ToInnerCoords(FCacheImageRect.TopLeft, TileTopLeft));
// draw to cache
DrawTile(TileHorzNum, TileVertNum, TileTopLeft, FCacheImage.Canvas);
// redraw the view
Refresh;
end;
// Draw single tile (TileHorzNum;TileVertNum) to canvas Canvas at point TopLeft
procedure TMapControl.DrawTile(TileHorzNum, TileVertNum: Cardinal; const TopLeft: TPoint; Canvas: TCanvas);
var Handled: Boolean;
begin
// check if user wants custom draw
if Assigned(FOnDrawTile) then
begin
Handled := False;
FOnDrawTile(Self, TileHorzNum, TileVertNum, TopLeft, Canvas, Handled);
if Handled then
Exit;
end;
// not handled - draw "loading"
if Assigned(FOnDrawTileLoading) then
begin
Handled := False;
FOnDrawTileLoading(Self, TileHorzNum, TileVertNum, TopLeft, Canvas, Handled);
if Handled then
Exit;
end;
// default draw
DrawTileLoading(TileHorzNum, TileVertNum, TopLeft, Canvas);
end;
// Draw single tile (TileHorzNum;TileVertNum) loading to canvas Canvas at point TopLeft
procedure TMapControl.DrawTileLoading(TileHorzNum, TileVertNum: Cardinal; const TopLeft: TPoint; Canvas: TCanvas);
var
TileRect: TRect;
TextExt: TSize;
txt: string;
begin
TileRect.TopLeft := TopLeft;
TileRect.Size := TSize.Create(TILE_IMAGE_WIDTH, TILE_IMAGE_HEIGHT);
Canvas.Brush.Color := Color;
Canvas.Pen.Color := clDkGray;
Canvas.Rectangle(TileRect);
txt := Format(S_Lbl_Loading, [TileHorzNum, TileVertNum]);
TextExt := Canvas.TextExtent(txt);
Canvas.Font.Color := clGreen;
Canvas.TextOut(
TileRect.Left + (TileRect.Width - TextExt.cx) div 2,
TileRect.Top + (TileRect.Height - TextExt.cy) div 2,
txt);
end;
// Draw copyright label on bitmap and set its size. Happens only once.
class procedure TMapControl.DrawCopyright(const Text: string; DestBmp: TBitmap);
var
Canv: TCanvas;
TextExt: TSize;
begin
Canv := DestBmp.Canvas;
Canv.Font.Name := 'Arial';
Canv.Font.Size := 8;
Canv.Font.Style := [];
TextExt := Canv.TextExtent(Text);
DestBmp.SetSize(TextExt.cx, TextExt.cy);
// Fill background
Canv.Brush.Color := clWhite;
Canv.FillRect(Rect(0, 0, DestBmp.Width, DestBmp.Height));
// Text
Canv.Font.Color := clGray;
Canv.TextOut(0, 0, Text);
end;
// Draw scale line on bitmap and set its size. Happens every zoom change.
class procedure TMapControl.DrawScale(Zoom: TMapZoomLevel; DestBmp: TBitmap);
var
Canv: TCanvas;
LetterWidth, ScalebarWidthPixel, ScalebarWidthMeter: Cardinal;
Text: string;
TextExt: TSize;
ScalebarRect: TRect;
begin
Canv := DestBmp.Canvas;
GetScaleBarParams(Zoom, ScalebarWidthPixel, ScalebarWidthMeter, Text);
Canv.Font.Name := 'Arial';
Canv.Font.Size := 8;
Canv.Font.Style := [];
TextExt := Canv.TextExtent(Text);
LetterWidth := Canv.TextWidth('W');
DestBmp.Width := LetterWidth + TextExt.cx + LetterWidth + ScalebarWidthPixel; // text, space, bar
DestBmp.Height := 2*LabelMargin + TextExt.cy;
// Frame
Canv.Brush.Color := clWhite;
Canv.Pen.Color := clSilver;
Canv.Rectangle(0, 0, DestBmp.Width, DestBmp.Height);
// Text
Canv.Font.Color := clBlack;
Canv.TextOut(LetterWidth div 2, LabelMargin, Text);
// Scale-Bar
Canv.Brush.Color := clWhite;
Canv.Pen.Color := clBlack;
ScalebarRect.Left := LetterWidth div 2 + TextExt.cx + LetterWidth;
ScalebarRect.Top := (DestBmp.Height - TextExt.cy div 2) div 2;
ScalebarRect.Width := ScalebarWidthPixel;
ScalebarRect.Height := TextExt.cy div 2;
Canv.Rectangle(ScalebarRect);
end;
// Pixels => degrees
function TMapControl.MapToGeoCoords(const MapPt: TPoint): TGeoPoint;
begin
Result := OSM.SlippyMapUtils.MapToGeoCoords(FZoom, MapPt);
end;
function TMapControl.MapToGeoCoords(const MapRect: TRect): TGeoRect;
begin
Result := OSM.SlippyMapUtils.MapToGeoCoords(FZoom, MapRect);
end;
// Degrees => pixels
function TMapControl.GeoCoordsToMap(const GeoCoords: TGeoPoint): TPoint;
begin
Result := OSM.SlippyMapUtils.GeoCoordsToMap(FZoom, GeoCoords);
end;
function TMapControl.GeoCoordsToMap(const GeoRect: TGeoRect): TRect;
begin
Result := OSM.SlippyMapUtils.GeoCoordsToMap(FZoom, GeoRect);
end;
procedure TMapControl.ScrollMapBy(DeltaHorz, DeltaVert: Integer);
begin
HorzScrollBar.Position := HorzScrollBar.Position + DeltaHorz;
VertScrollBar.Position := VertScrollBar.Position + DeltaVert;
Invalidate;
end;
procedure TMapControl.ScrollMapTo(Horz, Vert: Integer);
begin
HorzScrollBar.Position := Horz;
VertScrollBar.Position := Vert;
Invalidate;
end;
// Move the view area to new top-left point
procedure TMapControl.SetNWPoint(const MapPt: TPoint);
begin
ScrollMapTo(MapPt.X, MapPt.Y);
end;
{}//?
function TMapControl.GetCenterPoint: TGeoPoint;
begin
Result := MapToGeoCoords(ViewAreaRect.CenterPoint);
end;
procedure TMapControl.SetCenterPoint(const GeoCoords: TGeoPoint);
var
ViewRect: TRect;
Pt: TPoint;
begin
// new center point in map coords
Pt := GeoCoordsToMap(GeoCoords);
// new NW point
ViewRect := ViewAreaRect;
Pt.Offset(-ViewRect.Width div 2, -ViewRect.Height div 2);
// move
SetNWPoint(Pt);
end;
// Get top-left point of the view area
function TMapControl.GetNWPoint: TGeoPoint;
begin
Result := MapToGeoCoords(ViewAreaRect.TopLeft);
end;
// Move the view area to new top-left point
procedure TMapControl.SetNWPoint(const GeoCoords: TGeoPoint);
begin
SetNWPoint(GeoCoordsToMap(GeoCoords));
end;
// Set zoom restriction and change current zoom if it is beyond this border
procedure TMapControl.SetZoomConstraint(Index: Integer; ZoomConstraint: TMapZoomLevel);
begin
case Index of
0: FMinZoom := ZoomConstraint;
1: FMaxZoom := ZoomConstraint;
end;
if FZoom < FMinZoom then
SetZoom(FMinZoom)
else
if FZoom > FMaxZoom then
SetZoom(FMaxZoom);
end;
procedure TMapControl.ZoomToArea(const GeoRect: TGeoRect);
var
zoom, NewZoomH, NewZoomV: TMapZoomLevel;
ViewRect: TRect;
begin
ViewRect := ViewToMap(ViewAreaRect);
// Determine maximal zoom in which selected region will fit into view
// Separately for width and height
NewZoomH := FMaxZoom;
for zoom := FZoom to FMaxZoom do
if OSM.SlippyMapUtils.GeoCoordsToMap(zoom, GeoRect).Width > ViewRect.Width then
begin
NewZoomH := zoom;
Break;
end;
NewZoomV := FMaxZoom;
for zoom := FZoom to FMaxZoom do
if OSM.SlippyMapUtils.GeoCoordsToMap(zoom, GeoRect).Height > ViewRect.Height then
begin
NewZoomV := zoom;
Break;
end;
SetZoom(Min(NewZoomH, NewZoomV));
SetNWPoint(GeoRect.TopLeft);
end;
// Zoom to fill view area as much as possible
procedure TMapControl.ZoomToFit;
begin
ZoomToArea(MapToGeoCoords(TRect.Create(Point(0, 0), FMapSize.cx, FMapSize.cy)));
end;
// Base method to draw mapmark. Calls callback to do custom actions
procedure TMapControl.DrawMapMark(Canvas: TCanvas; MapMark: TMapMark);
var
Handled: Boolean;
MMPt: TPoint;
MapMarkRect: TRect;
pEffGlStyle: PMapMarkGlyphStyle;
pEffCapStyle: PMapMarkCaptionStyle;
CapFont: TFont;
begin
Handled := False;
MMPt := ToInnerCoords(ViewAreaRect.TopLeft, GeoCoordsToMap(MapMark.Coord));
// ! Consider Canvas.ClipRect
MMPt.Offset(Canvas.ClipRect.TopLeft);
if Assigned(FOnDrawMapMark) then
FOnDrawMapMark(Self, Canvas, MMPt, MapMark, Handled);
if Handled then Exit;
if not MapMark.Visible then Exit;
// Draw glyph
// Determine effective glyph style
if propGlyphStyle in MapMark.CustomProps
then pEffGlStyle := @MapMark.GlyphStyle
else pEffGlStyle := @MapMarkGlyphStyle;
// Determine size
MapMarkRect.TopLeft := MMPt;
MapMarkRect.Offset(-pEffGlStyle.Size div 2, -pEffGlStyle.Size div 2);
MapMarkRect.Size := TSize.Create(pEffGlStyle.Size, pEffGlStyle.Size);
Canvas.Brush.Color := pEffGlStyle.BgColor;
Canvas.Pen.Color := pEffGlStyle.BorderColor;
case pEffGlStyle.Shape of
gshCircle:
Canvas.Ellipse(MapMarkRect);
gshSquare:
Canvas.Rectangle(MapMarkRect);
gshTriangle:
Triangle(Canvas, MapMarkRect);
end;
// Draw caption
if MapMark.Caption <> '' then
begin
// Determine effective caption style
if propCaptionStyle in MapMark.CustomProps
then pEffCapStyle := @MapMark.CaptionStyle
else pEffCapStyle := @MapMarkCaptionStyle;
// Determine effective caption font
if propFont in MapMark.CustomProps
then CapFont := MapMark.CaptionFont
else CapFont := MapMarkCaptionFont;
Canvas.Font := CapFont;
Canvas.Font.Color := pEffCapStyle.Color;
{}// TODO: text position, alignment, ...
MMPt := Point(MapMarkRect.Right + pEffCapStyle.DX, MapMarkRect.Top + pEffCapStyle.DY);
if pEffCapStyle.Transparent then
Canvas.Brush.Style := bsClear
else
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := pEffCapStyle.BgColor;
end;
Canvas.TextOut(MMPt.X, MMPt.Y, MapMark.Caption);
end;
end;
end.
|
unit hookedfunctions;
{$mode delphi}
interface
uses sysutils, windows, messages, syncobjs;
type TNtAllocateVirtualMemory=function(processHandle: THandle; BaseAddress: PPtrUint; ZeroBits: DWORD; RegionSize: PDWORD; AllocationType: DWORD; Protect: DWORD): DWORD; stdcall;
type TNtFreeVirtualMemory=function(processHandle: THandle; BaseAddress: PPtrUint; RegionSize: PDWORD; FreeType: DWORD ): DWORD; stdcall;
type TRtlAllocateHeap=function(HeapHandle: pointer; Flags: DWORD; size: integer): pointer; stdcall;
type TRtlFreeHeap=function(HeapHandle: pointer; Flags: DWORD; HeapBase: pointer): BOOL; stdcall;
type TRtlDestroyHeap=function(HeapHandle: pointer): pointer; stdcall;
function CeAllocateVirtualMemory(processHandle: THandle; BaseAddress: PPtrUint; ZeroBits: DWORD; RegionSize: PDWORD; AllocationType: DWORD; Protect: DWORD): DWORD; stdcall;
function CeFreeVirtualMemory(processHandle: THandle; BaseAddress: PPtrUint; RegionSize: PDWORD; FreeType: DWORD ): DWORD; stdcall;
function CeRtlAllocateHeap(HeapHandle: pointer; Flags: DWORD; size: integer): pointer; stdcall;
function CeRtlFreeHeap(HeapHandle: pointer; Flags: DWORD; HeapBase: pointer): BOOL; stdcall;
function CeRtlDestroyHeap(HeapHandle: pointer): pointer; stdcall;
function CeInitializeAllocHook: BOOL; stdcall;
var
NtAllocateVirtualMemoryOrig: TNtAllocateVirtualMemory;
NtFreeVirtualMemoryOrig: TNtFreeVirtualMemory;
RtlAllocateHeapOrig: TRtlAllocateHeap;
RtlFreeHeapOrig: TRtlFreeHeap;
RtlDestroyHeapOrig: TRtlDestroyHeap;
const
HOOKEVENT_ALLOC=0;
HOOKEVENT_FREE=1;
HOOKEVENT_HEAPALLOC=2;
HOOKEVENT_HEAPFREE=3;
HOOKEVENT_HEAPDESTROY=4;
type
TAllocData=record
handle: qword;
baseaddress: qword;
allocationType: dword;
protect: dword;
size: dword;
esp: qword;
end;
TFreeData=record
handle: qword;
baseaddress: qword;
size: dword;
FreeType: dword;
end;
THeapAllocData=record
HeapHandle: qword;
Flags: DWORD;
Size: dword;
esp:qword;
address: qword;
end;
THeapFreeData=record
HeapHandle: qword;
Flags: dword;
HeapBase: qword;
end;
THeapDestroyData=record
HeapHandle: qword;
end;
THookEvent = record
eventtype: integer;
case integer of
HOOKEVENT_ALLOC: (AllocEvent: TAllocData);
HOOKEVENT_FREE: (FreeEvent: TFreeData);
HOOKEVENT_HEAPALLOC: (HeapAllocEvent: THeapAllocData);
HOOKEVENT_HEAPFREE: (HeapFreeEvent: THeapFreeData);
HOOKEVENT_HEAPDESTROY: (HeapDestroyEvent: THeapDestroyData);
end;
var
HookEventData: THookEvent;
var HasSetupDataEvent: qword; //set by this routine
var CEHasHandledItEvent: qword; //set by ce
var CEInitializationFinished: qword; //set by CeInitializeAllocHook, and reset by ce (or never)
implementation
var allocCS: TCriticalSection;
function CeInitializeAllocHook: BOOL; stdcall;
//this function will gather the start memory situation using a heapwalk and pass off that information to ce (ce's lookup is faster for the pointerscan)
//call this after the hooks are in place and all configuration has been completed (handles)
var heaphandles: array of thandle;
size: integer;
h: THandle;
i: integer;
phe: TProcessHeapEntry;
begin
ResetEvent(CEInitializationFinished); //in case ce forgot to reset it...
h:=0;
size:=GetProcessHeaps(0,h);
if size>0 then
begin
setlength(heaphandles,size);
size:=GetProcessHeaps(size,heaphandles[0]);
if size>0 then
begin
for i:=0 to size-1 do
begin
heaplock(heaphandles[i]);
try
ZeroMemory(@phe,sizeof(phe));
while HeapWalk(heaphandles[i], phe) do
begin
if phe.wFlags=PROCESS_HEAP_ENTRY_BUSY then
begin
allocCS.Enter;
try
HookEventData.eventtype:=HOOKEVENT_HEAPALLOC;
HookEventData.HeapAllocEvent.HeapHandle:=heaphandles[i];
HookEventData.HeapAllocEvent.flags:=0;
HookEventData.HeapAllocEvent.size:=phe.cbData;
HookEventData.HeapAllocEvent.esp:=0;
HookEventData.HeapAllocEvent.address:=qword(phe.lpData);
//signal ce that the event has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('CeRtlAllocateHeap:timeout on CEHasHandledItEvent');
finally
allocCS.Leave;
end;
end;
end;
finally
heapunlock(heaphandles[i]);
end;
end;
end;
end;
result:=true;
setevent(CEInitializationFinished);
end;
function CeRtlAllocateHeap(HeapHandle: pointer; Flags: DWORD; size: integer): pointer; stdcall;
var
stack: dword;
begin
result:=RtlAllocateHeapOrig(heapHandle, flags,size);
if result<>nil then
begin
allocCS.Enter;
HookEventData.eventtype:=HOOKEVENT_HEAPALLOC;
HookEventData.HeapAllocEvent.HeapHandle:=qword(HeapHandle);
HookEventData.HeapAllocEvent.flags:=flags;
HookEventData.HeapAllocEvent.size:=size;
HookEventData.HeapAllocEvent.address:=qword(result);
//signal ce that the event has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('CeRtlAllocateHeap:timeout on CEHasHandledItEvent');
allocCS.Leave;
end;
end;
function CeRtlFreeHeap(HeapHandle: pointer; Flags: DWORD; HeapBase: pointer): BOOL; stdcall;
begin
result:=RtlFreeHeapOrig(heapHandle, Flags, HeapBase);
if result then
begin
allocCS.Enter;
HookEventData.eventtype:=HOOKEVENT_HEAPFREE;
HookEventData.HeapFreeEvent.HeapHandle:=qword(HeapHandle);
HookEventData.HeapFreeEvent.Flags:=flags;
HookEventData.HeapFreeEvent.HeapBase:=qword(HeapBase);
//signal ce that the event has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('CeRtlFreeHeap:timeout on CEHasHandledItEvent');
allocCS.Leave;
end;
end;
function CeRtlDestroyHeap(HeapHandle: pointer): pointer; stdcall;
//Hooked because destroying a heaphandle destroys ALL related heap allocs
begin
result:=RtlDestroyHeapOrig(heaphandle);
if result=nil then
begin
allocCS.Enter;
HookEventData.eventtype:=HOOKEVENT_HEAPDESTROY;
HookEventData.HeapDestroyEvent.HeapHandle:=qword(HeapHandle);
//signal ce that the event has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('CeRtlDestroyHeap:timeout on CEHasHandledItEvent');
allocCS.Leave;
end;
end;
function CeAllocateVirtualMemory(processHandle: THandle; BaseAddress: PPtrUint; ZeroBits: DWORD; RegionSize: PDWORD; AllocationType: DWORD; Protect: DWORD): DWORD; stdcall;
var
stack: dword;
begin
//note: don't call anything that allocs memory
result:=NtAllocateVirtualMemoryOrig(processHandle, BaseAddress, ZeroBits, RegionSize, AllocationType, Protect);
if result=0 then //successfully allocated
begin
allocCS.Enter;
//fill in allocation field
//post a message to the handlerthread with the address of CreateEvent and wait till it's done
HookEventData.eventtype:=HOOKEVENT_ALLOC;
HookEventData.AllocEvent.handle:=processHandle;
if baseaddress<>nil then
HookEventData.AllocEvent.baseaddress:=BaseAddress^
else
HookEventData.AllocEvent.baseaddress:=0;
HookEventData.AllocEvent.allocationType:=AllocationType;
HookEventData.AllocEvent.protect:=protect;
// asm
// mov stack,ebp
// end;
// HookEventData.AllocEvent.esp:=stack;
if regionsize<>nil then
HookEventData.AllocEvent.size:=regionsize^
else
HookEventData.AllocEvent.size:=0;
//signal ce that the createEvent has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('Alloc:timeout on CEHasHandledItEvent');
allocCS.Leave;
end;
end;
function CeFreeVirtualMemory(processHandle: THandle; BaseAddress: PPtrUint; RegionSize: PDWORD; FreeType: DWORD ): DWORD; stdcall;
begin
result:=NtFreeVirtualMemoryOrig(processHandle, BaseAddress, RegionSize, FreeType);
if result=0 then //success
begin
allocCS.Enter;
HookEventData.eventtype:=HOOKEVENT_FREE;
HookEventData.FreeEvent.handle:=processHandle;
if baseaddress <> nil then
HookEventData.FreeEvent.baseaddress:=baseaddress^
else
HookEventData.FreeEvent.baseaddress:=0;
if regionsize<>nil then
HookEventData.FreeEvent.size:=regionSize^
else
HookEventData.FreeEvent.size:=0;
HookEventData.FreeEvent.FreeType:=FreeType;
//signal ce that the createEvent has been filled in
SetEvent(HasSetupDataEvent);
//and wait till ce is done with it
if waitforsingleobject(CEHasHandledItEvent,5000)<>WAIT_OBJECT_0 then
outputdebugstring('Free:timeout on CEHasHandledItEvent');
allocCS.Leave;
end;
end;
initialization
allocCS:=TCriticalSection.Create;
end.
|
program EliminacionEinsercion;
uses
crt;
type
TV = array[1..20] of integer;
var
V: TV;
N: byte;
pos: byte;
X: integer;
Procedure ingresaVec(var V: TV; N: byte);
var
i: byte;
begin
for i:= 1 to N do
begin
writeln('Ingrese el elemento ',i); readln(V[i]);
end;
clrscr();
end;
Procedure Elimina(var V: TV; var N: byte; pos: byte);
var
i: byte;
begin
for i:= pos + 1 to N do // elimina la ultima posicion
V[i - 1]:= V[i];
N:= N - 1;
end;
Procedure inserta(var V: TV; var N: byte; pos: byte; X: integer);
var
i: byte;
begin
for i:= N downto pos do
V[i + 1]:= V[i];
V[pos]:= X;
N:= N + 1;
end;
Procedure show(V: TV; N: byte);
var
i: byte;
begin
for i:= 1 to N do
write(V[i],' ');
end;
begin
writeln('Ingrese la cantidad de elementos que tendra el arreglo'); readln(N);
writeln('Ingrese la posicion que desea eliminar'); readln(pos);
ingresaVec(V, N);
writeln('El arreglo ingresado es: ');
show(V, N);
writeln();
Elimina(V, N, pos);
writeln('Eliminando el ultimo elemento...');
writeln('===========================================');
show(V, N);
writeln();
writeln('===========================================');
writeln('Ingrese el elemento que desea ingresar en la posicion ingresada'); readln(X);
inserta(V, N, pos, X);
writeln('====================');
show(V, N);
readln();
end.
|
unit ExifCleaner;
interface
uses
CCR.Exif, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Controls,
Vcl.Forms;
type
TForm1 = class(TForm)
chooseDirButton: TButton;
Memo1: TMemo;
bRemoveExif: TButton;
bChangeDate: TButton;
ProgressBar1: TProgressBar;
bRenameFiles: TButton;
procedure chooseDirButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure bRemoveExifClick(Sender: TObject);
procedure bChangeDateClick(Sender: TObject);
procedure bRenameFilesClick(Sender: TObject);
private
procedure RemoveExifTags(filename: string);
procedure FixMonthInTags(filename: string; Date: string);
procedure ScanDir(StartDir: string; Mask: string; List: TStrings);
procedure AddToMemo(Text: string);
function RenameFileToExifData(filename: string): string;
public
{ Public declarations }
end;
var
Form1: TForm1;
chosenDir: string;
FileList: TStringList;
implementation
uses
Vcl.Dialogs, Vcl.FileCtrl;
{$R *.dfm}
procedure TForm1.AddToMemo(Text: string);
begin
Memo1.Lines.Add(Text);
end;
procedure TForm1.bChangeDateClick(Sender: TObject);
var
result: string;
Element: string;
begin
result := InputBox('Введите новую дату для фото', 'В формате ДД.ММ.ГГГГ', '');
AddToMemo('Установлена новая дата для фото:' + result);
ProgressBar1.Min := 0;
ProgressBar1.Max := FileList.Count;
ProgressBar1.Step := 1;
for Element in FileList do
begin
FixMonthInTags(Element, result);
ProgressBar1.StepIt;
AddToMemo('Изменена дата: ' + Element);
end;
ShowMessage('Всё готово');
end;
procedure TForm1.bRemoveExifClick(Sender: TObject);
var
Element: string;
begin
ProgressBar1.Min := 0;
ProgressBar1.Max := FileList.Count;
ProgressBar1.Step := 1;
for Element in FileList do
begin
RemoveExifTags(Element);
ProgressBar1.StepIt;
end;
ShowMessage('Всё готово');
end;
procedure TForm1.bRenameFilesClick(Sender: TObject);
var
Element: string;
begin
ProgressBar1.Min := 0;
ProgressBar1.Max := FileList.Count;
ProgressBar1.Step := 1;
for Element in FileList do
begin
RenameFileToExifData(Element);
ProgressBar1.StepIt;
end;
ShowMessage('Всё готово');
end;
procedure TForm1.chooseDirButtonClick(Sender: TObject);
begin
if SelectDirectory('Выберите каталог:', '', chosenDir) then
begin
ScanDir(chosenDir, '*.jpg', FileList);
bRemoveExif.Enabled := True;
bChangeDate.Enabled := True;
bRenameFiles.Enabled := True;
end;
end;
procedure TForm1.RemoveExifTags(filename: string);
var
ExifData: TExifData;
Section: TExifSection;
Tag: TExifTag;
begin
if FileExists(filename) then
begin
ExifData := TExifData.Create;
try
ExifData.LoadFromJPEG(filename);
for Section in ExifData do
for Tag in Section do
begin
Tag.Delete;
end;
ExifData.SaveToJPEG(filename);
finally
ExifData.Free;
end;
end;
end;
procedure TForm1.ScanDir(StartDir: string; Mask: string; List: TStrings);
var
SearchRec: TSearchRec;
begin
if Mask = '' then
Mask := '*.*';
if StartDir[Length(StartDir)] <> '\' then
StartDir := StartDir + '\';
if FindFirst(StartDir + Mask, faAnyFile, SearchRec) = 0 then
begin
repeat
Application.ProcessMessages;
if (SearchRec.Attr and faDirectory) <> faDirectory then
List.Add(StartDir + SearchRec.Name)
else if (SearchRec.Name <> '..') and (SearchRec.Name <> '.') then
begin
List.Add(StartDir + SearchRec.Name + '\');
ScanDir(StartDir + SearchRec.Name + '\', Mask, List);
end;
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
end;
procedure TForm1.FixMonthInTags(filename: string; Date: string);
var
ExifData: TExifData;
NewDate, OldDate: TDateTime;
begin
if FileExists(filename) then
begin
// Format:='yyyy:mm:dd';
NewDate := StrToDate(Date);
ExifData := TExifData.Create;
try
ExifData.LoadFromJPEG(filename);
OldDate := ExifData.DateTimeOriginal;
ReplaceDate(OldDate, NewDate);
ExifData.DateTimeOriginal := OldDate;
ExifData.SaveToJPEG(filename);
finally
ExifData.Free;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
AddToMemo('Программа запущена');
FileList := TStringList.Create;
bRemoveExif.Enabled := false;
bChangeDate.Enabled := false;
bRenameFiles.Enabled := false;
end;
function TForm1.RenameFileToExifData(filename: string): string;
var
ExifData: TExifData;
Date: TDateTime;
Path: string;
Name: string;
begin
ExifData := TExifData.Create;
try
ExifData.LoadFromJPEG(filename);
Date := ExifData.DateTimeOriginal;
Path := ExtractFilePath(filename);
Name := FormatDateTime('yyyymmddhhnnss'+Random(10),
Date) + '.jpg';
// AddToMemo(Name);
if RenameFile(filename, Path + Name)
then AddToMemo(Name)
else AddToMemo('Не удалось переименовать:'+ IntToStr(GetLastError));
finally
ExifData.Free;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.