text stringlengths 14 6.51M |
|---|
{ complete expand -- modified getc and putc to deal with end of file }
program expand (input, output);
const
ENDFILE = -1;
NEWLINE = 10; { ASCII value }
TILDE = 126;
type
character = -1..127; { ASCII, plus ENDFILE }
{ getc -- get one character from standard input, set end of file flag if eof }
function getc (var c : character; var eofflag: boolean) : character;
var
ch : char;
begin
if (eofflag) then
exit
else if (eof) then begin
c := ENDFILE;
eofflag := true
end
else if (eoln) then begin
readln;
c := NEWLINE
end
else begin
read(ch);
c := ord(ch)
end;
getc := c
end;
{ putc -- put one character on standard output if not past end of file }
procedure putc (c : character; eofflag : boolean);
begin
if (eofflag) then
exit
else if (c = NEWLINE) then
writeln
else
write(chr(c))
end;
{ isupper -- true if c is upper case letter }
function isupper (c : character) : boolean;
begin
isupper := c in [ord('A')..ord('Z')]
end;
{ expand -- uncompress standard input }
procedure expand;
const
WARNING = TILDE; { ~ }
var
c : character;
n : integer;
eofflag : boolean;
begin
eofflag := false;
while (getc(c, eofflag) <> ENDFILE) do
if (c <> WARNING) then
putc(c, eofflag)
else if (isupper(getc(c, eofflag))) then begin
n := c - ord('A') + 1;
getc(c, eofflag);
if (not eofflag) then
for n := n downto 1 do
putc(c, eofflag)
else begin
eofflag := false; { we want to print after all }
putc(WARNING, eofflag);
putc(n + ord('A') -1, eofflag);
break
end
end
else begin
putc(WARNING, eofflag);
putc(c, eofflag)
end
end;
begin { main program }
expand
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [R01]
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 R01VO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('R01')]
TR01VO = class(TVO)
private
FID: Integer;
FSERIE_ECF: String;
FCNPJ_EMPRESA: String;
FCNPJ_SH: String;
FINSCRICAO_ESTADUAL_SH: String;
FINSCRICAO_MUNICIPAL_SH: String;
FDENOMINACAO_SH: String;
FNOME_PAF_ECF: String;
FVERSAO_PAF_ECF: String;
FMD5_PAF_ECF: String;
FDATA_INICIAL: TDateTime;
FDATA_FINAL: TDateTime;
FVERSAO_ER: String;
FNUMERO_LAUDO_PAF: String;
FRAZAO_SOCIAL_SH: String;
FENDERECO_SH: String;
FNUMERO_SH: String;
FCOMPLEMENTO_SH: String;
FBAIRRO_SH: String;
FCIDADE_SH: String;
FCEP_SH: String;
FUF_SH: String;
FTELEFONE_SH: String;
FCONTATO_SH: String;
FPRINCIPAL_EXECUTAVEL: String;
FLOGSS: String;
public
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('SERIE_ECF', 'Serie Ecf', 160, [ldGrid, ldLookup, ldCombobox], False)]
property SerieEcf: String read FSERIE_ECF write FSERIE_ECF;
[TColumn('CNPJ_EMPRESA', 'Cnpj Empresa', 112, [ldGrid, ldLookup, ldCombobox], False)]
property CnpjEmpresa: String read FCNPJ_EMPRESA write FCNPJ_EMPRESA;
[TColumn('CNPJ_SH', 'Cnpj Sh', 112, [ldGrid, ldLookup, ldCombobox], False)]
property CnpjSh: String read FCNPJ_SH write FCNPJ_SH;
[TColumn('INSCRICAO_ESTADUAL_SH', 'Inscricao Estadual Sh', 112, [ldGrid, ldLookup, ldCombobox], False)]
property InscricaoEstadualSh: String read FINSCRICAO_ESTADUAL_SH write FINSCRICAO_ESTADUAL_SH;
[TColumn('INSCRICAO_MUNICIPAL_SH', 'Inscricao Municipal Sh', 112, [ldGrid, ldLookup, ldCombobox], False)]
property InscricaoMunicipalSh: String read FINSCRICAO_MUNICIPAL_SH write FINSCRICAO_MUNICIPAL_SH;
[TColumn('DENOMINACAO_SH', 'Denominacao Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property DenominacaoSh: String read FDENOMINACAO_SH write FDENOMINACAO_SH;
[TColumn('NOME_PAF_ECF', 'Nome Paf Ecf', 320, [ldGrid, ldLookup, ldCombobox], False)]
property NomePafEcf: String read FNOME_PAF_ECF write FNOME_PAF_ECF;
[TColumn('VERSAO_PAF_ECF', 'Versao Paf Ecf', 80, [ldGrid, ldLookup, ldCombobox], False)]
property VersaoPafEcf: String read FVERSAO_PAF_ECF write FVERSAO_PAF_ECF;
[TColumn('MD5_PAF_ECF', 'Md5 Paf Ecf', 256, [ldGrid, ldLookup, ldCombobox], False)]
property Md5PafEcf: String read FMD5_PAF_ECF write FMD5_PAF_ECF;
[TColumn('DATA_INICIAL', 'Data Inicial', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataInicial: TDateTime read FDATA_INICIAL write FDATA_INICIAL;
[TColumn('DATA_FINAL', 'Data Final', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataFinal: TDateTime read FDATA_FINAL write FDATA_FINAL;
[TColumn('VERSAO_ER', 'Versao Er', 32, [ldGrid, ldLookup, ldCombobox], False)]
property VersaoEr: String read FVERSAO_ER write FVERSAO_ER;
[TColumn('NUMERO_LAUDO_PAF', 'Numero Laudo Paf', 320, [ldGrid, ldLookup, ldCombobox], False)]
property NumeroLaudoPaf: String read FNUMERO_LAUDO_PAF write FNUMERO_LAUDO_PAF;
[TColumn('RAZAO_SOCIAL_SH', 'Razao Social Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property RazaoSocialSh: String read FRAZAO_SOCIAL_SH write FRAZAO_SOCIAL_SH;
[TColumn('ENDERECO_SH', 'Endereco Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property EnderecoSh: String read FENDERECO_SH write FENDERECO_SH;
[TColumn('NUMERO_SH', 'Numero Sh', 80, [ldGrid, ldLookup, ldCombobox], False)]
property NumeroSh: String read FNUMERO_SH write FNUMERO_SH;
[TColumn('COMPLEMENTO_SH', 'Complemento Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property ComplementoSh: String read FCOMPLEMENTO_SH write FCOMPLEMENTO_SH;
[TColumn('BAIRRO_SH', 'Bairro Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property BairroSh: String read FBAIRRO_SH write FBAIRRO_SH;
[TColumn('CIDADE_SH', 'Cidade Sh', 320, [ldGrid, ldLookup, ldCombobox], False)]
property CidadeSh: String read FCIDADE_SH write FCIDADE_SH;
[TColumn('CEP_SH', 'Cep Sh', 64, [ldGrid, ldLookup, ldCombobox], False)]
property CepSh: String read FCEP_SH write FCEP_SH;
[TColumn('UF_SH', 'Uf Sh', 16, [ldGrid, ldLookup, ldCombobox], False)]
property UfSh: String read FUF_SH write FUF_SH;
[TColumn('TELEFONE_SH', 'Telefone Sh', 80, [ldGrid, ldLookup, ldCombobox], False)]
property TelefoneSh: String read FTELEFONE_SH write FTELEFONE_SH;
[TColumn('CONTATO_SH', 'Contato Sh', 160, [ldGrid, ldLookup, ldCombobox], False)]
property ContatoSh: String read FCONTATO_SH write FCONTATO_SH;
[TColumn('PRINCIPAL_EXECUTAVEL', 'Principal Executavel', 320, [ldGrid, ldLookup, ldCombobox], False)]
property PrincipalExecutavel: String read FPRINCIPAL_EXECUTAVEL write FPRINCIPAL_EXECUTAVEL;
[TColumn('LOGSS', 'Log', 8, [], False)]
property HashRegistro: String read FLOGSS write FLOGSS;
end;
implementation
initialization
Classes.RegisterClass(TR01VO);
finalization
Classes.UnRegisterClass(TR01VO);
end.
|
unit Controle.Venda;
interface
uses
Bd.Gerenciador, uTipos, Modelo.Venda, Dao.Venda, Modelo.Produto, Dao.Produto,
Controle.Padrao;
type
TControleVenda = class(TControlePadrao)
public
Venda: TVenda;
Constructor Create;
Destructor Destroy; override;
procedure SalvarVenda(AEvento: TEstadoVenda);
function ObtemNumeroVago: Integer; override;
function ObtemTanqueNaVenda(ACodigo: string): Integer;
procedure ConsultaProduto(ACodigo: string);
end;
var
Bd : TBdGerenciador;
VendaDao : TVendaDao;
Produto : TProduto;
ProdutoDao : TProdutoDao;
implementation
uses
System.SysUtils, Classes.Calculos;
{ TControleVenda }
procedure TControleVenda.ConsultaProduto(ACodigo: string);
begin
ProdutoDao.RetornaProduto(StrToIntDef(ACodigo, 0), Produto);
end;
constructor TControleVenda.Create;
begin
if not Assigned(Venda) then
Venda := TVenda.Create;
if not Assigned(VendaDao) then
VendaDao := TVendaDao.Create;
if not Assigned(Produto) then
Produto := TProduto.Create;
if not Assigned(ProdutoDao) then
ProdutoDao := TProdutoDao.Create;
Bd := TBdGerenciador.ObterInstancia;
end;
destructor TControleVenda.Destroy;
begin
if Assigned(Venda) then
FreeAndNil(Venda);
if Assigned(VendaDao) then
FreeAndNil(VendaDao);
if Assigned(Produto) then
FreeAndNil(Produto);
if Assigned(ProdutoDao) then
FreeAndNil(ProdutoDao);
inherited Destroy;
end;
function TControleVenda.ObtemTanqueNaVenda(ACodigo: string): Integer;
begin
Result := VendaDao.RetornaTanqueNaVenda(ACodigo);
end;
function TControleVenda.ObtemNumeroVago: Integer;
begin
Result := Bd.RetornaMaxCodigo('Venda', 'Codigo');
end;
procedure TControleVenda.SalvarVenda(AEvento: TEstadoVenda);
begin
if AEvento = tevEmVenda then
VendaDao.Inserir(Venda);
end;
end.
|
unit errors_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, COMMONS;
type
TfrmError = class(TForm)
lblError: TLabel;
redError: TRichEdit;
Panel1: TPanel;
btnContinue: TButton;
btnCancel: TButton;
btnHelp: TButton;
procedure btnCancelClick(Sender: TObject);
procedure btnContinueClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure ResetButtons;
public
{ Public declarations }
end;
type
ErrorButtons = (hbHelp,hbCancel,hbContinue);
HelpProc = reference to procedure;
type
Error = class
private
var
sTitle,sMessage,sHelp : string;
hButtons : MArray<ErrorButtons>;
public
constructor Create(Title,oMessage:string;Buttons:MArray<ErrorButtons>;help:string);
procedure Show;
class procedure QuickShow(Title, oMessage:string;Buttons:MArray<ErrorButtons>;help:string); overload;
class procedure QuickShow(Title, oMessage:string;Buttons:MArray<ErrorButtons>);overload;
class procedure QuickShow(Title, oMessage:string;Buttons:array of ErrorButtons;help:string); overload;
class procedure QuickShow(Title, oMessage:string;Buttons:array of ErrorButtons);overload;
class procedure QuickShow(Title, oMessage:string);overload;
class procedure QuickShow(Title, oMessage, help:string);overload;
class procedure QuickShow(oMessage:string;Buttons:MArray<ErrorButtons>;help:string);overload;
class procedure QuickShow(oMessage:string;Buttons:MArray<ErrorButtons>);overload;
class procedure QuickShow(oMessage:string;Buttons:array of ErrorButtons;help:string);overload;
class procedure QuickShow(oMessage:string;Buttons:array of ErrorButtons);overload;
class procedure QuickShow(oMessage:string);overload;
end;
var
err : Error;
frmError: TfrmError;
implementation
uses help_u;
{$R *.dfm}
{ THelp }
constructor Error.Create(Title, oMessage: string; Buttons: MArray<ErrorButtons>;help:string);
begin
sTitle := Title;
sMEssage := oMessage;
hButtons := Buttons;
sHelp := help;
end;
class procedure Error.QuickShow(Title, oMessage: string);
begin
QuickShow(Title, oMessage,MArray<ErrorButtons>.Create([hbCancel]));
end;
class procedure Error.QuickShow(Title, oMessage: string;
Buttons: MArray<ErrorButtons>);
begin
QuickShow(Title,oMessage,Buttons,'')
end;
class procedure Error.QuickShow(Title, oMessage: string;
Buttons: MArray<ErrorButtons>; help:string);
begin
err := Error.Create(Title,oMessage,Buttons,help);
err.Show;
end;
class procedure Error.QuickShow(oMessage: string);
begin
QuickShow(oMessage,MArray<ErrorButtons>.Create(TArray<ErrorButtons>.Create(hbCancel)));
end;
class procedure Error.QuickShow(Title, oMessage, help: string);
begin
QuickShow(Title,oMessage,[hbCancel,hbHelp],help);
end;
class procedure Error.QuickShow(Title, oMessage: string;
Buttons: array of ErrorButtons);
begin
QuickShow(Title,oMessage,MArray<ErrorButtons>.Create(Buttons));
end;
class procedure Error.QuickShow(Title, oMessage: string;
Buttons: array of ErrorButtons; help:string);
begin
QuickShow(Title,oMessage,MArray<ErrorButtons>.Create(Buttons),help);
end;
class procedure Error.QuickShow(oMessage: string;
Buttons: array of ErrorButtons);
begin
QuickShow(oMessage,MArray<ErrorButtons>.Create(Buttons));
end;
class procedure Error.QuickShow(oMessage: string;
Buttons: array of ErrorButtons; help:string);
begin
QuickShow(oMessage,MArray<ErrorButtons>.Create(Buttons),help);
end;
class procedure Error.QuickShow(oMessage: string;
Buttons: MArray<ErrorButtons>);
begin
QuickShow(oMessage,Buttons,'');
end;
class procedure Error.QuickShow(oMessage: string;
Buttons: MArray<ErrorButtons>; help:string);
begin
QuickShow('',oMessage,Buttons,help);
end;
procedure Error.Show;
var
but : ErrorButtons;
x:integer;
begin
with frmError do
begin
ResetButtons;
if sTitle <> '' then
Caption := 'Error - '+sTitle
else
Caption := 'Error';
redError.Text := sMessage;
x := 345;
for but in hButtons.container do
begin
if but = hbContinue then
begin
btnContinue.Left := x;
btnContinue.Visible := True;
end
else if but = hbCancel then
begin
btnCancel.Left := x;
btnCancel.Visible := True;
end
else if but = hbHelp then
begin
btnHelp.Left := x;
btnHelp.Visible := True;
end;
x := x - 81;
end;
Show;
end;
end;
procedure TfrmError.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmError.btnContinueClick(Sender: TObject);
begin
Close;
end;
procedure TfrmError.btnHelpClick(Sender: TObject);
begin
if err <> nil then
frmHelp.Help(err.sHelp);
Close;
end;
procedure TfrmError.FormClose(Sender: TObject; var Action: TCloseAction);
begin
err.Free;
end;
procedure TfrmError.ResetButtons;
begin
btnContinue.Visible := False;
btnHelp.Visible := False;
btnCancel.Visible := False;
btnContinue.Left := 7;
btnHelp.Left := 7;
btnCancel.Left := 7;
end;
end.
|
Unit USplit;
interface
uses
SysUtils
,Classes // TString;
;
type
TSplitArray = array of String;
function Split(const Source, Delimiter: String): TSplitArray;
implementation
//-----------------------------------------------------------------------
// Découpage d'une chaîne en un tableau de chaînes suivant un délimiteur
//
// Paramètres :
// Source ........... Chaîne à découper
// Delimiter ........ Suite de délimiteurs à utiliser
//
// Retourne :
// Un tableau de chaînes contenant les sous-chaînes (sans les délimiteurs)
// Le tableau peut être vide
//-----------------------------------------------------------------------
function Split(const Source, Delimiter: String): TSplitArray;
var
iCount: Integer;
iPos: Integer;
iLength: Integer;
sTemp: String;
aSplit: TSplitArray;
begin
sTemp := Source;
iCount := 0;
iLength := Length(Delimiter) - 1;
repeat
iPos := Pos(Delimiter, sTemp);
if iPos = 0 then
break
else begin
Inc(iCount);
SetLength(aSplit, iCount);
aSplit[iCount - 1] := Copy(sTemp, 1, iPos - 1);
Delete(sTemp, 1, iPos + iLength);
end;
until False;
if Length(sTemp) > 0 then begin
Inc(iCount);
SetLength(aSplit, iCount);
aSplit[iCount - 1] := sTemp;
end;
Result := aSplit;
end;
end. |
unit oca.movements;
interface
uses
sysutils;
const
NULLIDX = -1;
type
idxRange = NULLIDX..MAXINT;
tOcaMovement = record
player : integer;
dice : integer;
next : idxRange;
end;
tControlRecord = record
first : idxRange;
last : idxRange;
erased : idxRange;
count : integer;
end;
tControl = file of tControlRecord;
tData = file of tOcaMovement;
tQueueOcaMvmt = record
data : tData;
control : tControl;
end;
//(var this : tQueueOcaMvmt);
procedure loadQueue (var this : tQueueOcaMvmt; path, filename : string);
procedure newEmptyQueue (var this : tQueueOcaMvmt; path, filename : string);
procedure insert (var this : tQueueOcaMvmt; item : tOcaMovement);
procedure deletePos (var this : tQueueOcaMvmt; pos : idxRange);
procedure deleteItem (var this : tQueueOcaMvmt; item : tOcaMovement);
procedure queue (var this : tQueueOcaMvmt; item : tOcaMovement);
function dequeue (var this : tQueueOcaMvmt) : tOcaMovement;
function peek (var this : tQueueOcaMvmt) : tOcaMovement;
function createMovement(var this : tQueueOcaMvmt; player, movement : integer) : tOcaMovement;
function get (var this : tQueueOcaMvmt; pos : idxRange) : tOcaMovement;
function isEmpty (var this : tQueueOcaMvmt) : boolean;
function length (var this : tQueueOcaMvmt) : integer;
function first (var this : tQueueOcaMvmt) : idxRange;
function last (var this : tQueueOcaMvmt) : idxRange;
function next (var this : tQueueOcaMvmt; pos : idxRange) : idxRange;
function isValidPos (var this : tQueueOcaMvmt; pos : idxRange) : boolean;
implementation
function getControlRecord(var this : tQueueOcaMvmt) : tControlRecord;
var
Rc : tControlRecord;
begin
reset(this.control);
seek (this.control, 0);
read (this.control, Rc);
close(this.control);
getControlRecord := Rc;
end;
procedure setControlRecord(var this : tQueueOcaMvmt; Rc : tControlRecord);
begin
reset(this.control);
seek (this.control, 0);
write(this.control, Rc);
close(this.control);
end;
procedure loadQueue (var this : tQueueOcaMvmt; path, filename : string);
var
fullFileName : string;
Rc : tControlRecord;
begin
fullFileName := path + filename;
//check if data file exists
assign(this.data, fullFileName + '.dat');
if not fileexists(fullFileName + '.dat') then
rewrite(this.data)
else
reset(this.data);
close(this.data);
//check if data file exists
assign(this.control, fullFileName + '.ctrl');
if not fileexists(fullFileName + '.ctrl') then
begin
rewrite(this.control);
Rc.first := NULLIDX;
Rc.last := NULLIDX;
Rc.erased := NULLIDX;
Rc.count := 0;
seek(this.control, 0);
write(this.control, Rc);
end
else
reset(this.control);
close(this.control);
end;
procedure newEmptyQueue (var this : tQueueOcaMvmt; path, filename : string);
var
fullFileName : string;
Rc : tControlRecord;
begin
fullFileName := path + filename;
//check if data file exists
assign(this.data, fullFileName + '.dat');
rewrite(this.data);
close(this.data);
//check if data file exists
assign(this.control, fullFileName + '.ctrl');
rewrite(this.control);
Rc.first := NULLIDX;
Rc.last := NULLIDX;
Rc.erased := NULLIDX;
Rc.count := 0;
seek(this.control, 0);
write(this.control, Rc);
close(this.control);
end;
function isEmpty (var this : tQueueOcaMvmt) : Boolean;
var
Rc : tControlRecord;
begin
Rc := getControlRecord(this);
isEmpty := Rc.first = NULLIDX;
end;
function length (var this : tQueueOcaMvmt) : integer;
var
Rc : tControlRecord;
begin
Rc := getControlRecord(this);
length := Rc.count;
end;
function first (var this : tQueueOcaMvmt) : idxRange;
var
Rc : tControlRecord;
begin
Rc := getControlRecord(this);
first := Rc.first;
end;
function last (var this : tQueueOcaMvmt) : idxRange;
var
Rc : tControlRecord;
begin
Rc := getControlRecord(this);
last := Rc.last;
end;
function get (var this : tQueueOcaMvmt; pos : idxRange) : tOcaMovement;
var
item: tOcaMovement;
begin
reset (this.data);
seek (this.data, pos);
read (this.data, item);
close (this.data);
get := item;
end;
procedure update (var this : tQueueOcaMvmt; pos : idxRange; var item : tOcaMovement);
begin
reset (this.data);
seek (this.data, pos);
write (this.data, item);
close (this.data);
end;
function append (var this : tQueueOcaMvmt; var item : tOcaMovement) : idxRange;
var
Rc : tControlRecord;
pos : idxRange;
auxItem : tOcaMovement;
begin
Rc := getControlRecord(this);
if Rc.erased = NULLIDX then
begin
reset(this.data);
pos := FileSize(this.data);
seek (this.data, pos);
write(this.data, item);
close(this.data);
end
else
begin
pos := Rc.erased;
auxItem := get(this, Rc.erased);
Rc.erased := auxItem.next;
update(this, pos, item);
setControlRecord(this, Rc);
end;
append := pos;
end;
function next (var this : tQueueOcaMvmt; pos : idxRange) : idxRange;
var
Rc : tControlRecord;
Ridx : idxRange;
item : tOcaMovement;
begin
if pos = NULLIDX then
begin
Rc := getControlRecord(this);
next := Rc.first;
end
else
begin
item := get(this, pos);
next := item.next;
end;
end;
procedure insert (var this : tQueueOcaMvmt; item : tOcaMovement);
var
pos, auxPos : idxRange;
auxItem : tOcaMovement;
Rc : tControlRecord;
begin
Rc := getControlRecord(this);
if Rc.first = Rc.last then
begin
auxPos := append(this, item);
Rc.first := auxPos;
Rc.last := auxPos;
Rc.count := 1;
setControlRecord(this, Rc);
end
else
begin
auxPos := append(this, item);
if pos = Rc.last then
setControlRecord(this, Rc);
auxItem := get(this, pos);
pos := auxItem.next;
auxItem.next := auxPos;
update(this, auxPos, auxItem);
item.next := pos;
update(this, pos, item);
Rc.count := Rc.count + 1;
setControlRecord(this, Rc);
end;
end;
procedure deletePos (var this : tQueueOcaMvmt; pos : idxRange);
begin
end;
procedure deleteItem (var this : tQueueOcaMvmt; item : tOcaMovement);
begin
end;
function isValidPos (var this : tQueueOcaMvmt; pos : idxRange) : Boolean;
begin
isValidPos := pos <> NULLIDX;
end;
procedure queue (var this : tQueueOcaMvmt; item : tOcaMovement);
var
Rc : tControlRecord;
itemPos : idxRange;
auxItem : tOcaMovement;
auxPos : idxRange;
begin
itemPos := append(this, item);
Rc := getControlRecord(this);
if Rc.first = NULLIDX then
begin
Rc.first := itemPos;
Rc.last := itemPos;
end
else
begin
auxPos := Rc.last;
auxItem := get(this, auxPos);
auxItem.next := itemPos;
update(this, auxPos, auxItem);
Rc.last := itemPos;
end;
setControlRecord(this, Rc);
end;
function dequeue (var this : tQueueOcaMvmt) : tOcaMovement;
var
Rc : tControlRecord;
itemPos : idxRange;
auxItem : tOcaMovement;
auxPos : idxRange;
begin
Rc := getControlRecord(this);
auxPos := Rc.first;
auxItem := get(this, auxPos);
Rc.first := auxItem.next;
auxItem.next := Rc.erased;
Rc.erased := auxPos;
update(this, auxPos, auxItem);
setControlRecord(this, Rc);
auxItem.next := NULLIDX;
dequeue := auxItem;
end;
function peek (var this : tQueueOcaMvmt) : tOcaMovement;
var
Rc : tControlRecord;
auxItem : tOcaMovement;
auxPos : idxRange;
begin
Rc := getControlRecord(this);
auxPos := Rc.first;
auxItem := get(this, auxPos);
auxItem.next := NULLIDX;
peek := auxItem;
end;
function createMovement(var this : tQueueOcaMvmt; player, movement : integer) : tOcaMovement;
var
item : tOcaMovement;
begin
item.player := player;
item.dice := movement;
item.next := NULLIDX;
createMovement := item;
end;
end.
|
unit SQLProgress;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, ActnList, Ora, BCDialogs.Dlg, System.Actions;
const
WM_AFTER_SHOW = WM_USER + 302; // custom message
type
TSQLProgressDialog = class(TDialog)
ActionList: TActionList;
CancelAction: TAction;
CancelButton: TButton;
ExecutionTimeLabel: TLabel;
procedure CancelActionExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure Formshow(Sender: TObject);
private
{ Private declarations }
FOnProgress: Boolean;
FOraSQL: TOraSQL;
FStartTime: TDateTime;
procedure SetExecutionTimeText(Value: string);
procedure WMAfterShow(var Msg: TMessage); message WM_AFTER_SHOW;
public
{ Public declarations }
property ExecutionTimeText: string write SetExecutionTimeText;
function Open(OraSQL: TOraSQL; StartTime: TDateTime): Boolean;
end;
function SQLProgressDialog: TSQLProgressDialog;
implementation
{$R *.dfm}
uses
BCCommon.StyleUtils;
var
FSQLProgressDialog: TSQLProgressDialog;
function SQLProgressDialog: TSQLProgressDialog;
begin
if not Assigned(FSQLProgressDialog) then
Application.CreateForm(TSQLProgressDialog, FSQLProgressDialog);
Result := FSQLProgressDialog;
SetStyledFormSize(Result);
end;
procedure TSQLProgressDialog.CancelActionExecute(Sender: TObject);
begin
FOnProgress := False;
ExecutionTimeLabel.Caption := 'Canceling...';
Application.ProcessMessages;
end;
procedure TSQLProgressDialog.WMAfterShow(var Msg: TMessage);
var
Success, UserCancel: Boolean;
begin
Success := False;
UserCancel := False;
if Assigned(FOraSQL) then
begin
while FOraSQL.Executing do
begin
ExecutionTimeText := Format('Time Elapsed: %s', [System.SysUtils.FormatDateTime('hh:nn:ss.zzz', Now - FStartTime)]);
if not FOnProgress then
begin
UserCancel := True;
Break;
end;
Application.ProcessMessages;
end;
Success := FOraSQL.ErrorOffset = 0;
end;
if Success and (not UserCancel) then
ModalResult := mrOk
else
ModalResult := mrCancel;
end;
procedure TSQLProgressDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FOnProgress := False;
Action := caFree;
end;
procedure TSQLProgressDialog.FormDestroy(Sender: TObject);
begin
FSQLProgressDialog := nil;
end;
procedure TSQLProgressDialog.Formshow(Sender: TObject);
begin
// Post the custom message WM_AFTER_SHOW to our form
PostMessage(Self.Handle, WM_AFTER_SHOW, 0, 0);
end;
function TSQLProgressDialog.Open(OraSQL: TOraSQL; StartTime: TDateTime): Boolean;
var
Rslt: Integer;
begin
FOnProgress := True;
ExecutionTimeText := '';
FOraSQL := OraSQL;
FStartTime := StartTime;
Rslt := ShowModal;
Result := Rslt = mrOK;
end;
procedure TSQLProgressDialog.SetExecutionTimeText(Value: string);
begin
if FOnProgress then
ExecutionTimeLabel.Caption := Value;
end;
end.
|
unit TextEditor.Undo;
interface
uses
System.Classes, TextEditor.Types;
type
TTextEditorUndo = class(TPersistent)
strict private
FOptions: TTextEditorUndoOptions;
procedure SetOptions(const AValue: TTextEditorUndoOptions);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
procedure SetOption(const AOption: TTextEditorUndoOption; const AEnabled: Boolean);
published
property Options: TTextEditorUndoOptions read FOptions write SetOptions default [uoGroupUndo];
end;
implementation
constructor TTextEditorUndo.Create;
begin
inherited;
FOptions := [uoGroupUndo];
end;
procedure TTextEditorUndo.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorUndo) then
with ASource as TTextEditorUndo do
Self.FOptions := FOptions
else
inherited Assign(ASource);
end;
procedure TTextEditorUndo.SetOption(const AOption: TTextEditorUndoOption; const AEnabled: Boolean);
begin
if AEnabled then
Include(FOptions, AOption)
else
Exclude(FOptions, AOption);
end;
procedure TTextEditorUndo.SetOptions(const AValue: TTextEditorUndoOptions);
begin
if FOptions <> AValue then
FOptions := AValue;
end;
end. |
{
Find plugins which can be converted to ESL
}
unit FindPotentialESL;
const
iESLMaxRecords = $800; // max possible new records in ESL
iESLMaxFormID = $fff; // max allowed FormID number in ESL
procedure CheckForESL(f: IInterface);
var
i: Integer;
e: IInterface;
RecCount, RecMaxFormID, fid: Cardinal;
HasCELL: Boolean;
begin
// iterate over all records in plugin
for i := 0 to Pred(RecordCount(f)) do begin
e := RecordByIndex(f, i);
// override doesn't affect ESL
if not IsMaster(e) then
Continue;
if Signature(e) = 'CELL' then
HasCell := True;
// increase the number of new records found
Inc(RecCount);
// no need to check for more if we are already above the limit
if RecCount > iESLMaxRecords then
Break;
// get raw FormID number
fid := FormID(e) and $FFFFFF;
// determine the max one
if fid > RecMaxFormID then
RecMaxFormID := fid;
end;
// too many new records, can't be ESL
if RecCount > iESLMaxRecords then
Exit;
AddMessage(Name(f));
if RecMaxFormID <= iESLMaxFormID then
AddMessage(#9'Can be turned into ESL by adding ESL flag in TES4 header')
else
AddMessage(#9'Can be turned into ESL by compacting FormIDs first, then adding ESL flag in TES4 header');
// check if plugin has new cell(s)
if HasCELL then
AddMessage(#9'Warning: Plugin has new CELL(s) which won''t work when turned into ESL and overridden by other mods due to the game bug');
end;
function Initialize: integer;
var
i: integer;
f: IInterface;
begin
// iterate over loaded plugins
for i := 0 to Pred(FileCount) do begin
f := FileByIndex(i);
// skip the game master
if GetLoadOrder(f) = 0 then
Continue;
// check non-light plugins only
if (GetElementNativeValues(ElementByIndex(f, 0), 'Record Header\Record Flags\ESL') = 0) and not SameText(ExtractFileExt(GetFileName(f)), '.esl') then
CheckForESL(f);
end;
end;
end.
|
unit OpenMHealthServer;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.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
SysUtils, Classes,
IdContext, IdCustomHTTPServer,
AdvObjects, AdvJson, DateSupport,
FHIRBase, FHIRSupport, FHIRTypes, FHIRResources, FHIRUtilities;
type
TOpenMHealthAdaptor = class (TFHIRFormatAdaptor)
private
function loadDataPoint(stream : TStream) : TFHIRObservation;
function readDataPoint(json : TJsonObject) : TFHIRObservation;
function readHeader(hdr: TJsonObject; obs: TFhirObservation) : String;
procedure readPhysicalActivity(body: TJsonObject; obs: TFhirObservation);
procedure readBloodGlucose(body: TJsonObject; obs: TFhirObservation);
function readTimeInterval(obj : TJsonObject) : TFHIRPeriod;
function readQuantity(obj : TJsonObject) : TFHIRQuantity;
function convertUCUMUnit(s : String) : String;
function convertObsStat(s : String) : String;
procedure writeObservation(obs : TFHIRObservation; json : TJsonObject);
procedure writeBundle(obs : TFHIRBundle; json : TJsonObject);
function writeHeader(obs : TFHIRObservation; hdr : TJsonObject) : String;
procedure writePhysicalActivity(obs : TFHIRObservation; body : TJsonObject);
procedure writeBloodGlucose(obs : TFHIRObservation; body : TJsonObject);
function writePeriod(period : TFHIRPeriod) : TJsonObject;
function writeQuantity(qty : TFHIRQuantity) : TJsonObject;
function unconvertUCUMUnit(s : String) : String;
function unconvertObsStat(s : String) : String;
public
procedure load(req : TFHIRRequest; stream : TStream); override;
function NewIdStatus : TCreateIdState; override;
function ResourceName : String; override;
procedure compose(response : TFHIRResponse; stream : TStream); override;
function MimeType : String; override;
procedure editSearch(req : TFHIRRequest); override;
end;
implementation
{ TOpenMHealthAdaptor }
procedure TOpenMHealthAdaptor.compose(response: TFHIRResponse; stream: TStream);
var
json : TJsonObject;
begin
json := TJsonObject.Create;
try
if response.Resource = nil then
raise Exception.Create('Cannot represent a resource of (nil) as an OpenMHealth data point')
else if response.Resource is TFHIRObservation then
writeObservation(response.Resource as TFHIRObservation, json)
else if response.Resource is TFHIRBundle then
writeBundle(response.Resource as TFHIRBundle, json)
else
raise Exception.Create('Cannot represent a resource of type '+response.Resource.fhirType+' as an OpenMHealth data point');
TJSONWriter.writeObject(stream, json, true);
finally
json.Free;
end;
end;
function TOpenMHealthAdaptor.convertObsStat(s: String): String;
begin
if (s = 'average') then
result := 'average'
else if (s = 'maximum') then
result := 'maximum'
else if (s = 'minimum') then
result := 'minimum'
else if (s = 'count') then
result := 'count'
else if (s = 'median') then
result := 'median'
else if (s = 'standard deviation') then
result := 'std-dev'
else if (s = 'sum') then
result := 'sum'
else if (s = 'variance') then
result := 'variance'
else if (s = '20th percentile') then
result := '%20'
else if (s = '80th percentile') then
result := '%80'
else if (s = 'lower quartile') then
result := '4-lower'
else if (s = 'upper quartile') then
result := '4-upper'
else if (s = 'quartile deviation') then
result := '4-dev'
else if (s = '1st quintile') then
result := '5-1'
else if (s = '2nd quintile') then
result := '5-2'
else if (s = '3rd quintile') then
result := '5-3'
else if (s = '4th quintile') then
result := '5-4'
else
result := s;
end;
function TOpenMHealthAdaptor.convertUCUMUnit(s: String): String;
begin
if (s = 'in') then
result := '[in_i]'
else if (s = 'ft') then
result := '[ft_i]'
else if (s = 'yd') then
result := '[yd_i]'
else if (s = 'mi') then
result := '[mi_i]'
else if (s = 'sec') then
result := 's'
else if (s = 'Mo') then
result := 'mo'
else if (s = 'yr') then
result := 'a'
else
result := s;
end;
procedure TOpenMHealthAdaptor.editSearch(req: TFHIRRequest);
var
p : String;
begin
if req.Parameters.GetVar('schema_namespace') <> 'omh' then
raise Exception.Create('Unknown schema namespace');
if req.Parameters.GetVar('schema_version') <> '1.0' then
raise Exception.Create('Unknown schema version for OMH 1.0');
p := '_profile=http://www.openmhealth.org/schemas/fhir/'+req.Parameters.GetVar('schema_namespace')+'/'+req.Parameters.GetVar('schema_version')+'/'+req.Parameters.GetVar('schema_name');
if req.Parameters.VarExists('created_on_or_after') then
p := p + '&date=ge'+req.Parameters.getvar('created_on_or_after');
if req.Parameters.VarExists('created_before') then
p := p + '&date=le'+req.Parameters.getvar('created_before');
req.LoadParams(p);
end;
procedure TOpenMHealthAdaptor.load(req: TFHIRRequest; stream : TStream);
begin
req.PostFormat := ffJson;
req.Resource := loadDataPoint(stream);
req.ResourceName := 'Observation';
req.Id := req.Resource.id;
end;
function TOpenMHealthAdaptor.loadDataPoint(stream: TStream): TFHIRObservation;
var
json : TJsonObject;
begin
json := TJSONParser.Parse(stream);
try
result := readDataPoint(json);
finally
json.Free;
end;
end;
function TOpenMHealthAdaptor.MimeType: String;
begin
result := 'application/json';
end;
function TOpenMHealthAdaptor.NewIdStatus: TCreateIdState;
begin
result := idCheckNew;
end;
function TOpenMHealthAdaptor.readDataPoint(json: TJsonObject): TFHIRObservation;
var
schema : string;
begin
result := TFHIRObservation.Create;
try
result.meta := TFHIRMeta.Create;
// not set by OMH
result.status := ObservationStatusFinal; // final is reasonable for most mobilde data
if (not json.has('header')) then // it must, but check anyway
raise Exception.Create('Cannot process without header');
schema := readHeader(json.obj['header'], result);
if (schema = 'physical-activity') then
readPhysicalActivity(json.obj['body'], result)
else if (schema = 'blood-glucose') then
readBloodGlucose(json.obj['body'], result)
else
raise Exception.Create('Unsupported schema type '+schema);
result.Link;
finally
result.Free;
end;
end;
function TOpenMHealthAdaptor.readHeader(hdr: TJsonObject; obs: TFhirObservation) : String;
var
ext : TFHIRExtension;
obj : TJsonObject;
begin
// id --> resource.id.
obs.id := hdr['id'];
// creation_date_time --> extension on metadata. What is the significance of this value? why does it matter? or is it actually last_updated?
ext := obs.meta.extensionList.Append;
ext.url := 'http://healthintersections.com.au/fhir/StructureDefinition/first-created';
ext.value := TFhirDateTime.Create(TDateTimeEx.fromXml(hdr['creation_date_time']));
// schema_id --> this maps to a profile on observation. todo: what is the correct URL?
obj := hdr.obj['schema_id'];
result := obj['name'];
obs.meta.profileList.Add(TFHIRUri.create('http://www.openmhealth.org/schemas/fhir/'+obj['namespace']+'/'+obj['version']+'/'+obj['name']));
obj := hdr.obj['acquisition_provenance'];
if (obj <> nil) then
begin
// acquisition_provenance.source_name --> observation.device
if obj.has('source_name') then // though this is required
begin
obs.device := TFhirReference.Create;
obs.device.display := obj['source_name'];
end;
// acquisition_provenance.source_creation_date_time --> observation.
if obj.has('source_creation_date_time') then
begin
obs.issued := TDateTimeEx.fromXml(obj['source_creation_date_time']);
end;
// acquisition_provenance.modality --> observation.method
if obj.has('modality') then
begin
obs.method := TFhirCodeableConcept.Create;
obs.method.text := obj['modality'];
end;
end;
// user_id --> Observation.subject
if hdr.has('user_id') then
begin
obs.subject := TFhirReference.Create;
obs.subject.reference := 'Patient/'+hdr['user_id'];
end;
end;
procedure TOpenMHealthAdaptor.readPhysicalActivity(body: TJsonObject; obs: TFhirObservation);
var
c : TFHIRCoding;
obj : TJsonObject;
begin
// physical activity is the category
c := obs.categoryList.Append.codingList.Append;
c.system := 'http://openmhealth.org/codes';
c.code := 'omh';
c.display := 'OpenMHealth Data';
// code comes from activity name
obs.code := TFhirCodeableConcept.Create;
obs.code.text := body['activity_name'];
// effective_time_frame --> Observation.effective
obj := body.obj['effective_time_frame'];
if (obj <> nil) then
begin
if (obj.has('time_interval')) then
obs.effective := readTimeInterval(obj.obj['time_interval'])
else if (obj.has('date_time')) then
obs.effective := TFhirDateTime.Create(TDateTimeEx.fromXml(obj['date_time']));
end;
// distance --> Observation.value
if body.has('distance') then
obs.value := readQuantity(body.obj['distance']);
if body.has('kcal_burned') then
obs.addComponent('http://loinc.org', '41981-2').value := readQuantity(body.obj['kcal_burned']);
if body.has('reported_activity_intensity') then
obs.addComponent('http://openmhealth.org/codes', 'reported_activity_intensity').value := TFHIRString.create(body['reported_activity_intensity']);
if body.has('met_value') then
obs.addComponent('http://snomed.info/sct', '698834005').value := readQuantity(body.obj['met_value']);
end;
function TOpenMHealthAdaptor.readQuantity(obj: TJsonObject): TFHIRQuantity;
begin
result := TFhirQuantity.Create;
try
result.value := obj['value'];
result.system := 'http://unitsofmeasure.org';
result.unit_ := obj['unit'];
result.code := convertUCUMUnit(result.unit_);
result.Link;
finally
result.Free;
end;
end;
function TOpenMHealthAdaptor.readTimeInterval(obj: TJsonObject): TFHIRPeriod;
var
qty : TFHIRQuantity;
ext : TFHIRExtension;
day : TDateTimeEx;
s : String;
begin
result := TFHIRPeriod.create;
try
// creation_date_time --> extension on metadata. What is the significance of this value? why does it matter? or is it actually last_updated?
ext := result.extensionList.Append;
ext.url := 'http://healthintersections.com.au/fhir/StructureDefinition/period-form';
if obj.has('start_date_time') and obj.has('end_date_time') then
begin
// The interval is defined by a precise start and end time
result.start := TDateTimeEx.fromXml(obj['start_date_time']);
result.end_ := TDateTimeEx.fromXml(obj['end_date_time']);
ext.value := TFhirCode.Create('normal');
end
else if obj.has('start_date_time') and obj.has('duration') then
begin
// The interval is defined by a precise start time and a duration
result.start := TDateTimeEx.fromXml(obj['start_date_time']);
qty := readQuantity(obj.obj['duration']);
try
result.end_ := result.start.add(qty.asDuration);
finally
qty.Free;
end;
ext.value := TFhirCode.Create('start.duration');
end
else if obj.has('end_date_time') and obj.has('duration') then
begin
// The interval is defined by a duration and a precise end time
result.end_ := TDateTimeEx.fromXml(obj['end_date_time']);
qty := readQuantity(obj.obj['duration']);
try
result.start := result.start.subtract(qty.asDuration);
finally
qty.Free;
end;
ext.value := TFhirCode.Create('end.duration');
end
else
begin
// the interval is defined by a date and a part of the day (morning, afternoon, evening, night)
day := TDateTimeEx.fromXml(obj['date']);
s := obj['part_of_day'];
if (s = 'morning') then
begin
ext.value := TFhirCode.Create('day.morning');
result.start := day.add(0.25); // 6am --> 12noon
result.end_ := day.add(0.5);
end
else if (s = 'afternoon') then
begin
ext.value := TFhirCode.Create('day.afternoon');
result.start := day.add(0.5); // 12noon --> 6pm
result.end_ := day.add(0.75);
end
else if (s = 'evening') then
begin
ext.value := TFhirCode.Create('day.evening');
result.start := day.add(0.75); // 6pm --> midnight
result.end_ := day.add(1);
end
else if (s = 'night') then
begin
ext.value := TFhirCode.Create('day.night');
result.start := day.add(0); // midnight --> 6am - but is it the next day?
result.end_ := day.add(0.25);
end;
end;
result.link;
finally
result.free;
end;
end;
function TOpenMHealthAdaptor.ResourceName: String;
begin
result := 'Observation';
end;
function TOpenMHealthAdaptor.unconvertObsStat(s: String): String;
begin
if (s = 'average') then
result := 'average'
else if (s = 'maximum') then
result := 'maximum'
else if (s = 'minimum') then
result := 'minimum'
else if (s = 'count') then
result := 'count'
else if (s = 'median') then
result := 'median'
else if (s = 'std-dev') then
result := 'standard deviation'
else if (s = 'sum') then
result := 'sum'
else if (s = 'variance') then
result := 'variance'
else if (s = '%20') then
result := '20th percentile'
else if (s = '%80') then
result := '80th percentile'
else if (s = '4-lower') then
result := 'lower quartile'
else if (s = '4-upper') then
result := 'upper quartile'
else if (s = '4-dev') then
result := 'quartile deviation'
else if (s = '5-1') then
result := '1st quintile'
else if (s = '5-2') then
result := '2nd quintile'
else if (s = '5-3') then
result := '3rd quintile'
else if (s = '5-4') then
result := '4th quintile'
else
result := s;
end;
function TOpenMHealthAdaptor.unconvertUCUMUnit(s: String): String;
begin
if (s = '[in_i]') then
result := 'in'
else if (s = '[ft_i]') then
result := 'ft'
else if (s = '[yd_i]') then
result := 'yd'
else if (s = '[mi_i]') then
result := 'mi'
else if (s = 's') then
result := 'sec'
else if (s = 'mo') then
result := 'Mo'
else if (s = 'a') then
result := 'yr'
else
result := s;
end;
procedure TOpenMHealthAdaptor.writeObservation(obs: TFHIRObservation; json: TJsonObject);
var
schema : String;
begin
schema := writeHeader(obs, json.forceObj['header']);
if (schema = 'physical-activity') then
writePhysicalActivity(obs, json.forceObj['body'])
else if (schema = 'blood-glucose') then
writeBloodGlucose(obs, json.forceObj['body'])
else
raise Exception.Create('Unsupported schema type '+schema);
end;
function TOpenMHealthAdaptor.writePeriod(period: TFHIRPeriod): TJsonObject;
var
form : String;
qty : TFhirQuantity;
begin
if (period.start.null) then
raise Exception.Create('Can''t convert a period to OpenMHealth when periods are incomplete');
if (period.end_.null) then
raise Exception.Create('Can''t convert a period to OpenMHealth when periods are incomplete');
result := TJsonObject.Create;
try
form := period.getExtensionString('http://healthintersections.com.au/fhir/StructureDefinition/period-form');
if (form = 'start.duration') then
begin
result['start_date_time'] := period.start.toXml;
qty := TFHIRQuantity.fromDuration(period.end_.UTC.dateTime - period.start.UTC.dateTime);
try
result.obj['duration'] := writeQuantity(qty);
finally
qty.Free;
end;
end
else if (form = 'end.duration') then
begin
result['end_date_time'] := period.end_.toXml;
qty := TFHIRQuantity.fromDuration(period.start.UTC.dateTime - period.end_.UTC.dateTime);
try
result.obj['duration'] := writeQuantity(qty);
finally
qty.Free;
end;
end
else if (form = 'day.morning') then
begin
result['date'] := period.start.toXml.Substring(0, 10);
result.str['part_of_day'] := 'morning';
end
else if (form = 'day.afternoon') then
begin
result['date'] := period.start.toXml.Substring(0, 10);
result.str['part_of_day'] := 'afternoon';
end
else if (form = 'day.evening') then
begin
result['date'] := period.start.toXml.Substring(0, 10);
result.str['part_of_day'] := 'evening';
end
else if (form = 'day.night') then
begin
result['date'] := period.start.toXml.Substring(0, 10);
result.str['part_of_day'] := 'night';
end
else
begin
result['start_date_time'] := period.start.toXml;
result['end_date_time'] := period.end_.toXml;
end;
result.Link;
finally
result.Free;
end;
end;
procedure TOpenMHealthAdaptor.writePhysicalActivity(obs: TFHIRObservation; body: TJsonObject);
var
comp : TFhirObservationComponent;
begin
body['activity_name'] := obs.code.text;
if (obs.effective <> nil) then
begin
if (obs.effective is TFhirPeriod) then
body.forceObj['effective_time_frame'].obj['time_interval'] := writePeriod(TFhirPeriod(obs.effective))
else if (obs.effective is TFhirDateTime) then
body.forceObj['effective_time_frame']['date_time'] := TFhirDateTime(obs.effective).value.toXml;
end;
if obs.value is TFHIRQuantity then
body.obj['distance'] := writeQuantity(obs.value as TFhirQuantity);
if obs.getComponent('http://loinc.org', '41981-2', comp) then
body.obj['kcal_burned'] := writeQuantity(comp.value as TFhirQuantity);
if obs.getComponent('http://openmhealth.org/codes', 'reported_activity_intensity', comp) then
body['reported_activity_intensity'] := (comp.value as TFhirString).value;
if obs.getComponent('http://snomed.info/sct', '698834005', comp) then
body.obj['met_value'] := writeQuantity(comp.value as TFhirQuantity);
end;
function TOpenMHealthAdaptor.writeQuantity(qty: TFHIRQuantity): TJsonObject;
begin
result := TJsonObject.Create;
try
result['value'] := qty.value;
result['unit'] := unconvertUCUMUnit(qty.code);
result.Link;
finally
result.Free;
end;
end;
function TOpenMHealthAdaptor.writeHeader(obs: TFHIRObservation; hdr: TJsonObject) : String;
var
obj : TJsonObject;
u : TFHIRUri;
s : String;
p : TArray<String>;
begin
hdr['id'] := obs.id;
if (obs.meta.hasExtension('http://healthintersections.com.au/fhir/StructureDefinition/first-created')) then
hdr['creation_date_time'] := obs.meta.getExtensionString('http://healthintersections.com.au/fhir/StructureDefinition/first-created');
s := '';
for u in obs.meta.profileList do
if u.value.StartsWith('http://www.openmhealth.org/schemas/fhir/') then
s := u.value;
if (s = '') then // todo: try doing it anyway
raise Exception.Create('Cannot represent an observation with no OpenMHealth profile as an OpenMHealth data point');
p := s.Split(['/']);
obj := hdr.forceObj['schema_id'];
obj['namespace'] := p[5];
obj['version'] := p[6];
obj['name'] := p[7];
result := p[7];
if (obs.device <> nil) or (obs.issued.notNull) or (obs.method <> nil) then
begin
obj := hdr.forceobj['acquisition_provenance'];
if (obs.device <> nil) then
obj['source_name'] := obs.device.display;
if (obs.issued.notNull) then
obj['source_creation_date_time'] := obs.issued.toXml;
if (obs.method <> nil) then
obj['modality'] := obs.method.text;
end;
if (obs.subject <> nil) and (obs.subject.reference.StartsWith('Patient/')) then
hdr['user_id'] := obs.subject.reference.Substring(8);
end;
procedure TOpenMHealthAdaptor.readBloodGlucose(body: TJsonObject; obs: TFhirObservation);
var
c : TFHIRCoding;
qty : TFhirQuantity;
sp : TFHIRSpecimen;
obj : TJsonObject;
begin
// physical activity is the category
c := obs.categoryList.Append.codingList.Append;
c.system := 'http://openmhealth.org/codes';
c.code := 'omh';
c.display := 'OpenMHealth Data';
// LOINC code depends on units..
qty := readQuantity(body.obj['blood_glucose']);
obs.value := qty;
obs.code := TFhirCodeableConcept.Create;
c := obs.code.codingList.Append;
c.system := 'http://loinc.org';
if (qty.code = 'mg/dL') then
begin
c.code := '2339-0';
c.display := 'Glucose [Mass/volume] in Blood';
end
else
begin
c.code := '15074-8';
c.display := 'Glucose [Moles/volume] in Blood';
end;
// specimen_source --> observation.specimen.code
if (body.has('specimen_source')) then
begin
sp := TFhirSpecimen.Create;
sp.id := 'sp';
obs.containedList.Add(sp);
obs.specimen := TFhirReference.Create;
obs.specimen.reference := '#sp';
sp.type_ := TFhirCodeableConcept.Create;
sp.type_.text := body['specimen_source']; // todo: can this be coded?
end;
// effective_time_frame --> Observation.effective
obj := body.obj['effective_time_frame'];
if (obj <> nil) then
begin
if (obj.has('time_interval')) then
obs.effective := readTimeInterval(obj.obj['time_interval'])
else if (obj.has('date_time')) then
obs.effective := TFhirDateTime.Create(TDateTimeEx.fromXml(obj['date_time']));
end;
// temporal_relationship_to_meal/sleep --> component.value
if (body.has('temporal_relationship_to_meal')) then
obs.addComponent('http://snomed.info/sct', '309602000').value := TFHIRString.create(body['temporal_relationship_to_meal']);
if (body.has('temporal_relationship_to_sleep')) then
obs.addComponent('http://snomed.info/sct', '309609009').value := TFHIRString.create(body['temporal_relationship_to_sleep']);
// descriptive stat- follow the $stats patterns
if (body.has('descriptive_statistic')) then
begin
obs.addComponent('http://hl7.org/fhir/observation-statistics', convertObsStat(body['descriptive_statistic'])).value := obs.value.Link;
obs.value := nil;
end;
// user_notes --> Observation.comment
if (body.has('user_notes')) then
obs.comment := body['user_notes'];
end;
procedure TOpenMHealthAdaptor.writeBloodGlucose(obs: TFHIRObservation; body: TJsonObject);
var
comp : TFhirObservationComponent;
sp : TFHIRSpecimen;
begin
if obs.getComponent('http://hl7.org/fhir/observation-statistics', comp) then
begin
body.obj['blood_glucose'] := writeQuantity(comp.value as TFHIRQuantity);
body['descriptive_statistic'] := unconvertObsStat(comp.code.codingList[0].code);
end
else
body.obj['blood_glucose'] := writeQuantity(obs.value as TFHIRQuantity);
sp := obs.Contained['sp'] as TFhirSpecimen;
if (sp <> nil) then
body['specimen_source'] := sp.type_.text;
if (obs.effective <> nil) then
begin
if (obs.effective is TFhirPeriod) then
body.forceObj['effective_time_frame'].obj['time_interval'] := writePeriod(TFhirPeriod(obs.effective))
else if (obs.effective is TFhirDateTime) then
body.forceObj['effective_time_frame']['date_time'] := TFhirDateTime(obs.effective).value.toXml;
end;
if obs.getComponent('http://snomed.info/sct', '309602000', comp) then
body['temporal_relationship_to_meal'] := (comp.value as TFhirString).value;
if obs.getComponent('http://snomed.info/sct', '309609009', comp) then
body['temporal_relationship_to_sleep'] := (comp.value as TFhirString).value;
if obs.comment <> '' then
body['user_notes'] := obs.comment;
end;
procedure TOpenMHealthAdaptor.writeBundle(obs: TFHIRBundle; json: TJsonObject);
var
arr : TJsonArray;
be : TFhirBundleEntry;
begin
arr := json.forceArr['matches'];
for be in obs.entryList do
begin
if be.resource is TFHIRObservation then
writeObservation(be.resource as TFHIRObservation, arr.addObject());
end;
end;
end.
|
Unit FMX.PlatformUtils;
Interface
Uses
FMX.Platform;
Type
TFMXUtils = Class
Public
Class Function TryGetClipboardService(Out AClipboard: IFMXClipboardService): boolean; static;
Class Function CopyToClipboard(const Value: string): Boolean; static;
Class Function CopyFromClipboard(out Value: String): boolean; static;
End;
Implementation
uses System.Rtti;
{ TFMXUtils }
class function TFMXUtils.CopyFromClipboard(out Value: String): boolean;
var
lClipboard: IFMXClipboardService;
lValue: TValue;
begin
Result := TryGetClipboardService(lClipboard);
if Result then
begin
lValue := lClipboard.GetClipboard;
if not lValue.TryAsType(Value) then
Value := '';
end;
end;
class function TFMXUtils.CopyToClipboard(const Value: string): Boolean;
var
lClipboard: IFMXClipboardService;
begin
Result := TryGetClipboardService(lClipboard);
if Result then
lClipboard.SetClipboard(Value);
end;
Class Function TFMXUtils.TryGetClipboardService(Out AClipboard: IFMXClipboardService): boolean;
Begin
Result := TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService);
If Result Then
AClipboard := IFMXClipboardService(TPlatformServices.Current.GetPlatformService(IFMXClipboardService));
End;
End.
|
unit Model.ExtratosExpressas;
interface
type
TExtratosExpressas = class
private
var
FId: Integer;
FAgente: Integer;
FEntregador: Integer;
FDataInicio: TDate;
FDataFinal: TDate;
FDataPagamento: TDate;
FVolumes: Integer;
FEntregas: Integer;
FAtrasos: Integer;
FVolumesExtra: Double;
FSLA: Double;
FVerba: Double;
FValorEntregas: Double;
FValorVolumesExtra: Double;
FValorProducao: Double;
FValorCreditos: Double;
FValorRestricao: Double;
FValorExtravio: Double;
FValorDebitos: Double;
FValorTotalCreditos: Double;
FValorTotalDebitos: Double;
FValorTotalGeral: Double;
FFechado: Integer;
FTotalVerbaFranquia: Double;
FLog: String;
FPFP: Integer;
public
property Id: Integer read FId write FId;
property Agente: Integer read FAgente write FAgente;
property Entregador: Integer read FEntregador write FEntregador;
property DataInicio: TDate read FDataInicio write FDataInicio;
property DataFinal: TDate read FDataFinal write FDataFinal;
property DataPagamento: TDate read FDataPagamento write FDataPagamento;
property Volumes: Integer read FVolumes write FVolumes;
property Entregas: Integer read FEntregas write FEntregas;
property Atrasos: Integer read FAtrasos write FAtrasos;
property VolumesExtra: Double read FVolumesExtra write FVolumesExtra;
property SLA: Double read FSLA write FSLA;
property Verba: Double read FVerba write FVerba;
property ValorEntregas: Double read FValorEntregas write FValorEntregas;
property ValorVolumesExtra: Double read FValorVolumesExtra write FValorVolumesExtra;
property ValorProducao: Double read FValorProducao write FValorProducao;
property ValorCreditos: Double read FValorCreditos write FValorCreditos;
property ValorRestricao: Double read FValorRestricao write FValorRestricao;
property ValorExtravio: Double read FValorExtravio write FValorExtravio;
property ValorDebitos: Double read FValorDebitos write FValorDebitos;
property ValorTotalCreditos: Double read FValorTotalCreditos write FValorTotalCreditos;
property ValorTotalDebitos: Double read FValorTotalDebitos write FValorTotalDebitos;
property ValorTotalGeral: Double read FValorTotalGeral write FValorTotalGeral;
property Fechado: Integer read FFechado write FFechado;
property TotalVerbaFranquia: Double read FTotalVerbaFranquia write FTotalVerbaFranquia;
property PFP: Integer read FPFP write FPFP;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create (pFId: Integer; pFAgente: Integer; pFEntregador: Integer; pFDataInicio: TDate; pFDataFinal: TDate; pFDataPagamento: TDate;
pFVolumes: Integer; pFEntregas: Integer; pFAtrasos: Integer; pFVolumesExtra: Double; pFSLA: Double; pFVerba: Double; pFValorEntregas: Double;
pFValorVolumesExtra: Double; pFValorProducao: Double; pFValorCreditos: Double; pFValorRestricao: Double; pFValorExtravio: double;
pFValorDebitos: Double; pFValorTotalCreditos: Double; pFValorTotalDebitos: Double; pFValorTotalGeral: Double; pFFechado: Integer;
pFTotalVerbaFranquia: Double; pFPFP: Integer; pFLog: String); overload;
end;
implementation
{ TExtratosExpressas }
constructor TExtratosExpressas.Create;
begin
inherited Create;
end;
constructor TExtratosExpressas.Create(pFId, pFAgente, pFEntregador: Integer; pFDataInicio, pFDataFinal, pFDataPagamento: TDate; pFVolumes, pFEntregas,
pFAtrasos: Integer; pFVolumesExtra, pFSLA, pFVerba, pFValorEntregas, pFValorVolumesExtra, pFValorProducao, pFValorCreditos, pFValorRestricao, pFValorExtravio, pFValorDebitos,
pFValorTotalCreditos, pFValorTotalDebitos, pFValorTotalGeral: Double; pFFechado: Integer; pFTotalVerbaFranquia: Double; pFPFP: Integer; pFLog: String);
begin
FId := pFId;
FAgente := pFAgente;
FEntregador := pFEntregador;
FDataInicio := pFDataInicio;
FDataFinal := pFDataFinal;
FDataPagamento := pFDataPagamento;
FVolumes := pFVolumes;
FEntregas := pFEntregas;
FAtrasos := pFAtrasos;
FVolumesExtra := pFVolumesExtra;
FSLA := pFSLA;
FVerba := pFVerba;
FValorEntregas := pFValorEntregas;
FValorVolumesExtra := pFValorVolumesExtra;
FValorProducao := pFValorProducao;
FValorCreditos := pFValorCreditos;
FValorRestricao := pFValorRestricao;
FValorExtravio := pFValorExtravio;
FValorDebitos := pFValorDebitos;
FValorTotalCreditos := pFValorTotalCreditos;
FValorTotalDebitos := pFValorTotalDebitos;
FValorTotalGeral := pFValorTotalGeral;
FFechado := pFFechado;
FTotalVerbaFranquia := pFTotalVerbaFranquia;
FPFP := pFPFP;
FLog := pFLog;
end;
end.
|
unit Model.FechamentoRestricao;
interface
type
TFechamentoRestricao = class
private
var
FRestricao: Integer;
FParcela: Integer;
FFechamento: Integer;
public
property Restricao: Integer read FRestricao write FRestricao;
property Parcela: Integer read FParcela write FParcela;
property Fechamento: Integer read FFechamento write FFechamento;
constructor Create; overload;
constructor Create(pFRestricao: Integer; pFParcela: Integer; pFFechamento: integer); overload;
end;
implementation
{ TFechamentoRestricao }
constructor TFechamentoRestricao.Create;
begin
inherited Create;
end;
constructor TFechamentoRestricao.Create(pFRestricao, pFParcela, pFFechamento: integer);
begin
FRestricao := pFRestricao;
FParcela := pFParcela;
FFechamento := pFFechamento;
end;
end.
|
(*
Category: SWAG Title: TEXT WINDOWING ROUTINES
Original name: 0005.PAS
Description: WINDOWS2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 14:08
Note: Shadow, SaveBox and RestoreBox omitted when porting
to FreePascal
*)
Uses Crt;
Function CharS(Len:Byte; C: Char): String;
Var
S: String;
begin { This Function returns a String of }
FillChar(S, Len+1, C); { Length Len and of Chars C. }
S[0] := Chr(Len);
CharS := S;
end;
Function Center(X1, X2: Byte; S: String): Byte;
Var
L, Max: Integer;
begin { This Function is used to center }
Max := (X2 - (X1-1)) div 2; { a String between two X coordinates. }
L := Length(S);
if Odd(L) then Inc(L);
Center := X1 + (Max - (L div 2));
end;
Procedure DrawBox(X1, Y1, X2, Y2: Integer; Attr: Byte; Title: String);
Var
L, Y, X: Integer;
S: String;
begin
X := X2 - (X1-1); { find box width }
Y := Y2 - (Y1-1); { find box height }
{ draw box }
S := Concat('+', CharS(X-2, '-'), '+');
GotoXY(X1, Y1);
TextAttr := Attr;
Write(S);
Title := Concat('= ', Title,' =');
GotoXY(Center(X1, X2, Title), Y1);
Write(Title);
For L := 2 to (Y-1) do
begin
GotoXY(X1, Y1+L-1);
Write('|', CharS(X-2, ' '), '|');
end;
GotoXY(X1, Y2);
Write('+', CharS(X-2, '-'), '+');
end;
Procedure Hello;
begin
{ note, that if you use shadow, save an xtra 2 columns
and 1 line to accomadate what Shadow does }
{ V V }
DrawBox(7, 7, 71, 13, $4F, 'Hello');
GotoXY(9, 9);
Write('Hello Terry! I hope this is what you were asking For.');
GotoXY(9, 11);
Write('Press Enter');
While ReadKey <> #13 do;
end;
Procedure Disclaimer;
begin
DrawBox(5, 5, 75, 20, $1F, 'DISCLAIMER');
Window(7, 7, 73, 19);
Writeln(' Seeing as I came up With these Procedures For');
Writeln('my own future Programs (I just recently wrote these)');
Writeln('please don''t Forget who wrote them originally if you');
Writeln('decide to use them in your own. Maybe a ''thanks to Eric Miller');
Writeln('For Window routines'' somewhere in your doCs?');
Writeln;
Writeln(' Also, if anyone can streamline this source, well, I''d');
Writeln('I''d like to see it...not that too much can be done.');
Writeln;
Writeln(' Eric Miller');
Window(1,1,80,25);
Hello;
TextAttr := $1F;
GotoXY(9, 18);
Writeln('Press Enter...');
While ReadKey <> #13 do;
end;
begin
TextAttr := $3F;
ClrScr;
Disclaimer;
end.
|
unit UNumberFunctions;
interface
uses Classes;
type
TNumberFunctions = class(TPersistent)
published
class function Contains(const iNumber: Integer; const iPart: array of Integer): Boolean;
class function FloatToInt(const RealNumber: real): Longint;
class function SumDigits(const Number: string): integer;
class function VarToCurrency(const Number: variant; const Default: currency = 0): currency;
class function VarToInt(const Number: variant; const Default: integer = 0): integer;
class function StrToCurrDef(AString: string; Default: Currency): Currency;
class function StrMoney(const Value: extended; const Cifrao: string = '"R$ "'): string;
class function NumberBetween(Number, NumberStart, NumberEnd: extended): Boolean;
class function Percent(const Value, Percent: Currency): Currency;
class function IsZero(const Value: Currency): boolean;
class function FormatValue(const Mask: string; const Value: Currency): string;
class function ExtractDecimalSeparator(const value: string): string;
class function ConvertPadToDecimal(const Number: string): currency;
end;
implementation
uses UStringFunctions, SysUtils, Variants, Math, StrUtils;
{ TNumberFunctions }
//******************************************************************************
// Funcao.....: FloatToInt
// Adaptacao..: 29/01/2007
// Tecnico....: Jose Mario
// Descricao..:
//******************************************************************************
class function TNumberFunctions.Contains(const iNumber: Integer;
const iPart: array of Integer): Boolean;
var
i: Integer;
begin
for i := Low(iPart) to High(iPart) do
begin
Result := iNumber = iPart[i];
if Result then
Break;
end;
end;
class function TNumberFunctions.FloatToInt(const RealNumber: real): Longint;
var
n: real;
aux: string;
begin
n := Int(RealNumber);
aux := floattostr(n);
Result := StrToInt(aux);
end;
class function TNumberFunctions.ConvertPadToDecimal(const Number: string): currency;
var
i: Integer;
DecimalSeparatorFound: Boolean;
IntegerPart, DecimalPart, DecimalSeparator: string;
begin
Result := 0;
if TStringFunctions.IsFull(TStringFunctions.ExtractNotNumbers(Number)) then
begin
DecimalSeparatorFound := False;
DecimalSeparator := ',';
for i := Length(Number) downto 0 do
begin
if DecimalSeparatorFound then
begin
DecimalPart := Copy(Number, i + 2, Length(Number));
IntegerPart := StringReplace(StringReplace(Copy(Number, 0, i), '.', '', [rfReplaceAll]), ',', '', [rfReplaceAll]);
Result := StrToCurrDef(IntegerPart + DecimalSeparator + DecimalPart, 0);
break;
end
else DecimalSeparatorFound := (Copy(Number, i, 1) = '.') or (Copy(Number, i, 1) = ',');
end;
if not DecimalSeparatorFound then
Result := StrToCurrDef(Number, 0);
end;
end;
class function TNumberFunctions.ExtractDecimalSeparator(const value: string): string;
var
i: Integer;
Vlrfmt: string;
begin
Result := '';
if Length(value) > 0 then
begin
for i := Length(value) downto 1 do
begin
if (value[i] = ',') or (value[i] = '.') then
begin
Result := value[i];
Break;
end;
end;
end;
end;
class function TNumberFunctions.FormatValue(const Mask: string;
const Value: Currency): string;
var
Vlrfmt: string;
begin
Vlrfmt := FormatFloat(Mask, Value);
Result := DupeString(' ', Length(Mask) - Length(Vlrfmt)) + Vlrfmt;
end;
class function TNumberFunctions.IsZero(const Value: Currency): boolean;
begin
Result := RoundTo(Value, -2) = 0;
end;
class function TNumberFunctions.NumberBetween(Number, NumberStart,
NumberEnd: extended): Boolean;
begin
Result := ((Number >= NumberStart) and (Number <= NumberEnd));
end;
class function TNumberFunctions.Percent(const Value,
Percent: Currency): Currency;
begin
Result := Value * (Percent / 100);
end;
{ Recebe um número no formato string e soma acumulando cada um de seus caracteres }
class function TNumberFunctions.StrToCurrDef(AString: string;
Default: Currency): Currency;
begin
AString := StringReplace(AString, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]);
Result := SysUtils.StrToCurrDef(AString, Default);
end;
class function TNumberFunctions.SumDigits(const Number: string): integer;
var
s: string;
i: integer;
begin
Result := 0;
s := TStringFunctions.ExtractNotNumbers(Number);
for i := 1 to Length(s) do
Inc(Result, StrToIntDef(s[i], 0));
end;
class function TNumberFunctions.VarToCurrency(const Number: variant;
const Default: currency): currency;
begin
if (Number = null) or (VarToStr(Number) = '') then
Result := Default
else Result := Currency(Number);
end;
class function TNumberFunctions.VarToInt(const Number: variant;
const Default: integer): integer;
begin
if (Number = null) or (VarToStr(Number) = '') then
Result := Default
else Result := Integer(Number);
end;
{ Retorna Value já no formato de moeda, em string }
class function TNumberFunctions.StrMoney(const Value: extended; const Cifrao: string = '"R$ "'): string;
begin
Result := FormatFloat(Cifrao + '#,##0.00', Value);
end;
end.
|
unit uServerProjectInfo;
interface
uses
Classes,
IniFiles;
type
TServerProject = class
Name: string;
ConnectionName: string;
ProjectPathID: string;
ProjectFileName: string;
ReloadConnections: Boolean;
procedure Load(aIniFile: TCustomIniFile; aSectionName: string);
end;
implementation
{ TServerProjectInfo }
procedure TServerProject.Load(aIniFile: TCustomIniFile; aSectionName: string);
begin
Name := aIniFile.ReadString(aSectionName, 'Name', '');
ConnectionName := aIniFile.ReadString(aSectionName, 'ConnectionName', '');
ProjectPathID := aIniFile.ReadString(aSectionName, 'ProjectPathID', '');
end;
end.
|
unit SmartOnFhirLoginFMX;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser,
FMX.StdCtrls, FMX.Controls.Presentation,
FileSupport,
FHIRResources, FHIRClient, SmartonFHIRUtilities;
type
TCheckScopesProc = reference to procedure (scopes : TArray<String>; var ok : boolean; var msg : String);
TSmartOnFhirLoginForm = class(TForm)
Panel1: TPanel;
Button2: TButton;
WebBrowser1: TWebBrowser;
private
FLogoPath: String;
FClient: TFHIRHTTPClient;
FScopes: TArray<String>;
FHandleError: boolean;
FToken: TSmartOnFhirAccessToken;
FErrorMessage: String;
procedure SetClient(const Value: TFHIRHTTPClient);
procedure SetToken(const Value: TSmartOnFhirAccessToken);
public
destructor Destroy; override;
property logoPath : String read FLogoPath write FLogoPath;
property client : TFHIRHTTPClient read FClient write SetClient;
property scopes : TArray<String> read FScopes write FScopes;
property handleError : boolean read FHandleError write FHandleError;
// if modalResult = mrok, you'll get a token. otherwise, you'll get an error message
property ErrorMessage : String read FErrorMessage write FErrorMessage;
Property Token : TSmartOnFhirAccessToken read FToken write SetToken;
end;
var
SmartOnFhirLoginForm: TSmartOnFhirLoginForm;
function doSmartOnFHIRLogin(owner : TComponent; client : TFHIRHTTPClient; cs : TFhirCapabilityStatement; authorize, token : String; scopes : TArray<String>; checkproc : TCheckScopesProc) : boolean;
implementation
{$R *.fmx}
function doSmartOnFHIRLogin(owner : TComponent; client : TFHIRHTTPClient; cs : TFhirCapabilityStatement; authorize, token : String; scopes : TArray<String>; checkproc : TCheckScopesProc) : boolean;
var
mr : integer;
begin
SmartOnFhirLoginForm := TSmartOnFhirLoginForm.Create(owner);
try
SmartOnFhirLoginForm.logoPath := path([ExtractFilePath(paramstr(0)), 'toolkit.png']);
SmartOnFhirLoginForm.client := client.Link;
SmartOnFhirLoginForm.scopes := scopes; // 'openid profile user/*.*';
SmartOnFhirLoginForm.handleError := true;
SmartOnFhirLoginForm.Caption := 'Login to '+client.address;
mr := SmartOnFhirLoginForm.ShowModal;
if mr = mrOK then
begin
client.SmartToken := SmartOnFhirLoginForm.Token.Link;
result := true;
end
else if (mr = mrAbort) and (SmartOnFhirLoginForm.ErrorMessage <> '') then
MessageDlg(SmartOnFhirLoginForm.ErrorMessage, TMsgDlgType.mtError, [TMsgDlgBtn.mbNo], 0);
finally
SmartOnFhirLoginForm.Free;
end;
end;
{ TSmartOnFhirLoginForm }
destructor TSmartOnFhirLoginForm.Destroy;
begin
FToken.free;
FClient.Free;
inherited;
end;
procedure TSmartOnFhirLoginForm.SetClient(const Value: TFHIRHTTPClient);
begin
FClient.Free;
FClient := Value;
end;
procedure TSmartOnFhirLoginForm.SetToken(const Value: TSmartOnFhirAccessToken);
begin
FToken.free;
FToken := Value;
end;
end.
|
unit UUsuarioLogado;
interface
uses
UUsuario
, URepositorioUsuario
, UUtilitarios
;
type
TUsuarioLogado = class
private
FUSUARIO: TUSUARIO;
FRepositorioUsuario: TRepositorioUsuario;
function InternoValidaLogin(const csLogin: String;const csSenha: String): Boolean;
function InternoRetornaHash(const csSenha: String): String;
procedure InternoRealizaLogin(const csLogin: String;const csSenha: String);
procedure InternoLogoff;
public
constructor Create;
destructor Destroy; override;
class procedure RealizaLogin(const csLogin: String;const csSenha: String);
class procedure Logoff;
class function USUARIO: TUSUARIO;
class function Unico: TUsuarioLogado;
class function ValidaLogin(const csLogin: String;const csSenha: String): Boolean;
class function RetornaHash(const csSenha: String): String;
end;
implementation
uses
SysUtils
, IdHashMessageDigest
, UMensagens
;
var
UsuarioLogado: TUsuarioLogado = nil;
{ TUsuarioLogado }
constructor TUsuarioLogado.Create;
begin
FRepositorioUsuario := TRepositorioUsuario.Create;
end;
destructor TUsuarioLogado.Destroy;
begin
FreeAndNil(FRepositorioUsuario);
inherited;
end;
procedure TUsuarioLogado.InternoLogoff;
begin
if Assigned(FUSUARIO) then
FreeAndNil(FUSUARIO);
end;
class procedure TUsuarioLogado.RealizaLogin(const csLogin, csSenha: String);
begin
Unico.InternoRealizaLogin(csLogin, csSenha);
end;
class function TUsuarioLogado.RetornaHash(const csSenha: String): String;
begin
Result := Unico.InternoRetornaHash(csSenha);
end;
procedure TUsuarioLogado.InternoRealizaLogin(const csLogin, csSenha: String);
begin
if not InternoValidaLogin(csLogin, csSenha) then
raise EValidacaoNegocio.Create(STR_USUARIO_ACESSO_INVALIDO);
FUSUARIO := FRepositorioUsuario.RetornaPeloLogin(csLogin);
end;
function TUsuarioLogado.InternoRetornaHash(const csSenha: String): String;
var
HashMessageDigest5: TIdHashMessageDigest5;
begin
HashMessageDigest5 := TIdHashMessageDigest5.Create;
try
Result := HashMessageDigest5.HashStringAsHex(csSenha);
finally
FreeAndNil(HashMessageDigest5);
end;
end;
function TUsuarioLogado.InternoValidaLogin(const csLogin, csSenha: String): Boolean;
var
loUSUARIO: TUSUARIO;
begin
loUSUARIO := FRepositorioUsuario.RetornaPeloLogin(csLogin);
if Assigned(loUSUARIO) then
Result := loUSUARIO.SENHA = InternoRetornaHash(csSenha)
else
Result := False;
end;
class procedure TUsuarioLogado.Logoff;
begin
Unico.InternoLogoff;
end;
class function TUsuarioLogado.Unico: TUsuarioLogado;
begin
if not Assigned(UsuarioLogado) then
UsuarioLogado := TUsuarioLogado.Create;
Result := UsuarioLogado;
end;
class function TUsuarioLogado.USUARIO: TUSUARIO;
begin
Result := Unico.FUSUARIO;
end;
class function TUsuarioLogado.ValidaLogin(const csLogin, csSenha: String): Boolean;
begin
Result := Unico.InternoValidaLogin(csLogin, csSenha);
end;
end.
|
Program verbal_number;
{Дано целое число в диапазоне 100-999. Вывести строку-словесное описание данного
числа, например:256-"двести пятьдесят шесть", 814-"восемьсот четырнадцать".}
const
c1: array [1..9] of string[6] = (
'один',
'два',
'три',
'четыре',
'пять',
'шесть',
'семь',
'восемь',
'девять'
);
c11: array [0..9] of string[12] = (
'десять',
'одиннадцать',
'двенадцать',
'тринадцать',
'четырнадцать',
'пятнадцать',
'шестнадцать',
'семнадцать',
'восемнадцать',
'девятнадцать'
);
c20: array [2..9] of string[9] = (
'двадцать',
'тридцать',
'сорок',
'пятьдесят',
'шестьдесят',
'семьдесят',
'восемьдесят',
'девяносто'
);
c100: array [1..9] of string[9] = (
'сто',
'двести',
'триста',
'четыреста',
'пятьсот',
'шестьсот',
'семьсот',
'восемьсот',
'девятьсот'
);
var x,y,z: String;
s1,s2,s3:Char;
begin
WriteLn;
Write ('Введите целое число в диапазоне (100-999): ');
ReadLn (s1, s2, s3);
x := c100 [ord(s1) - ord('0')];
if s2 = '1' then
begin
y := c11 [ord(s3) - ord('0')];
z := '';
end
else
if s2 <> '0' then
begin
y := c20 [ord(s2) - ord('0')];
if s3 <> '0' then
z := c1 [ord(s3) - ord('0')]
else
z := '';
end
else
begin
y := '';
if s3 <> '0' then
z := c1 [ord(s3) - ord('0')]
else z := '';
end;
WriteLn('Словесное описание: ', x+' '+y+' '+z);
readln;
end. |
unit RaceResults;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TRaceResults = class(TPersistent)
private
fWinHorseIndex: integer;
fPlaceHorseIndex: integer;
fShowHorseIndex: integer;
fWinHorseOdds: integer;
fPlaceHorseOdds: integer;
fShowHorseOdds: integer;
fWinHorsePayoffWin: currency;
fWinHorsePayoffPlace: currency;
fWinHorsePayoffShow: currency;
fPlaceHorsePayoffPlace: currency;
fPlaceHorsePayoffShow: currency;
fShowHorsePayoff: currency;
fQuinellaPayoff: currency;
fExactaPayoff: currency;
fTrifectaPayoff: currency;
public
property WinHorseIndex: integer read fWinHorseIndex write fWinHorseIndex;
property PlaceHorseIndex: integer read fPlaceHorseIndex write fPlaceHorseIndex;
property ShowHorseIndex: integer read fShowHorseIndex write fShowHorseIndex;
property WinHorseOdds: integer read fWinHorseOdds write fWinHorseOdds;
property PlaceHorseOdds: integer read fPlaceHorseOdds write fPlaceHorseOdds;
property ShowHorseOdds: integer read fShowHorseOdds write fShowHorseOdds;
property WinHorsePayoffWin: currency read fWinHorsePayoffWin write fWinHorsePayoffWin;
property WinHorsePayoffPlace: currency read fWinHorsePayoffPlace write fWinHorsePayoffPlace;
property WinHorsePayoffShow: currency read fWinHorsePayoffShow write fWinHorsePayoffShow;
property PlaceHorsePayoffPlace: currency read fPlaceHorsePayoffPlace write fPlaceHorsePayoffPlace;
property PlaceHorsePayoffShow: currency read fPlaceHorsePayoffShow write fPlaceHorsePayoffShow;
property ShowHorsePayoff: currency read fShowHorsePayoff write fShowHorsePayoff;
property QuinellaPayoff: currency read fQuinellaPayoff write fQuinellaPayoff;
property ExactaPayoff: currency read fExactaPayoff write fExactaPayoff;
property TrifectaPayoff: currency read fTrifectaPayoff write fTrifectaPayoff;
end;
implementation
end.
|
unit fingerprintreader;
{******************************************
RCurrentStateFP = Record - содержит информацию о текущем состоянии сканера.
Используется в сallback функции для индикации состояния.
TFingerPrintReader = поток для работы со сканером
OnTakeOn и OnTakeOff - ипользуются для обработки нажатия и отпускания пальца со сканера.
В этих обработчиках достаточно обратиться к CurrentStatusFP.
OnEnrollFingerPrint - выполняется после окончания сканирования отпечатка.
Следует анализировать CurrentStatusFP и Sample.
Для прерывания потока необходимо bCancel выставить в False.
******************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FtrApi, FtrScanApi, SyncObjs; //, DbugIntf ;
type
RCurrentStateFP = Record
Context: LongWord;
StateMask: FTR_STATE;
pResponse: LongWord;
Signal: FTR_SIGNAL;
pBitmap: FTR_BITMAP_PTR;
end;
TFingerPrintReader = class(TThread)
private
FbCancel: Boolean;
FrCode: FTRAPI_RESULT;
FbIdentification: Boolean;
FHaveSample: Boolean;
FSample: FTR_DATA;
FMutex: TMutex;
FTakeOn: TNotifyEvent;
FTakeOff: TNotifyEvent;
FCurrentStateFP: RCurrentStateFP;
FOnEnrollFingerPrint: TNotifyEvent;
FWithSynchro: Boolean;
FMyEvent: THandle;
procedure DoTakeOn;
procedure DoTakeOff;
procedure DoEnrollFingerPrint;
public
constructor Create(aSuspend:Boolean);
destructor Destroy;override;
procedure Execute;override;
procedure FtrInit;
function LockSynchro:Boolean;
property bIdentification: Boolean read FbIdentification write FbIdentification;
property bCancel:Boolean read FbCancel write FbCancel;
property WithSynchro: Boolean read FWithSynchro write FWithSynchro;
property rCode: FTRAPI_RESULT read FrCode write FrCode;
property CurrentStateFP: RCurrentStateFp read FCurrentStateFp;
property HaveSample:Boolean read FHaveSample write FHaveSample;
property MyEvent : THandle read FMyEvent write FMyEvent;
property Sample:FTR_DATA read FSample;
property OnTakeOn: TNotifyEvent read FTakeOn write FTakeOn;
property OnTakeOff: TNotifyEvent read FTakeOff write FTakeOff;
property OnEnrollFingerPrint:TNotifyEvent read FOnEnrollFingerPrint write FOnEnrollFingerPrint;
end;
procedure cbFingerPrint(AContext: LongWord; AStateMask: FTR_STATE;
ApResponse: LongWord; ASignal: FTR_SIGNAL; ApBitmap: FTR_BITMAP_PTR);stdcall;
var FPReader:TFingerPrintReader;
nUndef:Integer;
implementation
{ TFingerPrint }
constructor TFingerPrintReader.Create(aSuspend: Boolean);
begin
FbIdentification := True;
FWithSynchro := True;
inherited;
FreeOnTerminate := False;
FMutex := TMutex.Create();
// FMyEvent := CreateEvent(nil,true,false,nil);
end;
destructor TFingerPrintReader.Destroy;
begin
FMutex.Release;
FMutex.Free;
inherited;
end;
procedure TFingerPrintReader.DoEnrollFingerPrint;
begin
if Assigned(FOnEnrollFingerPrint) and LockSynchro then
begin
FOnEnrollFingerPrint(self);
FMutex.Release;
end;
end;
procedure TFingerPrintReader.DoTakeOff;
begin
if Assigned(FTakeOff) and LockSynchro then
begin
FTakeOff(Self);
FMutex.Release;
end;
end;
procedure TFingerPrintReader.DoTakeOn;
begin
if Assigned(FTakeOn) and LockSynchro then
begin
FTakeOn(Self);
FMutex.Release;
end;
end;
procedure TFingerPrintReader.Execute;
var aValue : LongWord;
hDevice: FTRHANDLE;
t1: Int64;
begin
bCancel := False;
FHaveSample := False;
aValue := 1;
FtrInit;
// Init не прошел
if bCancel then
begin
// SetEvent(FMyEvent);
Exit;
end;
rCode := FTRSetParam( 4, aValue );
if ( rCode <> FTR_RETCODE_OK ) then
begin
bCancel := True;
Exit;
end;
rCode := FTRSetParam( FTR_PARAM_CB_CONTROL, LongWord(Addr(CbFingerPrint)) );
if (rCode <> FTR_RETCODE_OK ) then
begin
bCancel := True;
Exit;
end;
rCode := FTRGetParam( FTR_PARAM_MAX_TEMPLATE_SIZE, @FSample.dwSize );
if( rCode = FTR_RETCODE_OK ) then
try
begin
while not bCancel and not Terminated do
begin
getMem(FSample.pData,FSample.dwSize);
try
if FbIdentification then
begin
FHaveSample := False;
rCode := FTREnroll(0, FTR_PURPOSE_IDENTIFY, @FSample );
end
else
if not FHaveSample then
begin
rCode := FTREnroll(0, FTR_PURPOSE_ENROLL, @FSample );
end;
FHaveSample := True;
if FwithSynchro then
Synchronize(DoEnrollFingerPrint)
else
DoEnrollFingerPrint;
if not bCancel then
begin
t1 := GetTickCount;
//Sleep(2000);
hDevice := ftrScanOpenDevice;
try
while ftrScanIsFingerPresent(hDevice,nil)=1 do
begin
Sleep(10);
if GetTickCount - t1 > 2000 then
Break;
end;
finally
FtrScanCloseDevice(hDevice);
end;
end;
finally
if Assigned(FSample.pData) then
FreeMem(FSample.pData);
if not FbIdentification then
bCancel := true;
end;
end;
end;
finally
FTRTerminate();
// SetEvent(MyEvent);
end;
end;
procedure TFingerPrintReader.FtrInit;
begin
rCode := FTRInitialize();
if (rCode <> FTR_RETCODE_OK ) then
begin
Exit;
bCancel := True;
end;
end;
function TFingerPrintReader.LockSynchro: Boolean;
begin
if Assigned(FMutex) then
Result := FMutex.WaitFor(10)=wrSignaled
else
Result := True;
end;
procedure cbFingerPrint(AContext: LongWord; AStateMask: FTR_STATE;
ApResponse:LongWord; ASignal: FTR_SIGNAL; ApBitmap: FTR_BITMAP_PTR);stdcall;
begin
if AStateMask = FTR_STATE_SIGNAL_PROVIDED then
begin
with FpReader.FCurrentstateFp do
begin
Context := AContext;
StateMask := AStateMask;
pResponse := Apresponse;
Signal := ASignal;
pBitmap := ApBitmap;
end;
case ASignal of
FTR_SIGNAL_TOUCH_SENSOR:
begin
begin
FpReader.DoTakeOn();
end
end;
FTR_SIGNAL_TAKE_OFF: begin
FpReader.DoTakeOff();
end;
end;
end
else
begin
case ASignal of
FTR_SIGNAL_UNDEFINED:begin
Inc(nUndef);
end;
end;
end;
if ( not FPreader.bCancel ) and ( not FPreader.Terminated) then
begin
PLongWord(ApResponse)^ := FTR_CONTINUE;
end
else
begin
PLongWord(ApResponse)^ := FTR_CANCEL;
PostMessage(FPreader.Handle,WM_CLOSE,0,0);
// SetEvent(FPReader.MyEvent);
end;
end;
Initialization;
nUndef := 0;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Janela Cadastro de Template
The MIT License
Copyright: Copyright (C) 2017 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 T2Ti
@version 2.0
*******************************************************************************}
unit UEtiquetaTemplate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids,
DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, EtiquetaTemplateVO,
EtiquetaTemplateController, Tipos, Atributos, Constantes, LabeledCtrls, Mask,
JvExMask, JvToolEdit, JvBaseEdits, Controller, Biblioteca, System.Actions,
Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin,
Vcl.ActnCtrls, frxBarcode, frxClass, frxDBSet, StrUtils;
type
TFEtiquetaTemplate = class(TFTelaCadastro)
EditLayout: TLabeledEdit;
EditTabela: TLabeledEdit;
EditIdLayout: TLabeledCalcEdit;
EditQuantidadeRepeticoes: TLabeledCalcEdit;
EditCampo: TLabeledEdit;
EditFiltro: TLabeledEdit;
ComboBoxFormato: TLabeledComboBox;
frxReport: TfrxReport;
frxTable: TfrxDBDataset;
frxBarCodeObject1: TfrxBarCodeObject;
ActionToolBar1: TActionToolBar;
ActionManager1: TActionManager;
ActionGerarEtiquetas: TAction;
CDSProduto: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure EditIdLayoutKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ActionGerarEtiquetasExecute(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
FEtiquetaTemplate: TFEtiquetaTemplate;
implementation
uses ULookup, EtiquetaLayoutController, EtiquetaLayoutVO, UDataModule,
ProdutoController, ProdutoVO;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFEtiquetaTemplate.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TEtiquetaTemplateVO;
ObjetoController := TEtiquetaTemplateController.Create;
inherited;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFEtiquetaTemplate.DoInserir: Boolean;
begin
Result := inherited DoInserir;
if Result then
begin
EditIdLayout.SetFocus;
end;
end;
function TFEtiquetaTemplate.DoEditar: Boolean;
begin
Result := inherited DoEditar;
if Result then
begin
EditIdLayout.SetFocus;
end;
end;
function TFEtiquetaTemplate.DoExcluir: Boolean;
begin
if inherited DoExcluir then
begin
try
TController.ExecutarMetodo('EtiquetaTemplateController.TEtiquetaTemplateController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean');
Result := TController.RetornoBoolean;
except
Result := False;
end;
end
else
begin
Result := False;
end;
if Result then
TController.ExecutarMetodo('EtiquetaTemplateController.TEtiquetaTemplateController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
end;
function TFEtiquetaTemplate.DoSalvar: Boolean;
begin
Result := inherited DoSalvar;
if Result then
begin
try
if not Assigned(ObjetoVO) then
ObjetoVO := TEtiquetaTemplateVO.Create;
TEtiquetaTemplateVO(ObjetoVO).IdEtiquetaLayout := EditIdLayout.AsInteger;
TEtiquetaTemplateVO(ObjetoVO).Tabela := EditTabela.Text;
TEtiquetaTemplateVO(ObjetoVO).Formato := ComboBoxFormato.ItemIndex;
TEtiquetaTemplateVO(ObjetoVO).QuantidadeRepeticoes := EditQuantidadeRepeticoes.AsInteger;
TEtiquetaTemplateVO(ObjetoVO).Campo := EditCampo.Text;
TEtiquetaTemplateVO(ObjetoVO).Filtro := EditFiltro.Text;
if StatusTela = stInserindo then
begin
TController.ExecutarMetodo('EtiquetaTemplateController.TEtiquetaTemplateController', 'Insere', [TEtiquetaTemplateVO(ObjetoVO)], 'PUT', 'Lista');
end
else if StatusTela = stEditando then
begin
if TEtiquetaTemplateVO(ObjetoVO).ToJSONString <> StringObjetoOld then
begin
TController.ExecutarMetodo('EtiquetaTemplateController.TEtiquetaTemplateController', 'Altera', [TEtiquetaTemplateVO(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 'Controles de Grid'}
procedure TFEtiquetaTemplate.GridParaEdits;
begin
inherited;
if not CDSGrid.IsEmpty then
begin
ObjetoVO := TEtiquetaTemplateVO(TController.BuscarObjeto('EtiquetaTemplateController.TEtiquetaTemplateController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET'));
end;
if Assigned(ObjetoVO) then
begin
EditIdLayout.AsInteger := TEtiquetaTemplateVO(ObjetoVO).IdEtiquetaLayout;
EditTabela.Text := TEtiquetaTemplateVO(ObjetoVO).Tabela;
ComboBoxFormato.ItemIndex := TEtiquetaTemplateVO(ObjetoVO).Formato;
EditQuantidadeRepeticoes.AsInteger := TEtiquetaTemplateVO(ObjetoVO).QuantidadeRepeticoes;
EditCampo.Text := TEtiquetaTemplateVO(ObjetoVO).Campo;
EditFiltro.Text := TEtiquetaTemplateVO(ObjetoVO).Filtro;
// Serializa o objeto para consultar posteriormente se houve alterações
FormatSettings.DecimalSeparator := '.';
StringObjetoOld := ObjetoVO.ToJSONString;
FormatSettings.DecimalSeparator := ',';
end;
end;
{$ENDREGION}
{$REGION 'Campos Transientes'}
procedure TFEtiquetaTemplate.EditIdLayoutKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdLayout.Value <> 0 then
Filtro := 'ID = ' + EditIdLayout.Text
else
Filtro := 'ID=0';
try
EditIdLayout.Clear;
EditLayout.Clear;
if not PopulaCamposTransientes(Filtro, TEtiquetaLayoutVO, TEtiquetaLayoutController) then
PopulaCamposTransientesLookup(TEtiquetaLayoutVO, TEtiquetaLayoutController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdLayout.Text := CDSTransiente.FieldByName('ID').AsString;
EditLayout.Text := CDSTransiente.FieldByName('CODIGO_FABRICANTE').AsString;
end
else
begin
Exit;
EditTabela.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
{$ENDREGION}
{$REGION 'Actions'}
procedure TFEtiquetaTemplate.ActionGerarEtiquetasExecute(Sender: TObject);
begin
/// EXERCICIO
/// Faça uso do campo TABELA para trazer dados de outas tabelas do banco de dados
/// EXERCICIO
/// Faça uso do campo CAMPO para informar qual campo deseja a impressão
/// Será preciso inserir outros campos desse tipo na tabela Template?
/// EXERCICIO
/// O relatório está configurado estaticamente para imprimir EAN
/// Pesquise como imprimir QRCode no FastReports e implemente a solução
/// EXERCICIO
/// Implemente o campo QUANTIDADE_REPETICOES. Ele é útil quando o usuário
/// quer imprimir uma mesma etiqueta várias vezes
ConfiguraCDSFromVO(CDSProduto, TProdutoVO);
TProdutoController.SetDataSet(CDSProduto);
TController.ExecutarMetodo('ProdutoController.TProdutoController', 'Consulta', [EditFiltro.Text, '0', False], 'GET', 'Lista');
/// EXERCICIO
/// Carregue o arquivo de acordo com o ID do Layout.
/// Pesquise uma maneira de criar o arquivo dinamicamente de acordo
/// com os dados cadastrados na tabela de layout.
frxReport.LoadFromFile('1.fr3');
frxTable.DataSet := CDSProduto;
frxReport.ShowReport;
end;
{$ENDREGION}
end. |
(* @file UGameOver.pas
* @author Willi Schinmeyer
* @date 2011-10-27
*
* UGameOver Unit
*
* Contains the Game Over Menu code which is executed once the game over
* state is entered.
*)
unit UGameOver;
interface
uses UGeneralTypes, USharedData;
(* @brief Main Function - called when Game Over Menu State is
* entered.
*
* Enters the game over menu loop, you can treat it like a program,
* except for the return value.
*
* @return The next state *)
function main(var sharedData : TSharedData) : TGameState;
implementation
uses UMenu, UMenuLine, crt, math, UKeyConstants;
function main(var sharedData : TSharedData) : TGameState;
var
menu : TMenu;
//menu definition
title : array [0..0] of TMenuLine =
(
(text: 'GAME OVER'; centered : true)
);
content : array[0..3] of TMenuLine =
(
(text: '<score>'; centered : true),
(text: '<level>'; centered : true),
(text: ''; centered : false),
(text: 'Press enter or escape.'; centered : false)
);
begin
//dynamically fill score and level
writeStr(content[0].text, 'Score: ', sharedData.lastScore);
writeStr(content[1].text, 'Level: ', sharedData.lastLevel);
//initialize menu...
UMenu.init(menu, title, content);
//... and draw it
UMenu.draw(menu);
//move cursor outside of menu because it blinks
gotoxy(1, 1);
//prepare loop
main := stateGameOver;
// "main loop" - repeatedly poll input and handle it.
repeat
begin
//was a key pressed?
if keyPressed() then
begin
//which one?
case readKey() of
#0:
//if it was the 0, we need to read another time.
readKey();
KEY_ESCAPE, KEY_RETURN:
//in that case we go to the main menu.
main := stateMainMenu;
end;
end;
//wait a little so we don't use the cpu unecessarily
delay(5); //in ms
end
until main <> stateGameOver;
end;
begin
end.
|
unit Inilocal;
interface
USES Forms, SysUtils, WinProcs, IniFiles;
function LocalIni : TIniFile;
function LocateIni( FileName : string ) : TIniFile;
implementation
function LocateIni( FileName : string ) : TIniFile;
var
WinDirP, SysDirP : array[0..255] of char;
WinDir, SysDir : string;
CurPath, CurName, CurExt : string;
function FindIniFile : string;
function FileInDir( dirnam : string ) : string;
begin
Result := dirnam + FileName + '.INI'
end;
begin
{ Get the current path to the executable }
CurPath := Application.ExeName;
{ Extract the name, extension, and path }
CurName := ExtractFileName(CurPath);
CurName := Copy(CurName,1,Pos('.',CurName)-1);
CurExt := ExtractFileExt(CurPath);
CurPath := ExtractFilePath(Application.ExeName);
{ Locate the windows and system directories }
GetWindowsDirectory(WinDirP, High(WinDirP) - Low(WinDirP) - 1);
GetSystemDirectory(SysDirP, High(SysDirP) - Low(SysDirP) - 1);
WinDir := StrPas(WinDirP);
SysDir := StrPas(SysDirP);
{ Check out the current, windows, and system directories }
Result := FileInDir(CurPath);
if FileExists( Result ) then Exit;
Result := FileInDir(WinDir);
if FileExists( Result ) then Exit;
Result := FileInDir(SysDir);
if FileExists( Result ) then Exit;
{ Assume it is in the current folder }
Result := FileInDir(CurPath);
end;
Begin
Result := TIniFile.Create(FindIniFile);
End;
function LocalIni : TIniFile;
{
Answer the name of a file exename.INI, where exename is the
name of the executable. If it is not in the current directory
check in the windows directory. If not in the windows directory,
check in the sytem directory. If not there either is doesn't
exist, so return the exename.INI file with the current path
attached.
}
function FindIniFile : string;
var
WinDirP, SysDirP : array[0..255] of char;
WinDir, SysDir : string;
CurPath, CurName, CurExt: string;
function FileInDir( dirnam : string ) : string;
begin
Result := dirnam + CurName + '.INI'
end;
begin
{ Get the current path to the executable }
CurPath := Application.ExeName;
{ Extract the name, extension, and path }
CurName := ExtractFileName(CurPath);
CurName := Copy(CurName,1,Pos('.',CurName)-1);
CurExt := ExtractFileExt(CurPath);
CurPath := ExtractFilePath(Application.ExeName);
{ Locate the windows and system directories }
GetWindowsDirectory(WinDirP, High(WinDirP) - Low(WinDirP) - 1);
GetSystemDirectory(SysDirP, High(SysDirP) - Low(SysDirP) - 1);
WinDir := StrPas(WinDirP);
SysDir := StrPas(SysDirP);
{ Check out the current, windows, and system directories }
Result := FileInDir(CurPath);
if FileExists( Result ) then Exit;
Result := FileInDir(WinDir);
if FileExists( Result ) then Exit;
Result := FileInDir(SysDir);
if FileExists( Result ) then Exit;
{ Assume it is in the current folder }
Result := FileInDir(CurPath);
end;
begin
Result := TIniFile.Create(FindIniFile);
end;
end.
|
unit GRRPosterTests;
interface
uses TestFramework, GRRObligationPoster, Facade,
BaseObjects, PersistentObjects, DBGate, GRRObligation;
type
TCheckGetError = procedure(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
TCheckSetError = procedure (ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
TNirStatePosterTest = class(TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
//CheckGetError: TCheckGetError;
procedure CheckSetError(ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetNirStates;
procedure TestSetNirState;
public
//property CheckError: TCheckGetError read CheckGetError write CheckGetError;
end;
TNirTypePosterTest = class(TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
procedure CheckSetError(ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetNirType;
procedure TestSetNirType;
end;
TNIRObligationPosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
// CheckSetError: TCheckSetError;
procedure CheckSetError(ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetNirObligation;
procedure TestSetNirObligation;
end;
TSeismicObligationPosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetSeismicObligation;
end;
TDrillingObligationPosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetDrillingObligation;
end;
TNirObligationPlacePosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetNirObligationPlace;
end;
TSeismicObligationPlacePosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetSeismicObligationPlace;
end;
TDrillingObligationWellPosterTest = class (TTestCase)
private
procedure CheckGetError(ADataPoster: TImplementedDataPoster; ARecordCount: integer; AText: string);
protected
procedure SetUp; override;
published
procedure TestGetDrillingObligationWell;
end;
// procedure CheckSetError(ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
implementation
uses SysUtils;
{procedure CheckSetError(ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(AResult >= 0, Format('Данные о %s не записаны в БД. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end; }
{ TNirStatePosterTest }
procedure TNirStatePosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNirStatePosterTest.CheckSetError(
ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(AResult >= 0, Format('Данные о %s не записаны в БД. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNirStatePosterTest.SetUp;
begin
inherited;
end;
procedure TNirStatePosterTest.TestGetNirStates;
var dp: TDataPoster;
objs: TNirStates;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRStateDataPoster] as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'состоянии работ по НИР');
objs := TNIRStates.Create;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', objs), 'состоянии работ по НИР в коллекцию объектов ');
Check(objs.Count > 0, 'Коллекция состояний не заполнена');
end;
procedure TNirStatePosterTest.TestSetNirState;
var dp: TDataPoster;
ns: TNIRState;
begin
ns := TNIRState.Create(nil);
ns.Name := 'Тестовое состояние';
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRStateDataPoster] as TImplementedDataPoster;
CheckSetError(dp as TImplementedDataPoster, dp.PostToDB(ns, nil), 'состоянии работ по НИР');
Check(ns.ID > 0, 'Новый идентификатор состояния работ по НИР не получен');
end;
{ TNirTypePosterTest }
procedure TNirTypePosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNirTypePosterTest.CheckSetError(
ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(AResult >= 0, Format('Данные о %s не записаны в БД. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNirTypePosterTest.SetUp;
begin
inherited;
end;
procedure TNirTypePosterTest.TestGetNirType;
var dp: TDataPoster;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRTypeDataPoster] as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'типе работ по НИР');
end;
procedure TNirTypePosterTest.TestSetNirType;
var dp: TDataPoster;
nt: TNIRType;
begin
nt := TNIRType.Create(nil);
nt.Name := 'Тестовое состояние';
//nt.ID := 730;
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRTypeDataPoster] as TImplementedDataPoster;
CheckSetError(dp as TImplementedDataPoster, dp.PostToDB(nt, nil), 'типе работ по НИР');
Check(nt.ID > 0, 'Новый идентификатор типа работ по НИР не получен');
end;
{ TNIRObligationPosterTest }
procedure TNIRObligationPosterTest.CheckGetError(ADataPoster: TImplementedDataPoster;
ARecordCount: integer; AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNIRObligationPosterTest.CheckSetError(
ADataPoster: TImplementedDataPoster; AResult: integer; AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(AResult >= 0, Format('Данные о %s не записаны в БД. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNIRObligationPosterTest.SetUp;
begin
inherited;
end;
procedure TNIRObligationPosterTest.TestGetNirObligation;
var dp: TDataPoster;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRDataPoster] as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'обязательствам по НИР');
end;
procedure TNIRObligationPosterTest.TestSetNirObligation;
var dp: TDataPoster;
no: TNIRObligation;
begin
no := TNIRObligation.Create(nil);
//no. := '';
//no.ID := 730;
dp := TMainFacade.GetInstance.DataPosterByClassType[TNIRTypeDataPoster] as TImplementedDataPoster;
CheckSetError(dp as TImplementedDataPoster, dp.PostToDB(no, nil), 'типе работ по НИР');
Check(no.ID > 0, 'Новый идентификатор типа работ по НИР не получен');
end;
{ TSeismicObligationPosterTest }
procedure TSeismicObligationPosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TSeismicObligationPosterTest.SetUp;
begin
inherited;
end;
procedure TSeismicObligationPosterTest.TestGetSeismicObligation;
var dp: TDataPoster;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TSeismicObligationDataPoster] as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'обязательствам по сейсмике');
end;
{ TDrillingObligationPosterTest }
procedure TDrillingObligationPosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TDrillingObligationPosterTest.SetUp;
begin
inherited;
end;
procedure TDrillingObligationPosterTest.TestGetDrillingObligation;
var dp: TDataPoster;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TDrillingObligationDataPoster] as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'обязательствам по бурению');
end;
{ TNirObligationPlacePosterTest }
procedure TNirObligationPlacePosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TNirObligationPlacePosterTest.SetUp;
begin
inherited;
end;
procedure TNirObligationPlacePosterTest.TestGetNirObligationPlace;
var dp: TDataPoster;
objs: TNirObligationPlaces;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TNirObligationPlaceDataPoster]
as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'месте проведения НИР');
objs := TNirObligationPlaces.Create;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', objs), 'места проведения НИР в коллекцию объектов ');
Check(objs.Count > 0, 'Коллекция состояний не заполнена');
end;
{ TSeismicObligationPlacePosterTest }
procedure TSeismicObligationPlacePosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TSeismicObligationPlacePosterTest.SetUp;
begin
inherited;
end;
procedure TSeismicObligationPlacePosterTest.TestGetSeismicObligationPlace;
var dp: TDataPoster;
objs: TSeismicObligationPlaces;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TSeismicObligationPlaceDataPoster]
as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'месте проведения сейсм работ');
objs := TSeismicObligationPlaces.Create;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', objs), 'места проведения сейсм работ в коллекцию объектов ');
Check(objs.Count > 0, 'Коллекция состояний не заполнена');
// тест на поиск хотя бы одного объекта с заданной структурой
// тест на поиск хотя бы одного объекта с заданной площадью
end;
{ TDrillingObligationWellPosterTest }
procedure TDrillingObligationWellPosterTest.CheckGetError(
ADataPoster: TImplementedDataPoster; ARecordCount: integer;
AText: string);
var
ds: TCommonServerDataset;
begin
ds := TMainFacade.GetInstance.DBGates.Add(ADataPoster);
Check(ARecordCount > 0, Format('Данные о %s не получены. Код ошибки [%s].', [AText, IntToStr(ds.LastResult)]));
end;
procedure TDrillingObligationWellPosterTest.SetUp;
begin
inherited;
end;
procedure TDrillingObligationWellPosterTest.TestGetDrillingObligationWell;
var dp: TDataPoster;
objs: TDrillingObligationWells;
begin
dp := TMainFacade.GetInstance.DataPosterByClassType[TDrillingObligationWellDataPoster]
as TImplementedDataPoster;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', nil), 'скажине пробуренной на лиц участке');
objs := TDrillingObligationWells.Create;
CheckGetError(dp as TImplementedDataPoster, dp.GetFromDB('', objs), 'скважине пробуренной на лиц участке в коллекцию объектов ');
Check(objs.Count > 0, 'Коллекция состояний не заполнена');
end;
initialization
RegisterTest('PosterTests\GRRPosters\TNirStatePosterTest', TNirStatePosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TNirTypePosterTest', TNirTypePosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TNIRObligationPosterTest', TNIRObligationPosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TSeismicObligationPosterTest', TSeismicObligationPosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TDrillingObligationPosterTest',TDrillingObligationPosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TNirObligationPlacePosterTest', TNirObligationPlacePosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TSeismicObligationPlacePosterTest', TSeismicObligationPlacePosterTest.Suite);
RegisterTest('PosterTests\GRRPosters\TDrillingObligationWellPosterTest', TDrillingObligationWellPosterTest.Suite);
// RegisterTest(t);
end.
|
unit delphiDatadog.statsDClient.interf;
interface
uses
delphiDatadog.header, delphiDatadog.serviceCheck, delphiDatadog.event;
type
IDataDogStatsClient = interface(IInterface)
procedure Count(Aspect: TDataDogAspect; Delta: Int64; Tags: TDataDogTags); overload;
procedure Count(Aspect: TDataDogAspect; Delta: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure IncrementCounter(Aspect: TDataDogAspect; Tags: TDataDogTags); overload;
procedure IncrementCounter(Aspect: TDataDogAspect; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Increment(Aspect: TDataDogAspect; Tags: TDataDogTags); overload;
procedure Increment(Aspect: TDataDogAspect; SampleRate: Double; Tags: TDataDogTags); overload;
procedure DecrementCounter(Aspect: TDataDogAspect; Tags: TDataDogTags); overload;
procedure DecrementCounter(Aspect: TDataDogAspect; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Decrement(Aspect: TDataDogAspect; Tags: TDataDogTags); overload;
procedure Decrement(Aspect: TDataDogAspect; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordGaugeValue(Aspect: TDataDogAspect; Value: Double; Tags: TDataDogTags); overload;
procedure RecordGaugeValue(Aspect: TDataDogAspect; Value: Double; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Gauge(Aspect: TDataDogAspect; Value: Double; Tags: TDataDogTags); overload;
procedure Gauge(Aspect: TDataDogAspect; Value: Double; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordGaugeValue(Aspect: TDataDogAspect; Value: Int64; Tags: TDataDogTags); overload;
procedure RecordGaugeValue(Aspect: TDataDogAspect; Value: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Gauge(Aspect: TDataDogAspect; Value: Int64; Tags: TDataDogTags); overload;
procedure Gauge(Aspect: TDataDogAspect; Value: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordExecutionTime(Aspect: TDataDogAspect; TimeInMs: Int64; Tags: TDataDogTags); overload;
procedure RecordExecutionTime(Aspect: TDataDogAspect; TimeInMs: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Time(Aspect: TDataDogAspect; Value: Int64; Tags: TDataDogTags); overload;
procedure Time(Aspect: TDataDogAspect; Value: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordHistogramValue(Aspect: TDataDogAspect; Value: Double; Tags: TDataDogTags); overload;
procedure RecordHistogramValue(Aspect: TDataDogAspect; Value: Double; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Histogram(Aspect: TDataDogAspect; Value: Double; Tags: TDataDogTags); overload;
procedure Histogram(Aspect: TDataDogAspect; Value: Double; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordHistogramValue(Aspect: TDataDogAspect; Value: Int64; Tags: TDataDogTags); overload;
procedure RecordHistogramValue(Aspect: TDataDogAspect; Value: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure Histogram(Aspect: TDataDogAspect; Value: Int64; Tags: TDataDogTags); overload;
procedure Histogram(Aspect: TDataDogAspect; Value: Int64; SampleRate: Double; Tags: TDataDogTags); overload;
procedure RecordEvent(Event: TDataDogEvent; Tags: TDataDogTags); overload;
procedure RecordSetValue(Aspect: TDataDogAspect; Value: string; Tags: TDataDogTags); overload;
function GetPrefix: string;
procedure SetPrefix(Value: string);
end;
implementation
end.
|
unit UCalc3D;
interface
uses UCalcVec;
{---------------------------------------------------------------}
type
{Orice 4 vectori nici care 3 din care nu sunt coliniari determina un reper afin}
TReper = packed array[0..3] of TVector; {O, e1, e2, e3}
TImReper = TReper;
{---------------------------------------------------------------}
var Depth: word; {Profunzime}
{---------------------------------------------------------------}
{Obtine coordonatele P din sistemul E in sistemul absolut de coordonate}
{ M := O + P1*e1 + P2*e2 +P3*e3 }
procedure CoordAbsol (P: TVector; E: TReper; var M: TVector);
procedure CoordAbsol2D(P: TVector; E: TImReper; var M: TVec2Real);
{Proiectarea centrala: 3D -> 2D}
function Proiec(xyz: TVector; var xy: TVec2Real): boolean; {Vectorul}
function ProiecReper(E3D: TReper; var EIm: TImReper): boolean;{Reperul}
{Obtinerea coordonatelor plane ale punctului din reper}
function Get2DVec(var P: TVector; E: TReper; Var M: TVector): boolean;
{Roteste reperul E cu rad radiani in jurul axei ax}
procedure RotSis(var E: TReper; rad: real; ax: byte);
procedure RotSisRel(var E: TReper; rad: real; ax: byte);
{---------------------------------------------------------------}
implementation
{---------------------------------------------------------------}
procedure CoordAbsol(P: TVector; E: TReper; var M: TVector);
begin { M = (O + P1*e1 + P2*e2 +P3*e3) }
MulScal(e[1], e[1], P[1]); {e1 := P1 * e1}
MulScal(e[2], e[2], P[2]); {e2 := P2 * e2}
MulScal(e[3], e[3], P[3]); {e3 := P3 * e3}
AddVec(M, e[0], e[1]); {M := O + e1}
AddVec(M, M, e[2]); {M := M + e2}
AddVec(M, M, e[3]); {M := M + e3}
end;
{---------------------------------------------------------------}
procedure CoordAbsol2D(P: TVector; E: TImReper; var M: TVec2Real);
begin
{ M = (O + P1*E1 + P2*E2 +P3*E3) }
MulScal2D(E[1], E[1], P[1]); {e1 := P1 * e1}
MulScal2D(E[2], E[2], P[2]); {e2 := P2 * e2}
MulScal2D(E[3], E[3], P[3]); {e3 := P3 * e3}
AddVec2D(M, e[0], e[1]); {M := O + e1}
AddVec2D(M, M, e[2]); {M := M + e2}
AddVec2D(M, M, e[3]); {M := M + e3}
end;
{---------------------------------------------------------------}
function Proiec(xyz: TVector; var xy: TVector): boolean;
begin {3D -> 2D}
{ Atentie! xyz[3] <> -Depth, altfel se obtine eroare }
if (xyz[3] <> -Depth) then begin
xy[3] := Depth / (xyz[3]+Depth);
Proiec := true;
end else begin {punct impropriu}
xy[3] := 1.7e+38; {infinit}
Proiec := false;
end;
xy [1] := xyz[1] * xy[3]; { x := x * (Depth / (z+Depth)) }
xy [2] := xyz[2] * xy[3]; { y := y * (Depth / (z+Depth)) }
end;
{---------------------------------------------------------------}
function ProiecReper(E3D: TReper; var EIm: TImReper): boolean;
var i: integer;
begin {3D -> 2D}
ProiecReper := true;
{Transformarea vectorilor reperului in puncte din spatiu}
AddVec(E3D[1], E3D[1], E3D[0]); {E1 = O + e1}
AddVec(E3D[2], E3D[2], E3D[0]); {E2 = O + e2}
AddVec(E3D[3], E3D[3], E3D[0]); {E3 = O + e3}
{Proiectarea reperului}
for i:=0 to 3 do begin
if not Proiec(E3D[i], EIm[i]) then ProiecReper := false;
end;
{Transformarea punctelor in vectori ai imaginii reperului}
SubVec2D(EIm[1], EIm[1], EIm[0]);
SubVec2D(EIm[2], EIm[2], EIm[0]);
SubVec2D(EIm[3], EIm[3], EIm[0]);
end;
{---------------------------------------------------------------}
function Get2DVec(var P: TVector; E: TReper; Var M: TVector): boolean;
begin
CoordAbsol(P, E, M);
Get2DVec := Proiec(M, M);
end;
{---------------------------------------------------------------}
procedure RotSis(var E: TReper; rad: real; ax: byte);
begin {A roti sistemul inseamna a roti vectorii sistemului}
ax := ax mod 3;
RotAx(e[1], rad, ax);
RotAx(e[2], rad, ax);
RotAx(e[3], rad, ax);
end;
{---------------------------------------------------------------}
procedure RotSisRel(var E: TReper; rad: real; ax: byte);
begin {A roti sistemul inseamna a roti vectorii sistemului}
ax := ax mod 3 + 1;
RotVec(e[ax], e[ax mod 3 + 1], rad, e[ax], e[ax mod 3 + 1]);
end;
{---------------------------------------------------------------}
begin
Depth := 10000;
end.
|
program Pr1Ej4;
uses
Crt;
type
str20=string[20];
persona = record
apellido:str20;
nombre:str20;
edad:integer;
dni:integer;
end;
ArchivoDePersonas= file of persona;
//////////////////////////////////////
procedure Leer(var a:ArchivoDePersonas);
var
p:persona ;
begin
writeln('Escriba su apellido: ');
readln(p.apellido);
while(p.apellido<>'')do begin
writeln('Escriba su nombre: ');
readln(p.nombre);
writeln('Escriba su edad: ');
readln(p.edad);
writeln('Escriba su dni: ');
readln(p.dni);
write(a,p);
writeln('*********Aca otra persona: *********');
writeln('Escriba su apellido: ');
readln(p.apellido);
end;
end;
procedure Listar(var arc:ArchivoDePersonas);
var
p:persona;
begin
reset(arc);
while (not eof(arc))do begin
read(arc,p);
with p do
writeln(nombre,' ', apellido);
end;
close(arc);
readln();
end;
procedure Listar18(var arc:ArchivoDePersonas);
var
p:persona;
begin
reset(arc);
while (not eof(arc))do begin
read(arc,p);
if (p.edad>18) then
with p do
writeln(nombre,' ', apellido);
end;
close(arc);
readln();
end;
procedure crearArchivo(var arc:ArchivoDePersonas);
var
nombre_fisico:string[40];
begin
ClrScr;
writeln('Escriba el nombre del archivo a crear:');
readln(nombre_fisico);
assign(arc,nombre_fisico);
rewrite(arc);
Leer(arc);
close(arc);
end;
procedure ListarApellidoDet(var arc:ArchivoDePersonas);
var
ap:str20;
p:persona;
begin
reset(arc);
writeln('Escriba el apellido para listarle todas las personas con ese apellido: ');
readln(ap);
while(not eof(arc))do begin
read(arc,p);
if(p.apellido=ap)then begin
writeln(p.apellido,' ',p.nombre);
end;
end;
close(arc);
readln();
end;
procedure AgregarPersonas(var arc:ArchivoDePersonas);
begin
reset(arc);
seek(arc,filesize(arc)-1);
Leer(arc);
close(arc);
end;
procedure ModificarEdad(var arc:ArchivoDePersonas);
var
p:persona;
dni:integer;
esta:boolean;
begin
reset(arc);
ClrScr;
writeln('Escriba el dni de la persona que quiere modificar la edad: (ingrese 0 para volver al menu inicial)');
readln(dni);
if(dni<>0)then begin
esta:=false;
while(not eof(arc)and not esta)do begin
read(arc,p);
if(dni=p.dni)then
esta:=true;
end;
if(esta) then begin
writeln(p.apellido,' ',p.nombre,' ',p.edad,' a;os');
writeln('Escriba que edad le quiere poner');
readln(dni);
p.edad:=dni;
writeln('Quiere guardar la edad?');
writeln('1_ si');
writeln('2_ no');
readln(dni);
if(dni=1)then begin
seek(arc,filepos(arc)-1);
write(arc,p);
writeln('Guardado Con Exito!');
end;
end;
end;
end;
procedure exportarTxt(var arc:ArchivoDePersonas);
var
archivotexto:text;
p:persona;
begin
reset(arc);
assign(archivotexto,'personas');
rewrite(archivotexto);
while(not eof(arc))do begin
read(arc,p);
with p do
writeln(archivotexto, apellido,' ', nombre,', ', edad,' años DNI: ', dni);
end;
close(archivotexto);
end;
procedure exportarTxtErroneo(var arc:ArchivoDePersonas);
var
archivotexto:text;
p:persona;
begin
reset(arc);
assign(archivotexto,'erroneo');
rewrite(archivotexto);
while(not eof(arc))do begin
read(arc,p);
if(p.dni=0)then
with p do
writeln(archivotexto, apellido,' ', nombre,', ', edad,'años DNI: ', dni);
end;
close(archivotexto);
end;
procedure menu(var arc:ArchivoDePersonas);
var
nombre_fisico:str20;
opc:integer;
begin
writeln('0_ Cerrar archivo.');
writeln('1_ Crear Archivo.');
writeln('2_ Abrir Archivo.');
readln(opc);
while(opc<>0) do begin
case opc of
1: crearArchivo(arc);
2: begin
ClrScr;
writeln('0_ Menu de inicio.');
writeln('1_ Abrir archivo especifico.');
writeln('2_ Listar todas las personas.');
writeln('3_ Listar las personas +18.');
writeln('4_ Listar Apellido Determinado.');
writeln('5_ Agregar personas al archivo.');
writeln('6_ Modificar edad a personas.');
writeln('7_ Exportar archivo personas.txt.');
writeln('8_ Exportar archivo erroneos.txt');
readln(opc);
case opc of
0: writeln('JEJEJJEJEJEJEEJJEJJE');
1:begin
ClrScr;
writeln('Escriba el nombre del archivo existente que quiere abrir.');
readln(nombre_fisico);
assign(arc,nombre_fisico);
end;
2: Listar(arc);
3: Listar18(arc);
4: ListarApellidoDet(arc);
5: AgregarPersonas(arc);
6: ModificarEdad(arc);
7: ExportarTxt(arc);
8: exportarTxtErroneo(arc);
end;
end;
end;
ClrScr;
writeln('0_ Cerrar archivo.');
writeln('1_ Crear Archivo.');
writeln('2_ Abrir Archivo.');
readln(opc);
end;
end;
var
arc:ArchivoDePersonas;
begin
menu(arc);
end.
|
program AlgLista1Ex4; (* Exercícios 4 da lista 1 de Algoritmos. Autor: Henrique Colodetti Escanferla. *)
var g, m, s: longint; (* Já que o processo só envolve inteiros, todas as variaveis são declaradas como inteiros. *)
begin (* Começo do processo. *)
writeln('Este algoritmo irá converter um dado valor inteiro em segundos para um valor inteiro correspondente em graus, minutos e segundos.'); (* Apresentação do algoritmo e sua função. *)
writeln('Digite o valor inteiro em segundos: '); (* Requerimento da entrada para o usuário. *)
read(s); (* Leitura da variável fornecida pelo usuário. *)
g:=(s)div(3600); (* Um grau contém 3600 segundos, assim justifica-se esta expressão. *)
s:=(s)mod(3600); (* Retirada do valor de "s" ja convertido deixando o restante ainda não convertido *)
m:=(s)div(60); (* O resto da divisão anterior dá a quantidade de segundos a ser incluida em minutos. Um minuto contém 60 segundos. *)
s:=(s)mod(60); (* Retirada do valor de "s" ja convertido em minutos deixando o restante agora em segundos. *)
g:=(g)mod(360); (* Retirada de voltas inteiras para fornecer o valor mínimo equivalente *)
writeln('O valor correspondente mínimo, desconsiderando as voltas inteiras, é de: ',g,' Graus, ',m,' Minutos e ',s,' Segundos.'); (* Apresentação da saída do processo conforme foi pedido. *)
end. (* Fim do Processo. *)
|
unit ReportSys;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, RzTreeVw, frxClass, RzButton, StdCtrls,
ExtCtrls, RzPanel, RzSplit, frxDBSet, frxDesgn, DB, ADODB,
Menus;
type
TReportSysForm = class(TForm)
tvReport: TRzTreeView;
PTool: TRzSizePanel;
MemoSQL: TMemo;
BtnSave: TRzBitBtn;
ADOQReport: TADOQuery;
frxReport3: TfrxReport;
frxDBDataset3: TfrxDBDataset;
PMReport: TPopupMenu;
NModifyTicket: TMenuItem;
NRename: TMenuItem;
NDelete: TMenuItem;
N4: TMenuItem;
NCopy: TMenuItem;
N6: TMenuItem;
NRefresh: TMenuItem;
procedure FormShow(Sender: TObject);
procedure BtnSaveClick(Sender: TObject);
procedure tvReportDblClick(Sender: TObject);
procedure NModifyTicketClick(Sender: TObject);
procedure NRenameClick(Sender: TObject);
procedure tvReportChange(Sender: TObject; Node: TTreeNode);
procedure NDeleteClick(Sender: TObject);
procedure NCopyClick(Sender: TObject);
procedure NRefreshClick(Sender: TObject);
private
{ Private declarations }
currentNode: string;
public
{ Public declarations }
procedure refreshTree;
procedure GetDirectories(Tree: TRzTreeView; Directory: string;
Item: TTreeNode; IncludeFiles: Boolean);
function reportFileExists(filename: string): Boolean;
function renameReportFile(filename, newFilename: string): Boolean;
function readReportSQL(filename: string): string;
procedure updateReportSQL(filename: string; sql: string);
procedure DeleteReportFile(filename: string);
procedure CopyReportFile(filename, newFilename: string);
end;
var
ReportSysForm: TReportSysForm;
implementation
uses
StrUtils, QueryDM, Filter;
{$R *.dfm}
procedure TReportSysForm.GetDirectories(Tree: TRzTreeView; Directory: string;
Item: TTreeNode; IncludeFiles: Boolean);
var
SearchRec: TSearchRec;
ItemTemp: TTreeNode;
begin
Tree.Items.BeginUpdate;
if Directory[Length(Directory)] <> '\' then
Directory := Directory + '\';
if FindFirst(Directory + '*.*', faDirectory, SearchRec) = 0 then
begin
repeat
if (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name[1] <> '.') then
begin
if (SearchRec.Attr and faDirectory > 0) then
Item := Tree.Items.AddChild(Item, SearchRec.Name);
ItemTemp := Item.Parent;
GetDirectories(Tree, Directory + SearchRec.Name, Item, IncludeFiles);
Item := ItemTemp;
end
else
begin
if IncludeFiles then
begin
if (SearchRec.Name[1] <> '.') and (RightStr(SearchRec.Name, 3) = 'fr3') then
begin
Tree.Items.AddChild(Item, SearchRec.Name);
end;
end;
end;
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
Tree.Items.EndUpdate;
end;
end;
procedure TReportSysForm.FormShow(Sender: TObject);
begin
ADOQReport.Connection := QueryDataModule.DBConnection;
RefreshTree();
end;
procedure TReportSysForm.BtnSaveClick(Sender: TObject);
begin
if currentNode = '' then
Exit;
try
updateReportSQL(currentNode, MemoSQL.Text);
Application.MessageBox('脚本更新成功!', '提示', MB_OK + MB_ICONINFORMATION
+ MB_DEFBUTTON2 + MB_TOPMOST);
except
end;
end;
procedure TReportSysForm.tvReportDblClick(Sender: TObject);
var s: string;
n: TTreeNode;
begin
MemoSQL.Clear;
if RightStr(tvReport.Selected.Text, 3) = 'fr3' then
begin
n := tvReport.Selected;
while n.Parent <> nil do
begin
s := n.Parent.Text + '\' + s;
n := n.Parent;
end;
currentNode := s + tvReport.Selected.Text;
if ReportFileExists(currentNode) then
begin
MemoSQL.Text := readReportSQL(currentNode);
Application.CreateForm(TFilterForm, FilterForm);
try
with ADOQReport do
begin
Close;
SQL.Clear;
FilterForm.adoqReport := ADOQReport;
FilterForm.ShowModal;
if FilterForm.ret = '' then
Exit;
SQL.Text := Format(MemoSQL.Text, [FilterForm.ret]);
Open;
if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then
begin
frxReport3.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode);
frxReport3.Variables['startDate1'] := FilterForm.DTPStartDate1.Date;
frxReport3.Variables['startTime1'] := FilterForm.DTPStartTime1.Time;
frxReport3.Variables['endDate1'] := FilterForm.DTPEndDate1.Date;
frxReport3.Variables['endTime1'] := FilterForm.DTPEndTime1.Time;
frxReport3.Variables['startDate2'] := FilterForm.DTPStartDate2.Date;
frxReport3.Variables['startTime2'] := FilterForm.DTPStartTime2.Time;
frxReport3.Variables['endDate2'] := FilterForm.DTPEndDate2.Date;
frxReport3.Variables['endDate2'] := FilterForm.DTPEndTime2.Time;
frxReport3.ShowReport();
end;
end;
finally
FilterForm.Free;
end;
end;
end;
end;
procedure TReportSysForm.NModifyTicketClick(Sender: TObject);
begin
if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then
begin
frxReport3.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode);
frxReport3.DesignReport();
end;
end;
procedure TReportSysForm.NRenameClick(Sender: TObject);
var newNode: string;
begin
//重命名:文件重命名+INI文件Section改名
if currentNode <> '' then
begin
newNode := InputBox('请输入新名称 ', '', currentNode);
renameReportFile(currentNode, newNode);
if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then
begin
RenameFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode,
ExtractFilePath(ParamStr(0)) + 'ReportII\' + newNode);
end;
RefreshTree();
end;
end;
procedure TReportSysForm.tvReportChange(Sender: TObject; Node: TTreeNode);
var s: string;
n: TTreeNode;
begin
MemoSQL.Clear;
if RightStr(tvReport.Selected.Text, 3) = 'fr3' then
begin
n := tvReport.Selected;
while n.Parent <> nil do
begin
s := n.Parent.Text + '\' + s;
n := n.Parent;
end;
currentNode := s + tvReport.Selected.Text;
MemoSQL.Text := readReportSQL(currentNode);
end;
end;
procedure TReportSysForm.NDeleteClick(Sender: TObject);
begin
if Application.MessageBox('你确定要删除这张报表吗?', '警告', MB_YESNO +
MB_ICONWARNING + MB_DEFBUTTON2 + MB_TOPMOST) = IDNO then
begin
Exit;
end;
if currentNode <> '' then
begin
DeleteReportFile(currentNode);
if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then
begin
DeleteFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode);
end;
RefreshTree();
end;
end;
procedure TReportSysForm.NCopyClick(Sender: TObject);
var newNode: string;
begin
//重命名:文件重命名+INI文件Section改名
if currentNode <> '' then
begin
newNode := InputBox('请输入新名称 ', '', currentNode);
CopyReportFile(currentNode, newNode);
if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then
begin
CopyFile(PAnsiChar(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode),
PAnsiChar(ExtractFilePath(ParamStr(0)) + 'ReportII\' + newNode), False);
end;
RefreshTree();
end;
end;
procedure TReportSysForm.NRefreshClick(Sender: TObject);
begin
RefreshTree();
end;
procedure TReportSysForm.refreshTree;
begin
tvReport.Items.Clear;
GetDirectories(tvReport, ExtractFilePath(ParamStr(0)) + 'ReportII', nil, True);
end;
procedure TReportSysForm.updateReportSQL(filename, sql: string);
var sl: TStringList;
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
sl := TStringList.Create;
try
if FileExists(filename) then
sl.LoadFromFile(filename);
sl.Text := AnsiToUtf8(sql);
sl.SaveToFile(filename);
finally
sl.Free;
end;
end;
function TReportSysForm.readReportSQL(filename: string): string;
var sl: TStringList;
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
sl := TStringList.Create;
try
if FileExists(filename) then
sl.LoadFromFile(filename);
Result := Utf8ToAnsi(sl.Text);
finally
sl.Free;
end;
end;
function TReportSysForm.reportFileExists(filename: string): Boolean;
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
Result := FileExists(filename);
end;
function TReportSysForm.renameReportFile(filename,
newFilename: string): Boolean;
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
newFilename := Copy(newFilename, 1, Length(newFilename) - 4);
newFilename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ newFilename + '.sql';
CopyFile(PAnsiChar(filename), PAnsiChar(newFilename), False);
if FileExists(filename) then
begin
DeleteFile(filename);
end;
end;
procedure TReportSysForm.DeleteReportFile(filename: string);
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
if FileExists(filename) then
begin
DeleteFile(filename);
end;
end;
procedure TReportSysForm.CopyReportFile(filename, newFilename: string);
begin
filename := Copy(filename, 1, Length(filename) - 4);
filename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ filename + '.sql';
newFilename := Copy(newFilename, 1, Length(newFilename) - 4);
newFilename := ExtractFilePath(ParamStr(0)) + 'ReportII\'
+ newFilename + '.sql';
CopyFile(PAnsiChar(filename), PAnsiChar(newFilename), False);
end;
end.
|
unit Thread.EncerraFechamento;
interface
uses
System.Classes, Model.FechamentoExpressas, DAO.FechamentosExpressas, Model.ExtratosExpressas, DAO.ExtratosExpressas, Generics.Collections, Model.ParcelamentoRestricao,
DAO.ParcelamentoRestricao, Model.ExtraviosMultas, DAO.ExtraviosMultas, clLancamentos, System.SysUtils, Forms, Windows, Global.Parametros, clRestricoes;
type
Thread_EncerraFechamento = class(TThread)
private
{ Private declarations }
fechamentos : TObjectList<TFechamentoExpressas>;
fechamentoDAO : TFechamentoExpressasDAO;
extratos : TObjectList<TExtratosExpressas>;
extratoTMP : TExtratosExpressasDAO;
parcelas : TObjectList<TParcelamentoRestricao>;
parcelaTMP : TParcelamentoRestricaoDAO;
extravios : TObjectList<TExtraviosMultas>;
extravioDAO : TExtraviosMultasDAO;
lancamentos : TLancamentos;
restricao : TRestricoes;
FdPos: Double;
sMensagem : String;
protected
procedure IniciaProcesso;
procedure AtualizaProcesso;
procedure TerminaProcesso;
procedure EncerraLancamentos;
procedure EncerraExtravios;
procedure EncerraParcelamentos;
procedure EncerraFechamento;
Procedure EncerraExtrato;
procedure Execute; override;
public
dtInicio: TDate;
dtFinal: TDate;
dtPagamento: TDate;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Thread_EncerraFechamento.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ Thread_EncerraFechamento }
uses View.FechamentoExpressas, udm, Common.Utils, uGlobais;
procedure Thread_EncerraFechamento.AtualizaProcesso;
begin
view_FechamentoExpressas.sbFechamento.Panels[0].Text := sMensagem;
view_FechamentoExpressas.sbFechamento.Refresh;
view_FechamentoExpressas.pbFechamento.Position := FdPos;
view_FechamentoExpressas.pbFechamento.Properties.Text := FormatFloat('0.00%',FdPos);
view_FechamentoExpressas.pbFechamento.Refresh;
end;
procedure Thread_EncerraFechamento.EncerraExtrato;
var
extratoTMP : TExtratosExpressas;
aParam: array of Variant;
iPos: Integer;
iTotal: Integer;
lLog: TStringList;
begin
try
iTotal := 0;
iPos := 0;
lLog := TStringList.Create;
sMensagem := 'Encerrando o Extrato em aberto. Aguarde...';
Synchronize(AtualizaProcesso);
SetLength(aPAram, 3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
extratos := TObjectList<TExtratosExpressas>.Create;
extratoDAO := TExtratosExpressasDAO.Create;
extratos := extratoDAO.FindExtrato('PERIODO',aParam);
Finalize(aParam);
iTotal := extratos.Count;
for extratoTMP in extratos do
begin
extratoTMP.DataPagamento := dtPagamento;
extratoTMP.Fechado := 1;
lLog.Text := extratoTMP.Log;
lLog.Add(FormatDateTime('yyyy/mm/dd h:mm:ss', Now()) + ' encerrado por ' + Global.Parametros.pUser_Name);
extratoTMP.Log := lLog.Text;
lLog.Clear;
if not extratoDAO.Update(extratoTMP) then
begin
Application.MessageBox(PChar('Erro ao fechar o extrato número ' + extratoTMP.Id.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR);
end;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
EXTRATOdao.Free;
end;
end;
procedure Thread_EncerraFechamento.EncerraExtravios;
var
extratoTMP : TExtratosExpressas;
extravioTMP : TExtraviosMultas;
aParam: array of Variant;
iPos: Integer;
iTotal: Integer;
sObs: String;
begin
try
iTotal := 0;
iPos := 0;
sMensagem := 'Encerrando os Extravios. Aguarde...';
Synchronize(AtualizaProcesso);
SetLength(aPAram, 3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
extravios := TObjectList<TExtraviosMultas>.Create;
extravioDAO := TExtraviosMultasDAO.Create;
extratos := TObjectList<TExtratosExpressas>.Create;
extratoDAO := TExtratosExpressasDAO.Create;
extratos := extratoDAO.FindExtrato('PERIODO', aParam);
Finalize(aParam);
iTotal := extratos.Count;
for extratoTMP in extratos do
begin
SetLength(aParam,1);
aParam[0] := extratoTMP.Id;
extravios := extravioDAO.FindExtravio('EXTRATO', aParam);
sObs := '';
for extravioTMP in extravios do
begin
extravioTMP.Percentual := 100;
extravioTMP.Manutencao := Now();
extravioTMP.Executor := Global.Parametros.pUser_Name;
sObs := extravioTMP.Obs;
sObs := sObs + #13 + 'Extravio encerrado em ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now()) + ' por ' + Global.Parametros.pUser_Name;
extravioTMP.Obs := sObs;
if not extravioDAO.Update(extravioTMP) then
begin
Application.MessageBox(PChar('Erro ao fechar o extravio NN ' + extravio.NN + ' !'), 'Atenção', MB_OK + MB_ICONERROR);
end;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
end;
finally
extratoDAO.Free;
extravioDAO.Free;
end;
end;
procedure Thread_EncerraFechamento.EncerraFechamento;
var
fechamentoTMP: TFechamentoExpressas;
aParam: array of Variant;
iPos: Integer;
iTotal: Integer;
lLog: TStringList;
begin
try
iTotal := 0;
iPos := 0;
lLog := TStringList.Create;
sMensagem := 'Encerrando o Fechamento em aberto. Aguarde...';
Synchronize(AtualizaProcesso);
SetLength(aPAram, 3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
fechamentos := TObjectList<TFechamentoExpressas>.Create;
fechamentoDAO := TFechamentoExpressasDAO.Create;
SetLength(aParam,3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
fechamentos := fechamentoDAO.FindFechamento('PERIODO', aParam);
Finalize(aParam);
iTotal := fechamentos.Count;
for fechamentoTMP in fechamentos do
begin
fechamentoTMP.Fechado := 1;
lLog.Text := fechamentoTMP.Log;
lLog.Add(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now()) + ' encerrado por ' + Global.Parametros.pUser_Name);
fechamentoTMP.Log := lLog.Text;
lLog.Clear;
if not fechamentoDAO.Update(fechamentoTMP) then
begin
Application.MessageBox(PChar('Erro ao encerrar o fechamento número ' + fechamentoTMP.Id.ToString + ' !'), 'Atenção', MB_OK + MB_ICONERROR);
end;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
Finalize(aParam);
fechamentoDAO.Free;
end;
end;
procedure Thread_EncerraFechamento.EncerraLancamentos;
var
aParam: array of Variant;
extratoTMP : TExtratosExpressas;
iPos: Integer;
iTotal: Integer;
begin
try
lancamentos := TLancamentos.Create;
iTotal := 0;
iPos := 0;
sMensagem := 'Encerrando os Lancaçamentos de Créditos e Débitos. Aguarde...';
Synchronize(AtualizaProcesso);
SetLength(aPAram, 3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
extratos := TObjectList<TExtratosExpressas>.Create;
extratoDAO := TExtratosExpressasDAO.Create;
extratos := extratoDAO.FindExtrato('PERIODO', aParam);
Finalize(aParam);
iTotal := extratos.Count;
for extratoTMP in extratos do
begin
if lancamentos.getObject(extratoTMP.Id.ToString, 'EXTRATO') then
begin
if lancamentos.Persistir <> 'S' then
begin
lancamentos.Descontado := 'S';
lancamentos.Desconto := dtPagamento;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
if not lancamentos.Update() then
begin
Application.MessageBox(PChar('Erro ao encerrar o lançamento número ' + lancamentos.Codigo.ToString + '!'), 'Erro', MB_OK + MB_ICONERROR);
end;
end;
end;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
lancamentos.Free;
extratoDAO.Free;
end;
end;
procedure Thread_EncerraFechamento.EncerraParcelamentos;
var
extratoTMP : TExtratosExpressas;
parcelaTMP : TParcelamentoRestricao;
aParam: array of Variant;
iPos: Integer;
iTotal: Integer;
sFiltro : String;
dValor : Double;
begin
try
iTotal := 0;
iPos := 0;
sFiltro := '';
restricao := TRestricoes.Create;
sMensagem := 'Encerrando os Parcelamentos de Restrição. Aguarde...';
Synchronize(AtualizaProcesso);
SetLength(aPAram, 3);
aParam[0] := dtInicio;
aParam[1] := dtFinal;
aParam[2] := 0;
parcelas := TObjectList<TParcelamentoRestricao>.Create;
parcelaDAO := TParcelamentoRestricaoDAO.Create;
extratos := TObjectList<TExtratosExpressas>.Create;
extratoDAO := TExtratosExpressasDAO.Create;
extratos := extratoDAO.FindExtrato('PERIODO', aParam);
Finalize(aParam);
iTotal := extratos.Count;
for extratoTMP in extratos do
begin
dValor := 0;
sFiltro := 'WHERE ID_EXTRATO = ' + extratoTMP.Id.ToString + ' AND DOM_DEBITADO = 0';
SetLength(aParam,1);
aParam[0] := sFiltro;
parcelas := parcelaDAO.FindParcelamentos('FILTRO', aParam);
Finalize(aParam);
for parcelaTMP in parcelas do
begin
parcelaTMP.Debitado := 1;
if not parcelaDAO.Update(parcelaTMP) then
begin
Application.MessageBox(PChar('Erro ao desvincular o parcelamento do extrato número '+ extratoTMP.Id.ToString + '!'), 'Erro', MB_OK + MB_ICONERROR);
end;
if restricao.getObject(parcelaTMP.Restricao.ToString, 'CODIGO') then
begin
dValor := dm.QryGetObject.FieldByName('VAL_RESTRICAO').AsFloat;
dValor := dValor - parcelaTMP.Valor;
dm.QryGetObject.Edit;
dm.QryGetObject.FieldByName('VAL_RESTRICAO').AsFloat := dValor;
dm.QryGetObject.FieldByName('VAL_debitar').AsFloat := dValor;
dm.QryGetObject.FieldByName('VAL_PAGO').AsFloat := dm.QryGetObject.FieldByName('VAL_PAGO').AsFloat + parcelaTMP.Valor;
dm.QryGetObject.Post;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
end;
end;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
extratoDAO.Free;
parcelaDAO.Free;
end;
end;
procedure Thread_EncerraFechamento.Execute;
begin
{ Place thread code here }
Synchronize(IniciaProcesso);
Synchronize(EncerraLancamentos);
Synchronize(EncerraExtravios);
Synchronize(EncerraParcelamentos);
Synchronize(EncerraFechamento);
Synchronize(EncerraExtrato);
Synchronize(TerminaProcesso);
end;
procedure Thread_EncerraFechamento.IniciaProcesso;
begin
view_FechamentoExpressas.actProcessar.Enabled := False;
view_FechamentoExpressas.actCancelar.Enabled := False;
view_FechamentoExpressas.actEncerrar.Enabled := False;
view_FechamentoExpressas.dsFechamento.Enabled := False;
view_FechamentoExpressas.sbFechamento.Panels[0].Text := '';
view_FechamentoExpressas.pbFechamento.Visible := True;
view_FechamentoExpressas.pbFechamento.Position := 0;
view_FechamentoExpressas.pbFechamento.Refresh;
view_FechamentoExpressas.sbFechamento.Refresh;
end;
procedure Thread_EncerraFechamento.TerminaProcesso;
begin
sMensagem := '';
FdPos := 0;
view_FechamentoExpressas.sbFechamento.Panels[0].Text := '';
view_FechamentoExpressas.pbFechamento.Position := 0;
view_FechamentoExpressas.pbFechamento.Refresh;
view_FechamentoExpressas.pbFechamento.Visible := False;
view_FechamentoExpressas.sbFechamento.Refresh;
view_FechamentoExpressas.dsFechamento.Enabled := True;
view_FechamentoExpressas.actProcessar.Enabled := True;
view_FechamentoExpressas.actCancelar.Enabled := False;
view_FechamentoExpressas.actEncerrar.Enabled := False;
view_FechamentoExpressas.datInicio.Properties.ReadOnly := False;
view_FechamentoExpressas.datTermino.Properties.ReadOnly := False;
view_FechamentoExpressas.datInicio.Clear;
view_FechamentoExpressas.datTermino.Clear;
view_FechamentoExpressas.mtbFechamento.Close;
view_FechamentoExpressas.datInicio.SetFocus;
view_FechamentoExpressas.cxLabel2.Caption := '0';
Common.Utils.TUtils.GravaIni(uGlobais.sIni,'Common','RaioX','0');
end;
end.
|
{
Copyright (c) 2023 by Ryan Joseph
GLCanvas Test #24
Tests blitting frame buffer regions into textures
}
{$mode objfpc}
{$modeswitch implicitfunctionspecialization}
program Test24;
uses
SysUtils, Classes, GLCanvas;
const
window_size_width = 500;
window_size_height = 500;
var
sourceRect: TRect;
destOffset: TVec2;
target: TTexture;
frameBuffer: TFrameBuffer;
procedure UpdateBlit;
var
image: TImage;
begin
// TODO: how can we clear the target texture?
image := TImage.Create(target.Width, target.height);
image.Fill(TColor.White);
target.LoadIfNeeded;
target.Reload(image.Data);
image.Free;
frameBuffer.Blit(target, sourceRect, destOffset);
end;
procedure EventCallback(event: TEvent);
begin
case event.EventType of
TEventType.KeyDown:
case event.KeyCode of
KEY_LEFT:
begin
// TODO: should have IsShiftDown modifier
if ssAlt in event.KeyboardModifiers then
destOffset.x -= 1
else
sourceRect.origin.x -= 1;
UpdateBlit;
end;
KEY_RIGHT:
begin
if ssAlt in event.KeyboardModifiers then
destOffset.x += 1
else
sourceRect.origin.x += 1;
UpdateBlit;
end;
KEY_UP:
begin
if ssAlt in event.KeyboardModifiers then
destOffset.y -= 1
else
sourceRect.origin.y -= 1;
UpdateBlit;
end;
KEY_DOWN:
begin
if ssAlt in event.KeyboardModifiers then
destOffset.y += 1
else
sourceRect.origin.y += 1;
UpdateBlit;
end;
end;
end;
end;
var
image: TTexture;
rect: TRect;
begin
SetupCanvas(window_size_width, window_size_height, @EventCallback);
image := TTexture.Create('checkers.png');
frameBuffer := TFrameBuffer.Create(64);
frameBuffer.Push;
DrawTexture(image, frameBuffer.Bounds);
frameBuffer.Pop;
// Create the target texture
target := TTexture.Create(frameBuffer.Size, nil);
// TODO: flipped texture property for DrawTexture calls
//target.Flipped := true;
destOffset := V2(16, 16);
sourceRect := RectMake(0, 0, 32, 32);
UpdateBlit;
SetWindowTitle('Use arrow keys to move blitting area');
while IsRunning do
begin
ClearBackground;
// Dest
rect := RectMake(100, 100, target.Size);
DrawTexture(target, rect, RectMake(0,1,1,-1));
StrokeRect(rect, TColor.Black);
StrokeRect(RectMake(rect.origin + destOffset, sourceRect.size), TColor.Black);
// Source
rect := RectMake(300, 100, frameBuffer.Size);
DrawTexture(frameBuffer.Texture, rect);
StrokeRect(rect, TColor.Black);
StrokeRect(RectMake(rect.origin + sourceRect.origin, sourceRect.size), TColor.Black);
SwapBuffers;
end;
QuitApp;
end. |
unit uCPU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfCPUregisters = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
lblPC: TLabel;
lblCInstr: TLabel;
lblRPA: TLabel;
lblWPA: TLabel;
lblRPB: TLabel;
lblWPB: TLabel;
lblAInstr: TLabel;
lblBInstr: TLabel;
Label9: TLabel;
lblPlayer: TLabel;
Label10: TLabel;
lblCycle: TLabel;
Label11: TLabel;
lblSourceA: TLabel;
Label13: TLabel;
lblTargetA: TLabel;
Label15: TLabel;
lblSourceB: TLabel;
Label17: TLabel;
lblTargetB: TLabel;
Label12: TLabel;
lblNextInQueue: TLabel;
Label14: TLabel;
lblStackBase: TLabel;
Label16: TLabel;
lblStackPointer: TLabel;
Label18: TLabel;
lblStackTop: TLabel;
Label19: TLabel;
lblProcessID: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
var
fCPUregisters: TfCPUregisters;
implementation
{$R *.dfm}
end.
|
unit SillyNetworkingU;
{$interfaces COM}
interface
uses
types, Classes, windows, sysutils, syncobjs,
blcksock, synsock;
type
ISharedObject = interface
function GetClassName: string;
end;
TSharedObject = class(TInterfacedObject, ISharedObject)
public
function GetClassName: string;
end;
ICriticalSection = interface(ISharedObject)
function TryEnter: Boolean;
procedure Enter;
procedure Leave;
end;
TCriticalSection = class(TSharedObject, ICriticalSection)
private
InternalCriticalSection: TRTLCriticalSection;
public
constructor Create;
function TryEnter: Boolean;
procedure Enter;
procedure Leave;
destructor Destroy; override;
end;
TMemoryStreamDynArray = array of TMemoryStream;
TMessageQueue = class
private
MessageArray: TMemoryStreamDynArray;
Count: Integer;
Locker: TRTLCriticalSection;
procedure Shrink1;
public
constructor Create(aCountOfMessagesLimit: Integer);
function Push(aMessage: TMemoryStream): Boolean;
function Pop: TMemoryStream;
destructor Destroy; override;
end;
TInt64MemoryBlock = array[0..7] of byte;
TMessageReceiver = class
strict private
ExpectedSizeDataPosition: Byte;
ExpectedSizeData: TInt64MemoryBlock;
ExpectedSize: Int64;
Memory: TMemoryStream;
TempMemory: TMemoryStream;
function Ready: Boolean;
procedure ShiftLeft(aRightPosition: Int64);
public
constructor Create;
procedure Write(const aBuffer: PByte; const aLength: Integer);
function Extract: TMemoryStream;
destructor Destroy; override;
end;
TMethodThread = class;
TMethodThreadMethod = procedure(aThread: TMethodThread) of object;
TMethodThread = class(TThread)
private
Method: TMethodThreadMethod;
protected
procedure Execute; override;
procedure WriteLog(s: string);
public
property Terminated;
constructor Create(aMethod: TMethodThreadMethod);
end;
TClient = class
private
MessageReceiver: TMessageReceiver;
Incoming: TMessageQueue;
Outgoing: TMessageQueue;
Socket: TTCPBlockSocket;
ReaderThread: TMethodThread;
WriterThread: TMethodThread;
ConnectionActiveF: Boolean;
KeepAliveInterval: Cardinal;
PushEvent: TEvent;
procedure ReaderRoutine(aThread: TMethodThread);
procedure WriterRoutine(aThread: TMethodThread);
function CheckConnectionActive: Boolean;
procedure WriteLog(aMessage: string);
public
// Pluggable.
IncomingMessageEvent: TEvent;
TargetAddress: string;
TargetPort: Word;
ThreadIdleInterval: DWord;
property ConnectionActive: Boolean read ConnectionActiveF;
constructor Create;
procedure Start;
procedure Stop;
procedure Push(aMessage: TMemoryStream);
function Pop: TMemoryStream;
destructor Destroy; override;
end;
// For testing purposes.
TEchoClient = class
private
Client: TClient;
EchoThread: TMethodThread;
EchoThreadEvent: TEvent;
procedure SetTargetAddress(a: string);
procedure SetTargetPort(a: Word);
procedure SetThreadIdleInterval(a: DWord);
procedure EchoThreadRoutine(a: TMethodThread);
public
property TargetAddress: string write SetTargetAddress;
property TargetPort: Word write SetTargetPort;
property ThreadIdleInterval: DWORD write SetThreadIdleInterval;
constructor Create;
procedure Start;
procedure Stop;
destructor Destroy; override;
end;
const
DefaultMessageBufferLimit = 10 * 1000;
DefaultThreadIdleInterval = 10;
DefaultKeepAliveInterval = 3000;
DefaultDateTimeFormat = 'yyyy-mm-dd_hh-nn-ss';
DefaultRecvBufferLength = 1;
var
LogFileLocation: string;
LogFileHandle: THandle;
procedure Initialize;
procedure Finalize;
implementation
{$REGION EXCEPTION}
function ExceptionCallStackToStrings: TStringDynArray;
var
i: Integer;
frames: PPointer;
begin
SetLength(result, 1 + ExceptFrameCount);
frames := ExceptFrames;
result[0] := BackTraceStrFunc(ExceptAddr);
for i := 0 to ExceptFrameCount - 1 do
result[i + 1] := BackTraceStrFunc(frames[i]);
end;
function JoinStringArray(aStringArray: TStringDynArray; aSeparator: string): string;
var
i: Integer;
begin
result := '';
for i := 0 to Length(aStringArray) - 1 do
begin
result := result + aStringArray[i];
if i < Length(aStringArray) - 1 then
result := result + aSeparator;
end;
end;
function ExceptionCallStackToText: string;
begin
result := JoinStringArray(ExceptionCallStackToStrings, LineEnding);
end;
function ExceptionToText(e: Exception): string;
begin
result := e.ClassName + ': "' + e.Message + '"' + LineEnding + ExceptionCallStackToText;
end;
{$ENDREGION}
{$REGION INT_64_MEMBLOCK}
function Int64ToMemoryBlock(aX: Int64): TInt64MemoryBlock;
var
i: Byte;
begin
for i := 0 to SizeOf(aX) - 1 do
begin
result[i] := (aX shr (i * 8)) and $FF;
end;
end;
function MemoryBlockToInt64(aBlock: TInt64MemoryBlock): Int64;
var
i: Byte;
currentValue: Int64;
begin
result := 0;
for i := 0 to SizeOf(result) - 1 do
begin
currentValue := aBlock[i];
result := result or (currentValue shl (i * 8));
end;
end;
{$ENDREGION}
{$REGION LOG}
function GetDefaultLogFileLocation: string;
var
currentMoment: TDateTime;
begin
currentMoment := Now;
result := 'silly_networking_log_'
+ FormatDateTime('yyyy-mm-dd_hh-nn-ss', currentMoment) + '.txt';
end;
procedure CreateLogFile;
begin
LogFileHandle := CreateFile(PChar(GetDefaultLogFileLocation),
GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
end;
procedure WriteLog(text: string);
var
writeResult: DWORD;
begin
text := FormatDateTime(DefaultDateTimeFormat, Now) + ' ' + IntToHex(GetCurrentThreadId, 8) + ': '
+ text + LineEnding;
writeResult := 0;
WriteFile(LogFileHandle, text[1], Length(text), writeResult, nil);
end;
procedure CloseLogFile;
begin
CloseHandle(LogFileHandle);
LogFileHandle := 0;
end;
{$ENDREGION}
procedure Initialize;
begin
CreateLogFile;
WriteLog('Log file created');
end;
procedure Finalize;
begin
WriteLog('Closing log file');
CloseLogFile;
end;
{ TEchoClient }
procedure TEchoClient.SetTargetAddress(a: string);
begin
Client.TargetAddress := a;
end;
procedure TEchoClient.SetTargetPort(a: Word);
begin
Client.TargetPort := a;
end;
procedure TEchoClient.SetThreadIdleInterval(a: DWord);
begin
Client.ThreadIdleInterval := a;
end;
procedure TEchoClient.EchoThreadRoutine(a: TMethodThread);
procedure Tick;
var
m: TMemoryStream;
begin
m := Client.Incoming.Pop;
if m <> nil then
Client.Outgoing.Push(m);
end;
begin
while not a.Terminated do
begin
Tick;
EchoThreadEvent.WaitFor(5);
end;
Tick;
end;
constructor TEchoClient.Create;
begin
inherited Create;
Client := TClient.Create;
EchoThreadEvent := TEvent.Create(nil, false, false, '');
Client.IncomingMessageEvent := EchoThreadEvent;
end;
procedure TEchoClient.Start;
begin
Client.Start;
EchoThread := TMethodThread.Create(@EchoThreadRoutine);
end;
procedure TEchoClient.Stop;
begin
if EchoThread <> nil then
begin
EchoThread.Terminate;
EchoThreadEvent.SetEvent;
EchoThread.WaitFor;
EchoThread.Free;
EchoThread := nil;
end;
Client.Stop;
end;
destructor TEchoClient.Destroy;
begin
Stop;
inherited Destroy;
end;
procedure TClient.ReaderRoutine(aThread: TMethodThread);
var
buffer: TByteDynArray;
procedure ConnectForward;
begin
if (TargetAddress <> '') and (TargetPort <> 0) then
begin
Socket.Connect(TargetAddress, IntToStr(TargetPort));
if Socket.LastError = 0 then
begin
ConnectionActiveF := True;
WriteLog('Successfully connected to address "' + TargetAddress + '" '
+ 'port ' + IntToStr(TargetPort));
end
else
begin
Socket.CloseSocket;
ConnectionActiveF := False;
WriteLog('Tried to connect; failed; Socket.LastError = ' + IntToStr(Socket.LastError) + ', '
+ 'Socket.LastErrorDesc = "' + Socket.LastErrorDesc + '"; '
+ 'target address is "' + TargetAddress + '", port ' + IntToStr(TargetPort));
end;
end;
end;
procedure ReadForward;
function ReadBuffer: Integer;
begin
result := self.Socket.RecvBufferEx(@buffer[0], Length(buffer), 1);
end;
procedure TryExtractMessages;
var
pushResult: Boolean;
incomingMessage: TMemoryStream;
begin
incomingMessage := MessageReceiver.Extract;
while incomingMessage <> nil do
begin
pushResult := Incoming.Push(incomingMessage);
if IncomingMessageEvent <> nil then
IncomingMessageEvent.SetEvent;
if not pushResult then
incomingMessage.Free;
incomingMessage := MessageReceiver.Extract;
end;
end;
var
incomingDataLength: Integer;
begin
while ConnectionActive do
begin
while True do
begin
incomingDataLength := ReadBuffer;
if incomingDataLength > 0 then
begin
MessageReceiver.Write(@buffer[0], incomingDataLength);
TryExtractMessages;
end
else
break;
end;
ConnectionActiveF := CheckConnectionActive;
if not ConnectionActiveF then
Socket.CloseSocket;
end;
end;
begin
SetLength(buffer, DefaultRecvBufferLength);
while not aThread.Terminated do
begin
if not ConnectionActive then
ConnectForward;
if ConnectionActive then
ReadForward
else
SysUtils.Sleep(1000); // failed to connect; do not attempt to connect again right away.
//SysUtils.Sleep(ThreadIdleInterval);
end;
ReadForward;
end;
procedure TClient.WriterRoutine(aThread: TMethodThread);
var
lastKeepAliveMoment: QWord;
procedure WriteMessage(aMessage: TMemoryStream);
var
sizeData: TInt64MemoryBlock;
begin
sizeData := Int64ToMemoryBlock(aMessage.Size);
WriteLog('WriteMessage: ' + IntToStr(aMessage.Size));
Socket.SendBuffer(@sizeData[0], SizeOf(Int64));
if aMessage.Size > 0 then
Socket.SendBuffer(aMessage.Memory, Integer(aMessage.Size));
end;
procedure SendKeepAliive;
var
emptyMessage: TMemoryStream;
begin
emptyMessage := TMemoryStream.Create;
WriteMessage(emptyMessage);
emptyMessage.Free;
end;
procedure SendKeepAliveIfRequired;
begin
if KeepAliveInterval < GetTickCount64 - lastKeepAliveMoment then
begin
SendKeepAliive;
lastKeepAliveMoment := GetTickCount64;
end;
end;
procedure WriteForward;
var
outgoingMessage: TMemoryStream;
begin
while self.ConnectionActive do
begin
outgoingMessage := Outgoing.Pop;
if outgoingMessage <> nil then
begin
WriteMessage(outgoingMessage);
outgoingMessage.Free;
ConnectionActiveF := CheckConnectionActive;
if not ConnectionActiveF then
Socket.CloseSocket;
end
else
break;
end;
end;
begin
while not aThread.Terminated do
begin
WriteForward;
PushEvent.WaitFor(ThreadIdleInterval);
end;
WriteForward;
end;
function TClient.CheckConnectionActive: Boolean;
begin
result := (Socket.LastError = 0) or (Socket.LastError = WSAETIMEDOUT);
end;
procedure TClient.WriteLog(aMessage: string);
begin
SillyNetworkingU.WriteLog('TClient: ' + aMessage);
end;
constructor TClient.Create;
begin
inherited Create;
KeepAliveInterval := DefaultKeepAliveInterval;
ThreadIdleInterval := DefaultThreadIdleInterval;
MessageReceiver := TMessageReceiver.Create;
Incoming := TMessageQueue.Create(DefaultMessageBufferLimit);
PushEvent := TEvent.Create(nil, false, false, '');
Outgoing := TMessageQueue.Create(DefaultMessageBufferLimit);
Socket := TTCPBlockSocket.Create;
end;
procedure TClient.Start;
begin
if nil = ReaderThread then
ReaderThread := TMethodThread.Create(@ReaderRoutine);
if nil = WriterThread then
WriterThread := TMethodThread.Create(@WriterRoutine);
end;
procedure TClient.Stop;
begin
if WriterThread <> nil then
begin
WriterThread.Terminate;
WriterThread.WaitFor;
WriterThread.Free;
WriterThread := nil;
end;
if ReaderThread <> nil then
begin
ReaderThread.Terminate;
ReaderThread.WaitFor;
ReaderThread.Free;
ReaderThread := nil;
end;
Socket.CloseSocket;
ConnectionActiveF := False;
end;
procedure TClient.Push(aMessage: TMemoryStream);
begin
Outgoing.Push(aMessage);
PushEvent.SetEvent;
end;
function TClient.Pop: TMemoryStream;
begin
result := Incoming.Pop;
end;
destructor TClient.Destroy;
begin
Stop;
Outgoing.Free;
PushEvent.Free;;
Incoming.Free;
MessageReceiver.Free;
Socket.Free;
inherited Destroy;
end;
constructor TMethodThread.Create(aMethod: TMethodThreadMethod);
begin
inherited Create(True);
self.Method := aMethod;
Start;
end;
procedure TMethodThread.Execute;
begin
try
Method(self);
except
on e: Exception do
WriteLog('Exception in thread ' + ExceptionToText(e));
end;
end;
procedure TMethodThread.WriteLog(s: string);
begin
SillyNetworkingU.WriteLog(self.ClassName + ': ' + s)
end;
procedure TMessageQueue.Shrink1;
var
i: Integer;
begin
for i := 0 to Count - 2 do
self.MessageArray[i] := self.MessageArray[i + 1];
Dec(Count);
end;
constructor TMessageQueue.Create(aCountOfMessagesLimit: Integer);
begin
inherited Create;
InitCriticalSection(Locker);
SetLength(MessageArray, aCountOfMessagesLimit);
end;
function TMessageQueue.Push(aMessage: TMemoryStream): Boolean;
begin
EnterCriticalsection(Locker);
result := self.Count < Length(self.MessageArray);
if result then
begin
self.MessageArray[self.Count] := aMessage;
Inc(self.Count);
end;
LeaveCriticalsection(Locker);
end;
function TMessageQueue.Pop: TMemoryStream;
begin
result := nil;
EnterCriticalsection(Locker);
if self.Count > 0 then
begin
result := self.MessageArray[0];
Shrink1;
end;
LeaveCriticalsection(Locker);
end;
destructor TMessageQueue.Destroy;
begin
DoneCriticalsection(Locker);
inherited Destroy;
end;
constructor TMessageReceiver.Create;
begin
inherited Create;
Memory := TMemoryStream.Create;
Memory.Size := DefaultMessageBufferLimit;
Memory.Position := 0;
TempMemory := TMemoryStream.Create;
TempMemory.Size := DefaultMessageBufferLimit;
TempMemory.Position := 0;
end;
procedure TMessageReceiver.Write(const aBuffer: PByte; const aLength: Integer);
var
offset: Integer;
begin
offset := 0;
while (ExpectedSizeDataPosition < SizeOf(ExpectedSize)) and (offset < aLength) do
begin
ExpectedSizeData[ExpectedSizeDataPosition] := aBuffer[offset];
Inc(ExpectedSizeDataPosition);
Inc(offset);
if ExpectedSizeDataPosition = SizeOf(ExpectedSize) then
ExpectedSize := MemoryBlockToInt64(ExpectedSizeData);
end;
if offset < aLength then
Memory.Write(aBuffer[offset], aLength - offset);
end;
function TMessageReceiver.Ready: Boolean;
begin
result := (ExpectedSizeDataPosition = SizeOf(ExpectedSize)) and (ExpectedSize <= Memory.Position);
end;
procedure TMessageReceiver.ShiftLeft(aRightPosition: Int64);
var
leftOverLength: Int64;
begin
leftOverLength := aRightPosition - ExpectedSize;
ExpectedSizeDataPosition := 0;
Memory.Position := 0;
if leftOverLength > 0 then
begin
Memory.Position := ExpectedSize;
TempMemory.Position := 0;
TempMemory.CopyFrom(Memory, leftOverLength);
Memory.Position := 0;
Write(PByte(TempMemory.Memory), leftOverLength);
end;
end;
// Beware: TStream.CopyFrom copies everything when specifying length = 0.
function TMessageReceiver.Extract: TMemoryStream;
var
rightPosition: Int64;
begin
if Ready then
begin
rightPosition := Memory.Position;
result := TMemoryStream.Create;
WriteLog(IntToStr(ExpectedSize));
if ExpectedSize > 0 then
begin
result.Size := ExpectedSize;
result.Position := 0;
Memory.Position := 0;
result.CopyFrom(Memory, result.Size);
end;
ShiftLeft(rightPosition);
end
else
result := nil;
end;
destructor TMessageReceiver.Destroy;
begin
Memory.Free;
TempMemory.Free;
inherited Destroy;
end;
function TSharedObject.GetClassName: string;
begin
result := self.ClassName;
end;
constructor TCriticalSection.Create;
begin
System.InitCriticalSection(InternalCriticalSection);
end;
function TCriticalSection.TryEnter: Boolean;
begin
result := System.TryEnterCriticalsection(InternalCriticalSection) <> 0;
end;
procedure TCriticalSection.Enter;
begin
System.EnterCriticalsection(InternalCriticalSection);
end;
procedure TCriticalSection.Leave;
begin
System.LeaveCriticalsection(InternalCriticalSection);
end;
destructor TCriticalSection.Destroy;
begin
inherited Destroy;
end;
end.
|
program raspinfo;
{$mode objfpc}{$H+}
uses {$IFDEF UNIX}
cthreads, {$ENDIF}
Classes,
SysUtils,
CustApp,
Process { you can add units after this },
ctypes,
ncurses;
Const
AppVersion = '0.1';
type
TRenderMode = (rmKeyValue, rmText);
TViewKind = (vkClocks, vkConfig, vkVoltage, vkCodecs, vkTemperature, vkBootLoader, vkOthers, vkAbout);
{ TRaspInfo }
TRaspInfo = class(TCustomApplication)
private
Data: TStringList;
ViewKind: TViewKind;
MaxCols, MaxRows: integer;
procedure DumpInfo;
function FormatFreq(const v: string): string;
function GetValue(const Command: string; const param: array of string): string;
procedure LoadBootLoader;
procedure LoadClocks;
procedure LoadCodecs;
procedure LoadConfig;
procedure LoadTemp;
procedure LoadOther;
procedure LoadVolts;
procedure RenderStatusBar;
procedure RenderText(Mode: TRenderMode; VirtualPos: integer; RealPos: integer);
function StripName(const v: string): string;
protected
procedure DoRun; override;
procedure HandleException(Sender: TObject); override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TRaspInfo }
type
functionKey = record
KeyLabel: string;
key: CHType;
Desc: string;
end;
const
FunctionKeys: array [0..7] of functionKey = (
(KeyLabel: 'F2'; Key: KEY_F2; Desc: 'Temperature'),
(KeyLabel: 'F3'; Key: KEY_F3; Desc: 'Clocks'),
(KeyLabel: 'F4'; Key: KEY_F4; Desc: 'Settings'),
(KeyLabel: 'F5'; Key: KEY_F5; Desc: 'Voltages'),
(KeyLabel: 'F6'; Key: KEY_F6; Desc: 'Codecs'),
(KeyLabel: 'F7'; Key: KEY_F6; Desc: 'BootLoader'),
(KeyLabel: 'F8'; Key: KEY_F7; Desc: 'Others'),
(KeyLabel: 'F10'; Key: KEY_F10; Desc: 'Exit'));
const
VC = 'vcgencmd';
const
READ_BYTES = 2048;
function TRaspInfo.GetValue(const Command: string; const param: array of string): string;
var
AProcess: TProcess;
M: TStringStream;
n, BytesRead: integer;
begin
AProcess := TProcess.Create(nil);
AProcess.Executable := Command;
AProcess.Parameters.AddStrings(param);
AProcess.Options := AProcess.Options + [poUsePipes, poStdErrToOutput];
AProcess.ShowWindow := swoHIDE;
AProcess.Execute;
M := TStringStream.Create;
BytesRead := 0;
while AProcess.Running do
begin
// make sure we have room
M.SetSize(BytesRead + READ_BYTES);
// try reading it
n := AProcess.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
begin
Inc(BytesRead, n);
end
else
begin
// no data, wait 100 ms
Sleep(10);
end;
end;
// read last part
repeat
// make sure we have room
M.SetSize(BytesRead + READ_BYTES);
// try reading it
n := AProcess.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0 then
begin
Inc(BytesRead, n);
end;
until n <= 0;
M.SetSize(BytesRead);
try
m.Position := 0;
Result := M.DataString;
except
Result := '';
end;
M.Free;
AProcess.Free;
end;
function TRaspInfo.FormatFreq(const v: string): string;
var
fx: int64;
begin
fx := StrToInt64Def(stripName(v), 0);
Result := Format('%8.2n Mhz', [fx / 1000000]);
end;
function TRaspInfo.StripName(const v: string): string;
var
tmp: string;
begin
tmp := copy(v, pos('=', v) + 1);
Delete(tmp, length(tmp), 1);
Result := tmp;
end;
procedure TRaspInfo.RenderStatusBar;
var
i: integer;
x: smallint;
begin
attron(COLOR_PAIR(2));
mvhline(MaxRows - 1, 0, $20, MaxCols);
x := 0;
for i := 0 to Length(FunctionKeys) - 1 do
begin
attron(COLOR_PAIR(4));
mvaddstr(MaxRows - 1, x, PChar(FunctionKeys[i].KeyLabel));
x := x + Length(FunctionKeys[i].KeyLabel);
attron(COLOR_PAIR(5));
mvaddstr(MaxRows - 1, x, PChar(FunctionKeys[i].Desc));
x := x+ Length(FunctionKeys[i].Desc);
end;
end;
procedure TRaspInfo.RenderText(Mode: TRenderMode; VirtualPos: integer; RealPos: integer);
var
i, row: integer;
MaxWidth: integer;
const
OFFSET = 1;
begin
MaxWidth := 0;
attron(COLOR_PAIR(2));
if Mode = rmKeyValue then
for i := virtualpos to Data.Count - 1 do
if Length(Data.Names[i]) > MaxWidth then
MaxWidth := Length(Data.Names[i]);
for i := virtualpos to Data.Count - 1 do
begin
Row := RealPos + i - VirtualPos;
if (VirtualPos > 0) and (i = virtualpos) then
begin
attron(COLOR_PAIR(3));
mvaddch(row, OFFSET - 1, ACS_UARROW);
end;
if Row > MaxRows - 2 then
begin
if i <> Data.Count - 1 then
begin
attron(COLOR_PAIR(3));
mvaddch(row - 1, OFFSET - 1, ACS_DARROW);
end;
break;
end;
case Mode of
rmKeyValue:
begin
if (Data.Names[I] = '') and (Data.ValueFromIndex[i] = '') then
continue;
attron(COLOR_PAIR(2));
mvprintw(row, OFFSET, PChar(Data.Names[i] + ':'));
attron(COLOR_PAIR(2));
attron(A_BOLD);
mvprintw(row, MaxWidth + OFFSET + 2, PChar(Data.ValueFromIndex[i]));
attroff(A_BOLD);
end;
rmText:
begin
attron(COLOR_PAIR(2));
mvprintw(Row, OFFSET, PChar(Data[i]));
end;
end;
end;
end;
procedure TRaspInfo.LoadBootLoader;
begin
Data.Text := GetValue(VC,['bootloader_config']);
end;
procedure TRaspInfo.LoadConfig;
begin
Data.Text := GetValue(VC,['get_config', 'str']) + GetValue(VC,['get_config', 'int']);
end;
procedure TRaspInfo.LoadClocks;
begin
Data.Clear;
Data.AddPair('ARM cores', formatfreq(GetValue(VC,['measure_clock', 'arm'])));
Data.AddPair('VC4 scaler cores', formatfreq(GetValue(VC,['measure_clock', 'core'])));
Data.AddPair('H264 block', formatfreq(GetValue(VC,['measure_clock', 'H264'])));
Data.AddPair('Image Signal Processor', formatfreq(GetValue(VC,['measure_clock', 'isp'])));
Data.AddPair('3D block', formatfreq(GetValue(VC,['measure_clock', 'v3d'])));
Data.AddPair('UART', formatfreq(GetValue(VC,['measure_clock', 'uart'])));
Data.AddPair('PWM block (analogue audio output)', formatfreq(GetValue(VC,['measure_clock', 'pwm'])));
Data.AddPair('SD card interface', formatfreq(GetValue(VC,['measure_clock', 'emmc'])));
Data.AddPair('Pixel valve', formatfreq(GetValue(VC,['measure_clock', 'pixel'])));
Data.AddPair('Analogue video encoder', formatfreq(GetValue(VC,['measure_clock', 'vec'])));
Data.AddPair('HDMI', formatfreq(GetValue(VC,['measure_clock', 'hdmi'])));
Data.AddPair('Display Peripheral Interface', formatfreq(GetValue(VC,['measure_clock', 'dpi'])));
end;
procedure TRaspInfo.LoadVolts;
begin
Data.Clear;
Data.AddPair('VC4 core voltage', StripName(GetValue(VC,['measure_volts', 'core'])));
Data.AddPair('sdram_c', StripName(GetValue(VC,['measure_volts', 'sdram_c'])));
Data.AddPair('sdram_i', StripName(GetValue(VC,['measure_volts', 'sdram_i'])));
Data.AddPair('sdram_p', StripName(GetValue(VC,['measure_clock', 'sdram_p'])));
end;
procedure TRaspInfo.LoadTemp;
type
bit = 0..1;
TFlag = packed record
case integer of
0: (full: dword);
1: (oneBit: bitpacked array[0..31] of bit);
end;
var
Mask: string;
IntMask: TFlag;
begin
Data.Clear;
Data.AddPair('Core Temperature', StripName(GetValue(VC,['measure_temp'])));
Data.Add('');
Mask := StripName(GetValue(VC,['get_throttled']));
Data.AddPair('Throttled mask', mask);
Data.add('');
Mask := StringReplace(MAsk, '0x', '$', []);
intMask.full := StrToIntdef(Mask, 0);
if intMask.Full = 0 then
begin
Data.Add('No throttling detected');
exit;
end;
if intmask.oneBit[0] = 1 then
Data.add('Under-voltage detected');
if intmask.oneBit[1] = 1 then
Data.add('Arm frequency capped');
if intmask.oneBit[2] = 1 then
Data.add('Currently throttled');
if intmask.oneBit[3] = 1 then
Data.add('Soft temperature limit active');
if intmask.oneBit[16] = 1 then
Data.add('Under-voltage has occurred');
if intmask.oneBit[17] = 1 then
Data.add('Arm frequency capping has occurred');
if intmask.oneBit[18] = 1 then
Data.add('Throttling has occurred');
if intmask.oneBit[19] = 1 then
Data.add('Soft temperature limit has occurred');
end;
function ValueAsBool(const s: string): boolean; inline;
begin
Result := s = '1';
end;
procedure TRaspInfo.LoadOther;
type
TFlag = bitpacked record
case integer of
0:(
Revision : 0..15;
PType : 0..255;
Processor : 0..15;
Manifacturer : 0..15;
MemSize : 0..7;
StyleRev : 0..1;
u2 : 0..1;
Warranty : 0..1;
u1 : 0..7;
OtpRead : 0..1;
OtpProgram : 0..1;
);
1:(full: dword);
end;
var
rev:string;
intmask : TFlag;
begin
Data.Clear;
Data.AddPair('Host Name', StripName(GetValue('uname' ,['-n'])));
Data.AddPair('Kernel version', StripName(GetValue('uname' ,['-r'])));
Data.add('');
Data.AddPair('Screen info', StripName(GetValue(VC,['get_lcd_info'])));
Data.AddPair('GPU Memory', StripName(GetValue(VC,['get_mem', 'gpu'])));
Data.AddPair('Camera enabled', BoolToStr(ValueAsBool(StripName(GetValue(VC,['get_camera'])))));
Data.AddPair('HDMI 1 powered', BoolToStr(ValueAsBool(StripName(GetValue(VC,['display_power', '-1','2'])))));
Data.AddPair('HDMI 2 powered', BoolToStr(ValueAsBool(StripName(GetValue(VC,['display_power', '-1','7'])))));
rev := StripName(GetValue('bash' ,['-c','vcgencmd otp_dump | grep 30:']));
rev := StringReplace(rev, '30:', '$00', []);
intMask.full := leton( StrToIntdef(rev, 0));
case intmask.PType of
$0: rev := 'A';
$1: rev := 'B';
$2: rev := 'A+';
$3: rev := 'B+';
$4: rev := '2B';
$5: rev := 'Alpha (early prototype)';
$6: rev := 'CM1';
$8: rev := '3B';
$9: rev := 'Zero';
$a: rev := 'CM3';
$c: rev := 'Zero W';
$d: rev := '3B+';
$e: rev := '3A+';
$f: rev := 'Internal use only';
$10: rev := 'CM3+';
$11: rev := '4B';
$13: rev := '400';
$14: rev := 'CM4';
else rev := 'Unknown';
end;
Data.AddPair('Type',rev);
Data.AddPair('Revision', '1.'+inttostr(intmask.Revision));
case intmask.memsize of
0 : rev:= '256MB';
1 : rev:= '512MB';
2 : rev:= '1GB';
3 : rev:= '2GB';
4 : rev:= '4GB';
5 : rev:= '8GB';
else rev := 'Unknown';
end;
Data.AddPair('Memory',rev);
case intmask.Processor of
0 : rev:= 'BCM2835';
1 : rev:= 'BCM2836';
2 : rev:= 'BCM2837';
3 : rev:= 'BCM2711';
else rev := 'Unknown';
end;
Data.AddPair('Processor', rev);
rev := StripName(GetValue('bash' ,['-c','vcgencmd otp_dump | grep 28:']));
rev := StringReplace(rev, '28:', '', []);
Data.AddPair('Serial',rev);
end;
procedure TRaspInfo.LoadCodecs;
begin
Data.Clear;
Data.add(GetValue(VC,['codec_enabled', 'AGIF']));
Data.add(GetValue(VC,['codec_enabled', 'FLAC']));
Data.add(GetValue(VC,['codec_enabled', 'H263']));
Data.add(GetValue(VC,['codec_enabled', 'H264']));
Data.add(GetValue(VC,['codec_enabled', 'MJPA']));
Data.add(GetValue(VC,['codec_enabled', 'MJPB']));
Data.add(GetValue(VC,['codec_enabled', 'MJPG']));
Data.add(GetValue(VC,['codec_enabled', 'MPG2']));
Data.add(GetValue(VC,['codec_enabled', 'MPG4']));
Data.add(GetValue(VC,['codec_enabled', 'MVC0']));
Data.add(GetValue(VC,['codec_enabled', 'PCM']));
Data.add(GetValue(VC,['codec_enabled', 'THRA']));
Data.add(GetValue(VC,['codec_enabled', 'VORB']));
Data.add(GetValue(VC,['codec_enabled', 'VP6']));
Data.add(GetValue(VC,['codec_enabled', 'VP8']));
Data.add(GetValue(VC,['codec_enabled', 'WMV9']));
Data.add(GetValue(VC,['codec_enabled', 'WVC1']));
end;
function setlocale(category: cint; locale: PChar): PChar; cdecl; external 'c' Name 'setlocale';
procedure TRaspInfo.DumpInfo;
var
f: Text;
tmpS: string;
begin
Data := TStringList.Create;
TmpS := GetOptionValue('d','dump');
if trim(tmps) ='' then
f := StdOut
else
begin
AssignFile(f, tmps);
Rewrite(f);
end;
LoadTemp;
WriteLn(f,'[Temperature]');
WriteLn(f,Data.Text);
LoadClocks;
WriteLn(f,'[Clocks]');
WriteLn(f,Data.Text);
LoadVolts;
WriteLn(f,'[Voltage]');
WriteLn(f,Data.Text);
LoadConfig;
WriteLn(f,'[Configuration]');
WriteLn(f,Data.Text);
LoadBootLoader;
WriteLn(f,'[Bootloader]');
WriteLn(f,Data.Text);
LoadOther;
WriteLn(f,'[Other]');
WriteLn(f,Data.Text);
if tmpS <> '' then
CloseFile(f);
Data.free;
end;
procedure TRaspInfo.DoRun;
var
ErrorMsg: string;
var
ch: longint = 0;
pad: PWINDOW;
tmpS:string;
my_bg: smallint = COLOR_BLACK;
VirtualPos: integer;
Ok: integer;
event: MEVENT;
tmp, i: integer;
Refresh: longint;
term: String;
begin
Refresh := 10;
// quick check parameters
ErrorMsg := CheckOptions('hu:d::', 'help update: dump::', true);
if ErrorMsg <> '' then
begin
Writeln(ErrorMsg);
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('d', 'dump') then
begin
DumpInfo;
Terminate;
exit;
end;
if HasOption('u', 'update') then
begin
TmpS := GetOptionValue('u','update');
if not TryStrToInt(tmpS, Refresh) then
begin
WriteLn('Invalid refresh parameter');
Terminate;
exit;
end
end;
{ add your program here }
Data := TStringList.Create;
setlocale(1, 'UTF-8');
initscr();
noecho();
keypad(stdscr, True);
curs_set(0);
Clear();
halfdelay(refresh);
mousemask($ffffffff, nil);
if has_colors() then
begin
start_color();
if (use_default_colors() = OK) then
my_bg := -1
else
my_bg := COLOR_BLACK;
init_pair(1, COLOR_YELLOW, my_bg);
init_pair(2, COLOR_WHITE, my_bg);
init_pair(3, my_bg, COLOR_WHITE);
init_pair(4, COLOR_WHITE, my_bg);
init_pair(5, COLOR_BLACK, COLOR_CYAN);
end;
term := GetEnvironmentVariable('TERM');
// fix for xterm terminal emulation
if term.StartsWith('xterm') or term.Equals('vt220') then
begin
ch:=define_key(#27'[12~', KEY_F2);
ch:=define_key(#27'[13~', KEY_F3);
ch:=define_key(#27'[14~', KEY_F4);
end;
ch := Key_F2;
try
while ch <> KEY_F10 do
begin
getmaxyx(stdscr, MaxRows, MaxCols);
Clear();
RenderStatusBar;
attron(COLOR_PAIR(3));
mvhline(0, 0, $20, MaxCols);
mvprintw(0, 0, 'Raspinfo');
if ch = KEY_MOUSE then
begin
ok := getmouse(@Event);
if boolean(event.bstate and BUTTON1_CLICKED) then
if (event.y = MaxRows - 1) then
begin
tmp := 0;
for i := 0 to length(FunctionKeys) - 1 do
begin
tmp := tmp + Length(FunctionKeys[i].KeyLabel) + Length(FunctionKeys[i].Desc);
if event.x < tmp then
begin
ch := FunctionKeys[i].Key;
doupdate;
break;
end;
end;
end;
end;
case ch of
KEY_F2:
begin
ViewKind := vkTemperature;
VirtualPos := 0;
end;
KEY_F3:
begin
ViewKind := vkClocks;
virtualPos := 0;
end;
KEY_F4:
begin
ViewKind := vkConfig;
LoadConfig;
VirtualPos := 0;
end;
KEY_F5:
begin
ViewKind := vkVoltage;
VirtualPos := 0;
end;
KEY_F6:
begin
ViewKind := vkCodecs;
LoadCodecs;
VirtualPos := 0;
end;
KEY_F7:
begin
ViewKind := vkBootloader;
LoadBootLoader;
VirtualPos := 0;
end;
KEY_F8:
begin
ViewKind := vkOthers;
LoadOther;
VirtualPos := 0;
end;
KEY_F10:
begin
Terminate;
exit;
end;
KEY_DOWN: if VirtualPos < (Data.Count - (MaxRows - 2)) then
Inc(VirtualPos);
KEY_UP: if VirtualPos > 0 then
Dec(VirtualPos);
end;
case ViewKind of
vkClocks:
begin
LoadClocks;
RenderText(rmKeyValue, VirtualPos, 2);
halfdelay(Refresh);
end;
vkVoltage:
begin
LoadVolts;
RenderText(rmKeyValue, VirtualPos, 2);
halfdelay(Refresh);
end;
vkCodecs, vkConfig, vkOthers, vkbootloader:
begin
RenderText(rmKeyValue, VirtualPos, 2);
cbreak;
end;
vkTemperature:
begin
LoadTemp;
RenderText(rmKeyValue, VirtualPos, 2);
halfdelay(Refresh);
end;
end;
attron(COLOR_PAIR(1));
doupdate();
ch := getch();
end;
finally
endwin();
Data.Free;
end;
// stop program loop
Terminate;
end;
procedure TRaspInfo.HandleException(Sender: TObject);
var
I: Integer;
Frames: PPointer;
Report: string;
e: exception;
begin
Report := 'Program exception! ' + LineEnding +
'Stacktrace:' + LineEnding + LineEnding;
e:= Exception(ExceptObject);
if E <> nil then begin
Report := Report + 'Exception class: ' + E.ClassName + LineEnding +
'Message: ' + E.Message + LineEnding;
end;
Report := Report + BackTraceStrFunc(ExceptAddr);
Frames := ExceptFrames;
for I := 0 to ExceptFrameCount - 1 do
Report := Report + LineEnding + BackTraceStrFunc(Frames[I]);
writeln(stderr, report);
end;
constructor TRaspInfo.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TRaspInfo.Destroy;
begin
inherited Destroy;
end;
procedure TRaspInfo.WriteHelp;
begin
{ add your help code here }
writeln('raspinfo ' + AppVersion);
writeln('This is an interactive application to show some info about your Raspberry Pi');
writeln('Usage: raspinfo [option]');
writeln;
writeln('-u <delay>, --update=<delay>' + sLineBreak +
' ' + ' Delay between updates, in tenths of seconds (default 10, i.e. one second');
writeln('-d [filename], --dump[=filename]' + sLineBreak +
' ' + 'Dump all information to stdout or to a specified file');
end;
var
Application: TRaspInfo;
begin
Application := TRaspInfo.Create(nil);
Application.Title := 'RaspInfo';
Application.Run;
Application.Free;
end.
|
unit uWebServer;
interface
uses
SysUtils, Classes,
IdBaseComponent, IdComponent, IdTCPServer, IdHTTPServer,
uTools,
uCallbackProcessor;
type
TWebServer = class
private
fServer: TIdHTTPServer;
fProcessor: ICallbackProcessor;
procedure CommandGet(AThread: TIdPeerThread; RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
procedure OnGET(RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
procedure OnPOST(RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
public
Constructor Create(port: Integer; processor: ICallbackProcessor);
Destructor Destroy; override;
Procedure Start;
Procedure Stop;
end;
implementation
{ TWebServer }
procedure TWebServer.CommandGet(AThread: TIdPeerThread; RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
begin
if RequestInfo.Command = 'GET' then
onGET(RequestInfo, ResponseInfo)
else if RequestInfo.Command = 'POST' then
onPOST(RequestInfo, ResponseInfo);
end;
constructor TWebServer.Create(port: Integer; processor: ICallbackProcessor);
begin
fProcessor := processor;
fServer := TIdHTTPServer.Create(nil);
fServer.DefaultPort := port;
fServer.OnCommandGet := CommandGet;
fServer.ServerSoftware := 'UnistreamSimpleServer';
end;
destructor TWebServer.Destroy;
begin
Stop;
fServer.Free;
inherited;
end;
procedure TWebServer.OnGET(RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
var
fileName: String;
begin
// Process HTTP GET request
if RequestInfo.Document <> '/' then
begin
fileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'data\sample.pdf';
ResponseInfo.ContentType := 'application/pdf';
ResponseInfo.ContentStream := TFileStream.Create(fileName, fmOpenRead);
ResponseInfo.ContentLength := ResponseInfo.ContentStream.Size;
ResponseInfo.WriteHeader;
ResponseInfo.WriteContent;
ResponseInfo.ContentStream.Free;
ResponseInfo.ContentStream := nil;
exit;
end;
ResponseInfo.ContentType := 'text/html; charset=windows-1251';
ResponseInfo.ContentText := '<html>Simple callback processor</html>';
end;
procedure TWebServer.OnPOST(RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo);
var
path: TStringList;
request: String;
response: String;
method : String;
begin
path := SplitString(RequestInfo.Document, ['\', '/']);
path.Delimiter := '/';
try
method := '';
if path.Count > 0 then
method := path[path.Count-1];
request := UTF8Decode(RequestInfo.UnparsedParams);
ResponseInfo.ContentType := 'application/json';
try
response := fProcessor.Process(request, method);
ResponseInfo.ContentText := UTF8Encode(response);
except
on E: Exception do
begin
ResponseInfo.ContentText := UTF8Encode(e.Message);
ResponseInfo.ResponseNo := 500;
end;
end;
finally
path.Free;
end;
end;
procedure TWebServer.Start;
begin
fServer.Active := True;
end;
procedure TWebServer.Stop;
begin
fServer.Active := False;
end;
end.
|
unit OptionsEditorToolBar;
interface
uses
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, BCControls.CheckBox,
BCCommon.OptionsContainer, BCFrames.OptionsFrame;
type
TOptionsEditorToolbarFrame = class(TOptionsFrame)
Panel: TPanel;
StandardCheckBox: TBCCheckBox;
PrintCheckBox: TBCCheckBox;
ExecuteCheckBox: TBCCheckBox;
IndentCheckBox: TBCCheckBox;
SortCheckBox: TBCCheckBox;
CaseCheckBox: TBCCheckBox;
DBMSCheckBox: TBCCheckBox;
TransactionCheckBox: TBCCheckBox;
ToolsCheckBox: TBCCheckBox;
ModeCheckBox: TBCCheckBox;
SearchCheckBox: TBCCheckBox;
CommandCheckBox: TBCCheckBox;
ExplainPlanCheckBox: TBCCheckBox;
private
{ Private declarations }
public
{ Public declarations }
destructor Destroy; override;
procedure GetData; override;
procedure PutData; override;
end;
function OptionsEditorToolbarFrame(AOwner: TComponent): TOptionsEditorToolbarFrame;
implementation
{$R *.dfm}
var
FOptionsEditorToolbarFrame: TOptionsEditorToolbarFrame;
function OptionsEditorToolbarFrame(AOwner: TComponent): TOptionsEditorToolbarFrame;
begin
if not Assigned(FOptionsEditorToolbarFrame) then
FOptionsEditorToolbarFrame := TOptionsEditorToolbarFrame.Create(AOwner);
Result := FOptionsEditorToolbarFrame;
end;
destructor TOptionsEditorToolbarFrame.Destroy;
begin
inherited;
FOptionsEditorToolbarFrame := nil;
end;
procedure TOptionsEditorToolbarFrame.PutData;
begin
OptionsContainer.ToolBarExecute := ExecuteCheckBox.Checked;
OptionsContainer.ToolBarTransaction := TransactionCheckBox.Checked;
OptionsContainer.ToolBarDBMS := DBMSCheckBox.Checked;
OptionsContainer.ToolBarExplainPlan := ExplainPlanCheckBox.Checked;
OptionsContainer.ToolBarStandard := StandardCheckBox.Checked;
OptionsContainer.ToolBarPrint := PrintCheckBox.Checked;
OptionsContainer.ToolBarIndent := IndentCheckBox.Checked;
OptionsContainer.ToolBarSort := SortCheckBox.Checked;
OptionsContainer.ToolBarCase := CaseCheckBox.Checked;
OptionsContainer.ToolBarCommand := CommandCheckBox.Checked;
OptionsContainer.ToolBarSearch := SearchCheckBox.Checked;
OptionsContainer.ToolBarMode := ModeCheckBox.Checked;
OptionsContainer.ToolBarTools := ToolsCheckBox.Checked;
end;
procedure TOptionsEditorToolbarFrame.GetData;
begin
ExecuteCheckBox.Checked := OptionsContainer.ToolBarExecute;
TransactionCheckBox.Checked := OptionsContainer.ToolBarTransaction;
DBMSCheckBox.Checked := OptionsContainer.ToolBarDBMS;
ExplainPlanCheckBox.Checked := OptionsContainer.ToolBarExplainPlan;
StandardCheckBox.Checked := OptionsContainer.ToolBarStandard;
PrintCheckBox.Checked := OptionsContainer.ToolBarPrint;
IndentCheckBox.Checked := OptionsContainer.ToolBarIndent;
SortCheckBox.Checked := OptionsContainer.ToolBarSort;
CaseCheckBox.Checked := OptionsContainer.ToolBarCase;
CommandCheckBox.Checked := OptionsContainer.ToolBarCommand;
SearchCheckBox.Checked := OptionsContainer.ToolBarSearch;
ModeCheckBox.Checked := OptionsContainer.ToolBarMode;
ToolsCheckBox.Checked := OptionsContainer.ToolBarTools;
end;
end.
|
unit sCommonData;
{$I sDefs.inc}
interface
uses
windows, Graphics, Classes, Controls, SysUtils, StdCtrls, Dialogs, sSkinManager, acntUtils,
Forms, Messages, sConst, extctrls, IniFiles, sLabel;
type
TsCommonData = class(TPersistent)
{$IFNDEF NOTFORHELP}
private
FSkinSection: TsSkinSection;
FCustomFont: boolean;
FCustomColor: boolean;
FHUEOffset: integer;
FSaturation: integer;
FUpdateCount: Integer;
procedure SetSkinSection(const Value: string);
function GetUpdating: boolean;
procedure SetUpdating(const Value: boolean);
procedure SetCustomColor(const Value: boolean);
procedure SetCustomFont(const Value: boolean);
function GetSkinManager: TsSkinManager;
procedure SetSkinManager(const Value: TsSkinManager);
procedure SetHUEOffset(const Value: integer);
procedure SetSaturation(const Value: integer);
public
GlowID : integer;
FUpdating : boolean;
FSkinManager : TsSkinManager;
BorderIndex : integer;
SkinIndex : integer;
Texture : integer;
HotTexture : integer;
GraphControl : pointer;
UrgentPainting : boolean;
BGChanged : boolean;
HalfVisible : boolean;
FOwnerControl : TControl;
FOwnerObject : TObject;
FCacheBmp : TBitmap;
FRegion : hrgn;
COC : integer;
FFocused : boolean;
FMouseAbove: Boolean;
CtrlSkinState : word;
BGType : word;
PrintDC : hdc;
InvalidRectH : TRect;
InvalidRectV : TRect;
property Updating : boolean read GetUpdating write SetUpdating default False;
constructor Create(AOwner : TObject; CreateCacheBmp : boolean);
destructor Destroy; override;
procedure UpdateIndexes;
procedure Loaded;
function RepaintIfMoved : boolean;
function ManagerStored : boolean;
{$ENDIF} // NOTFORHELP
procedure BeginUpdate;
procedure EndUpdate(Repaint : boolean = False);
procedure Invalidate;
function Skinned(CheckSkinActive : boolean = False) : boolean;
property HUEOffset : integer read FHUEOffset write SetHUEOffset default 0;
property Saturation : integer read FSaturation write SetSaturation default 0;
published
property CustomColor : boolean read FCustomColor write SetCustomColor default False;
property CustomFont : boolean read FCustomFont write SetCustomFont default False;
property SkinManager : TsSkinManager read GetSkinManager write SetSkinManager stored ManagerStored;
property SkinSection : TsSkinSection read FSkinSection write SetSkinSection;
end;
TsCtrlSkinData = class(TsCommonData)
published
property HUEOffset;
property Saturation;
end;
TsBoundLabel = class(TPersistent)
{$IFNDEF NOTFORHELP}
private
FMaxWidth: integer;
FText: acString;
FLayout: TsCaptionLayout;
FFont: TFont;
FIndent: integer;
procedure SetActive(const Value: boolean);
procedure SetLayout(const Value: TsCaptionLayout);
procedure SetMaxWidth(const Value: integer);
procedure SetText(const Value: acString);
procedure SetFont(const Value: TFont);
procedure SetIndent(const Value: integer);
function GetFont: TFont;
procedure UpdateAlignment;
function GetUseSkin: boolean;
procedure SetUseSkin(const Value: boolean);
public
FActive: boolean;
FTheLabel : TsEditLabel;
FCommonData : TsCommonData;
procedure AlignLabel;
constructor Create(AOwner : TObject; CommonData : TsCommonData);
destructor Destroy; override;
published
{$ENDIF} // NOTFORHELP
property Active : boolean read FActive write SetActive default False;
property Caption : acString read FText write SetText;
property Indent : integer read FIndent write SetIndent;
property Font : TFont read GetFont write SetFont;
property Layout : TsCaptionLayout read FLayout write SetLayout;
property MaxWidth: integer read FMaxWidth write SetMaxWidth;
property UseSkinColor : boolean read GetUseSkin write SetUseSkin;
end;
{$IFNDEF NOTFORHELP}
var
C1, C2 : TsColor;
RestrictDrawing : boolean = False;
function IsCached(SkinData : TsCommonData) : boolean;
function IsCacheRequired(SkinData : TsCommonData) : boolean;
procedure InitBGInfo(const SkinData : TsCommonData; const PBGInfo : PacBGInfo; const State : integer; Handle : THandle = 0);
function GetBGColor(const SkinData : TsCommonData; const State : integer; Handle : THandle = 0) : TColor;
function GetFontIndex(const Ctrl : TControl; const DefSkinIndex : integer; const SkinManager : TsSkinManager) : integer;
procedure ShowGlowingIfNeeded(const SkinData : TsCommonData; Clicked : boolean = False; CtrlHandle : HWND = 0);
function ParentTextured(const SkinData : TsCommonData) : boolean;
procedure InitCacheBmp(SkinData : TsCommonData);
function SkinBorderMaxWidth(SkinData : TsCommonData) : integer;
procedure UpdateData(SkinData : TsCommonData);
procedure UpdateSkinState(const SkinData : TsCommonData; UpdateChildren : boolean = True);
procedure AlignShadow(SkinData : TsCommonData);
function ControlIsActive(SkinData : TsCommonData): boolean;
function BgIsTransparent(CommonData : TsCommonData) : boolean;
procedure CopyWinControlCache(Control : TWinControl; SkinData : TsCommonData; SrcRect, DstRect : TRect; DstDC : HDC; UpdateCorners : boolean; OffsetX : integer = 0; OffsetY : integer = 0); overload;
procedure CopyHwndCache(hwnd : THandle; SkinData : TsCommonData; SrcRect, DstRect : TRect; DstDC : HDC; UpdateCorners : boolean; OffsetX : integer = 0; OffsetY : integer = 0); overload;
function CommonMessage(var Message: TMessage; SkinData : TsCommonData) : boolean;
function CommonWndProc(var Message: TMessage; SkinData : TsCommonData) : boolean;
{$ENDIF} // NOTFORHELP
function GetParentCache(SkinData : TsCommonData) : TCacheInfo;
function GetParentCacheHwnd(cHwnd : hwnd) : TCacheInfo;
implementation
uses sStyleSimply, sSkinProps, sMaskData, sMessages, sButton, sBitBtn, Math, ComCtrls, acGlow,
{$IFNDEF ALITE} sPageControl, sSplitter, sCustomComboEdit, {$ENDIF} sVclUtils{$IFDEF CHECKXP}, UxTheme, Themes{$ENDIF},
sGraphUtils, sAlphaGraph, sSkinProvider, sSpeedButton, sSkinMenus;
{$IFDEF RUNIDEONLY}
var
sTerminated : boolean = False;
{$ENDIF}
function IsCached(SkinData : TsCommonData) : boolean;
begin
Result := InAnimationProcess or (SkinData.CtrlSkinState and ACS_FAST <> ACS_FAST) or ControlIsActive(SkinData);
end;
procedure UpdateCtrlColors(SkinData : TsCommonData; Redraw : boolean);
var
C : TColor;
begin
with SkinData do if Skinned and (COC in sEditCtrls) then begin
if not CustomColor then begin
C := ChangeSaturation(ChangeHUE(HUEOffset, SkinManager.gd[SkinIndex].Color), Saturation);
if TsHackedControl(FOwnerControl).Color <> C then TsHackedControl(FOwnerControl).Color := C;
end;
if not CustomFont then begin
C := ChangeSaturation(ChangeHUE(HUEOffset, SkinManager.gd[SkinIndex].Props[0].FontColor.Color), Saturation);
if TsHackedControl(FOwnerControl).Font.Color <> C then TsHackedControl(FOwnerControl).Font.Color := C;
end;
if Redraw then SkinData.Invalidate;
end;
end;
procedure InitBGType(SkinData : TsCommonData);
begin
SkinData.BGType := 0;
if (SkinData.SkinManager <> nil) and (SkinData.SkinIndex > -1) then begin
if (SkinData.SkinManager.gd[SkinData.SkinIndex].ImagePercent <> 0) then SkinData.BGType := SkinData.BGType or BGT_TEXTURE;
if (SkinData.SkinManager.gd[SkinData.SkinIndex].GradientPercent <> 0) and (Length(SkinData.SkinManager.gd[SkinData.SkinIndex].GradientArray) > 0) then begin
case SkinData.SkinManager.gd[SkinData.SkinIndex].GradientArray[0].Mode1 of
0 : SkinData.BGType := SkinData.BGType or BGT_GRADIENTVERT;
1 : SkinData.BGType := SkinData.BGType or BGT_GRADIENTHORZ;
2 : SkinData.BGType := SkinData.BGType or BGT_GRADIENTHORZ or BGT_GRADIENTVERT;
end;
end;
{
if (SkinData.Texture > -1) and (SkinData.SkinManager.ma[SkinData.Texture].DrawMode > -1) then begin
try
case acFillModes[SkinData.SkinManager.ma[SkinData.Texture].DrawMode] of
fmStretchHorz, fmTiledHorz, fmDiscHorTop : SkinData.BGType := SkinData.BGType or BGT_TEXTURETOP;
fmStretchVert, fmTiledVert, fmDiscVertLeft : SkinData.BGType := SkinData.BGType or BGT_TEXTURELEFT;
fmTileVertRight, fmDiscVertRight, fmStretchVertRight : SkinData.BGType := SkinData.BGType or BGT_TEXTURERIGHT;
fmTileHorBtm, fmDiscHorBottom, fmStretchHorBtm : SkinData.BGType := SkinData.BGType or BGT_TEXTUREBOTTOM;
end;
except
end;
end;
}
end
end;
function IsCacheRequired(SkinData : TsCommonData) : boolean; // Used for non-active controls only, active controls have cache always
begin
Result := True;
if (SkinData.SkinManager <> nil) and (SkinData.SkinIndex > -1) then begin
with SkinData.SkinManager.gd[SkinData.SkinIndex] do begin
if (SkinData.BorderIndex > -1) // Border Is Too Big
and ((SkinData.SkinManager.ma[SkinData.BorderIndex].WL + SkinData.SkinManager.ma[SkinData.BorderIndex].WR > 20) or
(SkinData.SkinManager.ma[SkinData.BorderIndex].WT + SkinData.SkinManager.ma[SkinData.BorderIndex].WB > 20)) then Exit;
if (Transparency = 100) then begin
if Assigned(SkinData.FOwnerControl) and Assigned(SkinData.FOwnerControl.Parent){ and SkinData.Skinned} then begin
Result := SendAMessage(SkinData.FOwnerControl.Parent, AC_GETSKINSTATE) and ACS_FAST <> ACS_FAST;
if Result then Exit;
end
else Exit;
end
else if (Transparency <> 0) then Exit;
if (SkinData.SkinManager.gd[SkinData.SkinIndex].ImagePercent <> 0) then Exit;
if (SkinData.SkinManager.gd[SkinData.SkinIndex].GradientPercent <> 0) then Exit;
Result := False;
end;
end
else Result := False;
end;
procedure InitBGInfo(const SkinData : TsCommonData; const PBGInfo : PacBGInfo; const State : integer; Handle : THandle = 0);
var
iTransparency, iGradient, iTexture : integer;
WndRect : TRect;
WndPos : TPoint;
Parent : TWinControl;
begin
Parent := nil;
if SkinData.Skinned and not SkinData.CustomColor then begin
if State = 0 then begin
iTransparency := Skindata.SkinManager.gd[SkinData.SkinIndex].Transparency;
iGradient := Skindata.SkinManager.gd[SkinData.SkinIndex].GradientPercent;
iTexture := Skindata.SkinManager.gd[SkinData.SkinIndex].ImagePercent;
end
else begin
iTransparency := Skindata.SkinManager.gd[SkinData.SkinIndex].HotTransparency;
iGradient := Skindata.SkinManager.gd[SkinData.SkinIndex].HotGradientPercent;
iTexture := Skindata.SkinManager.gd[SkinData.SkinIndex].HotImagePercent;
end;
case iTransparency of
0 : begin
if (iGradient > 0) or (iTexture > 0) then begin
PBGInfo^.Color := SkinData.SkinManager.GetGlobalColor; // v6.58
if SkinData.FCacheBmp = nil then begin
PBGInfo^.Color := clFuchsia; // Debug
PBGInfo^.BgType := btFill;
Exit;
end;
PBGInfo^.BgType := btCache;
if PBGInfo^.PleaseDraw then begin
BitBlt(PBGInfo^.DrawDC, PBGInfo^.R.Left, PBGInfo^.R.Top, WidthOf(PBGInfo^.R), HeightOf(PBGInfo^.R),
SkinData.FCacheBmp.Canvas.Handle, PBGInfo^.Offset.X, PBGInfo^.Offset.Y, SRCCOPY);
end
else begin
PBGInfo^.Bmp := SkinData.FCacheBmp;
PBGInfo^.Offset := Point(0, 0);
end;
end
else begin
PBGInfo^.BgType := btFill;
PBGInfo^.Bmp := SkinData.FCacheBmp;
PBGInfo^.Color := GetBGColor(SkinData, State);
if PBGInfo^.PleaseDraw then FillDC(PBGInfo^.DrawDC, PBGInfo^.R, PBGInfo^.Color);
end
end;
100 : begin
if (SkinData.CtrlSkinState and ACS_FAST <> ACS_FAST) and (SkinData.FCacheBmp <> nil) and not (SkinData.BGChanged) then begin
PBGInfo^.BgType := btCache;
if PBGInfo^.PleaseDraw then begin
BitBlt(PBGInfo^.DrawDC, PBGInfo^.R.Left, PBGInfo^.R.Top, WidthOf(PBGInfo^.R), HeightOf(PBGInfo^.R),
SkinData.FCacheBmp.Canvas.Handle, PBGInfo^.Offset.X, PBGInfo^.Offset.Y, SRCCOPY);
end
else begin
PBGInfo^.Bmp := SkinData.FCacheBmp;
PBGInfo^.Offset := Point(0, 0);
end;
Exit;
end
else
{
if SkinData.SkinManager.IsValidImgIndex(SkinData.BorderIndex) // Border Is Too Big
and ((SkinData.SkinManager.ma[SkinData.BorderIndex].WL + SkinData.SkinManager.ma[SkinData.BorderIndex].WR > 24) or (SkinData.SkinManager.ma[SkinData.BorderIndex].WT + SkinData.SkinManager.ma[SkinData.BorderIndex].WB > 24)) then begin
if SkinData.FCacheBmp <> nil then begin
PBGInfo^.BgType := btCache;
if PBGInfo^.PleaseDraw then begin
BitBlt(PBGInfo^.DrawDC, PBGInfo^.R.Left, PBGInfo^.R.Top, WidthOf(PBGInfo^.R), HeightOf(PBGInfo^.R),
SkinData.FCacheBmp.Canvas.Handle, PBGInfo^.Offset.X, PBGInfo^.Offset.Y, SRCCOPY);
end
else begin
PBGInfo^.Bmp := SkinData.FCacheBmp;
PBGInfo^.Offset := Point(0, 0);
end;
end
else begin
PBGInfo^.BgType := btFill;
if (SkinData.FOwnerControl <> nil) and (SkinData.FOwnerControl.Parent <> nil)
then PBGInfo^.Color := GetControlColor(SkinData.FOwnerControl.Parent)
else PBGInfo^.Color := DefaultManager.GetGlobalColor
end;
Exit;
end;
}
if (SkinData.FOwnerControl <> nil) then begin
Parent := SkinData.FOwnerControl.Parent;
WndPos := Point(SkinData.FOwnerControl.Left, SkinData.FOwnerControl.Top);
end
else if (SkinData.FOwnerObject is TsSkinProvider) then begin
if TsSkinProvider(SkinData.FOwnerObject).Form <> nil then begin
Parent := TsSkinProvider(SkinData.FOwnerObject).Form.Parent;
WndPos := Point(TsSkinProvider(SkinData.FOwnerObject).Form.Left, TsSkinProvider(SkinData.FOwnerObject).Form.Top);
end;
end
else Parent := nil;
if (Parent <> nil) then begin
GetBGInfo(PBGInfo, Parent, PBGInfo^.PleaseDraw);
if PBGInfo^.BgType = btCache then begin
inc(PBGInfo^.Offset.X, WndPos.X);
inc(PBGInfo^.Offset.Y, WndPos.Y);
end;
end
else if Handle <> 0 then begin
GetBGInfo(PBGInfo, GetParent(Handle));
if PBGInfo^.BgType = btCache then begin
GetWindowRect(Handle, WndRect);
WndPos := Point(WndRect.Left, WndRect.Top);
ScreenToClient(GetParent(Handle), WndPos);
inc(PBGInfo^.Offset.X, WndPos.X);
inc(PBGInfo^.Offset.Y, WndPos.Y);
end;
end
else begin
PBGInfo^.BgType := btFill;
PBGInfo^.Color := DefaultManager.GetGlobalColor
end;
end
else begin
if SkinData.FCacheBmp = nil then begin
PBGInfo^.Color := clFuchsia; // Debug
PBGInfo^.BgType := btFill;
Exit;
end;
PBGInfo^.BgType := btCache;
if PBGInfo^.PleaseDraw then begin
BitBlt(PBGInfo^.DrawDC, PBGInfo^.R.Left, PBGInfo^.R.Top, WidthOf(PBGInfo^.R), HeightOf(PBGInfo^.R), SkinData.FCacheBmp.Canvas.Handle, PBGInfo^.Offset.X, PBGInfo^.Offset.Y, SRCCOPY);
end
else begin
PBGInfo^.Bmp := SkinData.FCacheBmp;
PBGInfo^.Offset := Point(0, 0);
end;
end;
end;
end
else begin
PBGInfo^.BgType := btFill;
if SkinData.FOwnerControl <> nil then PBGInfo^.Color := TsHackedControl(SkinData.FOwnerControl).Color else begin
if (SkinData.FOwnerObject <> nil) and (SkinData.FOwnerObject is TsSkinProvider) then PBGInfo^.Color := TsSkinProvider(SkinData.FOwnerObject).Form.Color;
end;
end;
end;
function GetBGColor(const SkinData : TsCommonData; const State : integer; Handle : THandle = 0) : TColor;
var
i, C : integer;
Hot : boolean;
function StdColor : TColor;
begin
if SkinData.FOwnerControl <> nil
then Result := TsHackedControl(SkinData.FOwnerControl).Color
else if SkinData.FOwnerObject is TsSkinProvider
then Result := TsSkinProvider(SkinData.FOwnerObject).Form.Color
else Result := clBtnFace;
end;
begin
if SkinData.Skinned then begin
Hot := (State > 0) and (SkinData.SkinManager.gd[SkinData.SkinIndex].States > 1);
i := SkinData.SkinManager.gd[SkinData.SkinIndex].Props[integer(Hot)].Transparency;
c := SkinData.SkinManager.gd[SkinData.SkinIndex].Props[integer(Hot)].Color;
case i of
0 : if SkinData.Skinned and not SkinData.CustomColor then Result := C else Result := StdColor;
100 : begin
if SkinData.FOwnerControl <> nil
then Result := GetControlColor(SkinData.FOwnerControl.Parent)
else if Handle <> 0 then Result := GetControlColor(GetParent(Handle)) else Result := clBtnFace;
end
else begin
if SkinData.FOwnerControl <> nil
then Result := MixColors(c, GetControlColor(SkinData.FOwnerControl.Parent), i / 100)
else if Handle <> 0 then Result := MixColors(c, GetControlColor(GetParent(Handle)), i / 100) else Result := clBtnFace;
end;
end
end
else Result := StdColor;
end;
function GetFontIndex(const Ctrl : TControl; const DefSkinIndex : integer; const SkinManager : TsSkinManager) : integer;
var
si : TacSectionInfo;
begin
Result := DefSkinIndex;
if Ctrl = nil then Exit;
si.SkinIndex := -1;
SendMessage(Ctrl.Parent.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETSKININDEX), integer(@si));
if si.SkinIndex >= 0 then begin
if (SkinManager.gd[si.SkinIndex].Transparency > 50) and (Ctrl.Parent <> nil) then begin
Result := GetFontIndex(Ctrl.Parent, DefSkinIndex, SkinManager);
end
else if SkinManager.gd[si.SkinIndex].GiveOwnFont then Result := si.SkinIndex else Result := DefSkinIndex;
end
end;
function ParentTextured(const SkinData : TsCommonData) : boolean;
begin
if Assigned(SkinData.FOwnerControl) and Assigned(SkinData.FOwnerControl.Parent) and SkinData.FOwnerControl.Parent.HandleAllocated
then Result := GetBoolMsg(SkinData.FOwnerControl.Parent, AC_CHILDCHANGED)
else Result := False;
end;
procedure ShowGlowingIfNeeded(const SkinData : TsCommonData; Clicked : boolean = False; CtrlHandle : HWND = 0);
var
GlowCount : integer;
R, RBox : TRect;
DC : hdc;
ParentForm : TCustomForm;
WndHandle : HWND;
begin
if SkinData.SkinManager.Effects.AllowGlowing and SkinData.SkinManager.IsValidSkinIndex(SkinData.SkinIndex) then begin
GlowCount := SkinData.SkinManager.gd[SkinData.SkinIndex].GlowCount;
if GlowCount < 1 then Exit;
if (SkinData.FOwnerControl <> nil) then begin
if SkinData.FMouseAbove and not (csLButtonDown in SkinData.FOwnerControl.ControlState) and (not Clicked or (SkinData.GlowID = -1)) then begin
ParentForm := GetParentForm(SkinData.FOwnerControl);
if ParentForm = nil then Exit;
if ParentForm.Parent <> nil //FormStyle = fsMDIChild
then WndHandle := ParentForm.Parent.Handle
else if (TForm(ParentForm).FormStyle = fsMDIChild) and (MDISkinProvider <> nil)
then WndHandle := TsSkinProvider(MDISkinProvider).Form.Handle
else WndHandle := ParentForm.Handle;
if (SkinData.FOwnerControl is TWinControl) then begin
GetWindowRect(TWinControl(SkinData.FOwnerControl).Handle, R);
DC := GetWindowDC(TWinControl(SkinData.FOwnerControl).Handle);
GetClipBox(DC, RBox);
ReleaseDC(TWinControl(SkinData.FOwnerControl).Handle, DC);
SkinData.GlowID := ShowGlow(R, RBox, SkinData.SkinSection, s_Glow, SkinData.SkinManager.gd[SkinData.SkinIndex].GlowMargin, 255, WndHandle, SkinData.SkinManager);
end
else begin
R.TopLeft := SkinData.FOwnerControl.ClientToScreen(Point(0, 0));
R.BottomRight := Point(R.Left + SkinData.FOwnerControl.Width, R.Top + SkinData.FOwnerControl.Height);
DC := GetDC(SkinData.FOwnerControl.Parent.Handle);
GetClipBox(DC, RBox);
ReleaseDC(SkinData.FOwnerControl.Parent.Handle, DC);
if SkinData.FOwnerControl.Left < 0 then RBox.Left := -SkinData.FOwnerControl.Left else RBox.Left := 0;
if SkinData.FOwnerControl.Top < 0 then RBox.Top := -SkinData.FOwnerControl.Top else RBox.Top := 0;
if SkinData.FOwnerControl.Left + SkinData.FOwnerControl.Width > RBox.Right
then RBox.Right := RBox.Right - SkinData.FOwnerControl.Left
else RBox.Right := SkinData.FOwnerControl.Width;
if SkinData.FOwnerControl.Top + SkinData.FOwnerControl.Height > RBox.Bottom
then RBox.Bottom := RBox.Bottom - SkinData.FOwnerControl.Top
else RBox.Bottom := SkinData.FOwnerControl.Height;
SkinData.GlowID := ShowGlow(R, RBox, SkinData.SkinSection, s_Glow, SkinData.SkinManager.gd[SkinData.SkinIndex].GlowMargin, 255, WndHandle, SkinData.SkinManager);
end;
end
else if (SkinData.GlowID <> -1) then begin
HideGlow(SkinData.GlowID);
SkinData.GlowID := -1;
end;
end
else if CtrlHandle <> 0 then begin
GetWindowRect(CtrlHandle, R);
DC := GetWindowDC(CtrlHandle);
GetClipBox(DC, RBox);
ReleaseDC(CtrlHandle, DC);
SkinData.GlowID := ShowGlow(R, RBox, SkinData.SkinSection, s_Glow, SkinData.SkinManager.gd[SkinData.SkinIndex].GlowMargin, 255, GetParentFormHandle(CtrlHandle), SkinData.SkinManager);
end;
end;
end;
procedure InitCacheBmp(SkinData : TsCommonData);
begin
with SkinData do begin
if not Assigned(FCacheBmp) then begin
FCacheBmp := TBitmap.Create;
FCacheBmp.PixelFormat := pf32bit;
end;
if FCacheBmp.HandleType <> bmDIB then FCacheBmp.HandleType := bmDIB;
if Assigned(FOwnerControl) then begin
if FCacheBmp.Width <> FOwnerControl.Width then FCacheBmp.Width := max(FOwnerControl.Width, 0);
if FCacheBmp.Height <> FOwnerControl.Height then FCacheBmp.Height := max(FOwnerControl.Height, 0);
end
end;
end;
function SkinBorderMaxWidth(SkinData : TsCommonData) : integer;
begin
Result := 0;
if (SkinData.BorderIndex > -1) and (SkinData.SkinManager.ma[SkinData.BorderIndex].DrawMode and BDM_ACTIVEONLY <> BDM_ACTIVEONLY) then with SkinData.SkinManager.ma[SkinData.BorderIndex] do begin
if WL > WT then Result := WL else Result := WT;
if WR > Result then Result := WR;
if WB > Result then Result := WB;
end
end;
function GetParentCache(SkinData : TsCommonData) : TCacheInfo;
var
BGInfo : TacBGInfo;
begin
if SkinData.Skinned and Assigned(SkinData.FOwnerControl) then begin
BGInfo.DrawDC := 0;
BGInfo.PleaseDraw := False;
if Assigned(SkinData.FOwnerControl.Parent) then begin
GetBGInfo(@BGInfo, SkinData.FOwnerControl.Parent);
end
else begin
if SkinData.FOwnerControl is TWinControl then GetBGInfo(@BGInfo, GetParent(TWinControl(SkinData.FOwnerControl).Handle)) else begin
Result.X := 0;
Result.Y := 0;
Result.FillColor := GetBGColor(SkinData, 0);
Result.Ready := False;
Exit;
end;
end;
Result := BGInfoToCI(@BGInfo);
end
else begin
Result.X := 0;
Result.Y := 0;
Result.FillColor := GetBGColor(SkinData, 0);
Result.Ready := False;
end;
end;
function GetParentCacheHwnd(cHwnd : hwnd) : TCacheInfo;
var
pHwnd : hwnd;
BGInfo : TacBGInfo;
begin
Result.Ready := False;
pHwnd := GetParent(cHwnd);
if pHwnd <> 0 then begin
BGInfo.PleaseDraw := False;
GetBGInfo(@BGInfo, pHwnd);
Result := BGInfoToCI(@BGInfo);
end
else Result := EmptyCI;
end;
procedure UpdateData(SkinData : TsCommonData);
begin
with SkinData do if SkinSection = '' then case COC of
COC_TsSpinEdit..COC_TsListBox, COC_TsCurrencyEdit, COC_TsDBEdit, COC_TsDBMemo, COC_TsDBListBox, COC_TsDBGrid,
COC_TsDBLookupListBox, COC_TsTreeView, COC_TsCustomComboEdit, COC_TsDateEdit, COC_TsAdapter, COC_TsListView : SkinSection := s_Edit;
COC_TsCustomComboBox..COC_TsComboBoxEx, COC_TsDBComboBox, COC_TsDBLookupComboBox : SkinSection := s_ComboBox;
COC_TsButton, COC_TsBitBtn : SkinSection := s_Button;
COC_TsPanel, COC_TsCustomPanel, COC_TsMonthCalendar, COC_TsGrip : SkinSection := s_Panel;
COC_TsPanelLow : SkinSection := s_PanelLow;
COC_TsStatusBar : SkinSection := s_StatusBar;
COC_TsTabControl : SkinSection := s_PageControl;
COC_TsTabSheet : SkinSection := s_TabSheet;
COC_TsDBNavigator, COC_TsToolBar, COC_TsCoolBar : SkinSection := s_ToolBar;
COC_TsNavButton : SkinSection := s_ToolButton;
COC_TsDragBar : SkinSection := s_DragBar;
COC_TsScrollBox : SkinSection := s_PanelLow;
COC_TsSplitter : SkinSection := s_Splitter;
COC_TsGroupBox : SkinSection := s_GroupBox;
COC_TsGauge : SkinSection := s_Gauge;
COC_TsCheckBox, COC_TsHeaderControl : SkinSection := s_CheckBox;
COC_TsRadioButton : SkinSection := s_RadioButton;
COC_TsFrameAdapter : SkinSection := s_GroupBox;
COC_TsTrackBar : SkinSection := s_TrackBar;
COC_TsPageControl : SkinSection := s_PageControl;
COC_TsFrameBar : SkinSection := s_Bar;
COC_TsBarTitle : SkinSection := s_BarTitle;
COC_TsSpeedButton, COC_TsColorSelect : SkinSection := s_SpeedButton;
else SkinSection := FOwnerObject.ClassName;
end
else UpdateIndexes;
end;
procedure UpdateSkinState(const SkinData : TsCommonData; UpdateChildren : boolean = True);
var
i : integer;
begin
SkinData.CtrlSkinState := SkinData.CtrlSkinState and not ACS_FAST;
if SkinData.FOwnerControl <> nil then begin
if (SkinData.FOwnerControl is TFrame) or (SkinData.FOwnerControl is TPanel) or (SkinData.FOwnerControl is TScrollingWinControl) or (SkinData.FOwnerControl is TPageControl) then begin
if not IsCacheRequired(SkinData) then SkinData.CtrlSkinState := SkinData.CtrlSkinState or ACS_FAST else SkinData.CtrlSkinState := SkinData.CtrlSkinState and not ACS_FAST;
end;
if UpdateChildren and (SkinData.FOwnerControl is TWinControl) then with TWinControl(SkinData.FOwnerControl) do begin
for i := 0 to ControlCount - 1 do SendAMessage(Controls[i], AC_GETSKINSTATE, 1);
end;
end
else if SkinData.FOwnerObject is TsSkinProvider then begin
if not IsCacheRequired(SkinData) then begin
if TsSkinProvider(SkinData.FOwnerObject).Form.FormStyle <> fsMDIForm then SkinData.CtrlSkinState := SkinData.CtrlSkinState or ACS_FAST
end
end
end;
function ControlIsActive(SkinData : TsCommonData): boolean;
begin
Result := False;
with SkinData do begin
if not Assigned(FOwnerControl) or (csDestroying in FOwnerControl.ComponentState) then Exit;
if FOwnerControl.Enabled and not (csDesigning in FOwnerControl.ComponentState) then begin
if FFocused
then Result := True
else if (FOwnerControl is TWinControl) and ((TWinControl(FOwnerControl).Handle = GetFocus) and (TWinControl(FOwnerControl).Handle <> 0))
then Result := not (FOwnerControl is TCustomPanel)
else if SkinData.FMouseAbove then Result := not (SkinData.COC in sForbidMouse);
end;
end;
end;
function BgIsTransparent(CommonData : TsCommonData) : boolean;
begin
Result := False;
if CommonData.SkinIndex < 0 then Exit;
Result := CommonData.SkinManager.gd[CommonData.SkinIndex].Transparency > 0;
end;
procedure AlignShadow(SkinData : TsCommonData);
begin
end;
{ TsCommonData }
procedure TsCommonData.BeginUpdate;
begin
Inc(FUpdateCount);
FUpdating := True;
CtrlSkinState := CtrlSkinState or ACS_LOCKED;
if FOwnerControl <> nil then begin
FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_BEGINUPDATE), 0)
end
else if (FOwnerObject <> nil) and (FOwnerObject is TsSkinProvider) then SendMessage(TsSkinProvider(FOwnerObject).Form.Handle, SM_ALPHACMD, MakeWParam(0, AC_BEGINUPDATE), 0);
end;
constructor TsCommonData.Create(AOwner : TObject; CreateCacheBmp : boolean);
begin
SkinIndex := -1;
BorderIndex := -1;
GlowID := -1;
Texture := -1;
HotTexture := -1;
if AOwner is TControl then FOwnerControl := TControl(AOwner) else FOwnerControl := nil;
FOwnerObject := AOwner;
FFocused := False;
FMouseAbove := False;
FUpdating := False;
BGChanged := True;
GraphControl := nil;
HalfVisible := True;
FSkinManager := nil;
FCacheBmp := nil;
FUpdateCount := 0;
CtrlSkinState := 0;
BGType := 0;
PrintDC := 0;
InvalidRectH.Right := 0;
InvalidRectV.Bottom := 0;
FSaturation := 0;
FHUEOffset := 0;
if CreateCacheBmp then FCacheBmp := CreateBmp32(0, 0);
{$IFDEF RUNIDEONLY}
if not IsIDERunning and not ((FOwnerObject is TComponent) and (csDesigning in TComponent(FOwnerObject).ComponentState)) and not sTerminated then begin
sTerminated := True;
ShowWarning(sIsRUNIDEONLYMessage);
end;
{$ENDIF}
end;
destructor TsCommonData.Destroy;
begin
SkinIndex := -1;
Texture := -1;
HotTexture := -1;
FOwnerControl := nil;
FOwnerObject := nil;
FSkinManager := nil;
if Assigned(FCacheBmp) then FreeAndNil(FCacheBmp);
if GlowID <> -1 then HideGlow(GlowID);
inherited Destroy;
end;
procedure TsCommonData.EndUpdate(Repaint : boolean = False);
begin
Dec(FUpdateCount);
FUpdating := False;
CtrlSkinState := CtrlSkinState and not ACS_LOCKED;
If FUpdateCount > 0 then Exit;
if FOwnerControl <> nil then begin
FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_ENDUPDATE), 0)
end
else if (FOwnerObject <> nil) and (FOwnerObject is TsSkinProvider) then begin
SendMessage(TsSkinProvider(FOwnerObject).Form.Handle, SM_ALPHACMD, MakeWParam(0, AC_ENDUPDATE), 0);
end;
if Repaint then Invalidate;
end;
function TsCommonData.GetSkinManager: TsSkinManager;
begin
if FSkinManager <> nil then Result := FSkinManager else Result := DefaultManager;
end;
function TsCommonData.GetUpdating: boolean;
var
sm : TsSkinManager;
begin
if (Self = nil) then Exit;
sm := SkinManager;
if sm = nil then begin
Result := False;
Exit
end
else if csDesigning in sm.ComponentState then begin
Result := False;
Exit
end
else if not IsCached(Self) then begin
Result := FUpdating;
Exit
end
else Result := FUpdating;
if (FOwnerControl <> nil) then begin
if (csDestroying in FOwnerControl.ComponentState) then Exit;
if FUpdating
then Result := True
else if (FOwnerControl.Parent <> nil)
then Result := GetBoolMsg(FOwnerControl.Parent, AC_PREPARING)
else Result := False;
end
else if (FOwnerObject is TsSkinProvider) and (TsSkinProvider(FOwnerObject).Form.Parent <> nil)
then Result := GetBoolMsg(TsSkinProvider(FOwnerObject).Form.Parent, AC_PREPARING)
else Result := False
end;
procedure TsCommonData.Invalidate;
begin
if Assigned(FOwnerControl) then begin
if not ((csDestroying in FOwnerControl.ComponentState) or (csLoading in FOwnerControl.ComponentState)) then begin
BGChanged := True;
if ControlIsReady(FOwnerControl) then begin
if not (FOwnerControl is TWinControl)
then FOwnerControl.Repaint//Invalidate
else if TWinControl(FOwnerControl).HandleAllocated
then RedrawWindow(TWinControl(FOwnerControl).Handle, nil, 0, {RDW_UPDATENOW or }RDW_FRAME or RDW_ERASE or RDW_INVALIDATE or RDW_ALLCHILDREN);
end;
end;
end
else if (FOwnerObject <> nil) and (FOwnerObject is TsSkinProvider) then begin
BGChanged := True;
if TsSkinProvider(FOwnerObject).Form.HandleAllocated
then RedrawWindow(TsSkinProvider(FOwnerObject).Form.Handle, nil, 0, {RDW_UPDATENOW or }RDW_FRAME or RDW_ERASE or RDW_INVALIDATE or RDW_ALLCHILDREN);
end;
end;
procedure TsCommonData.Loaded;
begin
UpdateData(Self);
if Skinned and Assigned(FOwnerControl) and Assigned(FOwnerControl.Parent) and not (csLoading in FOwnerControl.ComponentState) then begin
if FOwnerControl is TWinControl then AddToAdapter(TWinControl(FOwnerControl));
UpdateCtrlColors(Self, False);
end;
end;
function TsCommonData.ManagerStored: boolean;
begin
Result := (FSkinManager <> nil)
end;
function TsCommonData.RepaintIfMoved: boolean;
begin
if (Self = nil) or UrgentPainting or not Skinned or{$IFNDEF ALITE}(FOwnerControl is TsTabSheet) or{$ENDIF} (FOwnerControl = nil) {or
(csCreating in FOwnerControl.ControlState) or not FOwnerControl.Visible }then begin
Result := True;
Exit;
end;
// if (SkinIndex < 0) or (SkinIndex > High(SkinManager.gd)) then { if is not skinned } Result := False else
if not FOwnerControl.Enabled then Result := True else
if (SkinManager.gd[SkinIndex].Transparency > 0) and Assigned(FOwnerControl.Parent) and FOwnerControl.Parent.HandleAllocated
then Result := GetBoolMsg(FOwnerControl.Parent, AC_CHILDCHANGED)
else Result := False;
end;
procedure TsCommonData.SetCustomColor(const Value: boolean);
begin
if FCustomColor <> Value then begin
FCustomColor := Value;
if (FOwnerControl <> nil) and not (csLoading in FOwnerControl.ComponentState) then UpdateCtrlColors(Self, True);
(*
if Skinned and Assigned(FOwnerControl) and (FOwnerControl is TControl{TCustomEdit}) and not (csLoading in FOwnerControl.ComponentState) then begin
if not CustomColor and (TsHackedControl(FOwnerControl).Color <> SkinManager.gd[SkinIndex].Color) then TsHackedControl(FOwnerControl).Color := SkinManager.gd[SkinIndex].Color;
if not CustomFont and (TsHackedControl(FOwnerControl).Font.Color <> SkinManager.gd[SkinIndex].FontColor[1]) then TsHackedControl(FOwnerControl).Font.Color := SkinManager.gd[SkinIndex].FontColor[1];
Invalidate
end;
*)
end;
end;
procedure TsCommonData.SetCustomFont(const Value: boolean);
begin
if FCustomFont <> Value then begin
FCustomFont := Value;
if (FOwnerControl <> nil) and not (csLoading in FOwnerControl.ComponentState) then UpdateCtrlColors(Self, True);
// Invalidate
end;
end;
procedure TsCommonData.SetHUEOffset(const Value: integer);
begin
if FHUEOffset <> Value then begin
FHUEOffset := Value;
Loaded;
Invalidate;
end;
end;
procedure TsCommonData.SetSaturation(const Value: integer);
begin
if FSaturation <> Value then begin
FSaturation := Value;
Loaded;
Invalidate;
end;
end;
procedure TsCommonData.SetSkinManager(const Value: TsSkinManager);
var
m : TMEssage;
begin
if FSkinManager <> Value then begin
if Value <> DefaultManager then FSkinManager := Value else FSkinManager := nil;
if (FOwnerControl <> nil) and (csLoading in FOwnerControl.ComponentState) then Exit;
if Assigned(Value) and (Length(Value.gd) > 0) then UpdateIndexes else SkinIndex := -1;
if Assigned(FOwnerObject) and (FOwnerObject is TsSkinProvider) then begin
if Assigned(Value) and (Length(Value.gd) > 0) and Value.IsValidSkinIndex(SkinIndex) then m.WParam := MakeWParam(0, AC_REFRESH) else m.WParam := MakeWParam(0, AC_REMOVESKIN);
m.Msg := SM_ALPHACMD;
m.LParam := LongWord(Value);
TsSkinProvider(FOwnerObject).DsgnWndProc(m);
end
else if (FOwnerControl <> nil) and (FOwnerControl.Parent <> nil) and not (csDestroying in FOwnerControl.ComponentState) then begin
if Assigned(Value) and (Length(Value.gd) > 0) and Value.IsValidSkinIndex(SkinIndex)
then FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_REFRESH), LongWord(Value))
else FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_REMOVESKIN), LongWord(Value));
end;
end;
end;
procedure TsCommonData.SetSkinSection(const Value: string);
begin
if FSkinSection <> Value then begin
if Value = '' then FSkinSection := s_Unknown else FSkinSection := UpperCase(Value);
if Assigned(SkinManager) and (Length(SkinManager.gd) > 0) then UpdateIndexes else SkinIndex := -1;
if (FOwnerControl <> nil) and not (csLoading in FOwnerControl.ComponentState) and not (csReading in FOwnerControl.ComponentState) and
(FOwnerControl.Parent <> nil) and not (csDestroying in FOwnerControl.ComponentState) then begin
if Assigned(SkinManager) and (Length(SkinManager.gd) > 0) and SkinManager.IsValidSkinIndex(SkinIndex)
then FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_REFRESH), LongWord(SkinManager))
else FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(0, AC_REMOVESKIN), LongWord(SkinManager));
if (GlowID <> -1) then begin
HideGlow(GlowID);
GlowID := -1;
end;
end
else if (FOwnerObject <> nil) and (FOwnerObject is TsSkinProvider) then BGChanged := True;
end;
end;
procedure TsCommonData.SetUpdating(const Value: boolean);
begin
FUpdating := Value;
end;
function TsCommonData.Skinned(CheckSkinActive : boolean = False): boolean;
var
SM : TsSkinManager;
begin
Result := False;
SM := SkinManager;
if (FSkinSection = '') or (SM = nil) or (csDestroying in SM.ComponentState) or not SM.IsValidSkinIndex(SkinIndex) then Exit;
if (Self.FOwnerObject <> nil) and (csDestroying in TComponent(Self.FOwnerObject).ComponentState) then Exit;
if CheckSkinActive
then Result := SkinManager.SkinData.Active
else Result := True;
end;
function CommonMessage(var Message: TMessage; SkinData : TsCommonData) : boolean;
var
i : integer;
b : boolean;
begin
Result := False;
if SkinData <> nil then with SkinData do if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_PRINTING : begin
if Message.LParam = 0 then SkinData.CtrlSkinState := SkinData.CtrlSkinState and not ACS_PRINTING else SkinData.CtrlSkinState := SkinData.CtrlSkinState or ACS_PRINTING;
SkinData.PrintDC := hdc(Message.LParam);
Result := True;
Exit;
end;
AC_UPDATESECTION : if UpperCase(SkinSection) = GlobalSectionName then begin
RestrictDrawing := False;
Invalidate;
end;
AC_PREPARING : begin
Message.Result := integer(BGChanged or FUpdating);
Result := True;
Exit;
end;
AC_UPDATING : FUpdating := Message.WParamLo = 1;
AC_GETHALFVISIBLE : begin
Message.Result := integer(HalfVisible);
Result := True;
Exit;
end;
AC_URGENTPAINT : UrgentPainting := Message.WParamLo = 1;
AC_CHILDCHANGED : if (SkinData.SkinIndex > -1) then begin
if (SkinData.SkinManager.gd[SkinData.SkinIndex].Transparency = 100) and (FOwnerControl <> nil) and (FOwnerControl.Parent <> nil)
then Message.LParam := integer(ParentTextured(SkinData))
else Message.LParam := integer((SkinData.SkinManager.gd[SkinData.SkinIndex].GradientPercent + SkinData.SkinManager.gd[SkinData.SkinIndex].ImagePercent > 0) or SkinData.RepaintIfMoved);
Message.Result := Message.LParam;
Result := True;
end;
AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
UpdateIndexes;
UpdateSkinState(SkinData, False);
RestrictDrawing := False;
end;
AC_SETBGCHANGED : BGChanged := True;
AC_SETHALFVISIBLE : HalfVisible := True;
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
BGChanged := True;
Updating := False;
UpdateCtrlColors(SkinData, True);
{ if Skinned and Assigned(FOwnerControl) then begin
if (FOwnerControl is TCustomEdit) then begin
if not CustomColor then TsHackedControl(FOwnerControl).Color := SkinData.SkinManager.gd[SkinIndex].Color;
if not CustomFont then TsHackedControl(FOwnerControl).Font.Color := SkinData.SkinManager.gd[SkinIndex].FontColor[1];
RedrawWindow(TCustomEdit(FOwnerControl).Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
end;
end; }
UpdateSkinState(SkinData, False);
end;
AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin
if (SkinData.SkinManager <> nil) and (csDestroying in SkinData.SkinManager.ComponentState) then FSkinManager := nil;
BorderIndex := -1;
SkinIndex := -1;
Texture := -1;
HotTexture := -1;
FUpdating := True;
if Assigned(FCacheBmp) then begin
FCacheBmp.Width := 0;
FCacheBmp.Height := 0;
end;
if Assigned(FOwnerControl) then begin
if (FOwnerControl is TCustomEdit) then begin
if not CustomColor then TsHackedControl(FOwnerControl).Color := clWindow;
if not CustomFont then TsHackedControl(FOwnerControl).Font.Color := clWindowText;
RedrawWindow(TCustomEdit(FOwnerControl).Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
end
else if (FOwnerControl is TWinControl) then for i := 0 to TWinControl(FOwnerControl).ControlCount - 1 do if TWinControl(FOwnerControl).Controls[i] is TLabel
then TLabel(TWinControl(FOwnerControl).Controls[i]).Font.Color := clWindowText;
end;
{$IFDEF CHECKXP}
// if UseThemes and (SkinData.FOwnerControl <> nil) and (SkinData.FOwnerControl is TWinControl) then begin
// SetWindowTheme(TWinControl(SkinData.FOwnerControl).Handle, nil, nil);
// end;
{$ENDIF}
end;
AC_GETCONTROLCOLOR : if Assigned(FOwnerControl) then begin
if SkinData.Skinned then begin
case SkinData.SkinManager.gd[SkinData.Skinindex].Transparency of
0 : Message.Result := SkinData.SkinManager.gd[SkinData.Skinindex].Color;
100 : begin if FOwnerControl.Parent <> nil
then begin
Message.Result := SendMessage(FOwnerControl.Parent.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETCONTROLCOLOR), 0);
if Message.Result = clFuchsia {if AlphaMessage is not supported} then Message.Result := TsHackedControl(FOwnerControl.Parent).Color
end
else Message.Result := ColorToRGB(TsHackedControl(FOwnerControl).Color);
end
else begin
if FOwnerControl.Parent <> nil
then Message.Result := SendMessage(FOwnerControl.Parent.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETCONTROLCOLOR), 0)
else Message.Result := ColorToRGB(TsHackedControl(FOwnerControl).Color);
// Mixing of colors
C1.C := Message.Result;
C2.C := SkinData.SkinManager.gd[SkinData.Skinindex].Color;
C1.R := IntToByte(((C1.R - C2.R) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.R shl 8) shr 8);
C1.G := IntToByte(((C1.G - C2.G) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.G shl 8) shr 8);
C1.B := IntToByte(((C1.B - C2.B) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.B shl 8) shr 8);
Message.Result := C1.C;
end
end;
end
else Message.Result := ColorToRGB(TsHackedControl(FOwnerControl).Color);
Result := True;
end;
AC_SETCHANGEDIFNECESSARY : begin
b := SkinData.RepaintIfMoved;
SkinData.BGChanged := SkinData.BGChanged or b;
if (SkinData.FOwnerControl <> nil) and (SkinData.FOwnerControl is TWinControl) then begin
if (Message.WParamLo = 1) then RedrawWindow(TWinControl(SkinData.FOwnerControl).Handle, nil, 0, RDW_NOERASE + RDW_NOINTERNALPAINT + RDW_INVALIDATE + RDW_ALLCHILDREN);
if b and Assigned(FOwnerControl) then for i := 0 to TWinControl(SkinData.FOwnerControl).ControlCount - 1 do begin
if (i < TWinControl(SkinData.FOwnerControl).ControlCount) and not (csDestroying in TWinControl(SkinData.FOwnerControl).Controls[i].ComponentState)
then SendAMessage(TWinControl(FOwnerControl).Controls[i], AC_SETCHANGEDIFNECESSARY)
end
end;
end;
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_CTRLHANDLED : begin
Message.Result := 1;
Result := True;
end;
AC_GETBG : begin
InitBGInfo(SkinData, PacBGInfo(Message.LParam), 0);
Result := True;
end;
AC_GETSKININDEX : begin
PacSectionInfo(Message.LParam)^.SkinIndex := SkinIndex;
Result := True
end;
AC_GETSKINSTATE : begin
if Message.LParam = 1 then begin
UpdateSkinState(SkinData);
end
else begin
Message.Result := CtrlSkinState;
end;
Result := True
end;
AC_SETSECTION : if Message.LParam <> 0 then begin
SkinSection := PacSectionInfo(Message.LParam).Name;
end;
end;
end;
procedure TsCommonData.UpdateIndexes;
begin
{$IFNDEF SKININDESIGN}
if (FOwnerObject <> nil) and (FOwnerObject is TComponent) and (csDesigning in TComponent(FOwnerObject).ComponentState) and (GetOwnerFrame(TComponent(FOwnerObject)) <> nil) then begin
SkinIndex := -1;
Texture := -1;
HotTexture := -1;
Exit;
end;
{$ENDIF}
BGChanged := True;
if Assigned(SkinManager) and SkinManager.Active then SkinIndex := SkinManager.GetSkinIndex(SkinSection) else SkinIndex := -1;
InitBGType(Self);
CtrlSkinState := 0;
if SkinIndex > -1 then begin
BorderIndex := SkinManager.gd[SkinIndex].BorderIndex;// GetMaskIndex(SkinIndex, SkinSection, s_BordersMask);
Texture := SkinManager.GetTextureIndex(SkinIndex, SkinSection, s_Pattern);
HotTexture := SkinManager.GetTextureIndex(SkinIndex, SkinSection, s_HotPattern);
UpdateSkinState(Self, False);
{ if FOwnerControl <> nil then begin
if (FOwnerControl is TFrame) or (FOwnerControl is TPanel) or (FOwnerControl is TScrollingWinControl) then
if not IsCacheRequired(Self)
then CtrlSkinState := ACS_FAST;
end
else if FOwnerObject is TsSkinProvider then begin
if not IsCacheRequired(Self) then CtrlSkinState := ACS_FAST;
end;}
end
else begin
Texture := -1;
HotTexture := -1;
end;
end;
function CommonWndProc(var Message: TMessage; SkinData : TsCommonData) : boolean;
var
i : integer;
begin
Result := False;
if SkinData <> nil then with SkinData do begin
if Message.Msg = SM_ALPHACMD then begin // Common messages for all components
Result := CommonMessage(Message, SkinData);
end
else case Message.Msg of
{$IFDEF CHECKXP}
WM_UPDATEUISTATE : if SkinData.Skinned
then Result := True
else if UseThemes and (SkinData.FOwnerControl <> nil) and (SkinData.FOwnerControl is TWinControl)
then SetWindowTheme(TWinControl(SkinData.FOwnerControl).Handle, nil, nil);
{$ENDIF}
WM_CONTEXTMENU : if (SkinData <> nil) and (SkinData.FOwnerControl <> nil) and (TsHackedControl(SkinData.FOwnerControl).PopupMenu <> nil) then begin
if SkinData.SkinManager <> nil
then SkinData.SkinManager.SkinableMenus.HookPopupMenu(TsHackedControl(SkinData.FOwnerControl).PopupMenu, SkinData.SkinManager.Active);
end;
CM_VISIBLECHANGED : if Assigned(SkinData) and Assigned(SkinData.FCacheBmp) then begin
if Message.WParam = 0 then begin
SkinData.FCacheBmp.Width := 0;
SkinData.FCacheBmp.Height := 0;
end
else begin
SkinData.Updating := False;
SkinData.BGChanged := True
end;
end;
CM_SHOWINGCHANGED : if Assigned(FOwnerControl) and FOwnerControl.Visible then SkinData.Loaded;
WM_PARENTNOTIFY : if Assigned(FOwnerControl) and (FOwnerControl is TWinControl) and
(Message.WParam and $FFFF = WM_CREATE) or (Message.WParam and $FFFF = WM_DESTROY) then begin
if Message.WParamLo = WM_CREATE then AddToAdapter(TWinControl(FOwnerControl))
end;
WM_SETFOCUS: if Assigned(FOwnerControl) and (FOwnerControl is TWinControl) and TWinControl(FOwnerControl).CanFocus and TWinControl(FOwnerControl).TabStop then begin
BGChanged := True;
FFocused := True;
if SkinData.Skinned and (COC in sEditCtrls) and (SkinData.SkinManager.gd[SkinData.SkinIndex].States > 1) then RedrawWindow(TWinControl(FOwnerControl).Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME);
end;
WM_KILLFOCUS : if Assigned(FOwnerControl) and (FOwnerControl is TWinControl) and TWinControl(FOwnerControl).CanFocus and TWinControl(FOwnerControl).TabStop then begin
BGChanged := True;
FFocused := False;
if (COC in sEditCtrls) and FOwnerControl.Visible then RedrawWindow(TWinControl(FOwnerControl).Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME);
end;
CM_ENABLEDCHANGED, WM_FONTCHANGE: begin
FMouseAbove := False;
FFocused := False;
if Assigned(FOwnerControl) and not FOwnerControl.Enabled and (SkinData.GlowID <> -1) then begin
HideGlow(SkinData.GlowID);
SkinData.GlowID := -1;
end;
end;
CM_MOUSEENTER : if not (csDesigning in FOwnerControl.ComponentState) and Skindata.Skinned then begin
if (FOwnerControl <> nil) and (FOwnerControl is TWinControl) and (DefaultManager <> nil) then begin
for i := 0 to TWinControl(FOwnerControl).ControlCount - 1 do begin
if (TWinControl(FOwnerControl).Controls[i] is TsSpeedButton) and (TWinControl(FOwnerControl).Controls[i] <> FOwnerControl) and (TWinControl(FOwnerControl).Controls[i] <> Pointer(Message.LParam)) and TsSpeedButton(TWinControl(FOwnerControl).Controls[i]).SkinData.FMouseAbove then begin
TWinControl(FOwnerControl).Controls[i].Perform(CM_MOUSELEAVE, 0, 0)
end;
end;
if not (COC in sForbidMouse) then FMouseAbove := True;
DefaultManager.ActiveControl := TWinControl(FOwnerControl).Handle;
if not (COC in sCanNotBeHot) and not (COC in [COC_TsButton, COC_TsBitBtn, COC_TsSpeedButton]) then ShowGlowingIfNeeded(SkinData);
if (Skindata.COC in sEditCtrls) and (SkinData.SkinManager.gd[Skindata.SkinIndex].States > 1) then begin
BGChanged := True;
SendMessage(TWinControl(FOwnerControl).Handle, WM_NCPAINT, 0, 0);
// RedrawWindow(TWinControl(FOwnerControl).Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME or RDW_UPDATENOW);
end;
end else if not (COC in sForbidMouse) then FMouseAbove := True;
end;
CM_MOUSELEAVE : if not (csDesigning in FOwnerControl.ComponentState) and Skindata.Skinned then begin
if not (COC in sForbidMouse) then FMouseAbove := False;
if not (COC in sCanNotBeHot) and not (COC in [COC_TsButton, COC_TsBitBtn, COC_TsSpeedButton]) then ClearGlows;
if FOwnerControl.Visible and (Skindata.COC in sEditCtrls) then begin
BGChanged := True;
SendMessage(TWinControl(FOwnerControl).Handle, WM_NCPAINT, 0, 0);
// RedrawWindow(TWinControl(FOwnerControl).Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME or RDW_UPDATENOW);
end;
end;
WM_SIZE : if Skinned then begin
BGChanged := True;
if (FOwnerControl <> nil) and (FOwnerControl is TWinControl) then begin
if Skinned and (Length(SkinData.SkinManager.gd) > SkinIndex) and (SkinData.SkinManager.gd[SkinIndex].GradientPercent > 0) then begin
for i := 0 to TWinControl(SkinData.FOwnerControl).ControlCount - 1 do
if (i < TWinControl(SkinData.FOwnerControl).ControlCount) and
not (csDestroying in TWinControl(SkinData.FOwnerControl).Controls[i].ComponentState) and
not ((akRight in TWinControl(SkinData.FOwnerControl).Controls[i].Anchors) or
(akBottom in TWinControl(SkinData.FOwnerControl).Controls[i].Anchors))
then TWinControl(FOwnerControl).Controls[i].Perform(SM_ALPHACMD, MakeWParam(1, AC_SETCHANGEDIFNECESSARY), 0);
end;
end;
if (SkinData.GlowID <> -1) then begin
HideGlow(SkinData.GlowID);
SkinData.GlowID := -1;
end;
end;
WM_MOVE : if SkinData.RepaintIfMoved then begin
SkinData.BGChanged := True;
if (SkinData.FOwnerControl <> nil) then SkinData.FOwnerControl.Perform(SM_ALPHACMD, MakeWParam(1, AC_SETCHANGEDIFNECESSARY), 0);
if (SkinData.GlowID <> -1) then begin
HideGlow(SkinData.GlowID);
SkinData.GlowID := -1;
end;
end;
end;
end;
end;
procedure CopyWinControlCache(Control : TWinControl; SkinData : TsCommonData; SrcRect, DstRect : TRect; DstDC : HDC; UpdateCorners : boolean; OffsetX : integer = 0; OffsetY : integer = 0);
var
SaveIndex : HDC;
i : integer;
Child : TControl;
begin
if SkinData.FCacheBmp = nil then Exit;
if UpdateCorners then sAlphaGraph.UpdateCorners(SkinData, 0);
SaveIndex := SaveDC(DstDC);
IntersectClipRect(DstDC, DstRect.Left, DstRect.Top, DstRect.Right, DstRect.Bottom);
try
for i := 0 to Control.ControlCount - 1 do begin
Child := Control.Controls[i];
if (Control.Controls[i] is TGraphicControl) and StdTransparency {$IFNDEF ALITE}or (Control.Controls[i] is TsSplitter){$ENDIF} then Continue;
if Child.Visible then begin
if (Control.Controls[i].Left < DstRect.Right) and (Control.Controls[i].Top < DstRect.Bottom) and
(Control.Controls[i].Left + Control.Controls[i].Width > DstRect.Left) and (Control.Controls[i].top + Control.Controls[i].Height > DstRect.Top) then begin
if (csDesigning in Control.Controls[i].ComponentState) or
(csOpaque in Control.Controls[i].ControlStyle) or
(Control.Controls[i] is TGraphicControl) then begin
ExcludeClipRect(DstDC, Control.Controls[i].Left + OffsetX, Control.Controls[i].Top + OffsetY,
Control.Controls[i].Left + Control.Controls[i].Width + OffsetX,
Control.Controls[i].Top + Control.Controls[i].Height + OffsetY);
end;
end;
end;
end;
BitBlt(DstDC, DstRect.Left, DstRect.Top, WidthOf(DstRect), HeightOf(DstRect), SkinData.FCacheBmp.Canvas.Handle, SrcRect.Left, SrcRect.Top, SRCCOPY);
finally
RestoreDC(DstDC, SaveIndex);
end;
end;
procedure CopyHwndCache(hwnd : THandle; SkinData : TsCommonData; SrcRect, DstRect : TRect; DstDC : HDC; UpdateCorners : boolean; OffsetX : integer = 0; OffsetY : integer = 0); overload;
var
SaveIndex : HDC;
hctrl : THandle;
R, hR : TRect;
Index : integer;
begin
if UpdateCorners then sAlphaGraph.UpdateCorners(SkinData, 0);
SaveIndex := SaveDC(DstDC);
IntersectClipRect(DstDC, DstRect.Left, DstRect.Top, DstRect.Right, DstRect.Bottom);
try
hctrl := GetTopWindow(hwnd);
GetWindowRect(hwnd, R);
while (hctrl <> 0) do begin
if IsWindowVisible(hctrl) then begin
GetWindowRect(hctrl, hR);
OffsetRect(hR, -R.Left - OffsetX, -R.Top - OffsetY);
if (GetWindowLong(hctrl, GWL_STYLE) and BS_GROUPBOX = BS_GROUPBOX) and (GetWindowLong(hctrl, GWL_EXSTYLE) and WS_EX_CLIENTEDGE <> WS_EX_CLIENTEDGE) {Prevent of Treeview filling} then begin
if DefaultManager <> nil then begin
Index := DefaultManager.GetSkinIndex(s_GroupBox);
Index := DefaultManager.GetMaskIndex(Index, s_GroupBox, s_BordersMask);
ExcludeClipRect(DstDC, hR.Left, hR.Top, hR.Right, hR.Top + SendAMessage(hctrl, AC_GETSERVICEINT));
ExcludeClipRect(DstDC, hR.Left, hR.Top, hR.Left + DefaultManager.MaskWidthLeft(Index), hR.Bottom);
ExcludeClipRect(DstDC, hR.Right - DefaultManager.MaskWidthRight(Index), hR.Top, hR.Right, hR.Bottom);
ExcludeClipRect(DstDC, hR.Left, hR.Bottom - DefaultManager.MaskWidthBottom(Index), hR.Right, hR.Bottom);
end;
end
else ExcludeClipRect(DstDC, hR.Left, hR.Top, hR.Right, hR.Bottom);
end;
hctrl := GetNextWindow(hctrl, GW_HWNDNEXT);
end;
BitBlt(DstDC, DstRect.Left, DstRect.Top, WidthOf(DstRect), HeightOf(DstRect), SkinData.FCacheBmp.Canvas.Handle, SrcRect.Left, SrcRect.Top, SRCCOPY);
finally
RestoreDC(DstDC, SaveIndex);
end;
end;
{ TsBoundLabel }
procedure TsBoundLabel.AlignLabel;
begin
if Assigned(FTheLabel) and FTheLabel.Visible then begin
FTheLabel.AutoSize := True;
case Layout of
sclLeft : begin
FTheLabel.Left := FTheLabel.FocusControl.Left - FTheLabel.Width - 4 - Indent;
FTheLabel.Top := FTheLabel.FocusControl.Top + (FTheLabel.FocusControl.Height - FTheLabel.Height) div 2 - 1;
end;
sclTopLeft : begin
FTheLabel.Left := FTheLabel.FocusControl.Left;
FTheLabel.Top := FTheLabel.FocusControl.Top - FTheLabel.Height - Indent;
end;
sclTopCenter : begin
FTheLabel.Left := FTheLabel.FocusControl.Left + (FTheLabel.FocusControl.Width - FTheLabel.Width) div 2;
FTheLabel.Top := FTheLabel.FocusControl.Top - FTheLabel.Height - Indent;
end;
sclTopRight : begin
FTheLabel.Left := FTheLabel.FocusControl.Left + FTheLabel.FocusControl.Width - FTheLabel.Width;
FTheLabel.Top := FTheLabel.FocusControl.Top - FTheLabel.Height - Indent;
end;
end;
FTheLabel.Parent := FCommonData.FOwnerControl.Parent;
if FMaxWidth <> 0 then begin
FTheLabel.AutoSize := False;
FTheLabel.Width := FMaxWidth;
FTheLabel.WordWrap := True;
FTheLabel.Height := Max(FTheLabel.Height, FTheLabel.FocusControl.Height);
end;
end;
end;
constructor TsBoundLabel.Create(AOwner: TObject; CommonData : TsCommonData);
begin
FCommonData := CommonData;
FFont := TFont.Create;
FActive := False;
end;
destructor TsBoundLabel.Destroy;
begin
FreeAndNil(FFont);
if Assigned(FTheLabel) then FreeAndNil(FTheLabel);
inherited Destroy;
end;
function TsBoundLabel.GetFont: TFont;
begin
if Assigned(FTheLabel) and Assigned(FTheLabel.Font) then Result := FTheLabel.Font else Result := FFont;
end;
function TsBoundLabel.GetUseSkin: boolean;
begin
if Assigned(FTheLabel) then Result := FTheLabel.UseSkinColor else Result := True;
end;
procedure TsBoundLabel.SetActive(const Value: boolean);
begin
if FActive = Value then Exit;
if Value then begin
FActive := True;
if FTheLabel = nil then FTheLabel := TsEditLabel.InternalCreate(FCommonData.FOwnerControl, Self);
FTheLabel.Visible := False;
FTheLabel.Parent := FCommonData.FOwnerControl.Parent;
FTheLabel.FocusControl := TWinControl(FCommonData.FOwnerControl);
UpdateAlignment;
FTheLabel.Name := FCommonData.FOwnerControl.Name + 'Label';
if FText = '' then FText := FCommonData.FOwnerControl.Name;
FTheLabel.Caption := FText;
FTheLabel.Visible := FCommonData.FOwnerControl.Visible or (csDesigning in FTheLabel.ComponentState);
FTheLabel.Enabled := FCommonData.FOwnerControl.Enabled;
AlignLabel;
end
else begin
if Assigned(FTheLabel) then FreeAndNil(FTheLabel);
FActive := False;
end;
end;
procedure TsBoundLabel.SetFont(const Value: TFont);
begin
if FTheLabel <> nil then begin
FTheLabel.Font.Assign(Value);
if FCommonData.FOwnerControl <> nil then FTheLabel.Parent := FCommonData.FOwnerControl.Parent;
AlignLabel;
end;
end;
procedure TsBoundLabel.SetIndent(const Value: integer);
begin
if FIndent <> Value then begin
FIndent := Value;
if Active then AlignLabel;
end;
end;
procedure TsBoundLabel.SetLayout(const Value: TsCaptionLayout);
begin
if FLayout <> Value then begin
FLayout := Value;
UpdateAlignment;
if Active then AlignLabel;
end;
end;
procedure TsBoundLabel.SetMaxWidth(const Value: integer);
begin
if FMaxWidth <> Value then begin
FMaxWidth := Value;
if Active then AlignLabel;
end;
end;
procedure TsBoundLabel.SetText(const Value: acString);
begin
if FText <> Value then begin
FText := Value;
if Active then begin
FTheLabel.Caption := Value;
AlignLabel;
end;
end;
end;
procedure TsBoundLabel.SetUseSkin(const Value: boolean);
begin
if Assigned(FTheLabel) then FTheLabel.UseSkinColor := Value;
end;
procedure TsBoundLabel.UpdateAlignment;
begin
if FTheLabel <> nil then case FLayout of
sclTopLeft : TsLabel(FTheLabel).Alignment := taLeftJustify;
sclTopCenter : TsLabel(FTheLabel).Alignment := taCenter;
sclTopRight, sclLeft : TsLabel(FTheLabel).Alignment := taRightJustify;
end;
end;
end.
|
unit Data.Entities.User;
interface
uses
Aurelius.Mapping.Attributes;
type
[Entity]
[Automapping]
[Table('Users')]
TUser = class
private
FId: Integer;
FFirstName: string;
FLastName: string;
[Column('LOGIN_NAME', [TColumnProp.Unique, TColumnProp.Required])]
FLoginName: string;
FPasswdHash: string;
FPasswdSalt: string;
public
property Id: Integer read FId write FId;
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property LoginName: string read FLoginName write FLoginName;
property PasswdHash: string read FPasswdHash write FPasswdHash;
property PasswdSalt: string read FPasswdSalt write FPasswdSalt;
end;
implementation
initialization
RegisterEntity(TUser);
end.
|
unit Classe.Calculadora;
interface
type
iCalculadora = interface
['{655C8757-9943-4A39-840C-D2DBC0B7039A}']
function Operacao(Num1, Num2 : double) : double;
end;
TSoma = class(TInterfacedObject, iCalculadora)
function Operacao(Num1, Num2 : double) : double;
function SomarDireto(Num1, Num2 : double) : double;
end;
TSubtrair = class(TInterfacedObject, iCalculadora)
function Operacao(Num1, Num2 : double) : double;
end;
TMultiplicar = class(TInterfacedObject, iCalculadora)
function Operacao(Num1, Num2 : double) : double;
end;
TDividir = class(TInterfacedObject, iCalculadora)
function Operacao(Num1, Num2 : double) : double;
end;
implementation
uses
System.SysUtils;
{ TSoma }
function TSoma.Operacao(Num1, Num2: double): double;
begin
Result := Num1 + Num2;
end;
function TSoma.SomarDireto(Num1, Num2: double): double;
begin
Result := Num1 + Num2;
end;
{ TSubtrair }
function TSubtrair.Operacao(Num1, Num2: double): double;
begin
Result := Num1 - Num2;
end;
{ TDividir }
function TDividir.Operacao(Num1, Num2: double): double;
begin
if Num2 <= 0 then
raise Exception.Create('Valor nao pode ser divido por zero');
Result := Num1 / Num2;
end;
{ TMultiplicar }
function TMultiplicar.Operacao(Num1, Num2: double): double;
begin
Result := Num1 * Num2;
end;
end.
|
unit PFacturaElectronica;
interface
uses Classes, SysUtils;
type
TPFDomicilioFiscal = record
Calle: String;
Numero: String;
NumeroInterior: String;
Colonia: String;
CodigoPostal: String;
Localidad: String;
Municipio: String;
Estado: String;
Pais: String;
end;
TPFNomina_ComplementoNomina = record
NumeroEmpleado: String;
Curp: String;
NumeroSeguridadSocial: String;
Departamento: String;
Banco: Integer;
ClabeBancaria: String;
FechaInicioLabores: TDateTime;
Puesto: String;
TipoDeContrato: String;
TipoDeJornada: String;
PeriodosDePago: String;
TipoDeRiesgo: Integer;
SalarioBase: Currency;
SalarioDiarioIntegrado: Currency;
FechaDePago: TDateTime;
PeriodoDePago_Inicial: TDateTime;
PeriodoDePago_Final: TDateTime;
DiasPagados: Real;
TipoDeRegimen: Integer;
end;
TPFNomina_Concepto = record
Tipo: Integer;
Clave: String;
Concepto: String;
ImporteGravado: Currency;
ImporteExento: Currency;
EsDeduccionTipoImpuestoRetenido: Boolean;
end;
TPFNomina_Conceptos = Array Of TPFNomina_Concepto;
TPFNomina_Percepcion = TPFNomina_Concepto;
TPFNomina_Percepciones = Array Of TPFNomina_Concepto;
TPFNomina_Deduccion = TPFNomina_Concepto;
TPFNomina_Deducciones = Array Of TPFNomina_Concepto;
TPFNomina_Incapacidad = record
Tipo: Integer;
Dias: Integer;
Descuento: Currency;
end;
TPFNomina_Incapacidades = Array Of TPFNomina_Incapacidad;
TPFNomina_HoraExtra = record
Dias: Integer;
HorasExtra: Integer;
TipoHoras: String;
ImportePagado: Currency;
end;
TPFNomina_HorasExtra = Array Of TPFNomina_HoraExtra;
TPFContribuyente = record
RazonSocial: String;
RFC: String;
Correo: String;
RegimenFiscal: String;
Domicilio: TPFDomicilioFiscal;
ExpedidoEn: TPFDomicilioFiscal;
RegistroPatronal: String;
ComplementoNomina: TPFNomina_ComplementoNomina;
end;
TPFTipoComprobante = (trFactura, trNomina);
TPFTipoImpuesto = (impTrasladado, impRetenido);
TPFTipoConcepto = (cPercepciones, cDeducciones);
TPFConcepto = record
Cantidad: Real;
Unidad: String;
Descripcion: String;
PrecioUnitario: Real;
AplicaIVA: String;
end;
TPFConceptos = Array of TPFConcepto;
TPFImpuesto = record
Tipo: TPFTipoImpuesto;
Impuesto: String;
Tasa: Currency;
Importe: Currency;
end;
TPFImpuestos = Array of TPFImpuesto;
TPFFolio = record
Serie: String;
Folio: Integer;
end;
TPFPropiedades = record
TipoDeComprobante: String;
FormaDePago: String;
MetodoDePago: String;
CondicionesDePago: String;
DescuentoDescripcion: String;
DescuentoImporte: Currency;
Moneda: String;
NumeroDeCuenta: String;
Folio : String ;
FolioFiscalOrig: String;
SerieFolioFiscalOrig: String;
FechaFolioFiscalOrig: TDateTime;
FechaValida: String;
MontoFolioFiscalOrig: Currency;
end;
TPFTimbre = record
Version : WideString;
UUID : WideString;
FechaTimbrado : TDateTime;
SelloCFD : WideString;
NoCertificadoSAT : WideString;
SelloSAT : WideString;
XML: WideString;
Timbre: WideString;
end;
TPFCredenciales = record
RFC: String;
ID: String;
Clave: String;
CertificadoB64: wideString;
LlaveB64: wideString;
end;
TPFParametros = record
EmisorRFC: String;
UrlTimbrado: String;
UrlCancelado: String;
UserPassword: String;
UserId: String;
UUID: String;
GenerarPDF: Boolean;
GenerarTXT: Boolean;
GenerarCBB: Boolean;
CertificadoB64: String;
LlaveB64: String;
end;
TPFResultados = record
Codigo: String;
Mensaje: String;
xmlb64: String;
pdfb64: String;
txtb64: String;
cbbb64: String;
uuid: String;
end;
TPFCSD = record
Certificado: wideString;
Llave: wideString;
Clave: wideString;
end;
TPFCertificado = record
VigenciaInicio: TDateTime;
VigenciaFin: TDateTime;
NumeroSerie: String;
RFC: String;
end;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings);
Function CantidadEnLetra(curCantidad: Currency; MonNal: integer): String;
implementation
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings);
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.DelimitedText := Str;
end;
Function CantidadEnLetra(curCantidad: Currency; MonNal: integer): String;
var
i: integer;
Cantidad, Centavos: Currency;
BloqueCero, NumeroBloques, Digito: Byte;
PrimerDigito, SegundoDigito, TercerDigito: Byte;
Resultado, Temp, strCentavos, Bloque: String;
Unidades: Array[0..28] of String;
Decenas: Array[0..8] of String;
Centenas: Array[0..8] of String;
begin
Unidades[0] := 'UN'; Unidades[1] := 'DOS'; Unidades[2] := 'TRES'; Unidades[3] := 'CUATRO';
Unidades[4] := 'CINCO'; Unidades[5] := 'SEIS'; Unidades[6] := 'SIETE'; Unidades[7] := 'OCHO';
Unidades[8] := 'NUEVE'; Unidades[9] := 'DIEZ'; Unidades[10] := 'ONCE'; Unidades[11] := 'DOCE';
Unidades[12] := 'TRECE'; Unidades[13] := 'CATORCE'; Unidades[14] := 'QUINCE'; Unidades[15] := 'DIECISÉIS';
Unidades[16] := 'DIECISIETE'; Unidades[17] := 'DIECIOCHO'; Unidades[18] := 'DIECINUEVE';
Unidades[19] := 'VEINTE'; Unidades[20] := 'VEINTIUNO'; Unidades[21] := 'VEINTIDÓS';
Unidades[22] := 'VEINTITRÉS'; Unidades[23] := 'VEINTICUATRO'; Unidades[24] := 'VEINTICINCO';
Unidades[25] := 'VEINTISÉIS'; Unidades[26] := 'VEINTISIETE'; Unidades[27] := 'VEINTIOCHO'; Unidades[28] := 'VEINTINUEVE';
Decenas[0] := 'DIEZ'; Decenas[1] := 'VEINTE'; Decenas[2] := 'TREINTA'; Decenas[3] := 'CUARENTA';
Decenas[4] := 'CINCUENTA'; Decenas[5] := 'SESENTA'; Decenas[6] := 'SETENTA'; Decenas[7] := 'OCHENTA'; Decenas[8] := 'NOVENTA';
Centenas[0] := 'CIENTO'; Centenas[1] := 'DOSCIENTOS'; Centenas[2] := 'TRESCIENTOS'; Centenas[3] := 'CUATROCIENTOS';
Centenas[4] := 'QUINIENTOS'; Centenas[5] := 'SEISCIENTOS'; Centenas[6] := 'SETECIENTOS'; Centenas[7] := 'OCHOCIENTOS'; Centenas[8] := 'NOVECIENTOS';
Cantidad := Trunc(curCantidad);
Centavos := (curCantidad - Cantidad) * 100;
NumeroBloques := 1;
Repeat
PrimerDigito := 0;
SegundoDigito := 0;
TercerDigito := 0;
Bloque := '';
BloqueCero := 0;
For i := 1 To 3 do begin
Digito := Round(Cantidad) Mod 10;
If Digito <> 0 Then begin
Case i of
1: begin
Bloque := ' ' + Unidades[Digito - 1];
PrimerDigito := Digito;
end;
2: begin
if Digito <= 2 Then begin
Bloque := ' ' + Unidades[(Digito * 10 + PrimerDigito - 1)];
end else begin
if PrimerDigito <> 0 then
Temp := ' Y' else Temp := '';
Bloque := ' ' + Decenas[Digito - 1] + Temp + Bloque;
end;
SegundoDigito := Digito;
end; //case 2
3: begin
if (Digito = 1) and (PrimerDigito = 0) and (SegundoDigito = 0) then
Temp := 'CIEN' else Temp := Centenas[Digito-1];
Bloque := ' ' + Temp + Bloque;
TercerDigito := Digito;
end; //case 3
end; //case
end else begin
BloqueCero := BloqueCero + 1;
end;
Cantidad := Int(Cantidad / 10);
if Cantidad = 0 Then begin
break;
end; // If Cantidad=0
end; //for
case NumeroBloques of
1: Resultado := Bloque;
2: begin
if BloqueCero = 3 then
Temp := '' else Temp := ' MIL';
Resultado := Bloque + Temp + Resultado;
end;
3: begin
if (PrimerDigito = 1) and (SegundoDigito = 0) and (TercerDigito = 0) then
Temp := ' MILLON' else Temp := ' MILLONES';
Resultado := Bloque + Temp + Resultado;
end; //case 3
end; //case
NumeroBloques := NumeroBloques + 1;
Until Cantidad = 0; //repeat
case MonNal of
0: begin
if curCantidad > 1 then
Temp := ' CENTAVOS ***' else Temp := ' CENTAVO ***';
CantidadEnLetra := Resultado + Temp;
end;
1: begin
if curCantidad > 1 then
Temp := ' PESOS '
else
Temp := ' PESO ';
if Centavos = 0 then
strCentavos := ' 00/100MN'
else
strCentavos := ' ' + FloatToStr(Centavos) + '/100MN';
// strCentavos := ' ' + CantidadEnLetra(Centavos, 0);
CantidadEnLetra := Resultado + Temp + strCentavos;
end;
2: begin
if curCantidad > 1 then
Temp := ' DOLARES '
else
Temp := ' DOLAR ';
if Centavos = 0 then
strCentavos := ' 00/100USD'
else
strCentavos := ' ' + FloatToStr(Centavos) + '/100USD';
// strCentavos := ' ' + CantidadEnLetra(Centavos, 0);
CantidadEnLetra := Resultado + Temp + strCentavos;
// if curCantidad > 1 then
// Temp := ' DLLS ' else Temp := ' DOLAR ';
// if Centavos=0 then strCentavos := '' else strCentavos := 'CON '+CantidadEnLetra(Centavos, 0);
// CantidadEnLetra := 'SON: *** ' + Resultado + Temp + strCentavos;
end;
end;
end;
end.
|
{
Created by BGRA Controls Team
Dibo, Circular, lainz (007) and contributors.
For detailed information see readme.txt
Site: https://sourceforge.net/p/bgra-controls/
Wiki: http://wiki.lazarus.freepascal.org/BGRAControls
Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit BGRAScript;
{$mode objfpc}{$H+}
{ $define debug}
interface
uses
Classes, SysUtils, BGRABitmap, BGRABitmapTypes, Dialogs;
{Template}
procedure SynCompletionList(itemlist: TStrings);
{Scripting}
function ScriptCommand(command: string; var bitmap: TBGRABitmap;
var variables: TStringList; var line: integer): boolean;
function ScriptCommandList(commandlist: TStrings; var bitmap: TBGRABitmap): boolean;
{Tools}
function StrToDrawMode(mode: string): TDrawMode;
implementation
procedure SynCompletionList(itemlist: TStrings);
begin
with itemlist do
begin
{Assign key values}
Add('let key "value"');
{Goto line}
Add('goto 10');
{Messages}
Add('print "Message"');
Add('input "Title","Message","Default value",result');
{Read Values}
Add('GetWidth width');
Add('GetHeight height');
{TFPCustomImage override}
Add('SetSize 320,240');
{Loading functions}
Add('SaveToFile "file.png"');
{Loading functions}
Add('SetHorizLine 0,0,100,"rgba(0,0,0,1)"');
Add('XorHorizLine 0,0,100,"rgba(0,0,0,1)"');
Add('DrawHorizLine 0,0,100,"rgba(0,0,0,1)"');
Add('FastBlendHorizLine 0,0,100,"rgba(0,0,0,1)"');
Add('AlphaHorizLine 0,0,100,"rgba(0,0,0,1)"');
Add('SetVertLine 0,0,100,"rgba(0,0,0,1)"');
Add('XorVertLine 0,0,100,"rgba(0,0,0,1)"');
Add('DrawVertLine 0,0,100,"rgba(0,0,0,1)"');
Add('FastBlendVertLine 0,0,100,"rgba(0,0,0,1)"');
Add('AlphaVertLine 0,0,100,"rgba(0,0,0,1)"');
Add('DrawHorizLinediff 0,0,100,"rgba(0,0,0,1)","rgba(255,255,255,1)",128');
//--
Add('FillTransparent');
Add('Rectangle 0,0,100,100,"rgba(0,0,0,1)","rgba(255,255,255,1)","dmDrawWithTransparency"');
Add('RectangleAntiAlias "0,5","0,5","99,5","99,5","rgba(0,0,0,1)","1,5","rgba(255,255,255,1)"');
{BGRA bitmap functions}
Add('RotateCW');
Add('RotateCCW');
Add('Negative');
Add('NegativeRect 0,0,100,100');
Add('LinearNegative');
Add('LinearNegativeRect 0,0,100,100');
Add('InplaceGrayscale');
Add('InplaceGrayscaleRect 0,0,100,100');
Add('SwapRedBlue');
Add('GrayscaleToAlpha');
Add('AlphaToGrayscale');
Add('ApplyGlobalOpacity 128');
Add('ConvertToLinearRGB');
Add('ConvertFromLinearRGB');
Add('DrawCheckers 0,0,100,100,"rgba(100,100,100,255)","rgba(0,0,0,0)"');
{Custom functions}
Add('VerticalFlip 0,0,100,100');
Add('HorizontalFlip 0,0,100,100');
Add('BlendBitmap 0,0,"file.png","boTransparent"');
Add('BlendBitmapOver 0,0,"file.png","boTransparent",255,"False"');
Add('ApplyBitmapMask "file.png",0,0,100,100,0,0');
{Filters}
Add('FilterFastBlur 5,"False"');
Add('FilterSmooth "False"');
Add('FilterSharpen 5,"False"');
Add('FilterContour');
Add('FilterEmboss "1,5"');
Add('FilterNormalize "True"');
Add('FilterSphere "True"');
Add('FilterCylinder "True"');
Add('FilterPlane "True"');
end;
end;
function ScriptCommand(command: string; var bitmap: TBGRABitmap;
var variables: TStringList; var line: integer): boolean;
function ParamCheck(passed, mustbe: integer): boolean;
begin
Result := True;
if passed <> mustbe then
Result := False;
{$ifdef debug}
if not Result then
begin
writeln('>> Wrong number of parameters: ' + IntToStr(passed));
writeln('>> Must be: ' + IntToStr(mustbe));
end;
{$endif}
end;
function ParamCheckAtLeast(passed, mustbe: integer): boolean;
begin
Result := True;
if passed < mustbe then
Result := False;
{$ifdef debug}
if not Result then
begin
writeln('>> Wrong number of parameters: ' + IntToStr(passed));
writeln('>> At least must be: ' + IntToStr(mustbe));
end;
{$endif}
end;
var
list: TStringList;
passed: integer;
tmpbmp1: TBGRABitmap;
i: integer;
a: string;
begin
{ $ifdef debug}
//writeln('---Script-Command---');
{ $endif}
Result := True;
list := TStringList.Create;
list.CommaText := command;
passed := list.Count;
{Replace values in variable names}
for i := 0 to list.Count - 1 do
if variables.Values[list[i]] <> '' then
list[i] := variables.Values[list[i]];
case LowerCase(list[0]) of
{Assign key values}
'let':
begin
Result := ParamCheck(passed, 3);
if Result then
variables.Add(list[1] + '=' + list[2]);
end;
{Messages}
'input':
begin
Result := ParamCheck(passed, 5);
if Result then
begin
a := InputBox(list[1],list[2],list[3]);
variables.Add(list[4] + '=' + a);
end;
end;
'print':
begin
Result := ParamCheckAtLeast(passed, 2);
if Result then
begin
a := '';
for i:=1 to passed -1 do
a := a + list[i];
ShowMessage(a);
end;
end;
{GoTo}
'goto':
begin
Result := ParamCheck(passed,2);
if Result then
begin
line := StrToInt(list[1]) - 2;
if line < 0 then
line := -1;
end;
end;
{Read values}
'getwidth':
begin
Result := ParamCheck(passed, 2);
if Result then
variables.Add(list[1] + '=' + IntToStr(bitmap.Width));
end;
'getheight':
begin
Result := ParamCheck(passed, 2);
if Result then
variables.Add(list[1] + '=' + IntToStr(bitmap.Height));
end;
{TFPCustomImage override}
'setsize':
begin
Result := ParamCheck(passed, 3);
if Result then
bitmap.SetSize(StrToInt(list[1]), StrToInt(list[2]));
end;
{Loading functions}
'savetofile':
begin
Result := ParamCheck(passed, 2);
if Result then
bitmap.SaveToFile(list[1]);
end;
{Pixel functions}
{Loading functions}
{* Horiz *}
'sethorizline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.SetHorizLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'xorhorizline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.XorHorizLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'drawhorizline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.DrawHorizLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'fastblendhorizline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.FastBlendHorizLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'alphahorizline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.AlphaHorizLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4]));
end;
{* Vert *}
'setvertline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.SetVertLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'xorvertline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.XorVertLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'drawvertline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.DrawVertLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'fastblendvertline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.FastBlendVertLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]));
end;
'alphavertline':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.AlphaVertLine(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4]));
end;
{* Misc *}
'drawhorizlinediff':
begin
Result := ParamCheck(passed, 7);
if Result then
bitmap.DrawHorizLineDiff(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToBGRA(list[4]), StrToBGRA(list[5]), StrToInt(list[6]));
end;
//---
'filltransparent':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.FillTransparent;
end;
'rectangle':
begin
Result := ParamCheck(passed, 8);
if Result then
bitmap.Rectangle(StrToInt(list[1]), StrToInt(list[2]), StrToInt(
list[3]), StrToInt(list[4]), StrToBGRA(list[5]), StrToBGRA(list[6]),
StrToDrawMode(list[7]));
end;
'rectangleantialias':
begin
Result := ParamCheck(passed, 8);
if Result then
bitmap.RectangleAntialias(StrToFloat(list[1]), StrToFloat(list[2]),
StrToFloat(list[3]), StrToFloat(list[4]), StrToBGRA(list[5]),
StrToFloat(list[6]), StrToBGRA(list[7]));
end;
{BGRA bitmap functions}
'verticalflip':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.VerticalFlip(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])));
end;
'horizontalflip':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.HorizontalFlip(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])));
end;
'rotatecw':
begin
Result := ParamCheck(passed, 1);
if Result then
try
tmpbmp1 := bitmap.RotateCW as TBGRABitmap;
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
finally
tmpbmp1.Free;
end;
end;
'rotateccw':
begin
Result := ParamCheck(passed, 1);
if Result then
try
tmpbmp1 := bitmap.RotateCCW as TBGRABitmap;
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
finally
tmpbmp1.Free;
end;
end;
'negative':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.Negative;
end;
'negativerect':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.NegativeRect(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])));
end;
'linearnegative':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.LinearNegative;
end;
'linearnegativerect':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.LinearNegativeRect(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])));
end;
'inplacegrayscale':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.InplaceGrayscale;
end;
'inplacegrayscalerect':
begin
Result := ParamCheck(passed, 5);
if Result then
bitmap.InplaceGrayscale(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])));
end;
'swapredblue':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.SwapRedBlue;
end;
'grayscaletoalpha':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.GrayscaleToAlpha;
end;
'alphatograyscale':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.AlphaToGrayscale;
end;
'applyglobalopacity':
begin
Result := ParamCheck(passed, 2);
if Result then
bitmap.ApplyGlobalOpacity(StrToInt(list[1]));
end;
'converttolinearrgb':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.ConvertToLinearRGB;
end;
'convertfromlinearrgb':
begin
Result := ParamCheck(passed, 1);
if Result then
bitmap.ConvertFromLinearRGB;
end;
'drawcheckers':
begin
Result := ParamCheck(passed, 7);
if Result then
bitmap.DrawCheckers(Rect(StrToInt(list[1]), StrToInt(list[2]),
StrToInt(list[3]), StrToInt(list[4])), StrToBGRA(list[5]), StrToBGRA(list[6]));
end;
{Filters}
{Custom Functions}
'blendbitmap':
begin
Result := ParamCheck(passed, 5);
if Result then
try
tmpbmp1 := TBGRABitmap.Create(list[3]);
bitmap.BlendImage(StrToInt(list[1]), StrToInt(list[2]), tmpbmp1,
StrToBlendOperation(list[4]));
finally
tmpbmp1.Free;
end;
end;
'blendbitmapover':
begin
Result := ParamCheck(passed, 7);
if Result then
try
tmpbmp1 := TBGRABitmap.Create(list[3]);
bitmap.BlendImageOver(StrToInt(list[1]), StrToInt(list[2]),
tmpbmp1, StrToBlendOperation(list[4]), StrToInt(list[5]),
StrToBool(list[6]));
finally
tmpbmp1.Free;
end;
end;
'applybitmapmask':
begin
Result := ParamCheck(passed, 8);
if Result then
try
tmpbmp1 := TBGRABitmap.Create(list[1]);
bitmap.ApplyMask(tmpbmp1, Rect(StrToInt(list[2]), StrToInt(
list[3]), StrToInt(list[4]), StrToInt(list[5])), Point(
StrToInt(list[6]), StrToInt(list[7])));
finally
tmpbmp1.Free;
end;
end;
'filterfastblur':
begin
Result := ParamCheck(passed, 3);
if Result then
begin
tmpbmp1 := bitmap.FilterBlurRadial(StrToInt(list[1]), rbFast) as TBGRABitmap;
if StrToBool(list[2]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filtersmooth':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterSmooth as TBGRABitmap;
if StrToBool(list[1]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filtersharpen':
begin
Result := ParamCheck(passed, 3);
if Result then
begin
tmpbmp1 := bitmap.FilterSharpen(StrToInt(list[1])) as TBGRABitmap;
if StrToBool(list[2]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filtercontour':
begin
Result := ParamCheck(passed, 1);
if Result then
begin
tmpbmp1 := bitmap.FilterContour as TBGRABitmap;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filteremboss':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterEmboss(StrToFloat(list[1])) as TBGRABitmap;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filternormalize':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterNormalize(StrToBool(list[1])) as TBGRABitmap;
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filtersphere':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterSphere as TBGRABitmap;
if StrToBool(list[1]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filtercylinder':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterCylinder as TBGRABitmap;
if StrToBool(list[1]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'filterplane':
begin
Result := ParamCheck(passed, 2);
if Result then
begin
tmpbmp1 := bitmap.FilterPlane as TBGRABitmap;
if StrToBool(list[1]) then
bitmap.FillTransparent;
bitmap.BlendImage(0, 0, tmpbmp1, boLinearBlend);
tmpbmp1.Free;
end;
end;
'//':
begin
// comment
end;
'{':
begin
{ comment }
end;
else
begin
{$ifdef debug}
writeln('>> Command "' + list[0] + '" not found.');
{$endif}
Result := False;
end;
end;
{$ifdef debug}
if not Result then
writeln('>> ERROR');
for i := 0 to list.Count - 1 do
writeln(' ' + list[i]);
writeln('____________________');
{$endif}
list.Free;
end;
function ScriptCommandList(commandlist: TStrings; var bitmap: TBGRABitmap): boolean;
var
line: integer;
variables: TStringList;
begin
{$ifdef debug}
//writeln('----SCRIPT--LIST----');
writeln(' Executing ' + IntToStr(commandlist.Count) + ' lines...');
writeln('____________________');
{$endif}
variables := TStringList.Create;
{Result := True;
for i := 0 to commandlist.Count - 1 do
if commandlist[i] <> '' then
ScriptCommand(commandlist[i], bitmap, variables);
}
Result := True;
line := 0;
repeat
if commandlist[line] <> '' then
ScriptCommand(commandlist[line], bitmap, variables, line);
Inc(line);
until line > commandList.Count;
variables.Free;
{$ifdef debug}
//writeln('----SCRIPT--LIST----');
writeln(' END');
writeln('____________________');
{$endif}
end;
function StrToDrawMode(mode: string): TDrawMode;
begin
case LowerCase(mode) of
'dmset': Result := dmSet;
'dmsetexcepttransparent': Result := dmSetExceptTransparent;
'dmlinearblend': Result := dmLinearBlend;
'dmdrawwithtransparency': Result := dmDrawWithTransparency;
'dmxor': Result := dmXor;
else
Result := dmDrawWithTransparency;
end;
end;
end.
|
unit HtmlDownloader;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,IdHTTP;
type
THtmlDownloader = class(TObject)
public
function download(url) : string;
end;
implementation
{ THtmlDownloader }
function THtmlDownloader.download(url): string;
var
idc : TIdHTTP;
stream : TStringStream;
begin
Result := '';
if Trim(url) = '' then
Exit;
idc := TIdHTTP.Create(nil);
try
idc.Get(url,stream);
except
on e : Exception do
begin
ShowMessage(e.Message);
end;
end;
Result := stream.DataString;
end;
end.
|
unit UniDBAccessesImpl;
interface
uses Windows, SysUtils, Classes, DB, Uni, HJYDBAccesses, HJYStoreProcParams,
UniProvider, Provider, DBClient, MySQLUniProvider, SQLiteUniProvider, HJYSyncObjs;
const
sSQLiteProvide = 'SQLite';
sMySQLProvide = 'MySQL';
type
TConnectionProp = record
Provider: string;
Server: string;
UserName: string;
Password: string;
Database: string;
Port: Integer;
UseUnicode: Boolean;
end;
THJYUniDBAccess = class(TInterfacedObject, IHJYDBAccess)
private
FConnectionProp: TConnectionProp;
FConnection: TUniConnection;
FCommand: TUniQuery;
FDspPublic: TDataSetProvider;
FQueryPublic: TUniQuery;
FRetMsg: string;
FExecCS: THJYCriticalSection;
FQueryCS: THJYCriticalSection;
procedure SetConnectionProp(AConnProp: TConnectionProp);
procedure DoExecSQL(AQuery: TUniQuery; ASQL: string);
procedure DoQuery(AQuery: TUniQuery; ASQL: string);
public
constructor Create(AConnProp: TConnectionProp);
destructor Destroy; override;
procedure BeginTrans;
procedure CommitTrans;
procedure RollbackTrans;
{ IHJYDBAccess }
function GetRetMsg: string;
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
//function Query(ACds: TClientDataSet; ASQL: string): Boolean;
function Query(ACds: TClientDataSet; ASQL: string): Boolean; overload;
function Query(ACdsArr: array of TClientDataSet; AList: TStrings): Boolean; overload;
function ExecSQL(ASQL: string): Boolean;
function ExecSQLs(AList: TStrings): Boolean;
function ApplyUpdates(ACds: TClientDataSet; ATableName, AKeyField: string): Boolean;
function GetSQLIntegerValue(ASQL: string; var Value: Integer): Boolean;
function GetSQLFloatValue(ASQL: string; var Value: Double): Boolean;
function GetSQLStringValue(ASQL: string; var Value: string): Boolean;
procedure WriteToList(ACds: TClientDataSet; AList: TStrings);
function ExecuteStoredProc(AStoredProcName: string;
AParams: THJYStoreProcParams): Boolean;
function QueryStoredProc(ACds: TClientDataSet;
AStoredProcName: string; AParams: THJYStoreProcParams): Boolean;
procedure ExecSQLEx(ASQL: string);
procedure QueryEx(ACds: TClientDataSet; ASQL: string);
end;
implementation
uses HJYLoggers, HJYDBUtils;
{ THJYUniDBAccess }
procedure THJYUniDBAccess.SetConnectionProp(AConnProp: TConnectionProp);
begin
FConnectionProp := AConnProp;
with FConnection do
begin
if Connected then
Connected := False;
LoginPrompt := False;
SpecificOptions.Clear;
ProviderName := AConnProp.Provider;
Database := AConnProp.Database;
// 如果数据库字符集为utf8,不设置UseUnicode属性会显示乱码
if AConnProp.UseUnicode then
SpecificOptions.Add(AConnProp.Provider + '.UseUnicode=True');
if SameText(AConnProp.Provider, sSQLiteProvide) then
begin
// SQLite数据库加密需要通过 SQLite.EncryptionKey 属性传入密码
SpecificOptions.Add(AConnProp.Provider + '.EncryptionKey=' + AConnProp.Password);
end
else
begin
Server := AConnProp.Server;
Username := AConnProp.UserName;
Password := AConnProp.Password;
Port := AConnProp.Port;
end;
end;
end;
procedure THJYUniDBAccess.WriteToList(ACds: TClientDataSet; AList: TStrings);
var
Bm: TBookmark;
begin
AList.Clear;
if not ACds.Active or ACds.IsEmpty then
Exit;
with ACds do
begin
Bm := GetBookmark;
DisableControls;
AList.BeginUpdate;
try
First;
while not Eof do
begin
AList.Add(Fields[0].AsString);
Next;
end;
finally
AList.EndUpdate;
EnableControls;
GotoBookmark(Bm);
FreeBookmark(Bm);
end;
end;
end;
constructor THJYUniDBAccess.Create(AConnProp: TConnectionProp);
begin
FConnection := TUniConnection.Create(nil);
FCommand := TUniQuery.Create(nil);
FCommand.Connection := FConnection;
FQueryPublic := TUniQuery.Create(nil);
FQueryPublic.Connection := FConnection;
FDspPublic := TDataSetProvider.Create(nil);
FDspPublic.DataSet := FQueryPublic;
FExecCS := THJYCriticalSection.Create;
FQueryCS := THJYCriticalSection.Create;
SetConnectionProp(AConnProp);
end;
destructor THJYUniDBAccess.Destroy;
begin
FExecCS.Free;
FQueryCS.Free;
FDspPublic.Free;
FCommand.Free;
if FConnection.Connected then
FConnection.Connected := False;
FConnection.Free;
inherited;
end;
procedure THJYUniDBAccess.DoExecSQL(AQuery: TUniQuery; ASQL: string);
begin
AQuery.Close;
AQuery.Connection := FConnection;
AQuery.SQL.Text := ASQL;
AQuery.ExecSQL;
end;
procedure THJYUniDBAccess.DoQuery(AQuery: TUniQuery; ASQL: string);
begin
if AQuery.Active then
AQuery.Close;
AQuery.Connection := FConnection;
AQuery.SQL.Text := ASQL;
AQuery.Open;
end;
procedure THJYUniDBAccess.SetConnected(const Value: Boolean);
begin
if FConnection.Connected <> Value then
FConnection.Connected := Value;
end;
function THJYUniDBAccess.ApplyUpdates(ACds: TClientDataSet;
ATableName, AKeyField: string): Boolean;
var
lList: TStrings;
begin
lList := TStringList.Create;
try
GenerateClientDataSetSQLs(ACds, ATableName, AKeyField, lList);
Result := ExecSQLs(lList);
finally
lList.Free;
end;
end;
procedure THJYUniDBAccess.BeginTrans;
begin
FConnection.StartTransaction;
end;
procedure THJYUniDBAccess.CommitTrans;
begin
FConnection.Commit;
end;
procedure THJYUniDBAccess.RollbackTrans;
begin
FConnection.Rollback;
end;
function THJYUniDBAccess.ExecSQL(ASQL: string): Boolean;
begin
FExecCS.Enter;
try
try
DoExecSQL(FCommand, ASQL);
Result := True;
except
on E: Exception do
begin
Result := False;
FRetMsg := E.Message;
RealtimeLog('ExecSQL Exception:' + E.Message);
end;
end;
finally
FExecCS.Leave;
end;
end;
procedure THJYUniDBAccess.ExecSQLEx(ASQL: string);
var
lvQuery: TUniQuery;
begin
lvQuery := TUniQuery.Create(nil);
try
DoExecSQL(lvQuery, ASQL);
finally
FreeAndNil(lvQuery);
end;
end;
function THJYUniDBAccess.ExecSQLs(AList: TStrings): Boolean;
var
I: Integer;
begin
FExecCS.Enter;
try
BeginTrans;
try
for I := 0 to AList.Count - 1 do
DoExecSQL(FCommand, AList[I]);
CommitTrans;
Result := True;
except
on E: Exception do
begin
Result := False;
RollbackTrans;
FRetMsg := E.Message;
RealtimeLog('ExecSQLs Exception:' + E.Message);
end;
end;
finally
FExecCS.Leave;
end;
end;
function THJYUniDBAccess.ExecuteStoredProc(AStoredProcName: string;
AParams: THJYStoreProcParams): Boolean;
begin
Result := True;
end;
function THJYUniDBAccess.GetConnected: Boolean;
begin
Result := FConnection.Connected;
end;
function THJYUniDBAccess.GetRetMsg: string;
begin
Result := FRetMsg;
end;
function THJYUniDBAccess.GetSQLFloatValue(ASQL: string; var Value: Double): Boolean;
begin
try
with TUniQuery.Create(nil) do
try
Connection := FConnection;
SQL.Text := ASQL;
Open;
Value := Fields[0].AsFloat;
Result := True;
finally
Free;
end;
except
on E: Exception do
begin
Result := False;
FRetMsg := E.Message;
RealtimeLog('GetSQLFloatValue Exception:' + E.Message);
end;
end;
end;
function THJYUniDBAccess.GetSQLIntegerValue(ASQL: string; var Value: Integer): Boolean;
begin
try
with TUniQuery.Create(nil) do
try
Connection := FConnection;
SQL.Text := ASQL;
Open;
Value := Fields[0].AsInteger;
Result := True;
finally
Free;
end;
except
on E: Exception do
begin
Result := False;
FRetMsg := E.Message;
RealtimeLog('GetSQLIntegerValue Exception:' + E.Message);
end;
end;
end;
function THJYUniDBAccess.GetSQLStringValue(ASQL: string; var Value: string): Boolean;
begin
try
with TUniQuery.Create(nil) do
try
Connection := FConnection;
SQL.Text := ASQL;
Open;
Value := Fields[0].AsString;
Result := True;
finally
Free;
end;
except
on E: Exception do
begin
Result := False;
FRetMsg := E.Message;
RealtimeLog('GetSQLStringValue Exception:' + E.Message);
end;
end;
end;
function THJYUniDBAccess.Query(ACds: TClientDataSet; ASQL: string): Boolean;
begin
FQueryCS.Enter;
try
try
if ACds.Active then
ACds.Close;
DoQuery(FQueryPublic, ASQL);
ACds.Data := FDspPublic.Data;
FQueryPublic.Close;
Result := True;
except
on E: Exception do
begin
Result := False;
FRetMsg := E.Message;
RealtimeLog('Query Exception:' + E.Message);
end;
end;
finally
FQueryCS.Leave;
end;
end;
function THJYUniDBAccess.Query(ACdsArr: array of TClientDataSet;
AList: TStrings): Boolean;
var
I: Integer;
begin
Result := False;
if AList.Count = 0 then Exit;
if AList.Count <> (Length(ACdsArr)) then Exit;
for I := 0 to Length(ACdsArr) - 1 do
ACdsArr[I].Active := False;
for I := 0 to Length(ACdsArr) - 1 do
if Query(ACdsArr[I], AList[I]) then
Exit;
Result := True;
end;
procedure THJYUniDBAccess.QueryEx(ACds: TClientDataSet; ASQL: string);
var
lvDsp: TDataSetProvider;
lvQry: TUniQuery;
begin
if ACds.Active then
ACds.Close;
lvQry := TUniQuery.Create(nil);
lvDsp := TDataSetProvider.Create(nil);
try
lvDsp.DataSet := lvQry;
DoQuery(lvQry, ASQL);
ACds.Data := lvDsp.Data;
finally
FreeAndNil(lvDsp);
FreeAndNil(lvQry);
end;
end;
function THJYUniDBAccess.QueryStoredProc(ACds: TClientDataSet;
AStoredProcName: string; AParams: THJYStoreProcParams): Boolean;
begin
Result := True;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado às tabelas [PRE_VENDA_CABECALHO e PRE_VENDA_DETALHE]
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</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit PreVendaController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos,
VO, PreVendaCabecalhoVO, PreVendaDetalheVO, Generics.Collections, Biblioteca;
type
TPreVendaController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TPreVendaCabecalhoVO>;
class function ConsultaObjeto(pFiltro: String): TPreVendaCabecalhoVO;
class procedure Insere(pObjeto: TPreVendaCabecalhoVO);
class function Altera(pObjeto: TPreVendaCabecalhoVO): 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 T2TiORM;
class procedure TPreVendaController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TPreVendaCabecalhoVO>;
begin
try
Retorno := TT2TiORM.Consultar<TPreVendaCabecalhoVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TPreVendaCabecalhoVO>(Retorno);
finally
end;
end;
class function TPreVendaController.ConsultaLista(pFiltro: String): TObjectList<TPreVendaCabecalhoVO>;
begin
try
Result := TT2TiORM.Consultar<TPreVendaCabecalhoVO>(pFiltro, '-1', True);
finally
end;
end;
class function TPreVendaController.ConsultaObjeto(pFiltro: String): TPreVendaCabecalhoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TPreVendaCabecalhoVO>(pFiltro, True);
finally
end;
end;
class procedure TPreVendaController.Insere(pObjeto: TPreVendaCabecalhoVO);
var
PreVendaDetalheEnumerator: TEnumerator<TPreVendaDetalheVO>;
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
// Detalhes
try
PreVendaDetalheEnumerator := pObjeto.ListaPreVendaDetalheVO.GetEnumerator;
with PreVendaDetalheEnumerator do
begin
while MoveNext do
begin
Current.IdPreVendaCabecalho := UltimoID;
TT2TiORM.Inserir(Current);
end;
end;
finally
FreeAndNil(PreVendaDetalheEnumerator);
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPreVendaController.Altera(pObjeto: TPreVendaCabecalhoVO): Boolean;
var
PreVendaDetalheEnumerator: TEnumerator<TPreVendaDetalheVO>;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
// Detalhes
try
PreVendaDetalheEnumerator := pObjeto.ListaPreVendaDetalheVO.GetEnumerator;
with PreVendaDetalheEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdPreVendaCabecalho := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(PreVendaDetalheEnumerator);
end;
finally
end;
end;
class function TPreVendaController.Exclui(pId: Integer): Boolean;
begin
try
raise Exception.Create('Não é permitido excluir uma PreVenda.');
finally
end;
end;
class function TPreVendaController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TPreVendaController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TPreVendaController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TPreVendaCabecalhoVO>(TObjectList<TPreVendaCabecalhoVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TPreVendaController);
finalization
Classes.UnRegisterClass(TPreVendaController);
end.
|
unit rescanhelper;
{$MODE Delphi}
interface
{$ifdef darwin}
uses macport, LCLIntf, classes, symbolhandler, CEFuncProc,NewKernelHandler, maps,
sysutils, syncobjs, pagemap, Sockets, (*CELazySocket, PointerscanNetworkCommands, *)
zstream, commonTypeDefs;
{$endif}
{$ifdef windows}
uses windows, LCLIntf, classes, symbolhandler, CEFuncProc,NewKernelHandler, maps,
sysutils, syncobjs, pagemap, Sockets, CELazySocket, PointerscanNetworkCommands,
zstream, commonTypeDefs;
{$endif}
type
TRescanHelper=class
private
pagemap: TPageMap;
pagemapcs: TCriticalsection;
memoryregion: TMemoryRegions;
function BinSearchMemRegions(address: ptrUint): integer;
procedure quicksortmemoryregions(lo,hi: integer);
public
function ispointer(address: ptrUint): boolean;
function GetMemoryRegion(Address: ptruint): TMemoryRegion;
function FindPage(index: ptruint): TPageInfo;
function getMemoryRegions: TMemoryRegions;
constructor create;
destructor destroy; override;
end;
implementation
uses ProcessHandlerUnit, Globals;
function TRescanHelper.BinSearchMemRegions(address: ptrUint): integer;
var
First: Integer;
Last: Integer;
Found: Boolean;
Pivot: integer;
begin
First := 0; //Sets the first item of the range
Last := length(memoryregion)-1; //Sets the last item of the range
Found := False; //Initializes the Found flag (Not found yet)
Result := -1; //Initializes the Result
while (First <= Last) and (not Found) do
begin
//Gets the middle of the selected range
Pivot := (First + Last) div 2;
//Compares the String in the middle with the searched one
if (address >= memoryregion[Pivot].BaseAddress) and (address<memoryregion[Pivot].BaseAddress+memoryregion[Pivot].MemorySize) then
begin
Found := True;
Result := Pivot;
end
//If the Item in the middle has a bigger value than
//the searched item, then select the first half
else if memoryregion[Pivot].BaseAddress > address then
Last := Pivot - 1
//else select the second half
else
First := Pivot + 1;
end;
end;
function TRescanHelper.ispointer(address: ptrUint): boolean;
{
Check the memoryregion array for this address. If it's in, return true
}
begin
result:=BinSearchMemRegions(address)<>-1;
end;
function TRescanHelper.GetMemoryRegion(Address: ptruint): TMemoryRegion;
var i: integer;
begin
i:=BinSearchMemRegions(address);
if i<>-1 then
result:=memoryregion[BinSearchMemRegions(address)]
else
result.BaseAddress:=0;
end;
function TRescanHelper.findPage(Index: ptrUint): TPageInfo;
{
will find the pageinfo. If not found, it will add it
}
var
pi: TPageInfo;
x: ptruint;
r: PPageInfo;
begin
//the old method is faster, but has a small threading issue where adding new entries would lead to a memory leak if multiple threads added the same thing
r:=pagemap.GetPageInfo(index);
if r=nil then
begin
//not yet added, add it to the list
pi.data:=nil;
if ispointer(index shl 12) then
begin
//save the data
{if socket>=0 then
begin
result:=DownloadPages(index shl 12);
exit;
end
else }
begin
getmem(pi.data, 4096);
if ReadProcessMemory(ProcessHandle, pointer(index shl 12), pi.data, 4096, x)=false then
begin
//unexpected failure reading the memory
freememandnil(pi.data);
end;
end;
end;
pagemapcs.enter; //adding on the other hand does require a lock, as it needs to fidn out where to add it, and what variables to initialize to what value (next/previous)
r:=pagemap.GetPageInfo(index);
if r=nil then
begin
//not yet added by another thread
//add it
pagemap.Add(index, pi.data);
result:=pi;
end
else
begin
//another thread added it, abort
if pi.data<>nil then
freememandnil(pi.data);
result:=r^;
end;
pagemapcs.Leave;
end
else //found:
result:=r^;
end;
function TRescanHelper.getMemoryRegions: TMemoryRegions;
begin
result:=memoryregion;
end;
procedure TRescanHelper.quicksortmemoryregions(lo,hi: integer);
var i,j: integer;
x,h: TMemoryRegion;
begin
i:=lo;
j:=hi;
if hi<0 then exit;
x:=memoryregion[(lo+hi) div 2];
repeat
while (memoryregion[i].BaseAddress<x.BaseAddress) do inc(i);
while (memoryregion[j].BaseAddress>x.BaseAddress) do dec(j);
if i<=j then
begin
h:=memoryregion[i];
memoryregion[i]:=memoryregion[j];
memoryregion[j]:=h;
inc(i);
dec(j);
end;
until i>j;
if (lo<j) then quicksortmemoryregions(lo,j);
if (i<hi) then quicksortmemoryregions(i,hi);
end;
constructor TRescanHelper.create;
var
mbi : _MEMORY_BASIC_INFORMATION;
address: ptrUint;
i: integer;
begin
pagemap:=TPageMap.Create;
pagemapcs:=TCriticalSection.create;
//enumerate all memory regions
address:=0;
while (Virtualqueryex(processhandle,pointer(address),mbi,sizeof(mbi))<>0) and ((address+mbi.RegionSize)>address) do
begin
if (not symhandler.inSystemModule(ptrUint(mbi.baseAddress))) and (not (not scan_mem_private and (mbi._type=mem_private))) and (not (not scan_mem_image and (mbi._type=mem_image))) and (not (not scan_mem_mapped and ((mbi._type and mem_mapped)>0))) and (mbi.State=mem_commit) and ((mbi.Protect and page_guard)=0) and ((mbi.protect and page_noaccess)=0) then //look if it is commited
begin
if Skip_PAGE_NOCACHE then
if (mbi.AllocationProtect and PAGE_NOCACHE)=PAGE_NOCACHE then
begin
address:=ptrUint(mbi.BaseAddress)+mbi.RegionSize;
continue;
end;
{$ifdef windows}
if Skip_PAGE_WRITECOMBINE then
if (mbi.AllocationProtect and PAGE_WRITECOMBINE)=PAGE_WRITECOMBINE then
begin
address:=ptrUint(mbi.BaseAddress)+mbi.RegionSize;
continue;
end;
{$endif}
setlength(memoryregion,length(memoryregion)+1);
memoryregion[length(memoryregion)-1].BaseAddress:=ptrUint(mbi.baseaddress); //just remember this location
memoryregion[length(memoryregion)-1].MemorySize:=mbi.RegionSize;
end;
address:=ptrUint(mbi.baseaddress)+mbi.RegionSize;
end;
//sort memoryregions from small to high
quicksortmemoryregions(0,length(memoryregion)-1);
end;
destructor TRescanHelper.destroy;
var i: integer;
data: PByteArray;
begin
setlength(memoryregion,0);
pagemapcs.free;
pagemap.Free;
inherited destroy;
end;
end.
|
unit Rand;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TEntropyAccumulator }
TEntropyAccumulator = class(TObject)
private
FArray: array[1..8] of Integer;
FMaxBits: Integer;
FStream: TMemoryStream;
FCounter: Byte;
FAccumulator: Cardinal;
FQuality: Double;
FOnEntropy: TNotifyEvent;
function GetData: Pointer;
function GetNumBits: Integer;
function GetSize: Integer;
procedure UpdateStats(DW: Cardinal);
public
constructor Create;
destructor Destroy;
//
procedure Reset;
procedure MouseMove(X,Y: Integer);
function Read: Cardinal;
property Data: Pointer read GetData;
property Size: Integer read GetSize;
property NumBits: Integer read GetNumBits;
property Quality: Double read FQuality;
property MaxBits: Integer read FMaxBits write FMaxBits;
property OnEntropy: TNotifyEvent read FOnEntropy write FOnEntropy;
end;
{ TLinearFeedbackShiftRegister }
TLinearFeedbackShiftRegister = class(TObject)
private
FSeed: Cardinal;
FCurrent: Cardinal;
procedure SetSeed(AValue: Cardinal);
public
constructor Create(ASeed: Cardinal = 0);
function Next: Cardinal;
procedure Reset;
property Seed: Cardinal read FSeed write SetSeed;
end;
{ TRandomNumberGenerator }
TRandomNumberGenerator = class(TObject)
private
FLFSR: TLinearFeedbackShiftRegister;
FEntropy: TEntropyAccumulator;
public
constructor Create;
destructor Destroy; override;
function Generate: Cardinal;
//
property Entropy: TEntropyAccumulator read FEntropy write FEntropy;
end;
var
RNG: TRandomNumberGenerator;
procedure FillRandom(Data: Pointer; Size: Integer);
implementation
uses
DateUtils, CryptoUtils;
procedure FillRandom(Data: Pointer; Size: Integer);
var
X: Integer;
R: Cardinal;
begin
for X := 1 to Size div 4 do
begin
R := RNG.Generate;
System.Move(R,Pointer(PtrUInt(Data)+((X-1) * SizeOf(R)))^,SizeOf(R));
end;
X := Size mod 4;
if X > 0 then
begin
R := RNG.Generate;
System.Move(R,Pointer(PtrUInt(Data)+((Size div 4) * SizeOf(R)))^,X);
end;
end;
{ TLinearFeedbackShiftRegister }
constructor TLinearFeedbackShiftRegister.Create(ASeed: Cardinal = 0);
begin
if ASeed = 0 then
Seed := Random($FFFFFFFE) + 1
else
Seed := ASeed;
end;
procedure TLinearFeedbackShiftRegister.SetSeed(AValue: Cardinal);
begin
if AValue = 0 then
AValue := $FFFFFFFF;
FSeed := AValue;
FCurrent := AValue;
end;
function TLinearFeedbackShiftRegister.Next: Cardinal;
begin
Result := LFSR(FCurrent);
if FCurrent = 0 then
FCurrent := $FFFFFFFF;
end;
procedure TLinearFeedbackShiftRegister.Reset;
begin
FCurrent := FSeed;
end;
{ TRandomNumberGenerator }
constructor TRandomNumberGenerator.Create;
begin
FLFSR := TLinearFeedbackShiftRegister.Create;
end;
destructor TRandomNumberGenerator.Destroy;
begin
FLFSR.Free;
inherited Destroy;
end;
function TRandomNumberGenerator.Generate: Cardinal;
begin
Result := FLFSR.Next xor Random($FFFFFFFF);
if (FEntropy <> nil) and (FEntropy.Size > SizeOf(Cardinal)) then
Result := FEntropy.Read xor Result;
end;
{ TEntropyAccumulator }
constructor TEntropyAccumulator.Create;
begin
FStream := TMemoryStream.Create;
FMaxBits := 2048;
FAccumulator := Random($FFFFFFFF);
end;
destructor TEntropyAccumulator.Destroy;
begin
FStream.Destroy;
end;
procedure TEntropyAccumulator.Reset;
var
X: Integer;
begin
FStream.Size := 0;
FQuality := 0;
FCounter := 0;
for X := 1 to 8 do
FArray[X] := 0;
end;
function TEntropyAccumulator.GetData: Pointer;
begin
Result := FStream.Memory;
end;
function TEntropyAccumulator.GetNumBits: Integer;
begin
Result := FStream.Size * 8;
end;
function TEntropyAccumulator.GetSize: Integer;
begin
Result := FStream.Size;
end;
procedure TEntropyAccumulator.UpdateStats(DW: Cardinal);
var
D: array[1..4] of Integer;
Q: Double;
X: Integer;
B: Byte;
begin
D[1] := DW and $FF;
D[2] := (DW and $FF00) shr 8;
D[3] := (DW and $FF0000) shr 16;
D[4] := (DW and $FF000000) shr 24;
// inc/dec bit array
for X := 1 to 4 do
begin
B := D[X];
if B and $80 > 0 then inc(FArray[1]) else dec(FArray[1]);
if B and $40 > 0 then inc(FArray[2]) else dec(FArray[2]);
if B and $20 > 0 then inc(FArray[3]) else dec(FArray[3]);
if B and $10 > 0 then inc(FArray[4]) else dec(FArray[4]);
if B and $8 > 0 then inc(FArray[5]) else dec(FArray[5]);
if B and $4 > 0 then inc(FArray[6]) else dec(FArray[6]);
if B and $2 > 0 then inc(FArray[7]) else dec(FArray[7]);
if B and $1 > 0 then inc(FArray[8]) else dec(FArray[8]);
end;
// Calculate a quality score
Q := 0;
for X := 1 to 8 do
Q := Q + (1-(Abs(FArray[X])/FStream.Size))*100;
FQuality := Q / 8;
end;
procedure TEntropyAccumulator.MouseMove(X, Y: Integer);
var
B,S: Byte;
Q: Cardinal = 0;
begin
if FStream.Size < (FMaxBits div 8) then
begin
if FCounter mod 2 = 1 then
B := ((X mod 16) shl 4) + (y mod 16)
else
B := ((Y mod 16) shl 4) + (X mod 16);
S := (FCounter mod 4) * 8;
Q := B shl S;
FAccumulator := LFSR(FAccumulator) xor Q;
inc(FCounter);
if FCounter mod 16 = 0 then
begin
FStream.Write(FAccumulator,SizeOf(Cardinal));
UpdateStats(FAccumulator);
end;
if FCounter = 128 then FCounter := 0;
if Assigned(FOnEntropy) and (FStream.Size >= (FMaxBits div 8)) then
FOnEntropy(Self);
end;
end;
function TEntropyAccumulator.Read: Cardinal;
begin
if FStream.Size > SizeOf(Cardinal) then
begin
FStream.Position := FStream.Size - SizeOf(Cardinal);
FStream.Read(Result,SizeOf(Result));
FStream.Size := FStream.Size - SizeOf(Cardinal);
end
else
Result := Random($FFFFFFFF);
end;
initialization
Randomize;
RNG := TRandomNumberGenerator.Create;
finalization
RNG.Free;
end.
|
unit lookup;
interface
uses Classes, SysUtils, iterators, strsim, csv;
type
TCSVLookup = class(TObject)
private
FData: PStringList;
function GetData (F: Integer): String;
public
constructor Create (fn: String; key: Integer; value: String);
destructor Destroy; override;
property Data[Index: Integer]: String read GetData;
end;
implementation
constructor TCSVLookup.Create (fn: String; key: Integer; value: String);
var maxset,tmp: PStringList;
maxscore,diff: Single;
FCSV: TStringList;
j:Integer;
begin
inherited Create;
FCSV := TStringList.Create;
FCSV.LoadFromFile(fn);
maxset := nil;
maxscore := -1;
for j := 0 to FCSV.Count-1 do begin
tmp := CSVSplit(FCSV.Strings[j]);
diff := StrDiff(tmp.Strings[key], value);
// Store the one that relates best to comparison value
if diff > maxscore then begin
if maxset <> nil then begin
maxset^.Free;
FreeMem(maxset);
end;
maxset := tmp;
maxscore := diff;
end else begin
tmp^.Free;
FreeMem(tmp);
end;
end;
FCSV.Free;
FData := maxset;
end;
destructor TCSVLookup.Destroy;
begin
if FData <> nil then begin
FData^.Free;
end;
inherited Destroy;
end;
function TCSVLookup.GetData (F: Integer): String;
begin
Result := FData^.Strings[F];
end;
end.
|
unit App.Model.Cliente;
interface
uses
Dialogs, SysUtils, System.Classes;
type
//json.Text := TJson.ObjectToJsonString(CooperadoDTO);
TClienteDetail = class(TPersistent)
private
FCPFCNPJ: String;
FRenda: Double;
FIdade: Integer;
FNome: String;
FRG: String;
FDataNascimento: TDatetime;
FAtivo: String;
FNomeFantasia: String;
FApelido: String;
FSituacao: String;
FTipo: String;
FEstadoCivil: String;
FObservacao: String;
FEmail: String;
FCalcRenda: Double;
published
property Nome: String read FNome write FNome;
property NomeFantasia: String read FNomeFantasia write FNomeFantasia;
property CPFCNPJ: String read FCPFCNPJ write FCPFCNPJ;
property Renda:Double read FRenda write FRenda;
property Idade: Integer read FIdade write FIdade;
property RG: String read FRG write FRG;
property DataNascimento:TDatetime read FDataNascimento write FDataNascimento;
property Ativo: String read FAtivo write FAtivo;
property Situacao:String read FSituacao write FSituacao;
property Tipo: String read FTipo write FTipo;
property EstadoCivil: String read FEstadoCivil write FEstadoCivil;
property Observacao:String read FObservacao write FObservacao;
property Email: String read FEmail write FEmail;
end;
implementation
initialization RegisterClass(TClienteDetail);
finalization UnRegisterClass(TClienteDetail);
end.
|
unit module_controller;
// PREPARE FOR MODULE CONTROLLER
{$mode objfpc}{$H+}
interface
uses
fpcgi, fpTemplate, fphttp, fpWeb, HTTPDefs, dateutils,
dynlibs,
Classes, SysUtils;
resourcestring
__err_module_call_failed = 'Failed call module "%s": %s';
type
// defined manually
THandle = DWord;
HWND = THandle;
TModuleCallResult = record
err: integer;
message: WideString;
ptr: Pointer;
end;
TModuleCall = function(AppHandle: HWND;
var ModuleResult: TModuleCallResult): Pointer; cdecl;
{ TModUtil }
TModUtil = class
private
FDirectory: string;
procedure SetDirectory(AValue: string);
public
constructor Create;
destructor Destroy; override;
property Directory: string read FDirectory write SetDirectory;
function Load(ModuleName: string): TLibHandle;
function Call(const ModuleName, FunctionName: string;
Parameter: array of string): TModuleCallResult;
end;
implementation
uses language_lib;
{ TModUtil }
procedure TModUtil.SetDirectory(AValue: string);
begin
if FDirectory = AValue then
Exit;
FDirectory := IncludeTrailingPathDelimiter(AValue);
end;
constructor TModUtil.Create;
begin
FDirectory := 'modules';
end;
destructor TModUtil.Destroy;
begin
inherited Destroy;
end;
// example
// ModUtl.Load('modulename');
function TModUtil.Load(ModuleName: string): TLibHandle;
var
lib_handle: TLibHandle;
begin
Result := 0;
{$ifdef windows}
ModuleName := ModuleName + '.dll';
{$else}
ModuleName := ModuleName + '.so';
{$endif}
if not FileExists(FDirectory + ModuleName) then
Exit;
lib_handle := LoadLibrary(PChar(FDirectory + ModuleName));
Result := lib_handle;
end;
// example
// Call( 'modulename', 'about', ['a=b','c=d']);
function TModUtil.Call(const ModuleName, FunctionName: string;
Parameter: array of string): TModuleCallResult;
var
lib_handle: TLibHandle;
function_pointer: pointer;
module_result: TModuleCallResult;
begin
Result.err := -1;
lib_handle := Load(ModuleName);
if lib_handle = 0 then
Exit;
try
function_pointer := GetProcAddress(lib_handle, FunctionName);
if function_pointer = nil then
begin
FreeLibrary(lib_handle);
Exit;
end;
TModuleCall(function_pointer)(0, module_result);
Result := module_result;
except
on e: Exception do
begin
Result.message := format(__(__err_module_call_failed), [ModuleName, e.Message]);
end;
end;
UnloadLibrary(lib_handle);
FreeLibrary(lib_handle);
end;
end.
|
unit NovusBasicStrParser;
interface
Uses NovusUtilities, NovusStringUtils, NovusParser, Classes,
SysUtils, StrUtils;
type
tNovusBasicStrParser = Class(tNovusParser)
private
FItems: TStringList;
stText : String; // The string passed to the constructor
stWordCount : Integer; // Internal count of words in the string
stFindString : String; // The substring used by FindFirst, FindNext
stFindPosition : Integer; // FindFirst/FindNext current position
procedure GetWordCount; // Calculates the word count
procedure SetText(const Value: String); // Changes the text string
// These methods and properties are all usable by instances of the class
published
// Called when creating an instance (object) from this class
// The passed string is the one that is operated on by the methods below
constructor Create(AText : String);
destructor Destroy; override;
// Utility to replace all occurences of a substring in the string
// The number of replacements is returned
// This utility is CASE SENSITIVE
function Replace(fromStr, toStr : String) : Integer;
// Utility to find the first occurence of a substring in the string
// The returned value is the found string position (strings start at 1)
// if not found, -1 is returned
// This utility is CASE SENSITIVE
function FindFirst(search : String) : Integer;
// Utility to find the next occurence of the FindFirst substring
// if not found, -1 is returned
// if no FindFirst performed before this call, -2 is returned
// This utility is CASE SENSITIVE
function FindNext : Integer;
// The string itself - allow it to be read and overwritten
property Text : String
read stText
write SetText; // We call a method to do this
// The number of words in the document. Words are groups of characters
// separated by blanks, tabs, carriage returns and line feeds
property WordCount : Integer
read stWordCount;
property Items: TStringList
read FItems
write FItems;
end;
implementation
// Constructor : Create an instance of the class. Takes a string as argument.
// -----------------------------------------------------------------------------
// The passed string is stored, and the number of words it contains is counted
// The FindFirst function string and position are reset
constructor tNovusBasicStrParser.Create(AText: String);
begin
FItems := TStringList.Create;
stText := AText; // Save the passed string
stFindPosition := 1; // Start a search at the string start
stFindString := ''; // No find string provided yet
GetWordCount; // Call a subroutine to get the word count
end;
destructor tNovusBasicStrParser.destroy;
begin
inherited destroy;
end;
// SetText : Routine to change the text string
// -----------------------------------------------------------------------------
// It is important that we call a routine to change the text because we must
// recalculate the word length, and reposition the find function at the start
procedure tNovusBasicStrParser.SetText(const Value: String);
begin
stText := Value; // Save the passed string
stFindPosition := 1; // Reposition the find mechanism to the start
GetWordCount; // Recalculate the word count
end;
// FindFirst : Finds the first position of a substring in the string
// -----------------------------------------------------------------------------
// The passed substring is saved, and the string scanned for an occurence
// The found string index is returned. If not found, -1 is returned
function tNovusBasicStrParser.FindFirst(search: String): Integer;
begin
// Here we sort of cheat - we save the search string and just call
// FindNext after setting the initial string start conditions
stFindString := search;
stFindPosition := 1;
Result := FindNext;
end;
// FindNext : Finds the next occurence of the substring in the string
// -----------------------------------------------------------------------------
// If FindFirst had not been called, -2 is returned
// If FindFirst had been called, string scanning is resumed where the left off
// If found, the index position is returned. Of not found, -1 is returned.
function tNovusBasicStrParser.FindNext: Integer;
var
index : Integer;
findSize : Integer;
begin
/// Only scan if we have a valid scan string
if Length(stFindString) = 0
then Result := -2
else
begin
// Set the search string size
findSize := Length(stFindString);
// Set the result to the 'not found' value
Result := -1;
// Start the search from where we last left off
index := stFindPosition;
// Scan the string :
// We check for a match with the first character of the fromStr as we step
// along the string. Only when the first character matches do we compare
// the whole string. This is more efficient.
// We abort the loop if the string is found.
while (index <= Length(stText)) and (Result < 0) do
begin
// Check the first character of the search string
if stText[index] = stFindString[1] then
begin
// Now check the whole string - setting up a loop exit condition if
// the string matches
if AnsiMidStr(stText, index, findSize) = stFindString
then Result := index;
end;
// Move along the string
Inc(index);
end;
// Position the next search from where the above leaves off
// Notice that index gets incremented even with a successful match
stFindPosition := index
end;
// This subroutine will now exit with the established Result value
end;
// Replace : Replaces all occurences of a substring in the string
// -----------------------------------------------------------------------------
// The string is scanned for occurences of the string, replacing where found
// The number of replacements is returned, or 0 if none performed.
function tNovusBasicStrParser.Replace(fromStr, toStr: String): Integer;
var
fromSize, count, index : Integer;
newText : String;
matched : Boolean;
begin
// Get the size of the from string
fromSize := Length(fromStr);
// Start with 0 replacements
count := 0;
// We will build the target string in the newText variable
newText := '';
index := 1;
// Scan the string :
// We check for a match with the first character of the fromStr as we step
// along the string. Only when the first character matches do we compare
// the whole string. This is more efficient.
while index <= Length(stText) do
begin
// Indicate no match for this character
matched := false;
// Check the first character of the fromStr
if stText[index] = fromStr[1] then
begin
if AnsiMidStr(stText, index, fromSize) = fromStr then
begin
// Increment the replace count
Inc(count);
// Store the toStr in the target string
newText := newText + toStr;
// Move the index past the from string we just matched
Inc(index, fromSize);
// Indicate that we have a match
matched := true;
end;
end;
// if no character match :
if not matched then
begin
// Store the current character in the target string, and
// then skip to the next source string character
newText := newText + stText[index];
Inc(index);
end;
end;
// Copy the newly built string back to stText - as long as we made changes
if count > 0 then stText := newText;
// Return the number of replacements made
Result := count;
end;
// GetWordCount : Subroutine used to calculate the string word count
// -----------------------------------------------------------------------------
// The string is scanned for character groups (separated by blanks, tabs etc)
// The number found is stored in the csWordCount private global variable
procedure tNovusBasicStrParser.GetWordCount;
const
// Define word separator types that we will recognise
LF = #10;
TAB = #9;
CR = #13;
BLANK = #32;
SEMICOL = ';';
EQUALS = '=';
var
lsWord: String;
WordSeparatorSet : Set of Char; // We will set on only the above characters
index : Integer; // Used to scan along the string
inWord : Boolean; // Indicates whether we are in the middle of a word
begin
// Turn on the TAB, CR, LF and BLANK characters in our word separator set
WordSeparatorSet := [LF, TAB, CR, BLANK, SEMICOL];
// Start with 0 words
stWordCount := 0;
// Scan the string character by character looking for word separators
inWord := false;
lsWord := '';
for index := 1 to Length(stText) do
begin
// Have we found a separator character?
if stText[index] In WordSeparatorSet then
begin
// Separator found - have we moved from a word?
if inWord then
begin
FItems.Add(lsWord);
Inc(stWordCount); // Yes - we have ended another word
lsWord := '';
end;
// Indicate that we are not in a word anymore
inWord := false;
end
else
// Separator not found - we are in a word
inWord := true;
if InWord then
lsWord := lsWord + stText[index];
end;
// Finally, were we still in a word at the end of the string?
// if so, we must add one to the word count since we did not meet a separator
if inWord then
begin
FItems.Add(lsWord);
Inc(stWordCount);
end;
end;
end.
|
{
Assets manager.
Allows to check existence of used assets including textures, materials, etc. in meshes,
and copy assets used by a plugin to separate folder or create a list of files in different formats
including the CK assets list used for packaging using CK.
Please keep in mind that the script checks only explicitly used assets defined in records.
Implicitly used assets are not processed and you need to handle them yourself, for example:
- voice files
- facegen files
- worldspace LOD files
- animations *.kf and behaviours *.hkx
- race models
}
unit AssetsManager;
const
// asset type
atMesh = 1;
atTexture = 2;
atSound = 4;
atMusic = 8;
atPapyrusScript = 16;
atSeqFile = 32;
atLODAsset = 64;
atSpeedTree = 128;
atAnimation = 256;
atInterface = 512;
atMaterial = 1024;
atProgram = 2048;
// work mode
wmNone = 0;
wmCheck = 1;
wmList = 2;
wmListCSV = 3;
wmListJSON = 4;
wmCopy = 5;
// records to skip without assets
sSkipSignatures = 'REFR,ACHR,ACRE,PGRE,LAND,NAVM,PGRD';
// music record signature
sMusicSignatures = 'MUSC,MUST,MSET';
var
slAssetsType, slAssetsExt, sl, slRes, slDump: TStringList;
slContainers, slTextures, slChecksum: TwbFastStringList;
CurrentRecord: IInterface;
optAsset, optMode: integer;
optPath: string;
ResDescrPrefix: string;
ChecksumsFileName: string;
bSkipChecksum: boolean;
frm: TForm;
lbl: TLabel;
clbAssets, clbContainers: TCheckListBox;
mnPopup: TPopupMenu;
MenuItem: TMenuItem;
rbModeCheck, rbModeList, rbModeCopy: TRadioButton;
rgList: TRadioGroup;
edPath: TLabeledEdit;
chkSkipChecksums: TCheckBox;
btnChecksums, btnPath, btnOk, btnCancel: TButton;
//===========================================================================
procedure GetTexturesFromTextureSet(aSet: TwbNifBlock; sl: TStringList);
var
i: integer;
el: TdfElement;
begin
if not Assigned(aSet) then
Exit;
el := aSet.Elements['Textures'];
for i := 0 to Pred(el.Count) do
sl.Add(wbNormalizeResourceName(el[i].EditValue, resTexture));
end;
//===========================================================================
procedure GetTexturesFromMaterial(aFileName: string; sl: TStringList);
var
bgsm: TwbBGSMFile;
bgem: TwbBGEMFile;
i: integer;
el: TdfElement;
begin
if SameText(ExtractFileExt(aFileName), '.bgsm') then begin
bgsm := TwbBGSMFile.Create;
bgsm.LoadFromResource(aFileName);
el := bgsm.Elements['Textures'];
if Assigned(el) then
for i := 0 to Pred(el.Count) do
sl.Add(wbNormalizeResourceName(el[i].EditValue, resTexture));
bgsm.Free;
end
else if SameText(ExtractFileExt(aFileName), '.bgem') then begin
bgem := TwbBGEMFile.Create;
bgem.LoadFromResource(aFileName);
el := bgem.Elements['Textures'];
if Assigned(el) then
for i := 0 to Pred(el.Count) do
sl.Add(wbNormalizeResourceName(el[i].EditValue, resTexture));
bgem.Free;
end
end;
//===========================================================================
procedure GetNifAssets(aFileName: string; sl: TStringList);
var
nif: TwbNifFile;
Block: TwbNifBlock;
el: TdfElement;
s: string;
i: integer;
bMaterial: Boolean;
begin
nif := TwbNifFile.Create;
try
nif.LoadFromResource(aFileName);
// iterate over all blocks in a nif file and gather used assets
for i := 0 to Pred(Nif.BlocksCount) do begin
Block := Nif.Blocks[i];
if Block.BlockType = 'BSLightingShaderProperty' then begin
// check for material file in the Name field of FO4 meshes
bMaterial := False;
if nif.NifVersion = nfFO4 then begin
// if shader material is used, get textures from it
s := Block.EditValues['Name'];
if SameText(ExtractFileExt(s), '.bgsm') then begin
s := wbNormalizeResourceName(s, resMaterial);
sl.Add(s);
GetTexturesFromMaterial(s, sl);
bMaterial := True;
end;
// wet material
s := Block.EditValues['Wet Material'];
if SameText(ExtractFileExt(s), '.bgsm') then begin
s := wbNormalizeResourceName(s, resMaterial);
sl.Add(s);
GetTexturesFromMaterial(s, sl);
end;
end;
// no material used, get textures from texture set
if not bMaterial then
GetTexturesFromTextureSet(Block.Elements['Texture Set'].LinksTo, sl);
end
else if Block.BlockType = 'BSEffectShaderProperty' then begin
// check for material file in the Name field of FO4 meshes
bMaterial := False;
if nif.NifVersion = nfFO4 then begin
s := Block.EditValues['Name'];
// if effect material is used, get textures from it
if SameText(ExtractFileExt(s), '.bgem') then begin
s := wbNormalizeResourceName(s, resMaterial);
sl.Add(s);
GetTexturesFromMaterial(s, sl);
end;
end;
// no material used, get textures from effect shader
if not bMaterial then begin
sl.Add(wbNormalizeResourceName(Block.EditValues['Source Texture'], resTexture));
sl.Add(wbNormalizeResourceName(Block.EditValues['Grayscale Texture'], resTexture));
sl.Add(wbNormalizeResourceName(Block.EditValues['Env Map Texture'], resTexture));
sl.Add(wbNormalizeResourceName(Block.EditValues['Normal Texture'], resTexture));
sl.Add(wbNormalizeResourceName(Block.EditValues['Env Mask Texture'], resTexture));
end;
end
else if Block.BlockType = 'BSShaderPPLightingProperty' then
GetTexturesFromTextureSet(Block.Elements['Texture Set'].LinksTo, sl)
else if (Block.BlockType = 'BSShaderNoLightingProperty') or
(Block.BlockType = 'TallGrassShaderProperty') or
(Block.BlockType = 'TileShaderProperty')
then
sl.Add(wbNormalizeResourceName(Block.EditValues['File Name'], resTexture))
else if Block.BlockType = 'BSSkyShaderProperty' then
sl.Add(wbNormalizeResourceName(Block.EditValues['Source Name'], resTexture))
// any block inherited from NiTexture
else if Block.IsNiObject('NiTexture', True) then
sl.Add(wbNormalizeResourceName(Block.EditValues['File Name'], resTexture))
// linked *.hkx file
else if Block.BlockType = 'BSBehaviorGraphExtraData' then
sl.Add(wbNormalizeResourceName(Block.EditValues['Behavior Graph File'], resMesh))
// linked bone weights *.ssf file
else if Block.BlockType = 'BSSubIndexTriShape' then
sl.Add(wbNormalizeResourceName(Block.EditValues['Segment Data\SSF File'], resMesh));
end;
finally
nif.Free;
end;
end;
//===========================================================================
procedure PopupMenuClick(Sender: TObject);
begin
if TMenuItem(Sender).Tag = 1 then
clbContainers.CheckAll(cbChecked, False, False)
else
clbContainers.CheckAll(cbUnChecked, False, False);
end;
//===========================================================================
procedure rbModeClick(Sender: TObject);
begin
rgList.Enabled := rbModeList.Checked;
edPath.Enabled := rbModeCopy.Checked;
btnPath.Enabled := rbModeCopy.Checked;
chkSkipChecksums.Enabled := rbModeCopy.Checked and FileExists(ChecksumsFileName);
end;
//===========================================================================
procedure btnPathClick(Sender: TObject);
var
s: string;
begin
s := SelectDirectory('Destination path to copy files to', '', edPath.Text, nil);
if s <> '' then
edPath.Text := s;
end;
//===========================================================================
procedure btnChecksumsClick(Sender: TObject);
var
i, j: integer;
cont, fname: string;
slAssets: TStringList;
begin
if MessageDlg('Build checksums index of files from selected containers? Warning: this can take some time, wait for a message box to appear.', mtConfirmation, [mbOk, mbCancel], 0) <> mrOk then
Exit;
slAssets := TStringList.Create;
slChecksum.Clear;
for i := 0 to Pred(clbContainers.Items.Count) do begin
if not clbContainers.Checked[i] then
Continue;
cont := slContainers[i];
AddMessage('Building index for ' + clbContainers.Items[i]);
slAssets.Clear;
ResourceList(cont, slAssets);
for j := 0 to Pred(slAssets.Count) do begin
fname := slAssets[j];
// index only valid assets
try
if slAssetsExt.IndexOf(ExtractFileExt(fname)) <> -1 then
slChecksum.Values[fname] := IntToHex(wbCRC32Data(ResourceOpenData(cont, fname)), 8);
except
AddMessage('Error reading file ' + fname + ' from ' + cont);
Exit;
end;
end;
end;
if slChecksum.Count > 0 then begin
slChecksum.SaveToFile(ChecksumsFileName);
chkSkipChecksums.Enabled := rbModeCopy.Checked;
ShowMessage(Format('%d files were indexed.', [slChecksum.Count]));
end else
ShowMessage('Nothing to index.');
slAssets.Free;
end;
//===========================================================================
// on key down event handler for form
procedure frmFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
TForm(Sender).ModalResult := mrCancel;
end;
//===========================================================================
// on close event handler for form
procedure frmFormClose(Sender: TObject; var Action: TCloseAction);
begin
if frm.ModalResult <> mrOk then Exit;
if rbModeCopy.Checked and not DirectoryExists(edPath.Text) then begin
MessageDlg('Please select existing destination folder', mtInformation, [mbOk], 0);
Action := caNone;
end;
end;
//===========================================================================
procedure ShowOptions;
var
i: integer;
begin
frm := TForm.Create(nil);
try
frm.Caption := wbGameName + ' Assets Manager';
frm.Width := 700;
frm.Height := 650;
frm.Position := poScreenCenter;
frm.BorderStyle := bsDialog;
frm.PopupMode := pmAuto;
frm.KeyPreview := True;
frm.OnKeyDown := frmFormKeyDown;
frm.OnClose := frmFormClose;
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.Top := 8;
lbl.Left := 8;
lbl.Caption := 'Processed assets';
clbAssets := TCheckListBox.Create(frm);
clbAssets.Parent := frm;
clbAssets.Top := 24;
clbAssets.Left := 8;
clbAssets.Width := 250;
clbAssets.Height := 170;
clbAssets.Items.AddStrings(slAssetsType);
clbAssets.CheckAll(cbChecked, False, False);
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.Top := clbAssets.Top + clbAssets.Height + 16;
lbl.Left := 8;
lbl.Caption := 'Processed containers';
clbContainers := TCheckListBox.Create(frm);
clbContainers.Parent := frm;
clbContainers.Top := clbAssets.Top + clbAssets.Height + 32;
clbContainers.Left := 8;
clbContainers.Width := 250;
clbContainers.Height := 340;
for i := 0 to Pred(slContainers.Count) do
clbContainers.Items.Add(SimpleName(slContainers[i]));
clbContainers.CheckAll(cbChecked, False, False);
btnChecksums := TButton.Create(frm);
btnChecksums.Parent := frm;
btnChecksums.Width := 100;
btnChecksums.Height := 22;
btnChecksums.Top := clbContainers.Top - 24;
btnChecksums.Left := clbContainers.Left + clbContainers.Width - btnChecksums.Width;
btnChecksums.Caption := 'Build cheksums';
btnChecksums.OnClick := btnChecksumsClick;
mnPopup := TPopupMenu.Create(frm);
clbContainers.PopupMenu := mnPopup;
MenuItem := TMenuItem.Create(mnPopup);
MenuItem.Caption := 'Select All';
MenuItem.OnClick := PopupMenuClick;
MenuItem.Tag := 1;
mnPopup.Items.Add(MenuItem);
MenuItem := TMenuItem.Create(mnPopup);
MenuItem.Caption := 'Select None';
MenuItem.OnClick := PopupMenuClick;
mnPopup.Items.Add(MenuItem);
rbModeCheck := TRadioButton.Create(frm);
rbModeCheck.Parent := frm;
rbModeCheck.Top := clbAssets.Top;
rbModeCheck.Left := clbAssets.Left + clbAssets.Width + 32;
rbModeCheck.Width := 200;
rbModeCheck.Font.Style := [fsBold];
rbModeCheck.Caption := 'Check for missing assets';
rbModeCheck.Checked := True;
rbModeCheck.OnClick := rbModeClick;
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.AutoSize := False;
lbl.Wordwrap := True;
lbl.Top := rbModeCheck.Top + 20;
lbl.Left := rbModeCheck.Left + 16;
lbl.Width := frm.Width - lbl.Left - 40;
lbl.Height := 60;
lbl.Caption := 'Process all selected records and check referenced asset files for existence in selected containers. Useful to find out if all required files are present for particular mod.';
rbModeList := TRadioButton.Create(frm);
rbModeList.Parent := frm;
rbModeList.Top := rbModeCheck.Top + 80;
rbModeList.Left := rbModeCheck.Left;
rbModeList.Width := 200;
rbModeList.Font.Style := [fsBold];
rbModeList.Caption := 'List referenced assets';
rbModeList.OnClick := rbModeClick;
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.AutoSize := False;
lbl.Wordwrap := True;
lbl.Top := rbModeList.Top + 20;
lbl.Left := rbModeList.Left + 16;
lbl.Width := frm.Width - lbl.Left - 40;
lbl.Height := 40;
lbl.Caption := 'List asset files referenced by selected records. All assets are shown no matter if they exist in selected containers or not.';
rgList := TRadioGroup.Create(frm);
rgList.Parent := frm;
rgList.Top := rbModeList.Top + 60;
rgList.Left := rbModeList.Left + 16;
rgList.Width := 200; rgList.Height := 80;
rgList.Items.Text := 'to Messages Tab'#13'to CSV file'#13'to CK import file';
rgList.ItemIndex := 0;
rbModeCopy := TRadioButton.Create(frm);
rbModeCopy.Parent := frm;
rbModeCopy.Top := rbModeList.Top + 170;
rbModeCopy.Left := rbModeCheck.Left;
rbModeCopy.Width := 200;
rbModeCopy.Font.Style := [fsBold];
rbModeCopy.Caption := 'Copy referenced assets';
rbModeCopy.OnClick := rbModeClick;
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.AutoSize := False;
lbl.Wordwrap := True;
lbl.Top := rbModeCopy.Top + 20;
lbl.Left := rbModeCopy.Left + 16;
lbl.Width := frm.Width - lbl.Left - 40;
lbl.Height := 60;
lbl.Caption := 'Copy assets used in a mod to the separate destination folder retaining directory structure. Useful to package mod for distribution. You might want to deselect the game''s BSA archives to avoid copying vanilla files. Existing files in destination folder are not overwritten.';
edPath := TLabeledEdit.Create(frm);
edPath.Parent := frm;
edPath.Left := lbl.Left;
edPath.Top := lbl.Top + 80;
edPath.Width := lbl.Width - 40;
edPath.LabelPosition := lpAbove;
edPath.EditLabel.Caption := 'Destination folder';
btnPath := TButton.Create(frm);
btnPath.Parent := frm;
btnPath.Top := edPath.Top - 1;
btnPath.Left := edPath.Left + edPath.Width + 6;
btnPath.Width := 32;
btnPath.Height := 22;
btnPath.Caption := '...';
btnPath.OnClick := btnPathClick;
chkSkipChecksums := TCheckBox.Create(frm);
chkSkipChecksums.Parent := frm;
chkSkipChecksums.Top := edPath.Top + 32;
chkSkipChecksums.Left := edPath.Left;
chkSkipChecksums.Width := 360;
chkSkipChecksums.Caption := 'Skip copying files with matching checksums (requires built checksums)';
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.AutoSize := False;
lbl.Wordwrap := True;
lbl.Top := chkSkipChecksums.Top + 80;
lbl.Left := rbModeCopy.Left;
lbl.Width := edPath.Width + 40;
lbl.Height := 60;
lbl.Caption := 'Keep in mind that disabling processing of meshes also disables processing of textures used in meshes.';
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;
// update default state of elements
rbModeClick(nil);
if frm.ShowModal = mrOk then begin
optAsset := 0;
for i := 0 to Pred(clbAssets.Items.Count) do
if clbAssets.Checked[i] then
optAsset := optAsset or Integer(clbAssets.Items.Objects[i]);
// consider speedtree is in mesh category
if optAsset and atMesh > 0 then
optAsset := optAsset or atSpeedTree;
for i := Pred(clbContainers.Items.Count) downto 0 do
if not clbContainers.Checked[i] then
slContainers.Delete(i);
if rbModeCheck.Checked then
optMode := wmCheck
else if rbModeList.Checked then begin
if rgList.ItemIndex = 0 then
optMode := wmList
else if rgList.ItemIndex = 1 then begin
optMode := wmListCSV;
slDump := TStringList.Create;
end
else if rgList.ItemIndex = 2 then begin
optMode := wmListJSON;
slDump := TStringList.Create;
end;
end
else if rbModeCopy.Checked then begin
optMode := wmCopy;
optPath := IncludeTrailingBackslash(edPath.Text);
bSkipChecksum := chkSkipChecksums.Checked;
end;
end else
optMode := wmNone;
finally
frm.Free;
end;
end;
//===========================================================================
// reduce container name to BSA file name or 'Data'
function SimpleName(aName: string): string;
begin
Result := ExtractFileName(aName);
if Result = '' then
Result := 'Data';
end;
//==========================================================================
function NormalizePath(value: string; atype: integer): string;
begin
if value = '' then
Exit;
// uncomment to not show errors on full paths
//if not SameText(Copy(value, 1, 3), 'c:\') then
if Copy(value, 1, 1) = '\' then
Delete(value, 1, 1);
if SameText(Copy(value, 1, 5), 'data\') then
value := Copy(value, 6, Length(value));
if (atype = atMesh) and not (Copy(value, 1, 7) = 'meshes\') then
value := 'meshes\' + value
else if (atype = atAnimation) and not (Copy(value, 1, 7) = 'meshes\') then
value := 'meshes\' + value
else if (atype = atTexture) and not (Copy(value, 1, 9) = 'textures\') then
value := 'textures\' + value
else if (atype = atSound) and not (Copy(value, 1, 6) = 'sound\') then
value := 'sound\' + value
else if (atype = atMusic) and not (Copy(value, 1, 6) = 'music\') then
value := 'music\' + value
else if (atype = atSpeedTree) and not (Copy(value, 1, 6) = 'trees\') then
value := 'trees\' + value
else if (atype = atInterface) and not (Copy(value, 1, 10) = 'interface\') then
value := 'interface\' + value
else if (atype = atMaterial) and not (Copy(value, 1, 9) = 'material\') then
value := 'materials\' + value
else if (atype = atProgram) and not (Copy(value, 1, 9) = 'programs\') then
value := 'programs\' + value;
Result := value;
end;
//==========================================================================
// perform operation with resource depending on workmode
// returns the last container's name (in selected) of resource if exists
function ProcessResource(aResName, aResDescr: string; aResType: integer): string;
var
i: integer;
begin
Result := '';
if optAsset and aResType = 0 then
Exit;
aResDescr := ResDescrPrefix + aResDescr;
slRes.Clear;
ResourceCount(aResName, slRes);
// dump everything regardless of asset existance in selected containers
if optMode = wmList then
AddMessage(aResName + ' <-- ' + aResDescr)
else if optMode = wmListCSV then
slDump.Add(Format('[%s];%s;%s', [
IntToHex(GetLoadOrderFormID(CurrentRecord), 8),
aResName,
aResDescr
]))
else if optMode = wmListJSON then
slDump.Add(aResName);
// check if resource is in any of selected containers
// starting from the last one
for i := Pred(slRes.Count) downto 0 do
if slContainers.IndexOf(slRes[i]) <> -1 then begin
Result := slRes[i];
Break;
end;
if optMode = wmCheck then begin
if Result = '' then
AddMessage(aResName + ' <-- ' + aResDescr);
end
else if (optMode = wmCopy) and (Result <> '') then begin
// do not overwrite existing files or copy same files several times
if FileExists(optPath + aResName) then
Exit;
// skip matching checksums
if bSkipChecksum then begin
i := slChecksum.IndexOfName(aResName);
if i <> - 1 then
if slChecksum.ValueFromIndex[i] = IntToHex(wbCRC32Data(ResourceOpenData(Result, aResName)), 8) then begin
AddMessage('[Skipped] matching checksum: ' + aResName + ' <-- ' + aResDescr);
Result := '';
Exit;
end;
end;
AddMessage(aResName + ' <-- ' + aResDescr);
ResourceCopy(Result, aResName, optPath);
end;
end;
//==========================================================================
procedure ProcessMeshAssets(aMesh, aContainer, aDescr: string);
var
i: integer;
begin
// some assets are in the "mesh" category but not nifs
if not SameText(ExtractFileExt(aMesh), '.nif') then
Exit;
// suppress possible errors for invalid meshes
sl.Clear;
try
GetNifAssets(aMesh, sl);
except on E: Exception do
AddMessage('Error reading NIF: ' + E.Message + ' ' + aMesh);
end;
// remove duplicates and empty
for i := 0 to Pred(sl.Count) do
if sl[i] <> '' then
slTextures.Add(sl[i]);
for i := 0 to Pred(slTextures.Count) do
ProcessResource(slTextures[i], 'Asset for ' + aDescr + ': ' + aMesh, atTexture);
slTextures.Clear;
end;
//==========================================================================
procedure ProcessMaterialAssets(aMaterial, aContainer, aDescr: string);
var
i: integer;
begin
// suppress possible errors for invalid meshes
sl.Clear;
try
GetTexturesFromMaterial(aMaterial, sl);
except on E: Exception do
AddMessage('Error reading material: ' + E.Message + ' ' + aMaterial);
end;
// remove duplicates and empty
for i := 0 to Pred(sl.Count) do
if sl[i] <> '' then
slTextures.Add(sl[i]);
for i := 0 to Pred(slTextures.Count) do
ProcessResource(slTextures[i], 'Asset for ' + aDescr + ': ' + aMaterial, atTexture);
slTextures.Clear;
end;
//==========================================================================
// process resource by value and type
procedure ProcessAssetEx(el: IInterface; value, valuedescr: string; atype: integer);
var
rescont, s: string;
begin
if value = '' then
Exit;
// just in case, resource container index is lowercased
value := LowerCase(value);
if valuedescr = '' then
if ResDescrPrefix = '' then
valuedescr := Name(CurrentRecord) + ' \ ' + Path(el)
else
valuedescr := Path(el);
rescont := ProcessResource(value, valuedescr, atype);
if rescont = '' then
Exit;
// check embedded assets
if ((atype = atMesh) or (atype = atLODAsset)) and (optAsset and (atTexture + atMaterial) <> 0) then
ProcessMeshAssets(value, rescont, valuedescr)
else if atype = atMaterial then
ProcessMaterialAssets(value, rescont, valuedescr);
end;
//==========================================================================
// detect asset type of element and process it
procedure ProcessAsset(el: IInterface);
var
value, ext, s: string;
i, atype: integer;
begin
if not Assigned(el) then
Exit;
value := LowerCase(GetEditValue(el));
if value = '' then
Exit;
// [FO3/FNV] Hardcoded: model lists in CREA use creature model path
if (wbGameMode = gmFO3) or (wbGameMode = gmFNV) then begin
s := Path(el);
if SameText(s, 'CREA \ NIFZ - Model List \ Model') then
value := ExtractFilePath(GetElementEditValues(CurrentRecord, 'Model\MODL')) + value
else if SameText(s, 'CREA \ KFFZ - Animations \ Animation') then
value := ExtractFilePath(GetElementEditValues(CurrentRecord, 'Model\MODL')) + 'specialanims\' + value;
end;
// asset extension
ext := ExtractFileExt(value);
// detect asset type
i := slAssetsExt.IndexOf(ext);
if i = -1 then Exit;
atype := Integer(slAssetsExt.Objects[i]);
// more detailed asset type detection depending on different factors
// sound files in those records are music
if (atype = atSound) and (Pos(Signature(CurrentRecord), sMusicSignatures) > 0) then
atype := atMusic
// speedtree files
else if (atype = atMesh) and SameText(ext, '.spt') then
atype := atSpeedTree
// hardcoded location for speedtree leaves billboards
else if (atype = atTexture) and ((wbGameMode = gmFO3) or (wbGameMode = gmFNV)) and (Signature(CurrentRecord) = 'TREE') then
value := 'textures\trees\leaves\' + value;
value := NormalizePath(LowerCase(value), atype);
ProcessAssetEx(el, value, '', atype);
end;
//==========================================================================
procedure ScanForAssets(e: IInterface);
var
i: integer;
begin
if not Assigned(e) then
Exit;
// special scanning case for Alternate textures
if SameText(Name(e), 'Alternate Texture') then begin
ResDescrPrefix := Format('Alternate texture for node %s in %s from %s \ ', [
GetElementEditValues(e, '3D Name'), // node name
GetEditValue(ElementByIndex(GetContainer(GetContainer(e)), 0)), // model file name
Name(LinksTo(ElementByName(e, 'New Texture'))) // TXST record name
]);
ScanForAssets(LinksTo(ElementByName(e, 'New Texture')));
ResDescrPrefix := '';
Exit;
end;
i := DefType(e);
if (i = dtString) or (i = dtLenString) then
// do extension check before processing asset to speed up execution
if (slAssetsExt.IndexOf(LowerCase(ExtractFileExt(GetEditValue(e)))) <> -1) then
ProcessAsset(e);
for i := 0 to Pred(ElementCount(e)) do
ScanForAssets(ElementByIndex(e, i));
end;
//==========================================================================
// scan VMAD subrecord for scripts
procedure ScanForPapyrusScripts(e: IInterface);
var
i: integer;
s: string;
begin
if not Assigned(e) then
Exit;
// skip VMAD properties
if Name(e) = 'Properties' then
Exit;
if Name(e) = 'scriptName' then begin
s := StringReplace(GetEditValue(e), ':', '\', [rfReplaceAll]);
ProcessAssetEx(e, 'scripts\' + s + '.pex', 'Papyrus script attached to ' + Name(CurrentRecord), atPapyrusScript);
ProcessAssetEx(e, 'scripts\source\' + s + '.psc', 'Source of papyrus script attached to ' + Name(CurrentRecord), atPapyrusScript);
end;
for i := 0 to Pred(ElementCount(e)) do
ScanForPapyrusScripts(ElementByIndex(e, i));
end;
//==========================================================================
function Initialize: integer;
begin
{if (wbGameMode <> gmFO3) and
(wbGameMode <> gmFNV) and
(wbGameMode <> gmTES4) and
(wbGameMode <> gmTES5) and
(wbGameMode <> gmSSE)
then begin
MessageDlg('Sorry, script supports Skyrim, SSE, Oblivion and Fallouts only for now.', mtInformation, [mbOk], 0);
Result := 1;
Exit;
end;}
// known extensions, unknown ones are skipped
slAssetsExt := TStringList.Create;
slAssetsExt.AddObject('.nif', atMesh);
slAssetsExt.AddObject('.dds', atTexture);
slAssetsExt.AddObject('.bgsm', atMaterial);
slAssetsExt.AddObject('.bgem', atMaterial);
slAssetsExt.AddObject('.wav', atSound);
slAssetsExt.AddObject('.mp3', atSound);
slAssetsExt.AddObject('.ogg', atSound);
slAssetsExt.AddObject('.xwm', atSound);
slAssetsExt.AddObject('.kf', atAnimation);
slAssetsExt.AddObject('.hkx', atAnimation);
slAssetsExt.AddObject('.spt', atMesh); // speedtree is in mesh category
slAssetsExt.AddObject('.psa', atMesh); // pose is in mesh category
slAssetsExt.AddObject('.tri', atMesh); // morphs
slAssetsExt.AddObject('.ssf', atMesh); // FO4 bone weights is in mesh category
slAssetsExt.AddObject('.seq', atSeqFile);
slAssetsExt.AddObject('.pex', atPapyrusScript);
slAssetsExt.AddObject('.psc', atPapyrusScript);
slAssetsExt.AddObject('.swf', atInterface);
// selection list
slAssetsType := TStringList.Create;
slAssetsType.AddObject('Meshes', atMesh);
slAssetsType.AddObject('Textures', atTexture);
slAssetsType.AddObject('[FO4] Materials', atMaterial);
slAssetsType.AddObject('Sounds', atSound);
slAssetsType.AddObject('Music', atMusic);
slAssetsType.AddObject('Animations', atAnimation);
slAssetsType.AddObject('Papyrus scripts', atPapyrusScript);
slAssetsType.AddObject('[TES5] SEQ file', atSeqFile);
slAssetsType.AddObject('Interface', atInterface);
slAssetsType.AddObject('LOD Assets ', atLODAsset);
slAssetsType.AddObject('[FO4] PipBoy Programs', atProgram);
slTextures := TwbFastStringList.Create;
slTextures.Sorted := True;
slTextures.Duplicates := dupIgnore;
slChecksum := TwbFastStringList.Create;
slContainers := TwbFastStringList.Create;
ResourceContainerList(slContainers);
slRes := TStringList.Create;
sl := TStringList.Create;
ChecksumsFileName := Format('%sAssets manager %s checksums.txt', [ScriptsPath, wbGameName]);
ShowOptions;
if optMode = wmCheck then
AddMessage('LIST OF MISSING ASSET FILES:')
else if optMode = wmList then
AddMessage('LIST OF USED ASSET FILES:')
else if optMode = wmCopy then begin
if bSkipChecksum and (slChecksum.Count = 0) and FileExists(ChecksumsFileName) then
slChecksum.LoadFromFile(ChecksumsFileName);
AddMessage('COPYING USED ASSET FILES:');
end
else if optMode = wmNone then begin
Finalize;
Result := 1;
end;
end;
//==========================================================================
function Process(e: IInterface): integer;
var
el, ent, ents: IInterface;
sig, s, contnr: string;
i, i1, i2: integer;
DisabledClouds: LongWord;
sl: TStringList;
begin
CurrentRecord := e;
sig := Signature(e);
// skip records without assets
if Pos(sig, sSkipSignatures) > 0 then
Exit;
// generic model common for all records
ScanForAssets(ElementByName(e, 'Model'));
// generic icon common for all records
ProcessAsset(ElementBySignature(e, 'ICON'));
ScanForAssets(ElementByName(e, 'Icon'));
// generic destruction models common for all records
ScanForAssets(ElementByPath(e, 'Destructible'));
// GAME SPECIFIC ELEMENTS
// --------------------------------------------------------------------------------
// Skyrim and SSE
// --------------------------------------------------------------------------------
if (wbGameMode = gmTES5) or (wbGameMode = gmSSE) then begin
// papyrus scripts
if optAsset and atPapyrusScript > 0 then
ScanForPapyrusScripts(ElementByPath(e, 'VMAD'));
if (sig = 'ARMA') then begin
i1 := GetElementNativeValues(e, 'DNAM\Weight slider - Male');
i2 := GetElementNativeValues(e, 'DNAM\Weight slider - Female');
for i := 1 to 4 do begin
if i = 1 then s := 'Male world model\MOD2'
else if i = 2 then s := 'Female world model\MOD3'
else if i = 3 then s := 'Male 1st Person\MOD4'
else if i = 4 then s := 'Female 1st Person\MOD5';
ent := ElementByPath(e, s);
if not Assigned(ent) then Continue;
ProcessAsset(ent);
// additional weight models
if ((i mod 2 = 1) and (i1 = 2)) or ((i mod 2 = 0) and (i2 = 2)) or (optMode = wmCopy) then begin
s := wbNormalizeResourceName(GetEditValue(ent), resMesh);
if SameText(Copy(s, Length(s)-5, 6), '_1.nif') then
ProcessAssetEx(ent, Copy(s, 1, Length(s)-6) + '_0.nif', '', atMesh)
else if SameText(Copy(s, Length(s)-5, 6), '_0.nif') then
ProcessAssetEx(ent, Copy(s, 1, Length(s)-6) + '_1.nif', '', atMesh);
end;
// the last element in the same container as model is alternate textures
ent := ElementByIndex(GetContainer(ent), ElementCount(GetContainer(ent)) - 1);
if Pos('Alternate', Name(ent)) > 0 then
ScanForAssets(ent);
end;
ScanForAssets(ElementByPath(e, 'Icon 2 (female)'));
end
else if (sig = 'ARMO') then begin
ScanForAssets(ElementByName(e, 'Male world model'));
ScanForAssets(ElementByName(e, 'Female world model'));
ScanForAssets(ElementByName(e, 'Icon 2 (female)'));
end
else if (sig = 'CELL') then begin
ProcessAsset(ElementByPath(e, 'XNAM'));
ProcessAsset(ElementByPath(e, 'XWEM'));
end
else if (sig = 'CLMT') then begin
ProcessAsset(ElementByPath(e, 'FNAM'));
ProcessAsset(ElementByPath(e, 'GNAM'));
end
else if (sig = 'DEBR') then
ScanForAssets(ElementByPath(e, 'Models'))
else if (sig = 'EFSH') then begin
ProcessAsset(ElementByPath(e, 'ICO2'));
ProcessAsset(ElementByPath(e, 'NAM7'));
ProcessAsset(ElementByPath(e, 'NAM8'));
ProcessAsset(ElementByPath(e, 'NAM9'));
end
else if (sig = 'FURN') then
ProcessAsset(ElementByPath(e, 'XMRK'))
else if (sig = 'LSCR') then
ProcessAsset(ElementByPath(e, 'MOD2'))
else if sig = 'LENS' then begin
ents := ElementByName(e, 'Lens Flare Sprites');
for i := 0 to Pred(ElementCount(ents)) do
ProcessAsset( ElementBySignature(ElementByIndex(ents, i), 'FNAM') );
end
else if (sig = 'MUST') then begin
ProcessAsset(ElementByPath(e, 'ANAM'));
ProcessAsset(ElementByPath(e, 'BNAM'));
end
else if (sig = 'PROJ') then
ProcessAsset(ElementByPath(e, 'Muzzle Flash Model\NAM1'))
else if (sig = 'QUST') then begin
if GetElementNativeValues(e, 'DNAM\Flags') and 1 > 0 then
if not Assigned(Master(e)) or (GetElementNativeValues(Master(e), 'DNAM\Flags') and 1 = 0) then
ProcessAssetEx(e, 'seq\' + ChangeFileExt(GetFileName(e), '.seq'), 'Start-game enabled quest requires SEQ file ' + Name(e), atSeqFile);
end
else if (sig = 'RACE') then begin
ProcessAsset(ElementByPath(e, 'ANAM - Male Skeletal Model'));
ProcessAsset(ElementByPath(e, 'ANAM - Female Skeletal Model'));
ScanForAssets(ElementByPath(e, 'Body Data'));
ProcessAsset(ElementByPath(e, 'Male Behavior Graph\Model\MODL'));
ProcessAsset(ElementByPath(e, 'Female Behavior Graph\Model\MODL'));
ProcessAsset(ElementByPath(e, 'Head Data\Male Head Data\Model'));
ProcessAsset(ElementByPath(e, 'Head Data\Female Head Data\Model'));
end
else if (sig = 'SNDR') then
ScanForAssets(ElementByPath(e, 'Sounds'))
// STAT LOD
else if (sig = 'STAT') and ElementExists(e, 'MNAM') then begin
ents := ElementBySignature(e, 'MNAM');
for i := 0 to Pred(ElementCount(ents)) do begin
ent := ElementByIndex(ents, i);
s := wbNormalizeResourceName(GetElementEditValues(ent, 'Mesh'), resMesh);
ProcessAssetEx(e, s, 'Static LOD level ' + IntToStr(i) + ' mesh for ' + Name(e), atLODAsset);
end;
end
// TREE LOD
// we don't know if a mesh must have lod or not since it is not referenced directly from record, so skip it in "check missing" mode
else if (sig = 'TREE') and (optMode <> wmCheck) then begin
s := GetElementEditValues(e, 'Model\MODL');
if s <> '' then begin
s := wbNormalizeResourceName(ChangeFileExt(s, '') + '_lod_flat.nif', resMesh);
ProcessAssetEx(e, s, 'Tree LOD mesh for ' + Name(e), atLODAsset);
end;
end
else if (sig = 'TXST') then
ScanForAssets(ElementByPath(e, 'Textures (RGB/A)'))
else if (sig = 'WATR') then
ProcessAsset(ElementByPath(e, 'NAM2'))
else if (sig = 'WRLD') then begin
ScanForAssets(ElementByPath(e, 'Cloud Model\Model'));
ProcessAsset(ElementByPath(e, 'XNAM'));
ProcessAsset(ElementByPath(e, 'TNAM'));
ProcessAsset(ElementByPath(e, 'UNAM'));
end
else if (sig = 'WTHR') then begin
// check cloud texture layers except disabled ones
sl := TStringList.Create;
sl.CommaText := '00TX,10TX,20TX,30TX,40TX,50TX,60TX,70TX,80TX,90TX,:0TX,;0TX,<0TX,=0TX,>0TX,?0TX,@0TX,A0TX,B0TX,C0TX,D0TX,E0TX,F0TX,G0TX,H0TX,I0TX,J0TX,K0TX,L0TX';
DisabledClouds := GetElementNativeValues(e, 'NAM1');
for i := 0 to Pred(sl.Count) do begin
if DisabledClouds and (1 shl i) = 0 then
ProcessAsset(ElementBySignature(e, sl[i]));
end;
sl.Free;
ProcessAsset(ElementByPath(e, 'Aurora\Model\MODL'));
end;
end
// --------------------------------------------------------------------------------
// Oblivion
// --------------------------------------------------------------------------------
else if wbGameMode = gmTES4 then begin
if (sig = 'WTHR') then begin
ProcessAsset(ElementByPath(e, 'DNAM'));
ProcessAsset(ElementByPath(e, 'CNAM'));
end;
end
// --------------------------------------------------------------------------------
// Fallout 3 and New Vegas
// --------------------------------------------------------------------------------
else if (wbGameMode = gmFO3) or (wbGameMode = gmFNV) then begin
if (sig = 'ARMA') or (sig = 'ARMO') then begin
ScanForAssets(ElementByPath(e, 'Male biped model'));
ScanForAssets(ElementByPath(e, 'Male world model'));
ScanForAssets(ElementByPath(e, 'Female biped model'));
ScanForAssets(ElementByPath(e, 'Female world model'));
ProcessAsset(ElementBySignature(e, 'MICO'));
ProcessAsset(ElementBySignature(e, 'ICO2'));
ProcessAsset(ElementBySignature(e, 'MIC2'));
end
else if (sig = 'CCRD') then
ScanForAssets(ElementByPath(e, 'High Res Image'))
else if (sig = 'CLMT') then begin
ProcessAsset(ElementByPath(e, 'FNAM'));
ProcessAsset(ElementByPath(e, 'GNAM'));
end
else if (sig = 'CREA') then begin
ScanForAssets(ElementByPath(e, 'NIFZ'));
ScanForAssets(ElementByPath(e, 'KFFZ'));
end
else if (sig = 'CSNO') then begin
ProcessAsset(ElementByPath(e, 'MODL'));
ProcessAsset(ElementByPath(e, 'MOD2'));
ProcessAsset(ElementByPath(e, 'MOD3'));
ProcessAsset(ElementByPath(e, 'MOD4'));
ScanForAssets(ElementByPath(e, 'Casino Chip Models'));
ScanForAssets(ElementByPath(e, 'Slot Reel Textures'));
ScanForAssets(ElementByPath(e, 'BlackJack Decks'));
end
else if (sig = 'DEBR') then
ScanForAssets(ElementByPath(e, 'Models'))
else if (sig = 'EFSH') then begin
ProcessAsset(ElementByPath(e, 'ICO2'));
ProcessAsset(ElementByPath(e, 'NAM7'));
end
else if (sig = 'MSET') then begin
ProcessAsset(ElementByPath(e, 'NAM2'));
ProcessAsset(ElementByPath(e, 'NAM3'));
ProcessAsset(ElementByPath(e, 'NAM4'));
ProcessAsset(ElementByPath(e, 'NAM5'));
ProcessAsset(ElementByPath(e, 'NAM6'));
ProcessAsset(ElementByPath(e, 'NAM7'));
end
else if (sig = 'MUSC') then
ProcessAsset(ElementByPath(e, 'FNAM'))
else if (sig = 'PROJ') then
ProcessAsset(ElementByPath(e, 'Muzzle Flash Model\NAM1'))
else if (sig = 'RACE') then begin
ScanForAssets(ElementByPath(e, 'Head Data'));
ScanForAssets(ElementByPath(e, 'Female Head Data'));
ScanForAssets(ElementByPath(e, 'Body Data'));
end
else if (sig = 'RGDL') then
ProcessAsset(ElementByPath(e, 'ANAM'))
else if (sig = 'SOUN') then begin
el := ElementBySignature(e, 'FNAM');
s := GetEditValue(el);
// single sound file
if ExtractFileName(s) <> '' then
ProcessAsset(el)
// folder with sounds
else if s <> '' then begin
s := wbNormalizeResourceName(s, resSound);
sl := TStringList.Create; sl.Sorted := True; sl.Duplicates := dupIgnore;
ResourceList('', sl, s);
// remove files from subdirectories
for i := Pred(sl.Count) downto 0 do
if ExtractFilePath(sl[i]) <> s then
sl.Delete(i);
// report missing files in folder when checking for missing assets
if sl.Count = 0 then begin
if optMode = wmCheck then
ProcessAssetEx(el, s, 'Folder is empty for ' + Name(e), atSound);
end else
for i := 0 to Pred(sl.Count) do
ProcessAssetEx(el, sl[i], '', atSound);
sl.Free;
end;
end
// Statics LOD
// we don't know if a mesh must have lod or not since it is not referenced directly from record, so skip it in "check missing" mode
else if (sig = 'STAT') and (optMode <> wmCheck) then begin
s := GetElementEditValues(e, 'Model\MODL');
if s <> '' then begin
s := wbNormalizeResourceName(ChangeFileExt(s, '') + '_lod.nif', resMesh);
ProcessAssetEx(e, s, 'Static LOD mesh for ' + Name(e), atLODAsset);
end;
end
// Trees billboard LOD
else if (sig = 'TREE') and (optMode <> wmCheck) then begin
s := ExtractFileName(GetElementEditValues(e, 'Model\MODL'));
if s <> '' then begin
s := 'textures\trees\billboards\' + ChangeFileExt(s, '.dds');
ProcessAssetEx(e, s, 'Tree billboard LOD texture for ' + Name(e), atLODAsset);
end;
end
else if (sig = 'TXST') then
ScanForAssets(ElementByPath(e, 'Textures (RGB/A)'))
else if (sig = 'WATR') then
ProcessAsset(ElementByPath(e, 'NNAM'))
else if (sig = 'WEAP') then begin
ScanForAssets(ElementByPath(e, 'Shell Casing Model'));
ScanForAssets(ElementByPath(e, 'Scope Model'));
ScanForAssets(ElementByPath(e, 'World Model'));
ProcessAsset(ElementByPath(e, 'MWD1'));
ProcessAsset(ElementByPath(e, 'MWD2'));
ProcessAsset(ElementByPath(e, 'MWD3'));
ProcessAsset(ElementByPath(e, 'MWD4'));
ProcessAsset(ElementByPath(e, 'MWD5'));
ProcessAsset(ElementByPath(e, 'MWD6'));
ProcessAsset(ElementByPath(e, 'MWD7'));
end
else if (sig = 'WRLD') then begin
ProcessAsset(ElementByPath(e, 'XNAM'));
ProcessAsset(ElementByPath(e, 'NNAM'));
end
else if (sig = 'WTHR') then begin
ProcessAsset(ElementByPath(e, 'DNAM'));
ProcessAsset(ElementByPath(e, 'CNAM'));
ProcessAsset(ElementByPath(e, 'ANAM'));
ProcessAsset(ElementByPath(e, 'BNAM'));
end;
end
// --------------------------------------------------------------------------------
// Fallout 4
// --------------------------------------------------------------------------------
else if wbGameMode = gmFO4 then begin
// generic second icon common for records
ProcessAsset(ElementBySignature(e, 'MICO'));
// papyrus scripts
if optAsset and atPapyrusScript > 0 then
ScanForPapyrusScripts(ElementBySignature(e, 'VMAD'));
if sig = 'ARMA' then begin
ProcessAsset(ElementByPath(e, 'Male world model\MOD2'));
ProcessAsset(ElementByPath(e, 'Female world model\MOD3'));
ProcessAsset(ElementByPath(e, 'Male 1st Person\MOD4'));
ProcessAsset(ElementByPath(e, 'Female 1st Person\MOD5'));
end
else if sig = 'ARMO' then begin
ProcessAsset(ElementByPath(e, 'Male world model\MOD2'));
ProcessAsset(ElementByPath(e, 'Female world model\MOD4'));
ProcessAsset(ElementBySignature(e, 'ICO2'));
ProcessAsset(ElementBySignature(e, 'MIC2'));
end
else if sig = 'BPTD' then begin
ents := ElementByName(e, 'Body Parts');
for i := 0 to Pred(ElementCount(ents)) do
ProcessAsset( ElementBySignature(ElementByIndex(ents, i), 'NAM1') );
end
else if (sig = 'DEBR') then
ScanForAssets(ElementByPath(e, 'Models'))
else if (sig = 'EFSH') then begin
ProcessAsset(ElementBySignature(e, 'ICO2'));
ProcessAsset(ElementBySignature(e, 'NAM7'));
ProcessAsset(ElementBySignature(e, 'NAM8'));
ProcessAsset(ElementBySignature(e, 'NAM9'));
end
else if (sig = 'FURN') then
ProcessAsset(ElementBySignature(e, 'XMRK'))
else if (sig = 'HDPT') then
ScanForAssets(ElementByName(e, 'Parts'))
else if (sig = 'IDLE') then begin
ProcessAsset(ElementBySignature(e, 'DNAM'));
ProcessAsset(ElementBySignature(e, 'GNAM'));
end
else if (sig = 'IMGS') then
ProcessAsset(ElementBySignature(e, 'TX00'))
else if sig = 'LENS' then begin
ents := ElementByName(e, 'Lens Flare Sprites');
for i := 0 to Pred(ElementCount(ents)) do
ProcessAsset( ElementBySignature(ElementByIndex(ents, i), 'FNAM') );
end
else if (sig = 'LIGH') then
ProcessAsset(ElementBySignature(e, 'NAM0'))
else if (sig = 'LSCR') then
ProcessAsset(ElementByPath(e, 'MOD2'))
else if (sig = 'MATT') then
ProcessAsset(ElementByPath(e, 'ANAM'))
else if (sig = 'MESG') then
ProcessAsset(ElementByPath(e, 'SNAM'))
else if sig = 'MSWP' then begin
ents := ElementByName(e, 'Material Substitutions');
for i := 0 to Pred(ElementCount(ents)) do
ProcessAsset( ElementBySignature(ElementByIndex(ents, i), 'SNAM') );
end
else if (sig = 'MUSC') then begin
ProcessAsset(ElementByPath(e, 'ANAM'));
ProcessAsset(ElementByPath(e, 'BNAM'));
end
else if (sig = 'NOTE') then begin
s := GetElementEditValues(e, 'PNAM');
if s <> '' then
ProcessAssetEx(e, NormalizePath(s, atProgram), 'PipBoy program for ' + Name(e), atProgram);
end
else if (sig = 'PERK') then
ProcessAsset(ElementByPath(e, 'FNAM'))
else if (sig = 'PROJ') then
ProcessAsset(ElementByPath(e, 'Muzzle Flash Model\NAM1'))
else if (sig = 'QUST') then
ProcessAsset(ElementByPath(e, 'SNAM'))
else if (sig = 'RACE') then begin
ProcessAsset(ElementByPath(e, 'ANAM - Male Skeletal Model'));
ProcessAsset(ElementByPath(e, 'ANAM - Female Skeletal Model'));
ScanForAssets(ElementByPath(e, 'Body Data'));
ProcessAsset(ElementByPath(e, 'Male Behavior Graph\Model\MODL'));
ProcessAsset(ElementByPath(e, 'Female Behavior Graph\Model\MODL'));
// need to scan tint layers for textures, but whatever... noone creates new races for FO4
end
else if (sig = 'SNDR') then
ScanForAssets(ElementByPath(e, 'Sounds'))
else if (sig = 'SPGD') then
ScanForAssets(ElementByPath(e, 'MNAM'))
// STAT LOD
else if (sig = 'STAT') and ElementExists(e, 'MNAM') then begin
ents := ElementBySignature(e, 'MNAM');
for i := 0 to Pred(ElementCount(ents)) do begin
ent := ElementByIndex(ents, i);
s := wbNormalizeResourceName(GetElementEditValues(ent, 'Mesh'), resMesh);
ProcessAssetEx(e, s, 'Static LOD level ' + IntToStr(i) + ' mesh for ' + Name(e), atLODAsset);
end;
end
else if (sig = 'TERM') then begin
ProcessAsset(ElementBySignature(e, 'XMRK'));
ents := ElementByName(e, 'Menu Items');
for i := 0 to Pred(ElementCount(ents)) do
ProcessAsset( ElementBySignature(ElementByIndex(ents, i), 'VNAM') );
end
else if (sig = 'TXST') then begin
ScanForAssets(ElementByPath(e, 'Textures (RGB/A)'));
ProcessAsset(ElementByPath(e, 'MNAM'));
end
else if (sig = 'WATR') then begin
ProcessAsset(ElementByPath(e, 'NAM2'));
ProcessAsset(ElementByPath(e, 'NAM3'));
ProcessAsset(ElementByPath(e, 'NAM4'));
end
else if (sig = 'WEAP') then
ProcessAsset(ElementByPath(e, '1st Person Model\MOD4'))
else if (sig = 'WRLD') then begin
ProcessAsset(ElementByPath(e, 'XWEM'));
ScanForAssets(ElementByPath(e, 'Cloud Model\Model'));
end
else if (sig = 'WTHR') then begin
// check cloud texture layers except disabled ones
sl := TStringList.Create;
sl.CommaText := '00TX,10TX,20TX,30TX,40TX,50TX,60TX,70TX,80TX,90TX,:0TX,;0TX,<0TX,=0TX,>0TX,?0TX,@0TX,A0TX,B0TX,C0TX,D0TX,E0TX,F0TX,G0TX,H0TX,I0TX,J0TX,K0TX,L0TX';
DisabledClouds := GetElementNativeValues(e, 'NAM1');
for i := 0 to Pred(sl.Count) do begin
if DisabledClouds and (1 shl i) = 0 then
ProcessAsset(ElementBySignature(e, sl[i]));
end;
sl.Free;
ProcessAsset(ElementByPath(e, 'Aurora\Model\MODL'));
end;
end;
end;
//==========================================================================
function Finalize: integer;
var
dlgSave: TSaveDialog;
json: TJSONArray;
slNoDups: TStringList;
i: integer;
begin
if optMode = wmListCSV then begin
dlgSave := TSaveDialog.Create(nil);
try
dlgSave.Options := dlgSave.Options + [ofOverwritePrompt];
dlgSave.InitialDir := wbDataPath;
dlgSave.FileName := 'UsedAssets.csv';
if dlgSave.Execute then begin
AddMessage('Saving assets list to ' + dlgSave.FileName);
slDump.SaveToFile(dlgSave.FileName);
end;
finally
dlgSave.Free;
end;
slDump.Free;
end;
if optMode = wmListJSON then begin
dlgSave := TSaveDialog.Create(nil);
try
dlgSave.Options := dlgSave.Options + [ofOverwritePrompt];
dlgSave.InitialDir := wbDataPath;
dlgSave.FileName := 'UsedAssets.achlist';
if dlgSave.Execute then begin
slNoDups := TStringList.Create;
slNoDups.Sorted := True;
slNoDups.Duplicates := dupIgnore;
slNoDups.Assign(slDump);
json := TJSONArray.Create;
for i := 0 to slNoDups.Count - 1 do
json.Add('data\' + slNoDups[i]);
AddMessage('Saving assets list to ' + dlgSave.FileName);
json.SaveToFile(dlgSave.FileName, False);
json.Free;
slNoDups.Free;
end;
finally
dlgSave.Free;
end;
slDump.Free;
end;
slAssetsType.Free;
slAssetsExt.Free;
slContainers.Free;
slTextures.Free;
slChecksum.Free;
slRes.Free;
sl.Free;
end;
end. |
program ans2utf;
// convert ansi codepaged file to utf8
//
// ans2utf codepage inputfile.ans outputfile.utf
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
StrUtils, Classes, SysUtils, LConvEncoding, Variants;
type
// Code page stuff.
TCodePages = (
CP1250, CP1251, CP1252, CP1253,
CP1254, CP1255, CP1256, CP1257,
CP1258, CP437, CP850, CP852,
CP866, CP874, CP932, CP936,
CP949, CP950, MACINTOSH, KOI8 );
TCodePageConverter = function(const s: string): string;
TCodePageUnconverter = function(const s: string; SetTargetCodePage: boolean = false): RawByteString;
const
FirstCP : TCodePages = CP1250;
LastCP : TCodePages = KOI8;
CodePageNames : array [ CP1250 .. KOI8 ] of string = (
'CP1250', 'CP1251', 'CP1252', 'CP1253',
'CP1254', 'CP1255', 'CP1256', 'CP1257',
'CP1258', 'CP437', 'CP850', 'CP852',
'CP866', 'CP874', 'CP932', 'CP936',
'CP949', 'CP950', 'MACINTOSH', 'KOI8' );
CodePageConverters : array [ CP1250 .. KOI8 ] of TCodePageConverter = (
@CP1250ToUTF8, @CP1251ToUTF8, @CP1252ToUTF8, @CP1253ToUTF8,
@CP1254ToUTF8, @CP1255ToUTF8, @CP1256ToUTF8, @CP1257ToUTF8,
@CP1258ToUTF8, @CP437ToUTF8, @CP850ToUTF8, @CP852ToUTF8,
@CP866ToUTF8, @CP874ToUTF8, @CP932ToUTF8, @CP936ToUTF8,
@CP949ToUTF8, @CP950ToUTF8, @MACINTOSHToUTF8, @KOI8ToUTF8 );
CodePageUnconverters : array [ CP1250 .. KOI8 ] of TCodePageUnconverter = (
@UTF8ToCP1250, @UTF8ToCP1251, @UTF8ToCP1252, @UTF8ToCP1253,
@UTF8ToCP1254, @UTF8ToCP1255, @UTF8ToCP1256, @UTF8ToCP1257,
@UTF8ToCP1258, @UTF8ToCP437, @UTF8ToCP850, @UTF8ToCP852,
@UTF8ToCP866, @UTF8ToCP874, @UTF8ToCP932, @UTF8ToCP936,
@UTF8ToCP949, @UTF8ToCP950, @UTF8ToMACINTOSH, @UTF8ToKOI8 );
CRLF = #13#10;
function Convert(cp : TCodePages; filename : string) : utf8string; register;
var
fin : TextFile;
linein : RawByteString;
str : utf8string;
begin
result := '';
str := '';
if fileexists(filename) then
begin
assign(fin, filename);
reset(fin);
while not eof(fin) do
begin
readln(fin, linein);
str += CodePageConverters[cp](linein) + CRLF;
end;
closefile(fin);
result := str;
end;
end;
{ Convert strin to UTF-8 }
function ConvertFromCP(cp : TCodePages; strin : string) : string; register;
begin
result := CodePageConverters[cp](strin);
end;
{ Convert strin to codepage }
function ConvertToCP(cp : TCodePages; strin : string) : RawByteString; register;
begin
result := CodePageUnconverters[cp](strin);
end;
procedure help;
begin
writeln('ans2utf -C codepage -I inputfile -O outputfile');
end;
var
found : boolean;
i : integer;
codepage,
infname,
outfname : string;
cp : TCodePages;
fout : Text;
data : utf8string;
arg : string;
state : integer;
begin
writeln('ans2utf - convert ansi file to utf8.' + CRLF
+ '(c) 2017 Dan Mecklenburg Jr.' + CRLF);
{$region Get args }
// get args
codepage := 'CP437';
infname := '';
outfname := '';
for i := 1 to argc - 1 do
begin
arg := argv[i];
case upcase(arg) of
'--?','-?','/?','-H':
begin
help;
exit;
end;
'-I': state := 1;
'-O': state := 2;
'-C': state := 3;
else
case state of
0:
begin
writeln('Illegal argument : ' + arg);
exit;
end;
1:
begin
// get input name
infname := arg;
state := 0;
end;
2:
begin
// get output name
outfname := arg;
state := 0;
end;
3:
begin
// get codepage
codepage := arg;
state := 0;
end;
end;
end;
end;
{$endregion}
{$region Check args }
// check args
if (infname = '') then
begin
writeln('No input file specified.');
exit;
end;
if not fileexists(infname) then
begin
writeln('Unable to locate file ' + infname + '.');
exit;
end;
if (outfname = '') then
begin
writeln('No output file specified.');
exit;
end;
// check codepages
found := false;
for cp := FirstCP to LastCP do
begin
if Upcase(codepage) = Upcase(CodePageNames[cp]) then
begin
found := true;
break;
end;
end;
if not found then
begin
writeln('Unknown codepage ' + codepage + '.');
exit;
end;
{$endregion}
// do it.
data := Convert(cp, infname);
assign(fout, outfname);
rewrite(fout);
write(fout, data);
close(fout);
writeln('Done.');
end.
|
(******************************************************************************
* *
* MpuWinNT.pas -- Contains header translations from WinNT.h and LM.h and *
* functions only available on Windows NT and higher *
* *
* Copyright (c) 2006 Michael Puff http://www.michael-puff.de *
* *
******************************************************************************)
(*****************************************************************************
* *
* COPYRIGHT NOTICE *
* *
* Copyright (c) 2001-2006, Michael Puff ["copyright holder(s)"] *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. 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. *
* 3. The name(s) of the copyright holder(s) may not 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 *
* FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* REGENTS 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. *
* *
******************************************************************************)
{$WARN SYMBOL_PLATFORM OFF}
{$I CompilerSwitches.inc}
unit MpuWinNT;
interface
uses
windows;
type
LPBYTE = PBYTE;
///// XP Themes ///////////////////////////////////////////////////////////////////
type
TEnableThemeDialogTexture = function(wnd: HWND; dwFlags: dword): HRESULT; stdcall;
const
ETDT_ENABLE = $00000002;
ETDT_USETABTEXTURE = $00000004;
///// CreateProcess //////////////////////////////////////////////////////////////
type
TStartupInfoW = record
cb: DWORD;
lpReserved: LPWSTR;
lpDesktop: LPWSTR;
lpTitle: LPWSTR;
dwX: DWORD;
dwY: DWORD;
dwXSize: DWORD;
dwYSize: DWORD;
dwXCountChars: DWORD;
dwYCountChars: DWORD;
dwFillAttribute: DWORD;
dwFlags: DWORD;
wShowWindow: WORD;
cbReserved2: WORD;
lpReserved2: LPBYTE;
hStdInput: THANDLE;
hStdOutput: THANDLE;
hStdError: THANDLE;
end;
PStartupInfoW = ^TStartupInfoW;
PPROCESS_INFORMATION = ^PROCESS_INFORMATION;
{$EXTERNALSYM PPROCESS_INFORMATION}
TProcessInformation = record
hProcess: THandle;
hThread: THandle;
dwProcessId: DWORD;
dwThreadId: DWORD;
end;
PProcessInformation = ^TProcessInformation;
const
STARTF_USESHOWWINDOW = $00000001;
STARTF_USESIZE = $00000002;
STARTF_USEPOSITION = $00000004;
STARTF_USECOUNTCHARS = $00000008;
STARTF_USEFILLATTRIBUTE = $00000010;
STARTF_RUNFULLSCREEN = $00000020;
STARTF_FORCEONFEEDBACK = $00000040;
STARTF_FORCEOFFFEEDBACK = $00000080;
STARTF_USESTDHANDLES = $00000100;
STARTF_USEHOTKEY = $00000200;
LOGON_WITH_PROFILE = $00000001;
LOGON_NETCREDENTIALS_ONLY = $00000002;
LOGON_ZERO_PASSWORD_BUFFER = DWORD($80000000);
CREATE_DEFAULT_ERROR_MODE = $04000000;
CREATE_NEW_CONSOLE = $00000010;
CREATE_NEW_PROCESS_GROUP = $00000200;
CREATE_SEPARATE_WOW_VDM = $00000800;
CREATE_SUSPENDED = $00000004;
CREATE_UNICODE_ENVIRONMENT = $00000400;
////////////////////////////////////////////////////////////////////////////////
/// CreateTimerQueueTimer //////////////////////////////////////////////////////
type
WAITORTIMERCALLBACKFUNC = procedure(P: Pointer; B: ByteBool); stdcall;
WAITORTIMERCALLBACK = WAITORTIMERCALLBACKFUNC;
function CreateProcessWithLogonW(lpUsername, lpDomain, lpPassword: LPWSTR;
dwLogonFlags: dword; lpApplicationName, lpCommandLine: LPWSTR;
dwCreationFlags: dword; lpEnvironment: pointer;
lpCurrentDirectory: LPWSTR; lpStartupInfo: PStartUpInfoW;
lpProcessInfo: PProcessInformation): boolean; stdcall; external 'advapi32.dll';
function CreateTimerQueueTimer(var phNewTimer: THandle; TimerQueue: THandle;
Callback: WAITORTIMERCALLBACK; Parameter: Pointer; DueTime, Period: DWORD;
Flags: ULONG): BOOL; stdcall;
function DeleteTimerQueueTimer(TimerQueue, Timer, CompletionEvent: THandle): BOOL; stdcall;
/// MessageboxCheck ///////////////////////////////////////////////////////////
function MessageBoxCheck(hWnd: THandle; Text: PChar; Title: PChar; dwType: DWORD; Default: Integer; RegVal: PChar):
Integer; stdcall;
function LoadThemeDLL(wnd: hWnd; dwFlags: DWord): Boolean;
function EnablePrivilege(const Privilege: string; fEnable: Boolean; out PreviousState: Boolean): DWORD;
implementation
const
netapi32lib = 'netapi32.dll';
advapi32 = 'advapi32.dll';
shlwapi = 'shlwapi.dll';
xptheme = 'uxtheme.dll';
function LoadThemeDLL(wnd: hWnd; dwFlags: DWord): Boolean;
var
EnableThemeDlgText: TEnableThemeDialogTexture;
hThemeDll : THandle;
DllResult : HRESULT;
begin
Result := False;
hThemeDll := LoadLibrary(xptheme);
if hThemeDll <> 0 then
begin
@EnableThemeDlgText := GetProcAddress(hThemeDll, 'EnableThemeDialogTexture');
if @EnableThemeDlgText <> nil then
begin
DllResult := EnableThemeDlgText(wnd, dwFlags);
Result := DllResult = S_OK;
end;
FreeLibrary(hThemeDll);
end;
end;
function MessageBoxCheck; external shlwapi index 185;
function CreateTimerQueueTimer; external 'kernel32.dll' name 'CreateTimerQueueTimer';
function DeleteTimerQueueTimer; external 'kernel32.dll' name 'DeleteTimerQueueTimer';
function EnablePrivilege(const Privilege: string; fEnable: Boolean; out PreviousState: Boolean): DWORD;
var
Token : THandle;
NewState : TTokenPrivileges;
Luid : TLargeInteger;
PrevState : TTokenPrivileges;
Return : DWORD;
begin
SetLastError(0); // Clear last system error state
PreviousState := True;
if (GetVersion() > $80000000) then // Win9x
Result := ERROR_SUCCESS
else // WinNT
begin
if OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, Token) then
begin
try
if LookupPrivilegeValue(nil, PChar(Privilege), Luid) then
begin
NewState.PrivilegeCount := 1;
NewState.Privileges[0].Luid := Luid;
if fEnable then
NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
else
NewState.Privileges[0].Attributes := 0;
if AdjustTokenPrivileges(Token, False, NewState, SizeOf(TTokenPrivileges), PrevState, Return) then
begin
PreviousState := (PrevState.Privileges[0].Attributes and SE_PRIVILEGE_ENABLED <> 0);
end;
end;
finally
CloseHandle(Token);
end;
end;
Result := GetLastError;
end;
end;
end.
|
unit Domain.Entity.TabelaPreco;
interface
uses
System.Classes, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types,EF.Core.List,
EF.Mapping.Atributes, Domain.Entity.ItensTabelaPreco, Domain.Consts;
type
[Table('TabelaPrecos')]
TTabelaPreco = class( TEntityBase )
private
FDescricao: TString;
FItensTabelaPreco: Collection<TItensTabelaPreco>;
public
constructor Create;override;
published
[Column('Descricao',varchar50,false)]
property Descricao: TString read FDescricao write FDescricao;
[NotMapped]
property ItensTabelaPreco: Collection<TItensTabelaPreco> read FItensTabelaPreco write FItensTabelaPreco;
end;
implementation
{ TTabelaPreco }
constructor TTabelaPreco.Create;
begin
inherited;
ItensTabelaPreco:= Collection<TItensTabelaPreco>.create;
end;
initialization RegisterClass(TTabelaPreco);
finalization UnRegisterClass(TTabelaPreco);
end.
|
unit CommentRemovalVisitor;
interface
uses
Classes, SysUtils,
ParseTreeNode, SourceToken, Tokens,
SourceTreeWalker;
type
TCommentRemovalVisitor = class (TInterfacedObject, INodeVisitor)
procedure Visit(Node: TParseTreeNode);
end;
implementation
{ TCommentRemovalVisitor }
procedure TCommentRemovalVisitor.Visit(Node: TParseTreeNode);
begin
if (Node is TSourceToken) and (TSourceToken(Node).TokenType = ttComment) then
Node.Parent.RemoveChild(Node);
end;
end.
|
{
***************************************************
PSPdisp (c) 2008 - 2015 Jochen Schleu
graphic.pas - screen capturing and drawing
This software is licensed under the BSD license.
See license.txt for details.
***************************************************
}
unit graphic;
interface
uses
main, Windows, Controls;
const
BitmapColorBytes = 3;
ROTATION_OFF: Cardinal = $00000000;
ROTATION_90: Cardinal = $01000000;
ROTATION_180: Cardinal = $02000000;
ROTATION_270: Cardinal = $03000000;
var
JpegBuffer: Array[0..500 * 1024] of Byte;
JpegQuality: Word;
ChangeRotationOnNextFrame: Boolean;
TargetWidth: Integer;
TargetHeight: Integer;
Rotation: LongWord;
TempViewportWidth: Integer;
TempViewportHeight: Integer;
ForceTransmission: Boolean;
procedure GraphicInitBitmaps;
procedure GraphicDrawCursor(x: Integer; y: Integer);
procedure GraphicDrawScreen;
function GraphicCompress(Width: LongWord; Height: LongWord): LongWord;
procedure GraphicChangeRotation;
procedure GraphicSetBitmapBuffer(Start: Pointer);
procedure GraphicDrawSideShowNotAvailableMessage;
procedure GetUpdatedMousePosition;
implementation
uses
compress, display, mainloop;
var
DesktopDC: HDC;
CompatibleDC: HDC;
LandscapeBitmapHandle: HBITMAP;
PortraitBitmapHandle: HBITMAP;
CurrentBitmapHandle: HBITMAP;
BitmapBuffer: Array[0..480 * 272 * BitmapColorBytes] of Byte;
HideMouseCursor: Boolean;
{
GraphicInitBitmaps
---------------------------------------------------
Create DCs and bitmaps.
---------------------------------------------------
}
procedure GraphicInitBitmaps;
begin
// These initializations only have to be done once.
DesktopDC := GetWindowDC(GetDesktopWindow());
CompatibleDC := CreateCompatibleDC(DesktopDC);
// Create Bitmaps
PortraitBitmapHandle := CreateCompatibleBitmap(DesktopDC, 272, 480);
LandscapeBitmapHandle := CreateCompatibleBitmap(DesktopDC, 480, 272);
CurrentBitmapHandle := PortraitBitmapHandle;
SelectObject(compatibleDC, CurrentBitmapHandle);
Rotation := ROTATION_OFF;
TempViewportWidth := 480;
TempViewportHeight := 272;
// Set mode for downsampling blits to the nicest looking one.
SetStretchBltMode(CompatibleDC, STRETCH_HALFTONE);
SetBrushOrgEx(CompatibleDC, 0, 0, nil);
end;
{
GraphicChangeRotation
---------------------------------------------------
Reinitialise the bitmaps when the orientation
changed.
---------------------------------------------------
}
procedure GraphicChangeRotation;
begin
ReleaseDC(CurrentBitmapHandle, CompatibleDC);
if (TempViewportWidth = 480) and (TempViewportHeight = 272) then
begin
// Unstretched, enable grabbing of transparent windows
SetStretchBltMode(CompatibleDC, COLORONCOLOR);
SetBrushOrgEx(CompatibleDC, 0, 0, nil);
end
else
begin
// Set mode for downsampling blits to the nicest looking one.
if MainForm.MenuFastImageStretching.Checked or ((480 div TempViewportWidth) > 0) and ((480 mod TempViewportWidth) = 0) then
SetStretchBltMode(CompatibleDC, COLORONCOLOR)
else
SetStretchBltMode(CompatibleDC, STRETCH_HALFTONE);
SetBrushOrgEx(CompatibleDC, 0, 0, nil);
end;
if MainForm.MenuRotationOff.Checked then
begin
CurrentBitmapHandle := LandscapeBitmapHandle;
TargetWidth := 480;
TargetHeight := 272;
ViewportWidth := TempViewportWidth;
ViewportHeight := TempViewportHeight;
Rotation := ROTATION_OFF;
end
else if MainForm.MenuRotation90.Checked then
begin
CurrentBitmapHandle := PortraitBitmapHandle;
TargetWidth := 272;
TargetHeight := 480;
ViewportWidth := TempViewportHeight;
ViewportHeight := TempViewportWidth;
Rotation := ROTATION_90;
end
else if MainForm.MenuRotation180.Checked then
begin
CurrentBitmapHandle := LandscapeBitmapHandle;
TargetWidth := 480;
TargetHeight := 272;
ViewportWidth := TempViewportWidth;
ViewportHeight := TempViewportHeight;
Rotation := ROTATION_180;
end
else if MainForm.MenuRotation270.Checked then
begin
CurrentBitmapHandle := PortraitBitmapHandle;
TargetWidth := 272;
TargetHeight := 480;
ViewportWidth := TempViewportHeight;
ViewportHeight := TempViewportWidth;
Rotation := ROTATION_270;
end;
SelectObject(compatibleDC, CurrentBitmapHandle);
end;
{
GraphicGetBitmapBits
---------------------------------------------------
Copy the bitmap from the Windows buffer to a
local buffer.
---------------------------------------------------
}
procedure GraphicGetBitmapBits;
var
Info : BITMAPINFO;
begin
// GetBitmapBits(LandscapeBitmapHandle, 480 * 272 * 4, @BitmapBuffer);
ZeroMemory(@Info, SizeOf(BITMAPINFO));
Info.bmiHeader.biSize := SizeOf(Info.bmiHeader);
Info.bmiHeader.biWidth := TargetWidth;
Info.bmiHeader.biHeight := {-1 *} TargetHeight;
Info.bmiHeader.biPlanes := 1;
Info.bmiHeader.biBitCount := BitmapColorBytes * 8;
if ((ConnectionMode = ModeUsb) and (MainForm.MenuQualityUncompressed.Checked)) then
GetDIBits(CompatibleDC, CurrentBitmapHandle, 0, TargetHeight, @JpegBuffer, Info, DIB_RGB_COLORS)
else
GetDIBits(CompatibleDC, CurrentBitmapHandle, 0, TargetHeight, @BitmapBuffer, Info, DIB_RGB_COLORS);
end;
{
GraphicDrawCursor
---------------------------------------------------
Draw the mouse cursor onto the bitmap send
to the psp.
---------------------------------------------------
}
procedure GraphicDrawCursor(x: Integer; y: Integer);
var
CursorInfo: TCursorInfo;
IconInfo: TIconInfo;
IconX: Integer;
IconY: Integer;
IconScalingX: Integer;
IconScalingY: Integer;
begin
CursorInfo.cbSize := SizeOf(TCursorInfo);
if GetCursorInfo(CursorInfo) then
begin
if CursorInfo.Flags = CURSOR_SHOWING then
begin
if GetIconInfo(CursorInfo.hCursor, IconInfo) then
begin
if MainForm.MenuFitScreen.Checked then
begin
IconX := Round((CursorInfo.ptScreenPos.x - MonitorLeft) / (MonitorWidth / TargetWidth)) - Integer(IconInfo.xHotspot);
IconY := Round((CursorInfo.ptScreenPos.y - MonitorTop) / (MonitorHeight / TargetHeight)) - Integer(IconInfo.yHotspot);
IconScalingX := Round(32 * TargetHeight / MonitorHeight);
IconScalingY := Round(32 * TargetWidth / MonitorWidth);
end
else if MainForm.MenuFitScreen16to9.Checked then
begin
IconX := Round((CursorInfo.ptScreenPos.x - MonitorLeft) / (MonitorWidth / TargetWidth)) - Integer(IconInfo.xHotspot);
IconY := Round((CursorInfo.ptScreenPos.y - MonitorTop - ((MonitorHeight - (MonitorWidth * 9) div 16) div 2)) / (((MonitorWidth * 9) div 16) / TargetHeight)) - Integer(IconInfo.yHotspot);
IconScalingX := Round(32 * TargetHeight / MonitorHeight);
IconScalingY := Round(32 * TargetWidth / MonitorWidth);
end
else begin
IconX := Round(((CursorInfo.ptScreenPos.x - MonitorLeft) - x - Integer(IconInfo.xHotspot)) * (TargetWidth / ViewPortWidth));
IconY := Round(((CursorInfo.ptScreenPos.y - MonitorTop) - y - Integer(IconInfo.yHotspot)) * (TargetHeight / ViewPortHeight));
IconScalingX := Round(32 * TargetHeight / ViewPortHeight);
IconScalingY := Round(32 * TargetWidth / ViewPortWidth);
end;
if (MainForm.MenuScaleCursor.Checked) then
DrawIconEx(CompatibleDC, IconX, IconY, CursorInfo.hCursor, IconScalingX, IconScalingY, 0, 0, DI_NORMAL)
else
DrawIcon(CompatibleDC, IconX, IconY, CursorInfo.hCursor);
DeleteObject(IconInfo.hbmMask);
DeleteObject(IconInfo.hbmColor);
end;
end;
end;
end;
{
GetUpdatedMousePosition
---------------------------------------------------
Retrieve the mouse cursor position.
---------------------------------------------------
}
procedure GetUpdatedMousePosition;
begin
try
tempX := Mouse.CursorPos.x - MonitorLeft;
tempY := Mouse.CursorPos.y - MonitorTop;
except
// An exception occurs here under Vista if the "elevation" dialog
// pops up or the display style is changed (e.g. Aero -> Vista Basic)
tempX := lastTempX;
tempY := lastTempY;
end;
lastTempX := tempX;
lastTempY := tempY;
// Check if the cursor must be hidden / restored
if ((lastCursorPosition.x <> tempX) or (lastCursorPosition.y <> tempY)) then
begin
TimeSinceLastMouseMove := 0;
HideMouseCursor := False;
end
else if (TimeSinceLastMouseMove > 3000) then
HideMouseCursor := MainForm.MenuHideCurser.Checked;
lastCursorPosition.x := tempX;
lastCursorPosition.y := tempY;
end;
{
GraphicDrawScreen
---------------------------------------------------
Copy the framebuffer to the Bitmap canvas,
choose the right viewport and apply stretching
if necessary.
---------------------------------------------------
}
procedure GraphicDrawScreen;
var
MonitorTop16to9Offset: Integer;
MonitorHeight16to9: Integer;
i: Integer;
NewDeviceNumber: Integer;
LastCursorPositionAbsolute: TPoint;
begin
if ChangeRotationOnNextFrame then
begin
ChangeRotationOnNextFrame := False;
GraphicChangeRotation;
end;
GetUpdatedMousePosition;
if MainForm.MenuFollowMouseAcrossScreens.Checked then
begin
// Check if the mouse is still on the current screen
if not ((tempX >= 0) and (tempX < MonitorWidth) and (tempY >= 0) and (tempY < MonitorHeight)) then
begin
// Get the screen the mouse is on
LastCursorPositionAbsolute.x := lastCursorPosition.x + MonitorLeft;
LastCursorPositionAbsolute.y := lastCursorPosition.y + MonitorTop;
NewDeviceNumber := DispGetDeviceContainingPoint(LastCursorPositionAbsolute);
if (NewDeviceNumber > -1) then
begin
for i := MenuDisplayDeviceFirstIndex to MainForm.MenuDisplay.Count - 1 do
begin
if MainForm.MenuDisplay.Items[i].Tag = NewDeviceNumber then
begin
MainForm.MenuDisplay.Items[i].Click;
GetUpdatedMousePosition;
ForceTransmission := True;
Break;
end;
end;
end;
end;
end;
if MainForm.MenuFitScreen.Checked then
begin
x := 0;
y := 0;
StretchBlt(compatibleDC, 0, 0, TargetWidth, TargetHeight, DesktopDC, MonitorLeft, MonitorTop, MonitorWidth, MonitorHeight, copyMode);
end
else if MainForm.MenuFitScreen16to9.Checked then
begin
x := 0;
y := 0;
MonitorHeight16to9 := (MonitorWidth * 9) div 16;
MonitorTop16to9Offset := (MonitorHeight - MonitorHeight16to9) div 2;
StretchBlt(compatibleDC, 0, 0,TargetWidth, TargetHeight, DesktopDC, MonitorLeft, MonitorTop + MonitorTop16to9Offset, MonitorWidth, MonitorHeight16to9, copyMode);
end
else begin
// Check if we are on the virtual screen and if mouse following is enabled.
if (tempX >= 0) and (tempX < MonitorWidth) and (tempY >= 0) and (tempY < MonitorHeight) then
begin
if MainForm.MenuFollowMouse.Checked then
begin
x := Round((tempX / MonitorWidth) * (MonitorWidth - ViewPortWidth));
y := Round((tempY / MonitorHeight) * (MonitorHeight - ViewPortHeight));
end
else if MainForm.MenuFollowMouse2.Checked then
begin
x := tempX - ViewPortWidth div 2;
y := tempY - ViewPortHeight div 2;
if (tempX < ViewPortWidth div 2) then
x := 0;
if (tempX > MonitorWidth - ViewPortWidth div 2) then
x := MonitorWidth - ViewPortWidth;
if (tempY < ViewPortHeight div 2) then
y := 0;
if (tempY > MonitorHeight - ViewPortHeight div 2) then
y := MonitorHeight - ViewPortHeight;
end
else if MainForm.MenuStaticViewport.Checked then
begin
x := StartXSetting;
y := StartYSetting;
end;
end
else begin
// not on the selected screen, use static viewport
x := StartXSetting;
y := StartYSetting;
end;
if (ViewPortWidth <> 480) then
StretchBlt(compatibleDC, 0, 0, TargetWidth, TargetHeight, DesktopDC, MonitorLeft + x, MonitorTop + y, ViewPortWidth, ViewPortHeight, copyMode)
else
BitBlt(compatibleDC, 0, 0, TargetWidth, TargetHeight, DesktopDC, MonitorLeft + x, MonitorTop + y, copyMode);
end;
if (not HideMouseCursor) then
GraphicDrawCursor(x, y);
GraphicGetBitmapBits;
end;
{
GraphicSetBitmapBuffer
---------------------------------------------------
Copy the bitmap or jpeg data to the final output
buffer.
---------------------------------------------------
}
procedure GraphicSetBitmapBuffer(Start: Pointer);
begin
if (not (ConnectionMode = ModeWlan) and (MainForm.MenuQualityUncompressed.Checked)) then
CopyMemory(@JpegBuffer, Start, 480 * 272 * 3)
else
CopyMemory(@BitmapBuffer, Start, 480 * 272 * 3);
end;
{
GraphicDrawSideShowNotAvailableMessage
---------------------------------------------------
Write a message to the SideShow canvas if the
driver is not available.
---------------------------------------------------
}
procedure GraphicDrawSideShowNotAvailableMessage;
begin
TargetWidth := 480;
TargetHeight := 272;
// SelectObject(compatibleDC, GetStockObject(DC_BRUSH));
SelectObject(compatibleDC, GetStockObject(BLACK_BRUSH));
SetTextColor(compatibleDC, RGB(255, 255, 255));
SetBkColor(compatibleDC, RGB(0, 0, 0));
Rectangle(compatibleDC, 0, 0, 480, 480);
TextOut(CompatibleDC, 50, 50, 'SideShow driver not loaded.', 27);
GraphicGetBitmapBits;
// ZeroMemory(@BitmapBuffer, 480 * 272 * 3);
end;
{
GraphicCompress
---------------------------------------------------
Do the compression.
---------------------------------------------------
Returns the size of the output image.
}
function GraphicCompress(Width: LongWord; Height: LongWord): LongWord;
begin
if ((ConnectionMode = ModeWlan) or (not MainForm.MenuQualityUncompressed.Checked)) then
begin
if (MainForm.MenuUseSideshow.Checked) then
Result := CompressToJPEG(MainForm.MenuQualitySideShow.Tag, BitmapBuffer, JpegBuffer, Width, Height)
else
Result := CompressToJPEG(JpegQuality, BitmapBuffer, JpegBuffer, Width, Height);
end
else
begin
// CopyMemory(@(JpegBuffer[0]), @(BitmapBuffer[0]), 480 * 272 * 3);
Result := 480 * 272 * 3;
end;
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>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.dml.generator.firebird;
interface
uses
SysUtils,
StrUtils,
Rtti,
ormbr.dml.generator,
ormbr.mapping.classes,
ormbr.mapping.explorer,
ormbr.factory.interfaces,
ormbr.driver.register,
ormbr.dml.commands,
ormbr.criteria;
type
/// <summary>
/// Classe de banco de dados Firebird
/// </summary>
TDMLGeneratorFirebird = class(TDMLGeneratorAbstract)
protected
function GetGeneratorSelect(ACriteria: ICriteria): string; override;
public
constructor Create; override;
destructor Destroy; override;
function GeneratorSelectAll(AClass: TClass; APageSize: Integer;
AID: Variant): string; override;
function GeneratorSelectWhere(AClass: TClass; AWhere: string; AOrderBy: string;
APageSize: Integer): string; override;
function GeneratorSequenceCurrentValue(AObject: TObject;
ACommandInsert: TDMLCommandInsert): Int64; override;
function GeneratorSequenceNextValue(AObject: TObject;
ACommandInsert: TDMLCommandInsert): Int64; override;
end;
implementation
{ TDMLGeneratorFirebird }
constructor TDMLGeneratorFirebird.Create;
begin
inherited;
FDateFormat := 'MM/dd/yyyy';
FTimeFormat := 'HH:MM:SS';
end;
destructor TDMLGeneratorFirebird.Destroy;
begin
inherited;
end;
function TDMLGeneratorFirebird.GetGeneratorSelect(ACriteria: ICriteria): string;
begin
inherited;
ACriteria.AST.Select.Columns.Columns[0].Name := 'FIRST %s SKIP %s ' +
ACriteria.AST.Select.Columns.Columns[0].Name;
Result := ACriteria.AsString;
end;
function TDMLGeneratorFirebird.GeneratorSelectAll(AClass: TClass;
APageSize: Integer; AID: Variant): string;
var
LCriteria: ICriteria;
begin
LCriteria := GetCriteriaSelect(AClass, AID);
if APageSize > -1 then
Result := GetGeneratorSelect(LCriteria)
else
Result := LCriteria.AsString;
end;
function TDMLGeneratorFirebird.GeneratorSelectWhere(AClass: TClass;
AWhere: string; AOrderBy: string; APageSize: Integer): string;
var
LCriteria: ICriteria;
begin
LCriteria := GetCriteriaSelect(AClass, -1);
LCriteria.Where(AWhere);
LCriteria.OrderBy(AOrderBy);
if APageSize > -1 then
Result := GetGeneratorSelect(LCriteria)
else
Result := LCriteria.AsString;
end;
function TDMLGeneratorFirebird.GeneratorSequenceCurrentValue(AObject: TObject;
ACommandInsert: TDMLCommandInsert): Int64;
begin
Result := ExecuteSequence(
Format('SELECT GEN_ID(%s, 0) FROM RDB$DATABASE;', [ACommandInsert.Sequence.Name]));
end;
function TDMLGeneratorFirebird.GeneratorSequenceNextValue(AObject: TObject;
ACommandInsert: TDMLCommandInsert): Int64;
begin
Result := ExecuteSequence(
Format('SELECT GEN_ID(%s, %s) FROM RDB$DATABASE;', [ACommandInsert.Sequence.Name,
IntToStr(ACommandInsert.Sequence.Increment)]));
end;
initialization
TDriverRegister.RegisterDriver(dnFirebird, TDMLGeneratorFirebird.Create);
end.
|
program P_10_2;
var
s: String;
procedure WriteDouble(s:String);
var
i: Integer;
begin
writeln('Double:');
for i := 0 to Length(s) do
begin
write(s[i],s[i]);
end;
end;
procedure CountLetterA(a:String);
var
letter: String;
i: Integer;
count:Integer;
begin
letter:= 'a';
count:= 0;
for i := 0 to Length(s) do
begin
if s[i] = letter then
count:= count + 1;
end;
writeln();
writeln('A count:');
writeln(letter,' was ',count,' times');
end;
begin
writeln('Please enter the text');
readln(s);
WriteDouble(s);
writeln();
CountLetterA(s);
readln();
end.
|
unit uEnumeratorInterface;
interface
type
IEnumerator<T> = interface
function GetCurrent: T;
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
IEnumerable<T> = interface
function GetEnumerator: IEnumerator<T>;
end;
TIndexedStringStorage = class(TInterfacedObject)
private
FString: string;
FIndex: Integer;
strict protected
function GetCurrent: Char; virtual;
public
constructor Create(const aString: string);
destructor Destroy(); override;
property Current: Char read GetCurrent;
end;
ICharEnumerator = IEnumerator<Char>;
TStringEnumerator = class(TIndexedStringStorage, ICharEnumerator)
public
constructor Create(const aString: string);
function MoveNext: Boolean; virtual;
end;
TForInDemoClassReverseEnumerator = class(TIndexedStringStorage, ICharEnumerator)
public
constructor Create(const aString: string);
function MoveNext(): Boolean; virtual;
end;
TEnumerationType = (Forward, Backwards);
TInterfaceEnumeratorDemo = class(TInterfacedObject, IEnumerable<Char>)
private
FTheString: string;
FDirection: TEnumerationType;
procedure SetTheString(const Value: string);
procedure SetDirection(const Value: TEnumerationType);
public
constructor Create(const aString: string);
function GetEnumerator: ICharEnumerator;
property Direction: TEnumerationType read FDirection write SetDirection;
property TheString: string read FTheString write SetTheString;
end;
procedure DoInterfaceStuff;
implementation
procedure DoInterfaceStuff;
var
InterfacedEnumerator: TInterfaceEnumeratorDemo;
c: Char;
begin
InterfacedEnumerator := TInterfaceEnumeratorDemo.Create('GoodbyeWorld');
try
for c in InterfacedEnumerator do
begin
Write(C, ',');
end;
WriteLn;
InterfacedEnumerator.Direction := TEnumerationType.Backwards;
for c in InterfacedEnumerator do
begin
Write(C, ',');
end;
WriteLn;
finally
InterfacedEnumerator.Free;
end;
end;
{ TInterfaceEnumerator }
constructor TInterfaceEnumeratorDemo.Create(const aString: string);
begin
inherited Create();
FTheString := aString;
FDirection := TEnumerationType.Forward;
end;
function TInterfaceEnumeratorDemo.GetEnumerator: IEnumerator<Char>;
begin
case Direction of
Forward: Result := TStringEnumerator.Create(TheString);
Backwards: Result := TForInDemoClassReverseEnumerator.Create(TheString);
end;
end;
procedure TInterfaceEnumeratorDemo.SetDirection(const Value: TEnumerationType);
begin
FDirection := Value;
end;
procedure TInterfaceEnumeratorDemo.SetTheString(const Value: string);
begin
FTheString := Value;
end;
{ TForInDemoClassReverseEnumerator }
constructor TForInDemoClassReverseEnumerator.Create(const aString: string);
begin
inherited Create(aString);
FIndex := Length(aString) + 1;
end;
function TForInDemoClassReverseEnumerator.MoveNext(): Boolean;
begin
Dec(FIndex);
Result := FIndex > 0;
end;
{ TStringEnumerator }
constructor TStringEnumerator.Create(const aString: string);
begin
inherited Create(aString);
FIndex := 0;
end;
function TStringEnumerator.MoveNext: Boolean;
begin
Result := FIndex < Length(FString);
if Result then
begin
Inc(FIndex);
end;
end;
{ TIndexedStringStorage }
constructor TIndexedStringStorage.Create(const aString: string);
begin
Writeln(ClassName, '.Create();');
inherited Create();
FString := aString;
end;
destructor TIndexedStringStorage.Destroy();
begin
inherited;
Writeln;
Writeln(ClassName, '.Destroy();');
end;
function TIndexedStringStorage.GetCurrent: Char;
begin
Result := FString[FIndex];
end;
end.
|
unit Model.DestinosTransporte;
interface
type
TDestinosTransporte = class
private
var
FDestino: Integer;
FDescricao: String;
FLog: String;
public
property Destino: Integer read FDestino write FDestino;
property Descricao: String read FDescricao write FDEscricao;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create(pFDestino: Integer; pFDescricao: String; pFLog: String); overload;
end;
implementation
{ TDestiosTransporte }
constructor TDestinosTransporte.Create;
begin
inherited Create;
end;
constructor TDestinosTransporte.Create(pFDestino: Integer; pFDescricao, pFLog: String);
begin
FDestino := pFDestino;
FDescricao := pFDescricao;
FLog := pFLog;
end;
end.
|
unit fAppointment;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uAppointments, System.Actions, Vcl.ActnList,
Data.DB, Aurelius.Bind.Dataset, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids,
Entities.Scheduling, Entidades.Cadastro, fAppointmentList, fAppointmentPlanner;
type
TfmAppointments = class(TForm)
Button1: TButton;
ActionList1: TActionList;
acNewAppointment: TAction;
PageControl1: TPageControl;
tsList: TTabSheet;
frmList: TfrmAppointmentList;
TabSheet2: TTabSheet;
frmPlanner1: TfrmAppointmentPlanner;
acCancelAppointment: TAction;
Button2: TButton;
acFinishAppointment: TAction;
Button3: TButton;
procedure acNewAppointmentExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure frmPlanner1Planner1PlannerDblClick(Sender: TObject; Position, FromSel, FromSelPrecise,
ToSel, ToSelPrecise: Integer);
procedure acCancelAppointmentUpdate(Sender: TObject);
procedure acCancelAppointmentExecute(Sender: TObject);
procedure acFinishAppointmentUpdate(Sender: TObject);
procedure acFinishAppointmentExecute(Sender: TObject);
private
Model: IAppointmentModel;
procedure RefreshData;
function SelectedAppointment: TAppointment;
public
class procedure Start(AModel: IAppointmentModel);
end;
implementation
uses
fNewAppointment;
{$R *.dfm}
{ TfmAppointments }
procedure TfmAppointments.acCancelAppointmentExecute(Sender: TObject);
begin
if MessageDlg(
Format('Confirma o CANCELAMENTO desse agendamento (%s - %s)?',
[SelectedAppointment.Animal.Nome,
SelectedAppointment.Animal.Proprietario.Nome]),
mtConfirmation,
[mbYes, mbNo], 0, mbNo) = mrYes then
begin
Model.CancelAppointment(SelectedAppointment);
RefreshData;
end;
end;
procedure TfmAppointments.acCancelAppointmentUpdate(Sender: TObject);
begin
acCancelAppointment.Enabled :=
(PageControl1.ActivePage = tsList)
and (SelectedAppointment <> nil)
and Model.CanCancelAppointment(SelectedAppointment);
end;
procedure TfmAppointments.acFinishAppointmentExecute(Sender: TObject);
begin
if MessageDlg(
Format('Confirma a CONCLUSÃO desse agendamento (%s - %s)?',
[SelectedAppointment.Animal.Nome,
SelectedAppointment.Animal.Proprietario.Nome]),
mtConfirmation,
[mbYes, mbNo], 0, mbNo) = mrYes then
begin
Model.FinishAppointment(SelectedAppointment);
RefreshData;
end;
end;
procedure TfmAppointments.acFinishAppointmentUpdate(Sender: TObject);
begin
acFinishAppointment.Enabled :=
(PageControl1.ActivePage = tsList)
and (SelectedAppointment <> nil)
and Model.CanFinishAppointment(SelectedAppointment);
end;
procedure TfmAppointments.acNewAppointmentExecute(Sender: TObject);
begin
if TfmNewAppointment.Start(Self.Model) then
RefreshData;
end;
procedure TfmAppointments.FormShow(Sender: TObject);
begin
RefreshData;
end;
procedure TfmAppointments.frmPlanner1Planner1PlannerDblClick(Sender: TObject; Position, FromSel,
FromSelPrecise, ToSel, ToSelPrecise: Integer);
var
Start, End2: TDateTime;
begin
frmPlanner1.Planner1.SelectionToAbsTime(Start, End2);
if TfmNewAppointment.Start(Self.Model, Start) then
RefreshData;
end;
procedure TfmAppointments.RefreshData;
begin
frmList.SetSourceCriteria(Model.GetPendingAppointments);
frmPlanner1.SetSourceCriteria(Model.GetPendingAppointments);
end;
function TfmAppointments.SelectedAppointment: TAppointment;
begin
Result := frmList.adsAppointments.Current<TAppointment>;
end;
class procedure TfmAppointments.Start(AModel: IAppointmentModel);
var
Form: TfmAppointments;
begin
Form := TfmAppointments.Create(Application);
try
Form.Model := AModel;
Form.ShowModal;
finally
Form.Free;
end;
end;
end.
|
unit UpdateTree;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, DB, Grids, DBGrids, DBGridEh, ComCtrls, Mask,
DBCtrlsEh, DataModule, sLabel, sEdit, sCheckBox, sMaskEdit, sComboBox, sMemo,
sDialogs, sSpeedButton, sTreeView, sBitBtn, MemDS, DBAccess, Uni, sSkinProvider, sSkinManager;
type
TFormUpdateTree = class(TForm)
BitBtnClose: TsBitBtn;
Tree: TsTreeView;
BitBtnSameNode: TsBitBtn;
BitBtnNewNode: TsBitBtn;
BitBtnDelete: TsBitBtn;
qSubTreeExists: TUniQuery;
qSubTreeExistsCNTR: TIntegerField;
QTreeClose: TUniSQL;
qLinesDelete: TUniSQL;
qTreeDelete: TUniSQL;
sSkinManager1: TsSkinManager;
sSkinProvider1: TsSkinProvider;
procedure TreeChange(Sender: TObject; Node: TTreeNode);
procedure TreeExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
procedure BitBtnSameNodeClick(Sender: TObject);
procedure BitBtnNewNodeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BitBtnDeleteClick(Sender: TObject);
private
MyNode:TNodeValue;
// procedure CreateTree;
public
procedure SetPosition(L, T: integer);
procedure SetTree;
end;
var
FormUpdateTree: TFormUpdateTree;
implementation
uses MainForm, ShowCompany, CommonUnit, NewItem, NewSubItem, System.UITypes;
{$R *.dfm}
{ TFormPriceShow }
procedure TFormUpdateTree.SetPosition(L,T:integer);
begin
Left:=L+ShiftLeft;
Top:=T+ShiftTop;
end;
procedure TFormUpdateTree.SetTree;
begin
DM.TreeFulFill(Tree, true,0);
end;
procedure TFormUpdateTree.TreeExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
begin
MyNode.ID:=Integer(Node.Data);
end;
procedure TFormUpdateTree.TreeChange(Sender: TObject; Node: TTreeNode);
begin
MyNode.ID:=Integer(Tree.Selected.Data);
end;
procedure TFormUpdateTree.BitBtnSameNodeClick(Sender: TObject);
begin
if Tree.SelectionCount=0 then
begin
MessageDlg('Выберите один из разделов дерева',mtWarning,[mbCancel],0);
exit;
end;
MyNode.ID:=Integer(Tree.Selected.Data);
if MyNode.ParentID<>0 then
begin
MessageDlg('Запрещено создавать раздел, переместитесь на одну ступень выше',mtError,[mbCancel],0);
exit;
end;
if FormNewSubItem=nil then Application.CreateForm(TFormNewSubItem, FormNewSubItem);
FormNewSubItem.SetPosition(Self.Left,Self.Top);
FormNewSubItem.SetNewSubItem(MyNode.ID,MyNode.Value);
FormNewSubItem.ShowModal;
DM.TreeFulFill(Tree, true,0);
end;
procedure TFormUpdateTree.BitBtnNewNodeClick(Sender: TObject);
begin
if Tree.SelectionCount=0 then
begin
MessageDlg('Выберите один из разделов дерева',mtWarning,[mbCancel],0);
exit;
end;
if MyNode.ParentID<>0 then
begin
MessageDlg('Выберите один из главных разделов',mtError,[mbCancel],0);
exit;
end;
if FormNewItem=nil then Application.CreateForm(TFormNewItem, FormNewItem);
FormNewItem.SetPosition(Self.Left,Self.Top);
FormNewItem.SetNewItem;
FormNewItem.ShowModal;
DM.TreeFulFill(Tree, true,0);
end;
procedure TFormUpdateTree.FormCreate(Sender: TObject);
begin
MyNode:=TNodeValue.Create;
end;
procedure TFormUpdateTree.FormDestroy(Sender: TObject);
begin
MyNode.Destroy;
end;
procedure TFormUpdateTree.BitBtnDeleteClick(Sender: TObject);
begin
if Tree.SelectionCount=0 then
begin
MessageDlg('Выберите один из (под)разделов дерева',mtWarning,[mbCancel],0);
exit;
end;
if MyNode.ParentID=0 then
begin
if MessageDlg('Хотите удалить раздел '+MyNode.Value+' в рубрикаторе? Сначала необходимо удалить подразделы',mtWarning, [mbNo, mbYes],0)=mrNo
then exit;
QSubTreeExists.Close;
QSubTreeExists.ParamByName('PARENTID').AsInteger:=MyNode.ID;
QSubTreeExists.Open;
if QSubTreeExists['CNTR']>0 then
begin
MessageDlg('У раздела есть активные подразделы, удалите их',mtError, [mbYes],0);
exit;
end;
QTreeClose.ParamByName('ID').AsInteger:=MyNode.ID;
QTreeClose.ParamByName('CDATE').AsDate:=Now();
QTreeClose.Execute;
end
else
begin
if MessageDlg('Подтверждаете удаление (под)раздела '+MyNode.Value+'?'+chr(10)+chr(13)
+'Все строки из прайс-листов также будут удалены.',mtConfirmation,[mbNo,mbYes],0)=mrNo then exit;
qLInesDelete.ParamByName('ID').AsInteger:=MyNode.ID;
qLInesDelete.ParamByName('PTDATE').AsDateTime:=Now();
qLInesDelete.Execute;
qTreeDelete.ParamByName('ID').AsInteger:=MyNode.ID;
qTReeDelete.ParamByName('PTDATE').AsDateTime:=Now();
qTReeDelete.Execute;
end;
DM.TreeFulFill(Tree, true,0);
end;
end.
|
unit PatchAPI;
interface
uses
Windows,
SysUtils;
const
//** **//
//** The following constants can be combined and used as the OptionFlags **//
//** parameter in the patch creation apis. **//
//** **//
// CreatePatch Flags...
PATCH_OPTION_USE_BEST = $00000000; // auto choose best (slower)
{$EXTERNALSYM PATCH_OPTION_USE_BEST}
PATCH_OPTION_USE_LZX_BEST = $00000003; // auto choose best of LZX
{$EXTERNALSYM PATCH_OPTION_USE_LZX_BEST}
PATCH_OPTION_USE_LZX_A = $00000001; // normal
{$EXTERNALSYM PATCH_OPTION_USE_LZX_A}
PATCH_OPTION_USE_LZX_B = $00000002; // better on some x86 binaries
{$EXTERNALSYM PATCH_OPTION_USE_LZX_B}
PATCH_OPTION_USE_LZX_LARGE = $00000004; // better support for files >8MB
{$EXTERNALSYM PATCH_OPTION_USE_LZX_LARGE}
PATCH_OPTION_NO_BINDFIX = $00010000; // PE bound imports
{$EXTERNALSYM PATCH_OPTION_NO_BINDFIX}
PATCH_OPTION_NO_LOCKFIX = $00020000; // PE smashed locks
{$EXTERNALSYM PATCH_OPTION_NO_LOCKFIX}
PATCH_OPTION_NO_REBASE = $00040000; // PE rebased image
{$EXTERNALSYM PATCH_OPTION_NO_REBASE}
PATCH_OPTION_FAIL_IF_SAME_FILE = $00080000; // don't create if same
{$EXTERNALSYM PATCH_OPTION_FAIL_IF_SAME_FILE}
PATCH_OPTION_FAIL_IF_BIGGER = $00100000; // fail if patch is larger than simply compressing new file (slower)
{$EXTERNALSYM PATCH_OPTION_FAIL_IF_BIGGER}
PATCH_OPTION_NO_CHECKSUM = $00200000; // PE checksum zero
{$EXTERNALSYM PATCH_OPTION_NO_CHECKSUM}
PATCH_OPTION_NO_RESTIMEFIX = $00400000; // PE resource timestamps
{$EXTERNALSYM PATCH_OPTION_NO_RESTIMEFIX}
PATCH_OPTION_NO_TIMESTAMP = $00800000; // don't store new file timestamp in patch
{$EXTERNALSYM PATCH_OPTION_NO_TIMESTAMP}
PATCH_OPTION_SIGNATURE_MD5 = $01000000; // use MD5 instead of CRC32
{$EXTERNALSYM PATCH_OPTION_SIGNATURE_MD5}
PATCH_OPTION_RESERVED1 = DWORD($80000000); // (used internally)
{$EXTERNALSYM PATCH_OPTION_RESERVED1}
PATCH_OPTION_VALID_FLAGS = $C0FF0007;
{$EXTERNALSYM PATCH_OPTION_VALID_FLAGS}
//** **//
//** The following flags are used with PATCH_OPTION_DATA SymbolOptionFlags: **//
//** **//
// Symbol Option Flags
PATCH_SYMBOL_NO_IMAGEHLP = $00000001; // don't use imagehlp.dll
{$EXTERNALSYM PATCH_SYMBOL_NO_IMAGEHLP}
PATCH_SYMBOL_NO_FAILURES = $00000002; // don't fail patch due to imagehlp failures
{$EXTERNALSYM PATCH_SYMBOL_NO_FAILURES}
PATCH_SYMBOL_UNDECORATED_TOO = $00000004; // after matching decorated symbols, try to match remaining by undecorated names
{$EXTERNALSYM PATCH_SYMBOL_UNDECORATED_TOO}
PATCH_SYMBOL_RESERVED1 = DWORD($80000000); // (used internally)
{$EXTERNALSYM PATCH_SYMBOL_RESERVED1}
//** **//
//** The following flags are used with PATCH_OPTION_DATA ExtendedOptionFlags: **//
//** **//
PATCH_TRANSFORM_PE_RESOURCE_2 = $00000100; // better handling of PE resources (requires 5.2 or higher applyer)
{$EXTERNALSYM PATCH_TRANSFORM_PE_RESOURCE_2}
PATCH_TRANSFORM_PE_IRELOC_2 = $00000200; // better handling of PE stripped relocs (requires 5.2 or higher applyer)
{$EXTERNALSYM PATCH_TRANSFORM_PE_IRELOC_2}
//** **//
//** The following constants can be combined and used as the ApplyOptionFlags **//
//** parameter in the patch apply and test apis. **//
//** **//
// ApplyPatch Flags
APPLY_OPTION_FAIL_IF_EXACT = $00000001; // don't copy new file
{$EXTERNALSYM APPLY_OPTION_FAIL_IF_EXACT}
APPLY_OPTION_FAIL_IF_CLOSE = $00000002; // differ by rebase, bind
{$EXTERNALSYM APPLY_OPTION_FAIL_IF_CLOSE}
APPLY_OPTION_TEST_ONLY = $00000004; // don't create new file
{$EXTERNALSYM APPLY_OPTION_TEST_ONLY}
APPLY_OPTION_VALID_FLAGS = $00000007;
{$EXTERNALSYM APPLY_OPTION_VALID_FLAGS}
//** **//
//** In addition to standard Win32 error codes, the following error codes may **//
//** be returned via GetLastError() when one of the patch APIs fails. **//
//** **//
// CreatePatch error codes
ERROR_PATCH_ENCODE_FAILURE = DWORD($C00E3101); // create
{$EXTERNALSYM ERROR_PATCH_ENCODE_FAILURE}
ERROR_PATCH_INVALID_OPTIONS = DWORD($C00E3102); // create
{$EXTERNALSYM ERROR_PATCH_INVALID_OPTIONS}
ERROR_PATCH_SAME_FILE = DWORD($C00E3103); // create
{$EXTERNALSYM ERROR_PATCH_SAME_FILE}
ERROR_PATCH_RETAIN_RANGES_DIFFER = DWORD($C00E3104); // create
{$EXTERNALSYM ERROR_PATCH_RETAIN_RANGES_DIFFER}
ERROR_PATCH_BIGGER_THAN_COMPRESSED = DWORD($C00E3105); // create
{$EXTERNALSYM ERROR_PATCH_BIGGER_THAN_COMPRESSED}
ERROR_PATCH_IMAGEHLP_FAILURE = DWORD($C00E3106); // create
{$EXTERNALSYM ERROR_PATCH_IMAGEHLP_FAILURE}
// ApplyPatch error codes
ERROR_PATCH_DECODE_FAILURE = DWORD($C00E4101); // apply
{$EXTERNALSYM ERROR_PATCH_DECODE_FAILURE}
ERROR_PATCH_CORRUPT = DWORD($C00E4102); // apply
{$EXTERNALSYM ERROR_PATCH_CORRUPT}
ERROR_PATCH_NEWER_FORMAT = DWORD($C00E4103); // apply
{$EXTERNALSYM ERROR_PATCH_NEWER_FORMAT}
ERROR_PATCH_WRONG_FILE = DWORD($C00E4104); // apply
{$EXTERNALSYM ERROR_PATCH_WRONG_FILE}
ERROR_PATCH_NOT_NECESSARY = DWORD($C00E4105); // apply
{$EXTERNALSYM ERROR_PATCH_NOT_NECESSARY}
ERROR_PATCH_NOT_AVAILABLE = DWORD($C00E4106); // apply
{$EXTERNALSYM ERROR_PATCH_NOT_AVAILABLE}
type
//**************************************************************************************************************************************************//
PATCH_PROGRESS_CALLBACK = function(
CallbackContext : Pointer;
CurrentPosition : ULONG;
MaximumPosition : ULONG) : BOOL; stdcall;
{$EXTERNALSYM PATCH_PROGRESS_CALLBACK}
TPatchProgressCallback = PATCH_PROGRESS_CALLBACK;
PPATCH_PROGRESS_CALLBACK = ^PATCH_PROGRESS_CALLBACK;
{$EXTERNALSYM PPATCH_PROGRESS_CALLBACK}
PPatchProgressCallback = PPATCH_PROGRESS_CALLBACK;
//**************************************************************************************************************************************************//
PATCH_SYMLOAD_CALLBACK = function(
WhichFile : ULONG;
SymbolFileName : LPCSTR;
SymType : ULONG;
SymbolFileCheckSum : ULONG;
SymbolFileTimeDate : ULONG;
ImageFileCheckSum : ULONG;
ImageFileTimeDate : ULONG;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM PATCH_SYMLOAD_CALLBACK}
TPatchSymLoadCallback = PATCH_SYMLOAD_CALLBACK;
PPATCH_SYMLOAD_CALLBACK = ^PATCH_SYMLOAD_CALLBACK;
{$EXTERNALSYM PPATCH_SYMLOAD_CALLBACK}
PPatchSymLoadCallback = PPATCH_SYMLOAD_CALLBACK;
//**************************************************************************************************************************************************//
PPATCH_IGNORE_RANGE = ^PATCH_IGNORE_RANGE;
{$EXTERNALSYM PPATCH_IGNORE_RANGE}
_PATCH_IGNORE_RANGE = record
OffsetInOldFile : ULONG;
LengthInBytes : ULONG;
end;
{$EXTERNALSYM _PATCH_IGNORE_RANGE}
PATCH_IGNORE_RANGE = _PATCH_IGNORE_RANGE;
{$EXTERNALSYM PATCH_IGNORE_RANGE}
TPatchIgnoreRange = PATCH_IGNORE_RANGE;
PPatchIgnoreRange = PPATCH_IGNORE_RANGE;
//**************************************************************************************************************************************************//
PPATCH_RETAIN_RANGE = ^PATCH_RETAIN_RANGE;
{$EXTERNALSYM PPATCH_RETAIN_RANGE}
_PATCH_RETAIN_RANGE = record
OffsetInOldFile : ULONG;
LengthInBytes : ULONG;
OffsetInNewFile : ULONG;
end;
{$EXTERNALSYM _PATCH_RETAIN_RANGE}
PATCH_RETAIN_RANGE = _PATCH_RETAIN_RANGE;
{$EXTERNALSYM PATCH_RETAIN_RANGE}
TPatchRetainRange = PATCH_RETAIN_RANGE;
PPatchRetainRange = PPATCH_RETAIN_RANGE;
//**************************************************************************************************************************************************//
PPATCH_OLD_FILE_INFO_A = ^PATCH_OLD_FILE_INFO_A;
{$EXTERNALSYM PPATCH_OLD_FILE_INFO_A}
_PATCH_OLD_FILE_INFO_A = record
SizeOfThisStruct : ULONG;
OldFileName : LPCSTR;
IgnoreRangeCount : ULONG; // maximum 255
IgnoreRangeArray : PPATCH_IGNORE_RANGE;
RetainRangeCount : ULONG; // maximum 255
RetainRangeArray : PPATCH_RETAIN_RANGE;
end;
{$EXTERNALSYM _PATCH_OLD_FILE_INFO_A}
PATCH_OLD_FILE_INFO_A = _PATCH_OLD_FILE_INFO_A;
{$EXTERNALSYM PATCH_OLD_FILE_INFO_A}
TPatchOldFileInfoA = PATCH_OLD_FILE_INFO_A;
PPatchOldFileInfoA = PPATCH_OLD_FILE_INFO_A;
//**************************************************************************************************************************************************//
PPATCH_OLD_FILE_INFO_W = ^PATCH_OLD_FILE_INFO_W;
{$EXTERNALSYM PPATCH_OLD_FILE_INFO_W}
_PATCH_OLD_FILE_INFO_W = record
SizeOfThisStruct : ULONG;
OldFileName : LPCWSTR;
IgnoreRangeCount : ULONG; // maximum 255
IgnoreRangeArray : PPATCH_IGNORE_RANGE;
RetainRangeCount : ULONG; // maximum 255
RetainRangeArray : PPATCH_RETAIN_RANGE;
end;
{$EXTERNALSYM _PATCH_OLD_FILE_INFO_W}
PATCH_OLD_FILE_INFO_W = _PATCH_OLD_FILE_INFO_W;
{$EXTERNALSYM PATCH_OLD_FILE_INFO_W}
TPatchOldFileInfoW = PATCH_OLD_FILE_INFO_W;
PPatchOldFileInfoW = PPATCH_OLD_FILE_INFO_W;
//**************************************************************************************************************************************************//
PPATCH_OLD_FILE_INFO_H = ^PATCH_OLD_FILE_INFO_H;
{$EXTERNALSYM PPATCH_OLD_FILE_INFO_H}
_PATCH_OLD_FILE_INFO_H = record
SizeOfThisStruct : ULONG;
OldFileHandle : THandle;
IgnoreRangeCount : ULONG; // maximum 255
IgnoreRangeArray : PPATCH_IGNORE_RANGE;
RetainRangeCount : ULONG; // maximum 255
RetainRangeArray : PPATCH_RETAIN_RANGE;
end;
{$EXTERNALSYM _PATCH_OLD_FILE_INFO_H}
PATCH_OLD_FILE_INFO_H = _PATCH_OLD_FILE_INFO_H;
{$EXTERNALSYM PATCH_OLD_FILE_INFO_H}
TPatchOldFileInfoH = PATCH_OLD_FILE_INFO_H;
PPatchOldFileInfoH = PPATCH_OLD_FILE_INFO_H;
//**************************************************************************************************************************************************//
PPATCH_OLD_FILE_INFO = ^PATCH_OLD_FILE_INFO;
{$EXTERNALSYM PPATCH_OLD_FILE_INFO}
_PATCH_OLD_FILE_INFO = record
SizeOfThisStruct : ULONG;
Union : record
case Integer of
0 : (OldFileNameA : LPCSTR);
1 : (OldFileNameW : LPCWSTR);
2 : (OldFileHandle : THandle);
end;
IgnoreRangeCount : ULONG; // maximum 255
IgnoreRangeArray : PPATCH_IGNORE_RANGE;
RetainRangeCount : ULONG; // maximum 255
RetainRangeArray : PPATCH_RETAIN_RANGE;
end;
{$EXTERNALSYM _PATCH_OLD_FILE_INFO}
PATCH_OLD_FILE_INFO = _PATCH_OLD_FILE_INFO;
{$EXTERNALSYM PATCH_OLD_FILE_INFO}
TPatchOldFileInfo = PATCH_OLD_FILE_INFO;
PPatchOldFileInfo = PPATCH_OLD_FILE_INFO;
//**************************************************************************************************************************************************//
PPATCH_OPTION_DATA = ^PATCH_OPTION_DATA;
{$EXTERNALSYM PPATCH_OPTION_DATA}
_PATCH_OPTION_DATA = record
SizeOfThisStruct : ULONG;
SymbolOptionFlags : ULONG; // PATCH_SYMBOL_xxx flags
NewFileSymbolPath : LPCSTR; // always ANSI, never Unicode
OldFileSymbolPathArray : ^LPCSTR; // array[ OldFileCount ]
ExtendedOptionFlags : ULONG;
SymLoadCallback : PATCH_SYMLOAD_CALLBACK;
SymLoadContext : Pointer;
end;
{$EXTERNALSYM _PATCH_OPTION_DATA}
PATCH_OPTION_DATA = _PATCH_OPTION_DATA;
{$EXTERNALSYM PATCH_OPTION_DATA}
TPatchOptionData = PATCH_OPTION_DATA;
PPatchOptionData = PPATCH_OPTION_DATA;
//**************************************************************************************************************************************************//
//** **//
//** Note that PATCH_OPTION_DATA contains LPCSTR paths, and no LPCWSTR (Unicode) **//
//** path argument is available, even when used with one of the Unicode APIs **//
//** such as CreatePatchFileW. This is because the underlying system services **//
//** for symbol file handling (IMAGEHLP.DLL) only support ANSI file/path names. **//
//** **//
//** **//
//** A note about PATCH_RETAIN_RANGE specifiers with multiple old files: **//
//** **//
//** Each old version file must have the same RetainRangeCount, and the same **//
//** retain range LengthInBytes and OffsetInNewFile values in the same order. **//
//** Only the OffsetInOldFile values can differ between old files for retain **//
//** ranges. **//
//** **//
//** **//
//** The following prototypes are interface for creating patches from files. **//
//** **//
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function CreatePatchFileA(
OldFileName : LPCSTR;
NewFileName : LPCSTR;
PatchFileName : LPCSTR;
OptionFlags : ULONG;
OptionData : PPatchOptionData) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileA}
//**************************************************************************************************************************************************//
function CreatePatchFileW(
OldFileName : LPCWSTR;
NewFileName : LPCWSTR;
PatchFileName : LPCWSTR;
OptionFlags : ULONG;
OptionData : PPatchOptionData) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileW}
//**************************************************************************************************************************************************//
function CreatePatchFileByHandles(
OldFileHandle : THandle;
NewFileHandle : THandle;
PatchFileHandle : THandle;
OptionFlags : ULONG;
OptionData : PPatchOptionData) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileByHandles}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function CreatePatchFileExA(
OldFileCount : ULONG; // maximum 255
OldFileInfoArray : PPatchOldFileInfoA;
NewFileName : LPCSTR;
PatchFileName : LPCSTR;
OptionFlags : ULONG;
OptionData : PPatchOptionData; // optional
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileExA}
//**************************************************************************************************************************************************//
function CreatePatchFileExW(
OldFileCount : ULONG; // maximum 255
OldFileInfoArray : PPatchOldFileInfoW;
NewFileName : LPCWSTR;
PatchFileName : LPCWSTR;
OptionFlags : ULONG;
OptionData : PPatchOptionData; // optional
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileExW}
//**************************************************************************************************************************************************//
function CreatePatchFileByHandlesEx(
OldFileCount : ULONG; // maximum 255
OldFileInfoArray : PPatchOldFileInfoH;
NewFileHandle : THandle;
PatchFileHandle : THandle;
OptionFlags : ULONG;
OptionData : PPatchOptionData; // optional
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM CreatePatchFileByHandlesEx}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function ExtractPatchHeaderToFileA(
PatchFileName : LPCSTR;
PatchHeaderFileName : LPCSTR) : BOOL; stdcall;
{$EXTERNALSYM ExtractPatchHeaderToFileA}
//**************************************************************************************************************************************************//
function ExtractPatchHeaderToFileW(
PatchFileName : LPCWSTR;
PatchHeaderFileName : LPCWSTR) : BOOL; stdcall;
{$EXTERNALSYM ExtractPatchHeaderToFileW}
//**************************************************************************************************************************************************//
function ExtractPatchHeaderToFileByHandles(
PatchFileHandle : THandle;
PatchHeaderFileHandle : THandle) : BOOL; stdcall;
{$EXTERNALSYM ExtractPatchHeaderToFileByHandles}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
//
// The following prototypes are interface for creating new file from old file
// and patch file. Note that it is possible for the TestApply API to succeed
// but the actual Apply to fail since the TestApply only verifies that the
// old file has the correct CRC without actually applying the patch. The
// TestApply API only requires the patch header portion of the patch file,
// but its CRC must be corrected.
//
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function TestApplyPatchToFileA(
PatchFileName : LPCSTR;
OldFileName : LPCSTR;
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM TestApplyPatchToFileA}
//**************************************************************************************************************************************************//
function TestApplyPatchToFileW(
PatchFileName : LPCWSTR;
OldFileName : LPCWSTR;
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM TestApplyPatchToFileW}
//**************************************************************************************************************************************************//
function TestApplyPatchToFileByHandles(
PatchFileHandle : THandle; // requires GENERIC_READ access
OldFileHandle : THandle; // requires GENERIC_READ access
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM TestApplyPatchToFileByHandles}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function ApplyPatchToFileA(
PatchFileName : LPCSTR;
OldFileName : LPCSTR;
NewFileName : LPCSTR;
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileA}
//**************************************************************************************************************************************************//
function ApplyPatchToFileW(
PatchFileName : LPCWSTR;
OldFileName : LPCWSTR;
NewFileName : LPCWSTR;
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileW}
//**************************************************************************************************************************************************//
function ApplyPatchToFileByHandles(
PatchFileHandle : THandle; // requires GENERIC_READ access
OldFileHandle : THandle; // requires GENERIC_READ access
NewFileHandle : THandle; // requires GENERIC_READ | GENERIC_WRITE
ApplyOptionFlags : ULONG) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileByHandles}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function ApplyPatchToFileExA(
PatchFileName : LPCSTR;
OldFileName : LPCSTR;
NewFileName : LPCSTR;
ApplyOptionFlags : ULONG;
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileExA}
//**************************************************************************************************************************************************//
function ApplyPatchToFileExW(
PatchFileName : LPCWSTR;
OldFileName : LPCWSTR;
NewFileName : LPCWSTR;
ApplyOptionFlags : ULONG;
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileExW}
//**************************************************************************************************************************************************//
function ApplyPatchToFileByHandlesEx(
PatchFileHandle : THandle; // requires GENERIC_READ access
OldFileHandle : THandle; // requires GENERIC_READ access
NewFileHandle : THandle; // requires GENERIC_READ | GENERIC_WRITE
ApplyOptionFlags : ULONG;
ProgressCallback : PPatchProgressCallBack;
CallbackContext : Pointer) : BOOL; stdcall;
{$EXTERNALSYM ApplyPatchToFileByHandlesEx}
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
//
// The following prototypes provide a unique patch "signature" for a given
// file. Consider the case where you have a new foo.dll and the machines
// to be updated with the new foo.dll may have one of three different old
// foo.dll files. Rather than creating a single large patch file that can
// update any of the three older foo.dll files, three separate smaller patch
// files can be created and "named" according to the patch signature of the
// old file. Then the patch applyer application can determine at runtime
// which of the three foo.dll patch files is necessary given the specific
// foo.dll to be updated. If patch files are being downloaded over a slow
// network connection (Internet over a modem), this signature scheme provides
// a mechanism for choosing the correct single patch file to download at
// application time thus decreasing total bytes necessary to download.
//
//**************************************************************************************************************************************************//
//**************************************************************************************************************************************************//
function GetFilePatchSignatureA(
FileName : LPCSTR;
OptionFlags : ULONG;
OptionData : Pointer;
IgnoreRangeCount : ULONG;
IgnoreRangeArray : PPatchIgnoreRange;
RetainRangeCount : ULONG;
RetainRangeArray : PPatchRetainRange;
SignatureBufferSize : ULONG;
SignatureBuffer : Pointer) : BOOL; stdcall;
{$EXTERNALSYM GetFilePatchSignatureA}
//**************************************************************************************************************************************************//
function GetFilePatchSignatureW(
FileName : LPCWSTR;
OptionFlags : ULONG;
OptionData : Pointer;
IgnoreRangeCount : ULONG;
IgnoreRangeArray : PPatchIgnoreRange;
RetainRangeCount : ULONG;
RetainRangeArray : PPatchRetainRange;
SignatureBufferSizeInBytes : ULONG;
SignatureBuffer : Pointer) : BOOL; stdcall;
{$EXTERNALSYM GetFilePatchSignatureW}
//**************************************************************************************************************************************************//
function GetFilePatchSignatureByHandle(
FileHandle : THandle;
OptionFlags : ULONG;
OptionData : Pointer;
IgnoreRangeCount : ULONG;
IgnoreRangeArray : PPatchIgnoreRange;
RetainRangeCount : ULONG;
RetainRangeArray : PPatchRetainRange;
SignatureBufferSize : ULONG;
SignatureBuffer : Pointer) : BOOL; stdcall;
{$EXTERNALSYM GetFilePatchSignatureByHandle}
//**************************************************************************************************************************************************//
implementation
function CreatePatchFileA; external 'mspatchc.dll' name 'CreatePatchFileA';
function CreatePatchFileW; external 'mspatchc.dll' name 'CreatePatchFileW';
function CreatePatchFileByHandles; external 'mspatchc.dll' name 'CreatePatchFileByHandles';
function CreatePatchFileExA; external 'mspatchc.dll' name 'CreatePatchFileExA';
function CreatePatchFileExW; external 'mspatchc.dll' name 'CreatePatchFileExW';
function CreatePatchFileByHandlesEx; external 'mspatchc.dll' name 'CreatePatchFileByHandlesEx';
function ExtractPatchHeaderToFileA; external 'mspatchc.dll' name 'ExtractPatchHeaderToFileA';
function ExtractPatchHeaderToFileW; external 'mspatchc.dll' name 'ExtractPatchHeaderToFileW';
function ExtractPatchHeaderToFileByHandles; external 'mspatchc.dll' name 'ExtractPatchHeaderToFileByHandles';
function TestApplyPatchToFileA; external 'mspatcha.dll' name 'TestApplyPatchToFileA';
function TestApplyPatchToFileW; external 'mspatcha.dll' name 'TestApplyPatchToFileW';
function TestApplyPatchToFileByHandles; external 'mspatcha.dll' name 'TestApplyPatchToFileByHandles';
function ApplyPatchToFileA; external 'mspatcha.dll' name 'ApplyPatchToFileA';
function ApplyPatchToFileW; external 'mspatcha.dll' name 'ApplyPatchToFileW';
function ApplyPatchToFileByHandles; external 'mspatcha.dll' name 'ApplyPatchToFileByHandles';
function ApplyPatchToFileExA; external 'mspatcha.dll' name 'ApplyPatchToFileExA';
function ApplyPatchToFileExW; external 'mspatcha.dll' name 'ApplyPatchToFileExW';
function ApplyPatchToFileByHandlesEx; external 'mspatcha.dll' name 'ApplyPatchToFileByHandlesEx';
function GetFilePatchSignatureA; external 'mspatcha.dll' name 'GetFilePatchSignatureA';
function GetFilePatchSignatureW; external 'mspatcha.dll' name 'GetFilePatchSignatureW';
function GetFilePatchSignatureByHandle; external 'mspatcha.dll' name 'GetFilePatchSignatureByHandle';
end.
|
// *************************************************************
// unit ECSCFG_Functions_ForLanguageSwitch
//
// Projekt: ECSWIN für WinCC
//
// Funktion: ECSCONFIG_CC Funktionen für Sprachumschaltung
//
// 04.08.2009 RIA erstellt
// 04.08.2009 RIA 2.7.0 Sprachumschaltung
// 13.04.2010 RIA 2.7.4 neue fnREAD_LANGUAGE_TEXTS
// 06.01.2011 RIA 2.7.13 Abfrage in fnREAD_LANGUAGE_TEXTS um "order by ... " erweitert um Sprachumschaltung im
// Formular für Sprachim- und export zu korrigieren
// 01.08.2011 RIA 2.9.0 ECS_OPTION -> ECS_CFG_OPTION
// 19.11.2012 RIA 2.11.0 neue Sprachumschaltung
//
// *************************************************************
unit ECSCFG_Functions_ForLanguageSwitch;
interface
uses ADODB, Classes, VCL.Controls, DB, VCL.Dialogs, VCL.Forms, SysUtils,
Windows;
function fnGetUserLanguage: string;
function fnGetSystemLanguage: string;
const
STR_LANGUAGES : array [1..5] of string = ('TEXT_L1', 'TEXT_L2', 'TEXT_L3', 'TEXT_L4', 'TEXT_L5');
N_REF_LANGUAGE = 1; // 1 = Referenzsprache ist Deutsch mit der verglichen wird
var
n_Language : smallint = N_REF_LANGUAGE; // Sprachkennung: 1 = Referenzsprache
b_LanguageSwitch : boolean; // true -> mit Sprachumschaltung
arr_nLanguages : array [1..5] of integer; // Länderkennungen
str_LangNames : array [1..5] of string;
// Texte für Messagebox
str_Confirm : string = 'Bestätigung'; // Meldungstitel
str_Error : string = 'Fehler'; // Meldungstitel
str_Info : string = 'Information'; // Meldungstitel
str_Warning : string = 'Warnung'; // Meldungstitel
str_DeleteRecord : string = 'Datensatz löschen?';
str_DeleteError : string = 'Fehler beim Löschen'; // Meldungstitel
str_UpdateError : string = 'Fehler beim Speichern'; // Meldungstitel
str_InsertError : string = 'Fehler beim Einfügen'; // Meldungstitel
str_SQLError : string = 'SQL Fehler'; // Meldungstitel
str_NoDelete_he : string = 'darf nicht gelöscht werden! Er wird bereits benutzt!';
str_NoDelete_she : string = 'darf nicht gelöscht werden! Sie wird bereits benutzt!';
str_NoModify_she : string = 'darf nicht geändert werden! Sie wird bereits benutzt!';
str_NotUnique : string = 'muss eindeutig sein! Bitte einen anderen Wert eingeben!';
str_NotNull : string = 'muss einen Wert haben! Bitte geben Sie einen Wert ein!';
str_NoModify_he : string = 'darf nicht geändert werden! Er wird bereits benutzt!';
str_NoModify_it : string = 'darf nicht geändert werden! Es wird bereits benutzt!';
// *************************************************************
// Texte für statische Texte in ECSCONFIG_CC Formularen lesen
// *************************************************************
function fnREAD_LANGUAGE_TEXTS (frmForm : TForm; nFormId : Integer; qryQuery: TADOQuery) : integer;
implementation
uses
ECSCFG_Functions; // Unit mit allgemeinen Funktionen
// *************************************************************
// Benutzersprache ermitteln
// *************************************************************
function fnGetUserLanguage: String;
var
Text: Array [0..100] of Char;
begin
VerLanguageName (GetUserDefaultLangID, Text, Length (Text));
Result := String (Text);
end;
// *************************************************************
// Systemsprache ermitteln
// *************************************************************
function fnGetSystemLanguage: String;
var
Text: Array [0..100] of Char;
begin
VerLanguageName (GetSystemDefaultLangID, Text, Length (Text));
Result := String (Text);
end;
// *************************************************************
// Texte für statische Texte in ECSCONFIG_CC Formularen lesen
//**************************************************************
function fnREAD_LANGUAGE_TEXTS (frmForm : TForm; nFormId : Integer; qryQuery: TADOQuery) : integer;
var
strSQL : string; // SQL Statement
strGroupOffset : string; // Offset
begin
strGroupOffset := ' 1000 + ';
if nFormId = 0 then strGroupOffset := ' 999 + ';
strSQL := 'select TEXT_L1, TEXT_L2, TEXT_L3, TEXT_L4, TEXT_L5, ITEM_REF as FORM_OBJECT_ID ' +
'from ECS_SYS_LANGUAGE join ECS_SYS_LANGUAGE_REF on ECS_SYS_LANGUAGE.TEXT_REF = ECS_SYS_LANGUAGE_REF.TEXT_REF ' +
'where TEXT_GRP = ' + strGroupOffset + IntToStr (nFormId) + ' order by ITEM_REF';
fnREAD_LANGUAGE_TEXTS := fn_OpenQuery (frmForm, qryQuery, strSQL, false); // Query öffnen
end;
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit UI.Aero.Globals;
interface
{$I '../../Common/CompilerVersion.Inc'}
type
TSnapMode = ( smTop, smBottom, smLeft, smRight );
TCompositionDraw = ( cdNone, cdImage, cdText, cdTheme );
TToolTipIcon = ( tiNone, tiApplication, tiHand, tiQuestion, tiExclamation, tiAsterisk, tiWinLogo, tiShield );
TToolTipIconPos = ( tipLeft, tipRight );
TAeroButtonState = ( bsNormal, bsHightLight, bsFocused, bsDown, bsDisabled );
TImagePosition = ( ipTopLeft, ipTopCenter, ipTopRight,
ipCenterLeft, ipCenter, ipCenterRight,
ipBottomLeft, ipBottomCenter, ipBottomRight,
ipStretch );
TAeroBackGround = ( bgSolid, bgGradient, bgTexture );
TTaskButtonImagePos = ( tbLeft, tbRight );
TPartOrientation = ( ioHorizontal, ioVertical );
TRenderState = ( rsGDIP, rsBuffer, rsComposited, rsPostDraw );
TRenderConfig = set of TRenderState;
TAnimationStyle = ( asNone, asLinear, asCubic, asSine );
TARenderState = ( arsGDIP, arsComposited, arsPostDraw );
TARenderConfig = set of TARenderState;
implementation
end.
|
unit MyMath;
interface
function arccos(x:extended):extended;
function arcsin(x:extended):extended;
function arctan2(a,b:extended):extended;
function tan(x:extended):extended;
implementation
function Tan(x:extended):extended;
begin
Result:=sin(x)/cos(x);
end;
function ArcTan2(a,b:extended):extended;
begin
Result:=ArcTan(a/b);
if b<0 then
Result:=Result+pi;
end;
function ArcSin(x:extended):extended;
begin
Result:=ArcTan(x/sqrt(1-x*x));
end;
function ArcCos(x:extended):extended;
begin
Result:=pi/2-ArcSin(x);
end;
end.
|
(*
* Copyright (c) 2009, Ciobanu Alexandru
* 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 the <organization> 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 AUTHOR ''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 AUTHOR 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.
*)
{$I ../Library/src/DeHL.Defines.inc}
unit Tests.MathAlgorithms;
interface
uses SysUtils,
Tests.Utils,
TestFramework,
DeHL.Types,
DeHL.Collections.List,
DeHL.Exceptions,
DeHL.Math.Algorithms;
type
TTestAlgorithms = class(TDeHLTestCase)
procedure TestAccSum();
procedure TestAccIntAvg();
procedure TestAccDoubleAvg();
end;
TTestPrimes = class(TDeHLTestCase)
published
procedure TestIsPrime;
procedure GetNearestProgressionPositive;
end;
implementation
{ TTestAlgorithms }
procedure TTestAlgorithms.TestAccDoubleAvg;
const
MaxNr = 100;
var
AListFull, AListEmpty: TList<Double>;
I: Integer;
X, Sum, Avg: Double;
begin
AListFull := TList<Double>.Create();
AListEmpty := TList<Double>.Create();
Sum := 0;
for I := 0 to MaxNr - 1 do
begin
X := Random(MaxNr);
Sum := Sum + X;
AListFull.Add(X);
end;
Avg := Sum / MaxNr;
Check(Accumulator.Average<Double>(AListFull, TType<Double>.Default) = Avg, '1. Accumulator.Average failed for Double');
Check(Accumulator.Average<Double>(AListFull) = Avg, '2. Accumulator.Average failed for Integer');
Check(Accumulator.Average<Double>(AListEmpty, TType<Double>.Default) = 0, '3. Accumulator.Average failed for Double');
Check(Accumulator.Average<Double>(AListEmpty) = 0, '4. Accumulator.Average failed for Double');
AListFull.Free;
AListEmpty.Free;
end;
procedure TTestAlgorithms.TestAccIntAvg;
const
MaxNr = 100;
var
AListFull, AListEmpty: TList<Integer>;
I, X, Sum, Avg: Integer;
begin
AListFull := TList<Integer>.Create();
AListEmpty := TList<Integer>.Create();
Sum := 0;
for I := 0 to MaxNr - 1 do
begin
X := Random(MaxNr);
Sum := Sum + X;
AListFull.Add(X);
end;
Avg := Sum div MaxNr;
Check(Accumulator.Average<Integer>(AListFull, TType<Integer>.Default) = Avg, '1. Accumulator.Average failed for Integer');
Check(Accumulator.Average<Integer>(AListFull) = Avg, '2. Accumulator.Average failed for Integer');
Check(Accumulator.Average<Integer>(AListEmpty, TType<Integer>.Default) = 0, '3. Accumulator.Average failed for Integer');
Check(Accumulator.Average<Integer>(AListEmpty) = 0, '4. Accumulator.Average failed for Integer');
AListFull.Free;
AListEmpty.Free;
end;
procedure TTestAlgorithms.TestAccSum;
const
MaxNr = 100;
var
AListFull, AListEmpty: TList<Integer>;
I, X, Sum: Integer;
begin
AListFull := TList<Integer>.Create();
AListEmpty := TList<Integer>.Create();
Sum := 0;
for I := 0 to MaxNr - 1 do
begin
X := Random(MaxNr);
Sum := Sum + X;
AListFull.Add(X);
end;
Check(Accumulator.Sum<Integer>(AListFull, TType<Integer>.Default) = Sum, '1. Accumulator.Sum failed for Integer');
Check(Accumulator.Sum<Integer>(AListFull) = Sum, '2. Accumulator.Sum failed for Integer');
Check(Accumulator.Sum<Integer>(AListEmpty, TType<Integer>.Default) = 0, '3. Accumulator.Sum failed for Integer');
Check(Accumulator.Sum<Integer>(AListEmpty) = 0, '4. Accumulator.Sum failed for Integer');
AListFull.Free;
AListEmpty.Free;
end;
{ TTestPrimes }
procedure TTestPrimes.TestIsPrime;
begin
Check(not Prime.IsPrime(0), '0 must be prime!');
Check(Prime.IsPrime(1), '1 must be prime!');
Check(Prime.IsPrime(-1), '-1 must be prime!');
Check(Prime.IsPrime(2), '2 must be prime!');
Check(Prime.IsPrime(-2), '-2 must be prime!');
Check(Prime.IsPrime(3), '3 must be prime!');
Check(Prime.IsPrime(-3), '-3 must be prime!');
Check(Prime.IsPrime(5), '5 must be prime!');
Check(Prime.IsPrime(-5), '-5 must be prime!');
Check(Prime.IsPrime(37), '37 must be prime!');
Check(Prime.IsPrime(-37), '-37 must be prime!');
Check(not Prime.IsPrime(4), '4 is not prime!');
Check(not Prime.IsPrime(9), '9 is not prime!');
Check(not Prime.IsPrime(-100), '-100 is not prime!');
end;
procedure TTestPrimes.GetNearestProgressionPositive;
const
NrX = 108000;
var
I, P : Integer;
begin
for I := -NrX to NrX do
begin
P := Prime.GetNearestProgressionPositive(I);
Check(P >= I, 'Prime size check failed at ' + IntToStr(I));
if I < 0 then
Check(P = 1, 'Negative values give 1 result for nearest prime.');
end;
end;
initialization
TestFramework.RegisterTest(TTestAlgorithms.Suite);
TestFramework.RegisterTest(TTestPrimes.Suite);
end.
|
unit uLog;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uPath, dateutils, uStrUtils;
type
TOnLineMonitoringElement = record
olm_msg:string;
olm_index:int64;
olm_dt:tDateTime;
olm_type:byte;
end;
procedure AddOnLineMsg(olm_msg:string;olm_type:byte);
procedure WriteLogMsg(log_msg:string);
procedure WriteReportMsg(rep_msg:string);
procedure WriteReportData(rep_msg:string);
procedure WriteOfflinePeriodMsg(td_begin,td_end:TdateTime;msg:string);
implementation
uses uMain;
// olm_type:
// 1 - log
// 2 - report msg
procedure AddOnLineMsg(olm_msg:string;olm_type:byte);
var
l,x,ind:integer;
prev_index:int64;
count_to_delete:integer;
const5min:Double;
const_now:TDateTime;
begin
const5min:=1/288;
const_now:=now;
// calculating how many elements we had to delete
count_to_delete:=0;
l:=length(uMain.arrOnLineMonitoring);
for x:=1 to l do
begin
ind:=l-x+1;
if (uMain.arrOnLineMonitoring[ind-1].olm_dt)<(const_now-const5min) then
begin
count_to_delete:=count_to_delete+1;
end;
end;
if (l-count_to_delete)<1 then
begin
count_to_delete:=l-1;
end;
if count_to_delete<0 then
begin
count_to_delete:=0;
end;
// deleting
for x:=1 to (l-count_to_delete) do
begin
uMain.arrOnLineMonitoring[x-1]:=uMain.arrOnLineMonitoring[x-1+count_to_delete];
end;
SetLength(uMain.arrOnLineMonitoring,l-count_to_delete);
l:=length(uMain.arrOnLineMonitoring);
if l=0 then
begin
prev_index:=0;
end
else
begin
prev_index:=uMain.arrOnLineMonitoring[l-1].olm_index;
end;
setlength(uMain.arrOnLineMonitoring,l+1);
uMain.arrOnLineMonitoring[l].olm_dt:=const_now;
uMain.arrOnLineMonitoring[l].olm_index:=prev_index+1;
uMain.arrOnLineMonitoring[l].olm_msg:=olm_msg;
uMain.arrOnLineMonitoring[l].olm_type:=olm_type;
end;
procedure WriteLogMsg(log_msg:string);
var
tf:textfile;
path:string;
prefix:string;
pNow:tDateTime;
begin
pNow:=now;
prefix:=DT2STR(pNow)+': ';
path:=uPath.GetDailyLogFilePath(pNow);
cs2.Enter;
AddOnLineMsg(prefix+log_msg,1);
AssignFile(tf,path);
try
if FileExists(path) then
begin
Append(tf);
end
else
begin
rewrite(tf);
end;
except
end;
try
writeln(tf,prefix+log_msg);
except
end;
try
closefile(tf);
except
end;
cs2.Leave;
end;
procedure WriteReportMsg(rep_msg:string);
var
tf:textfile;
path:string;
prefix:string;
pNow:tDateTime;
begin
pNow:=now;
prefix:=DT2STR(pNow)+': ';
path:=uPath.GetReportLogsFilePath(pNow);
cs2.Enter;
AddOnLineMsg(prefix+rep_msg,2);
AssignFile(tf,path);
try
if FileExists(path) then
begin
Append(tf);
end
else
begin
rewrite(tf);
end;
except
end;
try
writeln(tf,prefix+rep_msg);
except
end;
try
closefile(tf);
except
end;
cs2.Leave;
end;
procedure WriteReportData(rep_msg:string);
var
tf:textfile;
path:string;
begin
path:=uPath.GetReportDataFilePath(now);
cs3.Enter;
AssignFile(tf,path);
try
if FileExists(path) then
begin
Append(tf);
end
else
begin
rewrite(tf);
end;
except
end;
try
writeln(tf,rep_msg);
except
end;
try
closefile(tf);
except
end;
cs3.Leave;
end;
procedure WriteOfflinePeriodMsg(td_begin,td_end:TdateTime;msg:string);
var
tf:textfile;
path:string;
pNow:tDateTime;
first_dt,curr_dt,last_dt:tDateTime;
prefix:string;
tmp_begin_dt,tmp_end_dt:TDateTime;
begin
pNow:=now;
first_dt:=int(td_begin);
curr_dt:=int(td_begin);
last_dt:=int(td_end);
cs4.Enter;
while curr_dt<=last_dt do
begin
path:=uPath.GetOfflineLogFilePath(curr_dt);
AssignFile(tf,path);
try
if FileExists(path) then
begin
Append(tf);
end
else
begin
rewrite(tf);
end;
except
end;
try
//tmp_begin_dt
if curr_dt=first_dt then
begin
tmp_begin_dt:=td_begin;
end
else
begin
tmp_begin_dt:=curr_dt;
end;
//tmp_end_dt
if curr_dt=last_dt then
begin
tmp_end_dt:=td_end;
end
else
begin
tmp_end_dt:=dateutils.EndOfTheDay(curr_dt);
end;
prefix:=DT2STR(tmp_begin_dt)+' - ';
prefix:=prefix+DT2STR(tmp_end_dt)+': ';
writeln(tf,prefix+msg);
except
end;
try
closefile(tf);
except
end;
curr_dt:=curr_dt+1;
end;
cs4.Leave;
end;
end.
|
unit TextEditor.ActiveLine.Colors;
interface
uses
System.Classes, System.UITypes, TextEditor.Consts;
type
TTextEditorActiveLineColors = class(TPersistent)
strict private
FBackground: TColor;
FBackgroundUnfocused: TColor;
FForeground: TColor;
FForegroundUnfocused: TColor;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property Background: TColor read FBackground write FBackground default TDefaultColors.ActiveLineBackground;
property BackgroundUnfocused: TColor read FBackgroundUnfocused write FBackgroundUnfocused default TDefaultColors.ActiveLineBackgroundUnfocused;
property Foreground: TColor read FForeground write FForeground default TDefaultColors.ActiveLineForeground;
property ForegroundUnfocused: TColor read FForegroundUnfocused write FForegroundUnfocused default TDefaultColors.ActiveLineForegroundUnfocused;
end;
implementation
constructor TTextEditorActiveLineColors.Create;
begin
inherited;
FBackground := TDefaultColors.ActiveLineBackground;
FBackgroundUnfocused := TDefaultColors.ActiveLineBackgroundUnfocused;
FForeground := TDefaultColors.ActiveLineForeground;
FForegroundUnfocused := TDefaultColors.ActiveLineForegroundUnfocused;
end;
procedure TTextEditorActiveLineColors.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorActiveLineColors) then
with ASource as TTextEditorActiveLineColors do
begin
Self.FBackground := FBackground;
Self.FBackgroundUnfocused := FBackgroundUnfocused;
Self.FForeground := FForeground;
Self.FForegroundUnfocused := FForegroundUnfocused;
end
else
inherited Assign(ASource);
end;
end.
|
{
This software is Copyright (c) 2016 by Doddy Hackman.
This is free software, licensed under:
The Artistic License 2.0
The Artistic License
Preamble
This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software.
You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement.
Definitions
"Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package.
"Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures.
"You" and "your" means any person who would like to copy, distribute, or modify the Package.
"Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version.
"Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization.
"Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees.
"Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder.
"Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder.
"Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future.
"Source" form means the source code, documentation source, and configuration files for the Package.
"Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form.
Permission for Use and Modification Without Distribution
(1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version.
Permissions for Redistribution of the Standard Version
(2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package.
(3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License.
Distribution of Modified Versions of the Package as Source
(4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following:
(a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version.
(b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version.
(c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under
(i) the Original License or
(ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed.
Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source
(5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license.
(6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version.
Aggregating or Linking the Package
(7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation.
(8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package.
Items That are Not Considered Part of a Modified Version
(9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license.
General Provisions
(10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
(11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
(12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
(13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
(14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
// Unit : DH Snapshot
// Version : 1.0
// (C) Doddy Hackman 2016
unit DH_Snapshot;
interface
uses SysUtils, Windows, Vcl.Imaging.jpeg, Vcl.Graphics, VSample,
VFrames, Classes;
type
other_array_snapshot = array of string;
T_DH_Snapshot = class
private
procedure NewVideoFrameEvent(Sender: TObject; Width, Height: integer;
DataPtr: pointer);
public
constructor Create;
destructor Destroy; override;
function optimize_image(image: string): boolean;
function resize_image(filename: string; Width: integer;
Height: integer): boolean;
function take_screenshot_desktop(screenshot_name: string;
optimize: boolean): boolean;
function take_photo_webcam(screenshot_name: string;
optimize: boolean): boolean;
function check_webcam(): boolean;
function list_webcams(): other_array_snapshot;
function get_webcam_name(): string;
end;
var
video: TVideoImage;
count: integer;
webcam_screenshot: string;
webcam_optimize: boolean;
implementation
constructor T_DH_Snapshot.Create;
begin
inherited Create;
count := 0;
end;
destructor T_DH_Snapshot.Destroy;
begin
inherited Destroy;
end;
function T_DH_Snapshot.optimize_image(image: string): boolean;
var
image1: TBitmap;
image2: TJpegImage;
begin
try
begin
image1 := TBitmap.Create;
image2 := TJpegImage.Create;
image1.LoadFromFile(image);
image2.Assign(image1);
image2.CompressionQuality := 60;
image2.SaveToFile(image);
image1.Free;
image2.Free;
Result := True;
end;
except
begin
Result := False;
end;
end;
end;
function T_DH_Snapshot.resize_image(filename: string; Width: integer;
Height: integer): boolean;
// Credits :
// Based on : http://www.delphidabbler.com/tips/99
// Thanks to www.delphidabbler.com
var
jpeg_image: TJpegImage;
bitmap_image: TBitmap;
size: Double;
begin
try
begin
jpeg_image := TJpegImage.Create;
jpeg_image.LoadFromFile(filename);
if jpeg_image.Height > jpeg_image.Width then
begin
size := Height / jpeg_image.Height
end
else
begin
size := Width / jpeg_image.Width;
end;
bitmap_image := TBitmap.Create;
bitmap_image.Width := Round(jpeg_image.Width * size);
bitmap_image.Height := Round(jpeg_image.Height * size);
bitmap_image.Canvas.StretchDraw(bitmap_image.Canvas.Cliprect, jpeg_image);
jpeg_image.Assign(bitmap_image);
jpeg_image.SaveToFile(filename);
bitmap_image.Free();
jpeg_image.Free();
Result := True;
end;
except
Result := False;
end;
end;
function T_DH_Snapshot.take_screenshot_desktop(screenshot_name: string;
optimize: boolean): boolean;
// Function based in :
// http://forum.codecall.net/topic/60613-how-to-capture-screen-with-delphi-code/
// http://delphi.about.com/cs/adptips2001/a/bltip0501_4.htm
// http://stackoverflow.com/questions/21971605/show-mouse-cursor-in-screenshot-with-delphi
// Thanks to Zarko Gajic , Luthfi and Ken White
var
window: HDC;
size: TRect;
points: TPoint;
image1: TBitmap;
cursor_position: THandle;
response: boolean;
begin
response := False;
if not(screenshot_name = '') then
begin
if (FileExists(screenshot_name)) then
begin
DeleteFile(Pchar(screenshot_name));
end;
try
begin
window := GetWindowDC(GetDesktopWindow);
image1 := TBitmap.Create;
GetWindowRect(GetDesktopWindow, size);
image1.Width := size.Right - size.Left;
image1.Height := size.Bottom - size.Top;
BitBlt(image1.Canvas.Handle, 0, 0, image1.Width, image1.Height, window,
0, 0, SRCCOPY);
GetCursorPos(points);
cursor_position := GetCursor;
DrawIconEx(image1.Canvas.Handle, points.X, points.Y, cursor_position,
32, 32, 0, 0, DI_NORMAL);
image1.SaveToFile(screenshot_name);
image1.Free;
end;
except
begin
//
end;
end;
if (FileExists(screenshot_name)) then
begin
if (optimize = True) then
begin
if (optimize_image(screenshot_name)) then
begin
response := True;
end
else
begin
response := False;
end;
end
else
begin
response := True;
end;
end
else
begin
response := False;
end;
end
else
begin
response := False;
end;
Result := response;
end;
// Functions to Capture Webcam
Procedure T_DH_Snapshot.NewVideoFrameEvent(Sender: TObject;
Width, Height: integer; DataPtr: pointer);
var
bitmap: TBitmap;
name: string;
begin
name := webcam_screenshot;
if (FileExists(name)) then
begin
DeleteFile(Pchar(name));
end;
Inc(count);
try
begin
bitmap := TBitmap.Create;
bitmap.PixelFormat := pf24bit;
video.GetBitmap(bitmap);
bitmap.SaveToFile(name);
bitmap.Free;
end;
except
begin
//
end;
end;
if (FileExists(name) and (count = 10)) then
begin
count := 0;
video.VideoStop;
video.Free;
if (webcam_optimize = True) then
begin
optimize_image(name);
end;
end;
end;
function T_DH_Snapshot.take_photo_webcam(screenshot_name: string;
optimize: boolean): boolean;
var
cameras: TStringList;
response: boolean;
begin
response := False;
try
begin
video := TVideoImage.Create();
cameras := TStringList.Create;
video.GetListOfDevices(cameras);
if not(cameras.count = 0) then
begin
webcam_screenshot := screenshot_name;
webcam_optimize := optimize;
video.VideoStart(cameras[0]);
response := True;
end
else
begin
response := False;
end;
cameras.Free;
video.OnNewVideoFrame := NewVideoFrameEvent;
end;
except
begin
response := False;
end;
end;
Result := response;
end;
function T_DH_Snapshot.check_webcam(): boolean;
var
camera_control: TVideoImage;
cameras_found: TStringList;
response: boolean;
begin
response := False;
try
begin
camera_control := TVideoImage.Create();
cameras_found := TStringList.Create;
camera_control.GetListOfDevices(cameras_found);
if not(cameras_found.count = 0) then
begin
response := True;
end
else
begin
response := False;
end;
cameras_found.Free;
camera_control.Free;
end;
except
begin
response := False;
end;
end;
Result := response;
end;
function T_DH_Snapshot.list_webcams(): other_array_snapshot;
var
webcam_list: other_array_snapshot;
cameras_found: TStringList;
camera_control: TVideoImage;
i: integer;
begin
camera_control := TVideoImage.Create();
cameras_found := TStringList.Create;
camera_control.GetListOfDevices(cameras_found);
for i := 0 to cameras_found.count - 1 do
begin
SetLength(webcam_list, Length(webcam_list) + 1);
webcam_list[High(webcam_list)] := cameras_found[i];
end;
cameras_found.Free;
camera_control.Free;
Result := webcam_list;
end;
function T_DH_Snapshot.get_webcam_name(): string;
var
cameras_found: TStringList;
camera_control: TVideoImage;
webcam_name: string;
begin
webcam_name := '';
try
begin
camera_control := TVideoImage.Create();
cameras_found := TStringList.Create;
camera_control.GetListOfDevices(cameras_found);
if not(cameras_found.count = 0) then
begin
webcam_name := cameras_found[0];
end
else
begin
webcam_name := '?';
end;
cameras_found.Free;
camera_control.Free;
end;
except
begin
//
end;
end;
Result := webcam_name;
end;
//
end.
// The End ?
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
StdCtrls;
type
{ TForm1 }
tZustand = (gerade, ungerade); //Alle möglichen Zustände definieren
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
Zustand : tZustand;
implementation
{ TForm1 }
procedure Pritaetspruefer(var zustand : tZustand; bit : Integer);
begin
case zustand of
gerade: case bit of
0: zustand := gerade;
1: zustand := ungerade
end;
ungerade: case bit of
0: zustand := ungerade;
1: zustand := gerade
end;
end;
end;
function Ausgabe(zustand : tZustand) : String;
begin
case zustand of
gerade : Ausgabe := 'Gerade';
ungerade : Ausgabe := 'Ungerade'
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var Bitfolge : String;
i : Integer;
begin
Zustand := gerade;
Bitfolge := Edit1.Text;
for i:=1 to length(Bitfolge) do begin
Pritaetspruefer(Zustand,StrToInt(Bitfolge[i]));
end;
Label3.Caption := Ausgabe(Zustand);
end;
initialization
{$I unit1.lrs}
end.
|
unit HbWindowsMessages;
{$mode objfpc}{$H+}
interface
uses
messages, windows,
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons;
type
TCopyDataStruct = packed record
dwData: DWORD; //up to 32 bits of data to be passed to the receiving application
cbData: DWORD; //the size, in bytes, of the data pointed to by the lpData member
lpData: Pointer; //Points to data to be passed to the receiving application. This member can be nil.
end;
TWMCopyData = packed record
Msg: Cardinal;
From: HWND;//Handle of the Window that passed the data
CopyDataStruct: PCopyDataStruct; //data passed
Result: Longint;//Use it to send a value back to the "Sender"
end;
TMensagemRecebidaEvent = procedure(Sender: TObject; Mensagem: String) of object;
TErrorEvent = procedure(Sender: TObject; ErrorCode: Integer; ErrorMsg: String) of object;
{ TFormHbWindowsMsg }
TFormHbWindowsMsg = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ private declarations }
FMensagemRecebida: String;
FOnMensagemRecebida: TMensagemRecebidaEvent;
FOnError: TErrorEvent;
procedure SetMensagemRecebida(UmaMensagemRecebida: String);
procedure EmitirErro(Codigo: Integer; Mensagem: String);
public
{ public declarations }
class function Instance(WindowName: String = ''): TFormHbWindowsMsg;
class procedure DropInstance;
procedure EnviarMensagem(Destino, Mensagem: String);
property OnMensagemRecebida: TMensagemRecebidaEvent read FOnMensagemRecebida write FOnMensagemRecebida;
property OnError: TErrorEvent read FOnError write FOnError;
property MensagemRecebida: String read FMensagemRecebida write SetMensagemRecebida;
end;
const
HBWM_ERROR_NOT_FOUND = 1;
implementation
{$R *.lfm}
{ TFormHbWindowsMsg }
var
PrevWndProc: WNDPROC;
FInstance: TFormHbWindowsMsg;
class function TFormHbWindowsMsg.Instance(WindowName: String): TFormHbWindowsMsg;
begin
if not Assigned(FInstance) then begin
FInstance := TFormHbWindowsMsg.Create(Nil);
end;
if WindowName <> '' then begin
FInstance.Caption := WindowName;
end;
Result := FInstance;
end;
class procedure TFormHbWindowsMsg.DropInstance;
begin
if Assigned(FInstance) then begin
FreeAndNil(FInstance);
end;
end;
function WndCallback(Ahwnd: HWND; uMsg: UINT; wParam: WParam;
lParam: LParam): LRESULT; stdcall;
var
pMyData: CopyDataStruct;
ms: TMemoryStream;
begin
if uMsg = WM_COPYDATA then begin {Process it}
pMyData := PCopyDataStruct(lParam)^;
TFormHbWindowsMsg.Instance.MensagemRecebida := PChar(pMyData.lpData);
Exit;
end;
Result := CallWindowProc(PrevWndProc,Ahwnd,uMsg,WParam,LParam);
end;
procedure TFormHbWindowsMsg.FormCreate(Sender: TObject);
begin
FOnMensagemRecebida := Nil;
FOnError := Nil;
PrevWndProc := Windows.WNDPROC(SetWindowLongPtr(Self.Handle, GWL_WNDPROC, PtrInt(@WndCallback)));
end;
procedure TFormHbWindowsMsg.EnviarMensagem(Destino, Mensagem: String);
var
h: HWND;
Data: TCopyDataStruct;
begin
Data.dwData := 0; //use it to identify the message contents
Data.cbData := 1 + Length(Mensagem) ;
Data.lpData := PChar(Mensagem) ;
h := FindWindow(nil, PChar(Destino));
if IsWindow(h) then begin
SendMessage(h, WM_COPYDATA, Integer(Handle), Integer(@Data));
end else begin
EmitirErro(HBWM_ERROR_NOT_FOUND, 'Janela destino não encontrada');
end;
end;
procedure TFormHbWindowsMsg.EmitirErro(Codigo: Integer; Mensagem: String);
begin
if Assigned(FOnError) then begin
FOnError(Self, Codigo, Mensagem);
end;
end;
procedure TFormHbWindowsMsg.SetMensagemRecebida(UmaMensagemRecebida: String);
begin
FMensagemRecebida := UmaMensagemRecebida;
if Assigned(FOnMensagemRecebida) then begin
FOnMensagemRecebida(Self, FMensagemRecebida);
end;
end;
initialization
FInstance := Nil;
finalization
TFormHbWindowsMsg.DropInstance;
end.
|
unit uMatrix;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ListBox, FMX.Layouts, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.ImgList,
uFrame;
type
TMatrixFrame = class(TGFrame)
Main: TLayout;
Left: TLayout;
Img: TGlyph;
Text: TMemo;
Nums: TListBox;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxItem11: TListBoxItem;
ListBoxItem12: TListBoxItem;
ListBoxItem13: TListBoxItem;
ListBoxItem14: TListBoxItem;
ListBoxItem15: TListBoxItem;
List: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
procedure ListDragDrop(Sender: TObject; const Data: TDragObject;
const Point: TPointF);
procedure ListDragOver(Sender: TObject; const Data: TDragObject;
const Point: TPointF; var Operation: TDragOperation);
procedure ListMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure ListMouseLeave(Sender: TObject);
procedure ListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
protected
procedure onFCreate; override;
public
procedure onFShow; override;
end;
implementation
{$R *.fmx}
uses
System.Generics.Collections,
DesignManager;
var
last: TListBoxItem;
procedure TMatrixFrame.onFCreate;
var
i, id: byte;
m: single;
l: TList<TPair<Byte, String>>;
lt: TFormLayout;
begin
layouts:=[main];
if DM.tryGetFormLayout(name, 'List', lt) then m:=lt.FontSize
else m:=20;
l:=TList<TPair<Byte, String>>.Create;
if Assigned(fText) then
for i:=0 to 6 do
l.Add(TPair<byte, string>.Create(i, fText.Items[i]));
for i:=0 to 6 do
begin
id:=random(l.Count);
list.ListItems[i].Tag:=l[id].Key;
list.ListItems[i].Text:=l[id].Value;
list.ListItems[i].TextSettings.Font.Size:=m;
nums.ListItems[i].TextSettings.Font.Size:=m+6;
l.Delete(id);
end;
l.Free;
end;
procedure TMatrixFrame.onFShow;
begin
List.ItemHeight:=List.Height/7;
Nums.ItemHeight:=List.Height/7;
inherited;
end;
procedure TMatrixFrame.ListDragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF);
function check: boolean;
var
i:byte;
begin
result:=false;
for i:=0 to 6 do
with List.ListItems[i] do
if i<>Tag then exit;
result:=true;
end;
begin
if Assigned(List.ItemByPoint(Point.X, Point.Y)) and Assigned(Last) then
begin
List.ItemsExchange(List.ItemByPoint(Point.X, Point.Y), last);
if check then
begin
win;
setMedal(9);
end else clicks;
end;
end;
procedure TMatrixFrame.ListDragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation);
begin
if sender = Data.Source then
Operation:=TDragOperation.Move;
end;
procedure TMatrixFrame.ListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
if Assigned(List.ItemByPoint(X, Y)) then
last:=List.ItemByPoint(X, Y);
end;
procedure TMatrixFrame.ListMouseLeave(Sender: TObject);
begin
List.ItemIndex:=-1;
end;
procedure TMatrixFrame.ListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
begin
if Assigned(List.ItemByPoint(X, Y)) then
List.ItemIndex:=List.ItemByPoint(X, Y).Index;
end;
end.
|
unit FFrmPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uJogador,
uJogoDaVelha, uEnum;
type
TFFrmJogoDaVelha = class(TForm)
pbAll: TPanel;
btn11: TButton;
btn12: TButton;
btn13: TButton;
btn21: TButton;
btn22: TButton;
btn23: TButton;
btn31: TButton;
btn32: TButton;
btn33: TButton;
pnData: TPanel;
pnButtons: TPanel;
btnIniciarJogo: TButton;
edtJogadorX: TLabeledEdit;
edtJogadorO: TLabeledEdit;
procedure btnIniciarJogoClick(Sender: TObject);
procedure btn11Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
oJogaDaVelha: TJogoDaVelha;
oJogador1: TJogador;
oJogador2: TJogador;
procedure criaJogadores();
procedure criaJogo;
procedure iniciarJogo;
procedure limpaBotoes();
procedure fimDejogo();
public
{ Public declarations }
end;
var
FFrmJogoDaVelha: TFFrmJogoDaVelha;
implementation
{$R *.dfm}
procedure TFFrmJogoDaVelha.btn11Click(Sender: TObject);
var
simbolo: tSimbolo;
begin
if Assigned(oJogaDaVelha) then
begin
if not oJogaDaVelha.jogada.fimDejogo and
(TButton(Sender).Caption <> EmptyStr) then
Abort;
simbolo := oJogaDaVelha.Jogar;
if simbolo = tSimbolo.tsX then
TButton(Sender).Caption := 'X'
else
TButton(Sender).Caption := 'O';
if TButton(Sender).Name = 'btn11' then
oJogaDaVelha.jogada.jogadas(1, 1, simbolo);
if TButton(Sender).Name = 'btn12' then
oJogaDaVelha.jogada.jogadas(1, 2, simbolo);
if TButton(Sender).Name = 'btn13' then
oJogaDaVelha.jogada.jogadas(1, 3, simbolo);
if TButton(Sender).Name = 'btn21' then
oJogaDaVelha.jogada.jogadas(2, 1, simbolo);
if TButton(Sender).Name = 'btn22' then
oJogaDaVelha.jogada.jogadas(2, 2, simbolo);
if TButton(Sender).Name = 'btn23' then
oJogaDaVelha.jogada.jogadas(2, 3, simbolo);
if TButton(Sender).Name = 'btn31' then
oJogaDaVelha.jogada.jogadas(3, 1, simbolo);
if TButton(Sender).Name = 'btn32' then
oJogaDaVelha.jogada.jogadas(3, 2, simbolo);
if TButton(Sender).Name = 'btn33' then
oJogaDaVelha.jogada.jogadas(3, 3, simbolo);
oJogaDaVelha.jogada.contaSimbolos;
oJogaDaVelha.jogada.VerificaGanhador;
oJogaDaVelha.retornaVencedor;
oJogaDaVelha.jogada.VerificaVelha;
fimDejogo;
end;
end;
procedure TFFrmJogoDaVelha.btnIniciarJogoClick(Sender: TObject);
begin
iniciarJogo;
end;
procedure TFFrmJogoDaVelha.criaJogadores;
begin
if Assigned(oJogador1) and Assigned(oJogador2) then
begin
FreeAndNil(oJogador1);
FreeAndNil(oJogador2);
end;
oJogador1 := TJogador.Create();
oJogador2 := TJogador.Create();
oJogador1.nome := edtJogadorX.Text;
oJogador2.nome := edtJogadorO.Text;
oJogador1.simbolo := tSimbolo.tsX;
oJogador2.simbolo := tSimbolo.tsO;
end;
procedure TFFrmJogoDaVelha.criaJogo;
begin
if Assigned(oJogaDaVelha) then
FreeAndNil(oJogaDaVelha);
oJogaDaVelha := TJogoDaVelha.Create();
oJogaDaVelha.jogador1 := oJogador1;
oJogaDaVelha.jogador2 := oJogador2;
end;
procedure TFFrmJogoDaVelha.fimDejogo;
begin
if oJogaDaVelha.jogada.fimDejogo then
begin
if Application.MessageBox('Deseja jogar novamente?', 'Atenção',
MB_YESNO + MB_ICONQUESTION) = ID_YES then
begin
limpaBotoes;
criaJogadores;
criaJogo;
end
else
Close;
end;
end;
procedure TFFrmJogoDaVelha.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeAndNil(oJogador1);
FreeAndNil(oJogador2);
FreeAndNil(oJogaDaVelha);
end;
procedure TFFrmJogoDaVelha.iniciarJogo;
begin
if not Assigned(oJogaDaVelha) then
begin
pnButtons.Enabled := true;
criaJogadores;
criaJogo;
end
else
begin
if Application.MessageBox('Tem certeza que deseja reiniciar o jogo?',
'Atenção', MB_YESNO + MB_ICONQUESTION) = ID_YES then
begin
FreeAndNil(oJogaDaVelha);
limpaBotoes;
criaJogadores;
criaJogo;
end;
end;
end;
procedure TFFrmJogoDaVelha.limpaBotoes;
var
i: Integer;
begin
for i := FFrmJogoDaVelha.ComponentCount - 1 downto 0 do
begin
if (FFrmJogoDaVelha.Components[i] is TButton) and
(TButton(FFrmJogoDaVelha.Components[i]).Name <> 'btnIniciarJogo') then
TButton(FFrmJogoDaVelha.Components[i]).Caption := EmptyStr;
end;
end;
end.
|
unit imgImageSelect;
interface
uses Classes, Controls, Types, Messages, Graphics;
type
TImageSelect = class(TGraphicControl)
private
xDown: Integer;
yDown: Integer;
ptDown: TPoint;
dragging: Integer;
wDrag: Integer;
rcDown: TRect;
rcDrag: Array [0..7] of TRect;
rcCursor: Array [0..8] of TCursor;
FColorLineSelect: TColor;
FHotColorLineSelect: TColor;
FScrollPositionX: Integer;
FScrollPositionY: Integer;
FGlobalWidth: Integer;
FGlobalHeight: Integer;
FsbTop: Integer;
FsbBottom: integer;
FsbLeft: Integer;
FsbRight: Integer;
FMaxHeight: Integer;
FStartY: Integer;
FStartX: Integer;
FMaxWidth: Integer;
FOnMove: TNotifyEvent;
procedure SetGlobalHeight(const Value: Integer);
procedure SetGlobalWidth(const Value: Integer);
procedure SetsbBottom(const Value: integer);
procedure SetsbLeft(const Value: Integer);
procedure SetsbRight(const Value: Integer);
procedure SetsbTop(const Value: Integer);
procedure SetMaxHeight(const Value: Integer);
procedure SetMaxWidth(const Value: Integer);
procedure SetStartX(const Value: Integer);
procedure SetStartY(const Value: Integer);
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
destructor Destroy; override;
property OnDblClick;
property ParentShowHint;
property ShowHint;
property PopupMenu;
property ColorLineSelect: TColor read FColorLineSelect write FColorLineSelect;
property HotColorLineSelect: TColor read FHotColorLineSelect write FHotColorLineSelect;
property MaxWidth: Integer read FMaxWidth write SetMaxWidth;
property MaxHeight: Integer read FMaxHeight write SetMaxHeight;
property StartX: Integer read FStartX write SetStartX;
property StartY: Integer read FStartY write SetStartY;
property ScrollPositionX: Integer read FScrollPositionX write FScrollPositionX;
property ScrollPositionY: Integer read FScrollPositionY write FScrollPositionY;
property GlobalWidth: Integer read FGlobalWidth write SetGlobalWidth;
property GlobalHeight: Integer read FGlobalHeight write SetGlobalHeight;
property sbLeft: Integer read FsbLeft write SetsbLeft;
property sbTop: Integer read FsbTop write SetsbTop;
property sbRight: Integer read FsbRight write SetsbRight;
property sbBottom: integer read FsbBottom write SetsbBottom;
property OnMove: TNotifyEvent read FOnMove write FOnMove;
end;
implementation
{ TImageSelect }
constructor TImageSelect.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Canvas.Brush.Style := bsClear;
dragging := -1;
wDrag := 5;
ParentColor := True;
rcCursor[0] := crSizeNWSE;
rcCursor[1] := crSizeNS;
rcCursor[2] := crSizeNESW;
rcCursor[3] := crSizeWE;
rcCursor[4] := crSizeNWSE;
rcCursor[5] := crSizeNS;
rcCursor[6] := crSizeNESW;
rcCursor[7] := crSizeWE;
rcCursor[8] := crSizeAll;
end;
destructor TImageSelect.Destroy;
begin
inherited;
end;
procedure TImageSelect.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
i: Integer;
pt: TPoint;
begin
inherited;
pt := Point(X,Y);
ptDown := ClientToScreen(pt);
xDown := X;
yDown := Y;
rcDown := Rect(left,top,left+Width,top+Height);
dragging := -1;
for i := 0 to 7 do
if PtInRect(rcDrag[i],pt) then
dragging := i;
if dragging <> -1 then
Cursor := rcCursor[dragging]
else
if Cursor <> crArrow then
Cursor := crArrow;
Invalidate;
end;
procedure TImageSelect.MouseMove(Shift: TShiftState; X, Y: Integer);
var
i: Integer;
pt: TPoint;
xDif, yDif: Integer;
procedure SetW(leftOff,topOff,rightOff,bottomOff: Integer);
var
rc: TRect;
nLeft, nTop, nRight, nBottom: integer;
begin
rc := rcDown;
Inc(rc.Left,leftOff);
Inc(rc.Top,topOff);
Inc(rc.Right,rightOff);
Inc(rc.Bottom,bottomOff);
// Координаты обрезки
sbLeft := ABS (StartX) + rc.Left;
sbTop := ABS (StartY) + rc.Top;
sbRight := rc.Right - rc.Left;
sbBottom := rc.Bottom - rc.Top;
if sbLeft < 0 then sbLeft := 0;
if sbTop < 0 then sbTop := 0;
if rc.Top + 10 > rc.Bottom
then
begin
if topOff = 0 then rc.Bottom := rc.Top + 10;
if bottomOff = 0 then rc.Top := rc.Bottom - 10;
end;
if rc.Left + 10 > rc.Right
then
begin
if leftOff = 0 then rc.Right := rc.Left + 10;
if rightOff = 0 then rc.Left := rc.Right - 10;
end;
if (rc.Top < StartY)
then
begin
nTop := StartY;
rc.Bottom := nTop + Height;
end
else nTop := rc.Top;
//Блокирование ухода селкта левее, чем картинка
if (rc.Left < StartX)
then
begin
nLeft := StartX;
rc.Right := nLeft + Width;
end
else nLeft := rc.Left;
//Блокирование ухода селкта правее, чем картинка
if (rc.Right > MaxWidth)
then
begin
nRight := MaxWidth;
nLeft := nRight - width;
end
else nRight := rc.Right;
//Блокирование ухода селкта ниже, чем картинка
if (rc.Bottom > MaxHeight)
then
begin
nBottom := MaxHeight;
nTop := nBottom - Height;
end
else nBottom := rc.Bottom;
SetBounds(nLeft, nTop, nRight-nLeft, nBottom-nTop);
// Передаю координаты ImageSelect
if Assigned(FOnMove) then FOnMove(Self);
end;
begin
inherited;
pt := ClientToScreen(Point(X,Y));
xDif := pt.X - ptDown.X;
yDif := pt.Y - ptDown.Y;
if ssLeft in Shift then
case dragging of
-1: SetW(xDif,yDif,xDif,yDif);
0: SetW(xDif,yDif,0,0);
1: SetW(0,yDif,0,0);
2: SetW(0,yDif,xDif,0);
3: SetW(0,0,xDif,0);
4: SetW(0,0,xDif,yDif);
5: SetW(0,0,0,yDif);
6: SetW(xDif,0,0,yDif);
7: SetW(xDif,0,0,0);
end
else
begin
pt := Point(X,Y);
Cursor := rcCursor[8];
for i := 0 to 7 do
if PtInRect(rcDrag[i],pt) then
Cursor := rcCursor[i];
end;
end;
procedure TImageSelect.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
dragging := -1;
Invalidate;
end;
procedure TImageSelect.Paint;
var
rc: TRect;
i,w: Integer;
begin
with Canvas do
begin
Pen.Style := psDot;
if dragging = -1 then
Pen.Color := FColorLineSelect
else
Pen.Color := FHotColorLineSelect;
rc := GetClientRect;
w := wDrag div 2;
Rectangle(w-2, w-2, rc.right-w+2, rc.bottom-w+2);
Brush.Style := bsSolid;
Brush.Color := Pen.Color;
Pen.Style := psSolid;
for i := 0 to 7 do
Rectangle(rcDrag[i].Left,rcDrag[i].Top,rcDrag[i].Right,rcDrag[i].Bottom);
Brush.Style := bsClear;
end;
end;
procedure TImageSelect.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
r,b,r2,b2: Integer;
wDrag2: Integer;
begin
r := AWidth;
b := AHeight;
r2:= r div 2;
b2 := b div 2;
wDrag2 := wDrag div 2;
// Кубики толщина
rcDrag[0] := Rect(0,0,wDrag,wDrag);
rcDrag[1] := Rect(r2-wDrag2,0,r2+wDrag2,wDrag);
rcDrag[2] := Rect(r-wDrag+1,0,r,wDrag);
rcDrag[3] := Rect(r-wDrag+1,b2-wDrag2,r,b2+wDrag2);
rcDrag[4] := Rect(r-wDrag+1,b-wDrag,r,b);
rcDrag[5] := Rect(r2-wDrag2,b-wDrag,r2+wDrag2,b);
rcDrag[6] := Rect(0,b-wDrag,wDrag,b);
rcDrag[7] := Rect(0,b2-wDrag2,wDrag,b2+wDrag2);
inherited SetBounds(ALeft,ATop,AWidth,AHeight);
end;
procedure TImageSelect.SetGlobalHeight(const Value: Integer);
begin
FGlobalHeight := Value;
end;
procedure TImageSelect.SetGlobalWidth(const Value: Integer);
begin
FGlobalWidth := Value;
end;
procedure TImageSelect.SetMaxHeight(const Value: Integer);
begin
FMaxHeight := Value;
end;
procedure TImageSelect.SetMaxWidth(const Value: Integer);
begin
FMaxWidth := Value;
end;
procedure TImageSelect.SetsbBottom(const Value: integer);
begin
FsbBottom := Value;
end;
procedure TImageSelect.SetsbLeft(const Value: Integer);
begin
FsbLeft := Value;
end;
procedure TImageSelect.SetsbRight(const Value: Integer);
begin
FsbRight := Value;
end;
procedure TImageSelect.SetsbTop(const Value: Integer);
begin
FsbTop := Value;
end;
procedure TImageSelect.SetStartX(const Value: Integer);
begin
FStartX := Value;
end;
procedure TImageSelect.SetStartY(const Value: Integer);
begin
FStartY := Value;
end;
end.
|
unit PtMethodInvoker;
interface
uses TestFramework, System.SysUtils, System.Types, System.Classes, Generics.Collections, System.Rtti;
type
/// <summary>
/// Can invoke the desired overloaded method version
/// </summary>
TPtMethodInvoker = class
public
/// <summary>
/// This function can invoke the desired overloaded method version
/// </summary>
class function RttiMethodInvokeEx(const AMethodName: string; ARttiType: TRttiType;
AInstance: TValue; const AArgs: array of TValue; AIsClassMethod: Boolean): TValue; static;
// TODO: class function RttiConstructorInvokeEx
// TODO: class function RttiDestructorInvokeEx
end;
implementation
{ TPtMethodInvoker }
class function TPtMethodInvoker.RttiMethodInvokeEx(const AMethodName: string; ARttiType: TRttiType;
AInstance: TValue; const AArgs: array of TValue; AIsClassMethod: Boolean): TValue;
// http://stackoverflow.com/questions/10083448/trttimethod-invoke-function-doesnt-work-in-overloaded-methods
// Author - RRUZ (https://github.com/RRUZ)
var
Found: Boolean;
LMethod: TRttiMethod;
LIndex: Integer;
LParams: TArray<TRttiParameter>;
begin
Result := nil;
LMethod := nil;
Found := False;
for LMethod in ARttiType.GetMethods do
if SameText(LMethod.Name, AMethodName) and (LMethod.IsClassMethod = AIsClassMethod) then
begin
LParams := LMethod.GetParameters;
if Length(AArgs) = Length(LParams) then
begin
Found := True;
for LIndex := 0 to Length(LParams) - 1 do
if LParams[LIndex].ParamType.Handle <> AArgs[LIndex].TypeInfo then
begin
Found := False;
Break;
end;
end;
if Found then
Break;
end;
if (LMethod <> nil) and Found then
Result := LMethod.Invoke(AInstance, AArgs)
else
raise EMethodNotFound.CreateFmt('Method %s not found (IsClassMethod = ' +
AIsClassMethod.ToString(TUseBoolStrs.True) + ')', [AMethodName]);
end;
end.
|
{****************************************************************************************
SAPMM v1.01 /17.06.2013/
Thread memory management
****************************************************************************************}
unit SAPThreadMM;
interface
{$Include SAPOptions.inc}
uses
SAPDefs,
SAPSmallBlocks,
SAPSystem
;
// Create thread MM
function CreateThreadMM: PSAPThreadMM;
// Release all freed memory to OS on thread termination.
// If all blocks allocated by thread MM are released to OS, thread MM is destroyed,
// otherwise thread MM is kept with "zombie" flag set up
procedure ThreadReleaseMM(mm: PSAPThreadMM);
// Allocate memory for thread
function ThreadGetMem(mm: PSAPThreadMM; size: Integer): Pointer; inline;
// Free memory block p via given thread MM
// ! Check, that memory was allocated exactly by this MM, is NOT performed !
function ThreadFreeMem(mm: PSAPThreadMM; p: Pointer): Integer; inline;
// Reallocates memory block. Cases when size <= 0 and p = nil must be performed at the higher level before calling this method
function ThreadReallocMem(mm: PSAPThreadMM; var p: Pointer; size: LongWord): Integer; inline;
// Returns allocated block size without service info
function GetAllocatedSize(p: Pointer): LongWord; inline;
// Returns thread MM
function GetThreadMM: Pointer;
// Sync when freeing memory allocated from another thread MM
procedure LockForFreeFromOtherThread(mm: PSAPThreadMM); inline;
procedure UnlockForFreeFromOtherThread(mm: PSAPThreadMM); inline;
// If memory block was allocated by one thread MM and freed in another thread MM,
// it is put into special list instead of freeing "in place".
// All blocks from this list are freed by the following procedure
// It is called on each call of Get, Free, Realloc, and also when MM is destroyed
procedure FreeAllBlocksFreedInOtherThread(mm: PSAPThreadMM);
// Called before memory leak check to free all not freed blocks, allocated from threads,
// which are already terminated (their MMs were put into "zombie" MMs list)
procedure CheckAndReleaseZombiMM;
// Locks MMs list for enumeration or changing
procedure LockMMsList;
procedure UnlockMMsList;
// TLS addr for getting thread MM
var
TLSIndex: LongWord;
TLSOffset: LongWord;
var // variables are declared in interface for statistics
// they may only be used between LockMMsList/UnlockMMsList calls
work_mm: PSAPThreadMM = nil; // List of active MMs
zombi_mm: PSAPThreadMM = nil; // List of MMs, left from terminated threads
// which still have used memory (this may be either a memory leak
// or memory, which is now used by another thread)
var
memory_leaks_add: TSAPTags; // When memory leak check is performed,
// sap_used_in_leaks_reporting value is included into TSapTags
// Before this moment this set is empty
implementation
uses
Windows,
SAPOSBlocks,
SAPNormalBlocks,
SAPList,
SAPErrCodes,
SAPRelease,
SAPReportMemoryLeaks
//, SAPDebugUtils
;
var
HeapHandle: THandle = 0; // for allocation memory for ThreadMM
//----------------
var
// CS for adding or deleting thread MMs
gThreadMMsListCS: _RTL_CRITICAL_SECTION;
procedure LockMMsList;
begin
Windows.EnterCriticalSection(gThreadMMsListCS);
end;
procedure UnlockMMsList;
begin
Windows.LeaveCriticalSection(gThreadMMsListCS);
end;
//------------------------------------------------------------
function GetThreadMM: Pointer;
asm
mov eax,TLSOffset
mov ecx,fs:[$00000018]
mov eax,[ecx+eax]
mov Result, eax
end;
{ slower old implementation
function GetThreadMM: Pointer;
begin
Result := TlsGetValue(TLSIndex);
end; }
procedure TieToMMList(var list: PSAPThreadMM; x: PSAPThreadMM);
begin
if list = nil then
begin
x.next := nil;
x.prev := nil;
list := x;
end
else begin
// Вставить вторым
x.next := list.next;
x.prev := list;
if x.next <> nil then x.next.prev := x;
list.next := x;
end;
end;
procedure UntieFromMMList(var list: PSAPThreadMM; x: PSAPThreadMM);
begin
if x.next <> nil then x.next.prev := x.prev;
if x.prev <> nil then x.prev.next := x.next;
if list = x then list := x.next;
end;
function CreateThreadMM: PSAPThreadMM;
var
x: PSAPThreadMM;
begin
x := Windows.HeapAlloc(HeapHandle, Windows.HEAP_ZERO_MEMORY, SizeOf(TSAPThreadMM));
Windows.TlsSetValue(TLSIndex, x);
Windows.InitializeCriticalSection(x.crit_sect_for_other_threads);
x.magic := cMagicMM;
x.thread_id := GetCurrentThreadId; // for statistics and debug
InitSmallBlocksTable(x);
LockMMsList;
TieToMMList(work_mm, x);
UnlockMMsList;
Result := x;
end;
procedure ThreadReleaseMM(mm: PSAPThreadMM);
var
done: Boolean;
begin
if mm.blocks_to_free <> nil then
FreeAllBlocksFreedInOtherThread(mm);
done := TryToReleaseAllOSBlocks(mm);
CheckAndReleaseZombiMM;
LockMMsList;
UntieFromMMList(work_mm, mm);
if not done then
TieToMMList(zombi_mm, mm);
UnlockMMsList;
if done then
Windows.HeapFree(HeapHandle, 0, mm);
end;
//----------------------------------------------------------
procedure LockForFreeFromOtherThread(mm: PSAPThreadMM); {inline;}
begin
Windows.EnterCriticalSection(mm.crit_sect_for_other_threads);
end;
procedure UnlockForFreeFromOtherThread(mm: PSAPThreadMM); {inline;}
begin
Windows.LeaveCriticalSection(mm.crit_sect_for_other_threads);
end;
// Called when each thread MM is destroyed
// Checks the list of "zombie" ММs,
// if MM has not empty list "blocks_to_free", then frees it
// Code is optimized not to hold critical section for too long
procedure CheckAndReleaseZombiMM;
var
done: Boolean;
x: PSAPThreadMM;
released: Boolean;
begin
done := False;
while not done do
begin
done := True;
LockMMsList;
x := zombi_mm;
while x <> nil do
begin
if x.blocks_to_free <> nil then
begin
UntieFromMMList(zombi_mm, x);
done := False;
break;
end;
x := x.next;
end;
UnlockMMsList;
if not done then
begin
FreeAllBlocksFreedInOtherThread(x);
released := TryToReleaseAllOSBlocks(x);
if released then
Windows.HeapFree(HeapHandle, 0, x)
else
begin
LockMMsList;
TieToMMList(zombi_mm, x);
UnlockMMsList;
end;
end;
end;
end;
//----------------------------------------------------------
function ThreadGetMem(mm: PSAPThreadMM; size: Integer): Pointer;
var
s: PSAPSmallAllocatedBlock;
block_size: LongWord;
p: Pointer;
begin
// statistics
Inc(mm.no_get);
if mm.blocks_to_free <> nil then
FreeAllBlocksFreedInOtherThread(mm);
// 1. Allocate the block from small blocks list
if size <= cMaxSmallBlockSize - SizeOf(TSAPSmallAllocatedBlock) then
begin
s := AllocateSmallBlock(mm, size);
{$IFDEF SAP_MEMORYLEAKS}
s.tags := s.tags + memory_leaks_add;
{$ENDIF}
{$IFDEF SAP_STATIP}
SaveIP(s.ips);
{$ENDIF}
Result := Pointer(LongWord(s) + SizeOf(TSAPSmallAllocatedBlock));
{$IFDEF SAP_STAT}
Inc(mm.no_get_small);
{$ENDIF}
Exit;
end;
// 2. Allocate block from free blocks list
// Add service part size and alignment
block_size :=
( size // allocated size
+ SizeOf(TSAPAllocatedBlock) // header of allocated block
+ SizeOf(LongWord) // size at the end of the block
+ (cNormalAlignment - 1) // alignment
) and not (cNormalAlignment - 1);
p := AllocateNormalBlock(mm, block_size);
{$IFDEF SAP_STAT}
Inc(mm.no_get_normal);
{$ENDIF}
if p = nil then
begin
// What should I do here?
Result := nil;
Exit;
end;
{$IFDEF SAP_MEMORYLEAKS}
PSAPAllocatedBlock(p).tags := PSAPAllocatedBlock(p).tags + memory_leaks_add;
{$ENDIF}
{$IFDEF SAP_STATIP}
SaveIP(PSAPAllocatedBlock(p).ips);
{$ENDIF}
Result := Pointer(LongWord(p) + SizeOf(TSAPAllocatedBlock));
end;
function ThreadFreeMem(mm: PSAPThreadMM; p: Pointer): Integer;
var
small: PSAPSmallAllocatedBlock;
begin
if mm.blocks_to_free <> nil then
FreeAllBlocksFreedInOtherThread(mm);
if LongWord(p) and (cAlignment - 1) <> 0 then
begin
Result := cErrInvPtrAlignment; // pointer is not aligned to cAlignment
Exit;
end;
small := PSAPSmallAllocatedBlock(LongWord(p) - SizeOf(TSAPSmallAllocatedBlock));
if small.magic <> cMagic then
begin
Result := cErrWrongMagic; // wrong magic number
Exit;
end;
if not (sap_allocated in small.tags) then
begin
Result := cErrNotAllocated;
Exit;
end;
Inc(mm.no_free);
// 1. Free small block
if sap_small_block in small.tags then
begin
FreeSmallBlock(mm, small);
Result := 0;
Exit;
end;
// 2. Insert into free blocks list
InsertIntoFreeList(mm, p);
Result := 0;
end;
//----------------------------------------------
// Reallocate
// Get the size of allocated block without service info size
function GetAllocatedSize(p: Pointer): LongWord; inline;
var
s: PSAPSmallAllocatedBlock;
h: PSAPSmallBlocksHeader;
b: PSAPAllocatedBlock;
begin
s := Pointer(LongWord(p) - SizeOf(TSAPSmallAllocatedBlock));
if sap_small_block in s.tags then
begin
h := Pointer(LongWord(s) - s.ofs);
if h.header_magic <> cSmallBlockHeaderMagic then
begin
Result := 0;
Exit;
end;
Result := h.block_size - SizeOf(TSAPSmallAllocatedBlock);
end
else begin
b := Pointer(LongWord(p) - SizeOf(TSAPAllocatedBlock));
if b.block_magic <> cNormalBlockMagic then
begin
Result := 0;
Exit;
end;
Result := b.size - cBlockOverhead;
end;
end;
function ThreadReallocMem(mm: PSAPThreadMM; var p: Pointer; size: LongWord): Integer; inline;
var
new_p: Pointer;
block_size: LongWord;
move_size: LongWord;
begin
{$IFDEF SAP_STAT}
Inc(mm.no_realloc);
{$ENDIF}
if mm.blocks_to_free <> nil then
FreeAllBlocksFreedInOtherThread(mm);
block_size := GetAllocatedSize(p);
if (block_size >= size) and ((block_size - size <= 64) or (size > block_size shr 1)) then
begin
// Keep block "in place" if:
// 1. difference is small
// 2. if is shrunk into not less than 50% of current block size
{$IFDEF SAP_STAT}
Inc(mm.no_realloc_at_place);
{$ENDIF}
Result := 0;
Exit;
end;
if block_size < size then
size := size + size shr 2; // allocate 25% more than required to reduce relocations
new_p := ThreadGetMem(mm, size);
if new_p <> nil then
begin
if size > block_size then
begin
{$IFDEF SAP_STAT}
Inc(mm.no_realloc_extend);
{$ENDIF}
move_size := block_size;
end
else begin
{$IFDEF SAP_STAT}
Inc(mm.no_realloc_shrink);
{$ENDIF}
move_size := size
end;
{$IFDEF SAP_STAT}
Inc(mm.no_realloc_copy_bytes, move_size);
{$ENDIF}
// System.Move(p^, new_p^, move_size);
SAPMoveMemory(new_p, p, move_size);
end;
Result := ThreadFreeMem(mm, p);
p := new_p;
end;
procedure FreeAllBlocksFreedInOtherThread(mm: PSAPThreadMM);
var
x: PSAPBlocksFreedInOtherThreads;
next: PSAPBlocksFreedInOtherThreads;
begin
LockForFreeFromOtherThread(mm);
x := mm.blocks_to_free;
mm.blocks_to_free := nil;
UnlockForFreeFromOtherThread(mm);
while x <> nil do
begin
next := x.next;
ThreadFreeMem(mm, x);
{$IFDEF SAP_STAT}
Inc(mm.no_free_from_other_thread);
{$ENDIF}
x := next;
end;
end;
procedure CreateHeap;
begin
if HeapHandle = 0 then
HeapHandle := Windows.HeapCreate(0, 32 * 1024, 0); // initial memory: 32 KB
end;
initialization
memory_leaks_add := [];
CreateHeap;
TLSIndex := Windows.TlsAlloc;
TLSOffset := TLSIndex * 4 + $0e10;
Windows.InitializeCriticalSection(gThreadMMsListCS);
end.
|
unit uRendererFMX;
interface
uses
System.UITypes,
FMX.Graphics,
uSimpleRayTracer;
type
TRendererFMX = class
private
FSimpleRayTracer: TSimpleRayTracer;
function GetPixelColor(x,y: integer): TAlphaColor;
public
constructor Create(aWidth, aHeight: integer; aAntiAlias: integer = 1);
destructor Destroy; override;
function DoRender: TBitmap;
end;
implementation
{ TRendererFMX }
constructor TRendererFMX.Create(aWidth, aHeight: integer; aAntiAlias: integer = 1);
begin
FSimpleRayTracer := TSimpleRayTracer.Create(aWidth, aHeight, aAntiAlias);
end;
destructor TRendererFMX.Destroy;
begin
FSimpleRayTracer.Free;
inherited;
end;
function TRendererFMX.DoRender: TBitmap;
var bmp: TBitmap; data: TBitmapData;
w,h,x,y: integer; c: TAlphaColor;
begin
FSimpleRayTracer.CalculatePixelColors;
w := FSimpleRayTracer.getWidth;
h := FSimpleRayTracer.getHeight;
bmp := TBitmap.Create;
bmp.Width := w;
bmp.Height := h;
bmp.Map(TMapAccess.Write, data);
try
for x := 0 to w - 1 do
for y := 0 to h - 1 do
begin
c := GetPixelColor(x, h-y);
data.SetPixel(x, y, c);
end;
finally
bmp.Unmap(data);
end;
Result := bmp;
end;
function TRendererFMX.GetPixelColor(x, y: integer): TAlphaColor;
var c: RGBType; colorF: TAlphaColorF;
begin
c := FSimpleRayTracer.getPixelData(x, y);
colorF := TAlphaColorF.Create(c.r, c.g, c.b);
Result := colorF.ToAlphaColor;
end;
end.
|
unit uAbstractFactory;
interface
uses
Spring.Collections
;
type
IBattery = interface
['{AE55BF10-3945-43BC-886D-AC8556334D55}']
function GetType: string;
end;
IElectricalDevice = interface
['{14655F2F-8B5A-4A45-BC7F-459FEB99F8B6}']
function GetName: string;
procedure UseBattery(aBattery: IBattery);
end;
IElectricalDeviceFactory = interface
['{EFB88733-99B0-4E3C-B626-19D6C6CDA111}']
function CreateBattery: IBattery;
function CreateElectricalDevice: IElectricalDevice;
end;
TLitiumIonBattery = class(TInterfacedOBject, IBattery)
function GetType: string;
end;
TCellPhone = class(TInterfacedObject, IElectricalDevice)
function GetName: string;
procedure UseBattery(aBattery: IBattery);
end;
TAABatteries = class(TInterfacedObject, IBattery)
function GetType: string;
end;
TToyRaceCar = class(TInterfacedObject, IElectricalDevice)
function GetName: string;
procedure UseBattery(aBattery: IBattery);
end;
// Concrete Factories
TCellPhoneFactory = class(TInterfacedObject, IElectricalDeviceFactory)
function CreateBattery: IBattery;
function CreateElectricalDevice: IElectricalDevice;
end;
TToyRaceCarFactory = class(TInterfacedObject, IElectricalDeviceFactory)
function CreateBattery: IBattery;
function CreateElectricalDevice: IElectricalDevice;
end;
// Client class
TElectrical = class
private
FBattery: IBattery;
FElectricalDevice: IElectricalDevice;
public
constructor Create(aElectricalDeviceFactory: IElectricalDeviceFactory);
procedure TurnOnDevice;
end;
procedure DoIt;
implementation
procedure DoIt;
var
CellPhoneFactory: IElectricalDeviceFactory;
ToyCarFactory: IElectricalDeviceFactory;
Electrical: TElectrical;
begin
CellPhoneFactory := TCellPhoneFactory.Create;
Electrical := TElectrical.Create(CellPhoneFactory);
try
Electrical.TurnOnDevice;
finally
Electrical.Free;
end;
ToyCarFactory := TToyRaceCarFactory.Create;
Electrical := TElectrical.Create(ToyCarFactory);
try
Electrical.TurnOnDevice;
finally
Electrical.Free;
end;
end;
function TCellPhoneFactory.CreateElectricalDevice: IElectricalDevice;
begin
Result := TCellPhone.Create;
end;
function TCellPhoneFactory.CreateBattery: IBattery;
begin
Result := TLitiumIonBattery.Create;
end;
function TToyRaceCarFactory.CreateElectricalDevice: IElectricalDevice;
begin
Result := TToyRaceCar.Create;
end;
function TToyRaceCarFactory.CreateBattery: IBattery;
begin
Result := TAABatteries.Create;
end;
constructor TElectrical.Create(aElectricalDeviceFactory: IElectricalDeviceFactory);
begin
inherited Create;
FBattery := aElectricalDeviceFactory.CreateBattery;
FElectricalDevice := aElectricalDeviceFactory.CreateElectricalDevice;
end;
procedure TElectrical.TurnOnDevice;
begin
FElectricalDevice.UseBattery(FBattery);
end;
{ TLitiumIonBattery }
function TLitiumIonBattery.GetType: string;
begin
Result := 'Lithium Ion Battery';
end;
{ TCellPhone }
function TCellPhone.GetName: string;
begin
Result := 'Cell Phone';
end;
procedure TCellPhone.UseBattery(aBattery: IBattery);
begin
WriteLn(Self.GetName, ' is powered by a ', aBattery.GetType);
end;
{ TAABatteries }
function TAABatteries.GetType: string;
begin
Result := 'AA Batteries';
end;
{ TToyRaceCar }
function TToyRaceCar.GetName: string;
begin
Result := 'Toy Race Car';
end;
procedure TToyRaceCar.UseBattery(aBattery: IBattery);
begin
WriteLn(Self.GetName, ' is powered by a ', aBattery.GetType);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP 3.0
Description: Controller relacionado à tabela [NFE_CONFIGURACAO]
The MIT License
Copyright: Copyright (C) 2021 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 (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit NfeConfiguracaoController;
interface
uses mvcframework, mvcframework.Commons,
System.SysUtils, System.Classes,
MVCFramework.SystemJSONUtils, MVCFramework.Serializer.Defaults;
type
[MVCDoc('CRUD NfeConfiguracao')]
[MVCPath('/nfe-configuracao')]
TNfeConfiguracaoController = class(TMVCController)
public
[MVCDoc('Atualiza os dados')]
[MVCPath('/atualiza-dados/')]
[MVCHTTPMethod([httpPOST])]
procedure AtualizarDados(Context: TWebContext);
end;
implementation
{ TNfeConfiguracaoController }
uses NfeConfiguracaoService, NfeConfiguracao, Commons, Filtro, Constantes,
ObjetoPdvConfiguracao, Biblioteca;
procedure TNfeConfiguracaoController.AtualizarDados(Context: TWebContext);
var
Cnpj, ObjetoJsonString: string;
NfeConfiguracao: TNfeConfiguracao;
PdvConfiguracao: TObjetoPdvConfiguracao;
begin
try
Cnpj := Biblioteca.DecifrarDCPCrypt(Context.Request.Headers['cnpj']);
NfeConfiguracao := TNfeConfiguracao.Create;
ObjetoJsonString := Biblioteca.DecifrarDCPCrypt(Context.Request.Body);
GetDefaultSerializer.DeserializeObject(ObjetoJsonString, NfeConfiguracao);
PdvConfiguracao := TObjetoPdvConfiguracao.Create;
ObjetoJsonString := Biblioteca.DecifrarDCPCrypt(Context.Request.Headers['pdv-configuracao']);
GetDefaultSerializer.DeserializeObject(ObjetoJsonString, PdvConfiguracao);
except
on E: EServiceException do
begin
raise EMVCException.Create('Objeto inválido [Atualizar NfeConfiguracao] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
try
NfeConfiguracao := TNfeConfiguracaoService.AtualizarDados(NfeConfiguracao, cnpj, PdvConfiguracao.DecimaisQuantidade, PdvConfiguracao.DecimaisValor);
ObjetoJsonString := GetDefaultSerializer.SerializeObject(NfeConfiguracao);
Render(Biblioteca.CifrarDCPCrypt(ObjetoJsonString));
except
on E: EServiceException do
begin
raise EMVCException.Create('Problemas na inserção [Atualizar NfeConfiguracao] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VENDA_ORCAMENTO_CABECALHO]
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 VendaOrcamentoCabecalhoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB,
VendedorVO, ViewPessoaTransportadoraVO, ViewPessoaClienteVO, VendaCondicoesPagamentoVO,
VendaOrcamentoDetalheVO;
type
[TEntity]
[TTable('VENDA_ORCAMENTO_CABECALHO')]
TVendaOrcamentoCabecalhoVO = class(TVO)
private
FID: Integer;
FID_VENDA_CONDICOES_PAGAMENTO: Integer;
FID_VENDEDOR: Integer;
FID_TRANSPORTADORA: Integer;
FID_CLIENTE: Integer;
FTIPO: String;
FCODIGO: String;
FDATA_CADASTRO: TDateTime;
FDATA_ENTREGA: TDateTime;
FVALIDADE: TDateTime;
FTIPO_FRETE: String;
FVALOR_SUBTOTAL: Extended;
FVALOR_FRETE: Extended;
FTAXA_COMISSAO: Extended;
FVALOR_COMISSAO: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_TOTAL: Extended;
FOBSERVACAO: String;
FSITUACAO: String;
//Transientes
FVendedorNome: String;
FTransportadoraNome: String;
FClienteNome: String;
FVendaCondicoesPagamentoNome: String;
FVendedorVO: TVendedorVO;
FTransportadoraVO: TViewPessoaTransportadoraVO;
FClienteVO: TViewPessoaClienteVO;
FVendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO;
FListaVendaOrcamentoDetalheVO: TObjectList<TVendaOrcamentoDetalheVO>;
public
constructor Create; override;
destructor Destroy; override;
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_VENDA_CONDICOES_PAGAMENTO', 'Id Venda Condicoes Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdVendaCondicoesPagamento: Integer read FID_VENDA_CONDICOES_PAGAMENTO write FID_VENDA_CONDICOES_PAGAMENTO;
[TColumnDisplay('CONDICOESPAGAMENTO.NOME', 'Condições Pagamento', 100, [ldGrid, ldLookup, ldComboBox], ftString, 'VendaCondicoesPagamentoVO.TVendaCondicoesPagamentoVO', True)]
property VendaCondicoesPagamentoNome: String read FVendaCondicoesPagamentoNome write FVendaCondicoesPagamentoNome;
[TColumn('ID_VENDEDOR', 'Id Vendedor', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdVendedor: Integer read FID_VENDEDOR write FID_VENDEDOR;
[TColumnDisplay('VENDEDOR.NOME', 'Vendedor Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'VendedorVO.TVendedorVO', True)]
property VendedorNome: String read FVendedorNome write FVendedorNome;
[TColumn('ID_TRANSPORTADORA', 'Id Transportadora', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdTransportadora: Integer read FID_TRANSPORTADORA write FID_TRANSPORTADORA;
[TColumnDisplay('TRANSPORTADORA.NOME', 'Transportadora Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'ViewPessoaTransportadoraVO.TViewPessoaTransportadoraVO', True)]
property TransportadoraNome: String read FTransportadoraNome write FTransportadoraNome;
[TColumn('ID_CLIENTE', 'Id Cliente', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE;
[TColumnDisplay('CLIENTE.NOME', 'Cliente Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'ViewPessoaClienteVO.TViewPessoaClienteVO', True)]
property ClienteNome: String read FClienteNome write FClienteNome;
[TColumn('TIPO', 'Tipo', 8, [ldGrid, ldLookup, ldCombobox], False)]
property Tipo: String read FTIPO write FTIPO;
[TColumn('CODIGO', 'Codigo', 160, [ldGrid, ldLookup, ldCombobox], False)]
property Codigo: String read FCODIGO write FCODIGO;
[TColumn('DATA_CADASTRO', 'Data Cadastro', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
[TColumn('DATA_ENTREGA', 'Data Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataEntrega: TDateTime read FDATA_ENTREGA write FDATA_ENTREGA;
[TColumn('VALIDADE', 'Validade', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Validade: TDateTime read FVALIDADE write FVALIDADE;
[TColumn('TIPO_FRETE', 'Tipo Frete', 8, [ldGrid, ldLookup, ldCombobox], False)]
property TipoFrete: String read FTIPO_FRETE write FTIPO_FRETE;
[TColumn('VALOR_SUBTOTAL', 'Valor Subtotal', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
[TColumn('VALOR_FRETE', 'Valor Frete', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
[TColumn('TAXA_COMISSAO', 'Taxa Comissao', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property TaxaComissao: Extended read FTAXA_COMISSAO write FTAXA_COMISSAO;
[TColumn('VALOR_COMISSAO', 'Valor Comissao', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorComissao: Extended read FVALOR_COMISSAO write FVALOR_COMISSAO;
[TColumn('TAXA_DESCONTO', 'Taxa Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
[TColumn('VALOR_DESCONTO', 'Valor Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
[TColumn('VALOR_TOTAL', 'Valor Total', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
[TColumn('OBSERVACAO', 'Observacao', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Observacao: String read FOBSERVACAO write FOBSERVACAO;
[TColumn('SITUACAO', 'Situacao', 8, [ldGrid, ldLookup, ldCombobox], False)]
property Situacao: String read FSITUACAO write FSITUACAO;
//Transientes
[TAssociation('ID', 'ID_TRANSPORTADORA')]
property TransportadoraVO: TViewPessoaTransportadoraVO read FTransportadoraVO write FTransportadoraVO;
[TAssociation('ID', 'ID_CLIENTE')]
property ClienteVO: TViewPessoaClienteVO read FClienteVO write FClienteVO;
[TAssociation('ID', 'ID_VENDEDOR')]
property VendedorVO: TVendedorVO read FVendedorVO write FVendedorVO;
[TAssociation('ID', 'ID_VENDA_CONDICOES_PAGAMENTO')]
property VendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO read FVendaCondicoesPagamentoVO write FVendaCondicoesPagamentoVO;
[TManyValuedAssociation('ID_VENDA_ORCAMENTO_CABECALHO', 'ID')]
property ListaVendaOrcamentoDetalheVO: TObjectList<TVendaOrcamentoDetalheVO> read FListaVendaOrcamentoDetalheVO write FListaVendaOrcamentoDetalheVO;
end;
implementation
constructor TVendaOrcamentoCabecalhoVO.Create;
begin
inherited;
FTransportadoraVO := TViewPessoaTransportadoraVO.Create;
FClienteVO := TViewPessoaClienteVO.Create;
FVendedorVO := TVendedorVO.Create;
FVendaCondicoesPagamentoVO := TVendaCondicoesPagamentoVO.Create;
FListaVendaOrcamentoDetalheVO := TObjectList<TVendaOrcamentoDetalheVO>.Create;
end;
destructor TVendaOrcamentoCabecalhoVO.Destroy;
begin
FreeAndNil(FTransportadoraVO);
FreeAndNil(FClienteVO);
FreeAndNil(FVendedorVO);
FreeAndNil(FVendaCondicoesPagamentoVO);
FreeAndNil(FListaVendaOrcamentoDetalheVO);
inherited;
end;
initialization
Classes.RegisterClass(TVendaOrcamentoCabecalhoVO);
finalization
Classes.UnRegisterClass(TVendaOrcamentoCabecalhoVO);
end.
|
{==============================================================================|
| MicroCoin |
| Copyright (c) 2018 MicroCoin Developers |
|==============================================================================|
| 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 opies 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. |
|==============================================================================|
| File: MicroCoin.Forms.ChangeAccountKey.pas |
| Created at: 2018-09-04 |
| Purpose: Form to change account key |
|==============================================================================}
unit MicroCoin.Forms.ChangeAccountKey;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, Buttons, PngBitBtn,
ExtCtrls, MicroCoin.Account.Editors, MicroCoin.Account.AccountKey, UCrypto,
MicroCoin.Common, MicroCoin.Account.Data, MicroCoin.Transaction.ChangeKey,
MicroCoin.Node.Node, MicroCoin.Transaction.Base,
MicroCoin.Crypto.Keys,
MicroCoin.Transaction.ITransaction, MicroCoin.Transaction.Transaction;
type
TChangeAccountKeyForm = class(TForm)
edNewPublicKey: TLabeledEdit;
Label3: TLabel;
edFee: TEdit;
payloadPanel: TPanel;
Label7: TLabel;
Label9: TLabel;
Label6: TLabel;
cbEncryptMode: TComboBox;
edPassword: TEdit;
edPayload: TMemo;
Panel2: TPanel;
btnSave: TPngBitBtn;
btnCancel: TPngBitBtn;
edSignerAccount: TAccountEditor;
Label1: TLabel;
procedure cbEncryptModeChange(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
FAccount: TAccount;
procedure SetAccount(const Value: TAccount);
{ Private declarations }
public
{ Public declarations }
published
property Account : TAccount read FAccount write SetAccount;
end;
var
ChangeAccountKeyForm: TChangeAccountKeyForm;
implementation
uses UECIES, UAES;
resourcestring
StrUnlockWallet = 'Unlock wallet';
StrPassword = 'Password:';
StrInvalidKey = 'Invalid key: ';
StrInvalidFee = 'Invalid fee';
StrKeyNotFound = 'Key not found';
StrDoYouWantExecute = 'Do you want execute this transaction: ';
StrTransactionExecuted = 'Transaction executed';
{$R *.dfm}
procedure TChangeAccountKeyForm.btnSaveClick(Sender: TObject);
var
xNewkey: TECPublicKey;
xErrors: AnsiString;
xFee: Int64;
xSignerAccount: TAccount;
xTransaction: ITransaction;
xPayload : AnsiString;
xIndex: integer;
xPassword: string;
begin
while not TNode.Node.KeyManager.IsValidPassword
do begin
if not InputQuery(StrUnlockWallet, [#30+StrPassword], xPassword) then exit;
TNode.Node.KeyManager.WalletPassword := xPassword;
end;
if not TAccountKey.AccountKeyFromImport(edNewPublicKey.Text, xNewkey, xErrors) then
begin
MessageDlg(StrInvalidKey + xErrors, mtError, [mbOK],0);
exit;
end;
if not TCurrencyUtils.ParseValue(edFee.Text, xFee) then begin
MessageDlg(StrInvalidFee, mtError, [mbOk], 0);
exit;
end;
xIndex := TNode.Node.KeyManager.IndexOfAccountKey(Account.AccountInfo.AccountKey);
if xIndex<0 then begin
MessageDlg(StrKeyNotFound, mtError, [mbOk], 0);
exit;
end;
xSignerAccount := edSignerAccount.Account;
if Trim(edPayload.Text)<>'' then begin
case cbEncryptMode.ItemIndex of
0: xPayload := edPayload.Text;
1: xPayload := ECIESEncrypt(account.AccountInfo.AccountKey, edPayload.Text);
2: xPayload := ECIESEncrypt(xSignerAccount.AccountInfo.AccountKey, edPayload.Text);
3: xPayload := TAESComp.EVP_Encrypt_AES256(edPayload.Text, edPassword.Text);
end;
end else xPayload := '';
xTransaction := TChangeKeyTransaction.Create(xSignerAccount.AccountNumber, xSignerAccount.NumberOfTransactions+1, Account.AccountNumber,
TNode.Node.KeyManager.Key[xIndex].PrivateKey,
xNewkey, xFee, xPayload);
if MessageDlg(StrDoYouWantExecute+xTransaction.ToString+'?',mtConfirmation, [mbYes, mbNo], 0) <> mrYes
then exit;
if not TNode.Node.AddTransaction(nil, xTransaction, xErrors) then begin
MessageDlg(xErrors, mtError, [mbOK], 0);
end else begin
MessageDlg(StrTransactionExecuted, mtInformation, [mbOK], 0);
end;
end;
procedure TChangeAccountKeyForm.cbEncryptModeChange(Sender: TObject);
begin
edPassword.Enabled := cbEncryptMode.ItemIndex = 3;
end;
procedure TChangeAccountKeyForm.SetAccount(const Value: TAccount);
begin
FAccount := Value;
edSignerAccount.AccountNumber := TAccount.AccountNumberToString(account.AccountNumber);
end;
end.
|
(*******************************************************************)
(* Programmname : LIFO.PAS V1.0 *)
(* Programmautor : Michael Rippl *)
(* Compiler : Quick Pascal V1.0 *)
(* Inhalt : Routinen zur Verwaltung eines Stapels (LIFO) *)
(* Bemerkung : - *)
(* Letzte nderung : 25-May-1990 *)
(*******************************************************************)
UNIT Lifo;
INTERFACE
TYPE pStack = ^Stack; (* Zeigt auf Stackelement *)
Stack = RECORD (* Stackelement *)
Content : POINTER; (* Inhalt vom Stackelement *)
Next, (* Nchstes Stackelement *)
Prev : pStack; (* Vorheriges Stackelement *)
END;
(* Erzeugen eines Stapels *)
PROCEDURE CreateStack(VAR Top : pStack);
(* Stack wird berprft, ob er leer ist *)
FUNCTION StackIsEmpty(Top : pStack) : BOOLEAN;
(* Element auf dem Stapel ablegen *)
PROCEDURE Push(VAR Top : pStack; ItemContent : POINTER);
(* Element vom Stapel nehmen *)
PROCEDURE Pop(VAR Top : pStack; VAR ItemContent : POINTER);
(* Der komplette Stapel wird gelscht *)
PROCEDURE DeleteStack(VAR Top : pStack);
(* Durch Inhalt bestimmtes Objekt suchen und lschen *)
PROCEDURE DeleteElement(VAR Top : pStack; Content : POINTER);
IMPLEMENTATION
(* Erzeugen eines Stapels *)
PROCEDURE CreateStack(VAR Top : pStack);
BEGIN
Top := NIL;
END; (* CreateStack *)
(* Stack wird berprft, ob er leer ist *)
FUNCTION StackIsEmpty(Top : pStack) : BOOLEAN;
BEGIN
StackIsEmpty := Top = NIL;
END; (* StackIsEmpty *)
(* Element auf dem Stapel ablegen *)
PROCEDURE Push(VAR Top : pStack; ItemContent : POINTER);
VAR Item : pStack;
BEGIN
New(Item); (* Neues Stackelement *)
WITH Item^ DO
BEGIN
Content := ItemContent; (* Inhalt eintragen *)
Next := Top;
Prev := NIL;
END;
IF NOT StackIsEmpty(Top) THEN (* Schon Element auf Stack *)
Top^.Prev := Item; (* Vorgnger eintragen *)
Top := Item; (* Neue Stackspitze *)
END; (* Push *)
(* Element vom Stapel nehmen *)
PROCEDURE Pop(VAR Top : pStack; VAR ItemContent : POINTER);
VAR Item : pStack;
BEGIN
IF StackIsEmpty(Top) THEN ItemContent := NIL
ELSE
BEGIN
ItemContent := Top^.Content; (* Inhalt zuweisen *)
Item := Top;
Top := Top^.Next; (* Neue Stackspitze *)
Dispose(Item); (* Stackspitze lschen *)
IF NOT StackIsEmpty(Top) THEN (* Noch Element auf Stack *)
Top^.Prev := NIL; (* Kein Vorgnger mehr *)
END;
END; (* Pop *)
(* Der komplette Stapel wird gelscht *)
PROCEDURE DeleteStack(VAR Top : pStack);
VAR Content : POINTER;
BEGIN
WHILE NOT StackIsEmpty(Top) DO
Pop(Top, Content); (* Stapel leeren *)
Dispose(Top); (* Kopf vom Stapel lschen *)
Top := NIL;
END; (* DeleteStack *)
(* Durch Inhalt bestimmtes Objekt suchen und lschen *)
PROCEDURE DeleteElement(VAR Top : pStack; Content : POINTER);
VAR Item : pStack; (* Hilfszeiger *)
BEGIN
IF NOT StackIsEmpty(Top) THEN (* Stapel nicht leer *)
BEGIN
Item := Top;
REPEAT (* Stapel durchlaufen *)
IF Item^.Content = Content THEN (* Gesuchtes Element *)
BEGIN
IF Item^.Next <> NIL THEN (* Nachfolger betrachten *)
Item^.Next^.Prev := Item^.Prev; (* Nachfolgers Vorgnger *)
IF Item^.Prev <> NIL THEN (* Vorgnger betrachten *)
Item^.Prev^.Next := Item^.Next; (* Vorgngers Nachfolger *)
IF Item = Top THEN Top := Item^.Next; (* Neue Stapelspitze *)
Dispose(Item);
Item := NIL;
END
ELSE Item := Item^.Next; (* Nchstes Element *)
UNTIL Item = NIL;
END;
END; (* DeleteElement *)
END. (* Lifo *)
|
unit BreakpointTypeDef;
{$mode delphi}
interface
uses
Classes, SysUtils, {$ifdef windows}windows,{$endif} FoundCodeUnit, formchangedaddresses, frmTracerUnit,
commonTypeDefs, debuggertypedefinitions;
type
PBreakpoint = ^TBreakPoint;
TBreakpointEvent=function(bp: pointer; OnBreakpointContext: pointer):boolean of object;
TBreakpoint = record
{
the following 2 items: active and markedfordeletion handle the case when a
breakpoint has been removed right at the same moment it has fired and the user
thread managed to get to the critical section first
}
active: boolean; //todo: Perhaps a per/threadid activate field
//set if the debugger should handle it fully, or just skip it (but no dbg_nothandled)
markedfordeletion: boolean;
deletetickcount: dword;
deletecountdown: integer; //when markedfordeletion is set and deletecountdown hits 0, it'll get deleted
referencecount: integer; //the number of windows this bp is currently being edited in (mainly used in 'set/change condition')
//If set the next time no events take place this breakpoint will be removed
// condition: TCondition;
owner: PBreakpoint;
//in case of a multi DR/address breakpoint, removing one of these or the owner, affects the others
address: ptruint;
size: integer; //size of this breakpoint (can be any size in case of exception bp)
originalbyte: byte;
originalaccessrights: TAccessRights;
breakpointMethod: TBreakpointMethod;
breakpointAction: TBreakOption;
breakpointTrigger: TBreakpointTrigger;
debugRegister: integer; //if debugRegister bp this will hold which debug register is used for it
dbvmwatchid: integer; //DBVM watch id in case of a bpmDBVM
FoundcodeDialog: TFoundcodedialog;
frmchangedaddresses: Tfrmchangedaddresses;
frmTracer: TfrmTracer;
tracecount: integer;
traceendcondition: pchar;
tracestepOver: boolean; //when set the tracer will step over instead of single step
traceStepOverRep: boolean; //when set the tracer will step over rep instructions
traceNoSystem: boolean; //when set the tracer will step over system module addresses
traceStayInsideModule: boolean; //when set the tracer will step over any address not inside the startmodule
traceStartmodulebase: ptruint;
traceStartmodulesize: dword;
isTracerStepOver: boolean; //
//set if it's a bpaFetchRegistersandcontinue set on memory access
//ChangedAddresses: TfrmChangedAddresses; //set if it's a bpaFetchRegistersandcontinue set on execute
ThreadID: DWORD;
//set if the breakpoint is for one specific thread, ignore breaks if it happens on other threads
OneTimeOnly: boolean; //true if the breakpoint should be removed after the first time it is hit
StepOverBp: boolean;
changereg: tregistermodificationBP; //todo: obsolete this and replace by just changeregEx
changeregEx: TRegisterModificationBPEx;
conditonalbreakpoint: record
script: pchar;
easymode: boolean;
end;
OnBreakpoint: TBreakpointEvent; //method to be called by the debuggerthread when this breakpoint triggers
OnBreakpointContext: pointer;
end;
TBreakpointSplit = record //the breakpointsplit type is used by GetBreakpointList
address: ptruint; //address alligned on size
size: integer; //1, 2 or 4
end;
TBreakpointSplitArray = array of TBreakpointSplit;
implementation
end.
|
unit HJYCryptors;
interface
uses Windows, Classes, SysUtils, IdGlobal, IdCoderMIME;
function AESEcbEncrypt(const Value, AKey: string): string;
function AESEcbDecrypt(const Value, AKey: string): string;
function AESCbcEncrypt(const Value, AKey: string): string;
function AESCbcDecrypt(const Value, AKey: string): string;
function MD5(const Value: string): string;
function Base64Encode(const Value: string): string; overload;
function Base64Encode(const Bytes: TBytes): string; overload;
function Base64Decode(const Value: string): string; overload;
function Base64DecodeBytes(const Value: string): TBytes;
function AESCbcEncryptBase64(const Value, AKey: string): string;
function AESCbcDecryptBase64(const Value, AKey: string): string;
implementation
uses CnMD5, CnAES;
const
cInitVector = '1234567890123456';
function AESEcbEncrypt(const Value, AKey: string): string;
begin
Result := string(AESEncryptEcbStrToHex(AnsiString(Value), AnsiString(AKey)));
Result := LowerCase(Result);
end;
function AESEcbDecrypt(const Value, AKey: string): string;
begin
Result := string(AESDecryptEcbStrFromHex(AnsiString(Value), AnsiString(AKey)));
end;
function AESCbcEncrypt(const Value, AKey: string): string;
var
InitVector: TAESBuffer;
begin
FillChar(InitVector, SizeOf(InitVector), 0);
Move(PAnsiChar(cInitVector)^, InitVector, Length(cInitVector));
Result := string(AESEncryptCbcStrToHex(AnsiString(Value),
AnsiString(AKey), InitVector));
Result := LowerCase(Result);
end;
function AESCbcDecrypt(const Value, AKey: string): string;
var
InitVector: TAESBuffer;
begin
FillChar(InitVector, SizeOf(InitVector), 0);
Move(PAnsiChar(cInitVector)^, InitVector, Length(cInitVector));
Result := string(AESDecryptCbcStrFromHex(AnsiString(Value),
AnsiString(AKey), InitVector));
end;
function MD5(const Value: string): string;
var
lStr: AnsiString;
begin
lStr := AnsiString(Value);
Result := CnMD5.MD5Print(CnMD5.MD5StringA(lStr));
Result := LowerCase(Result);
end;
function Base64Encode(const Value: string): string;
var
base64: TIdEncoderMIME;
tmpBytes: TBytes;
begin
base64 := TIdEncoderMIME.Create(nil);
try
base64.FillChar := '=';
tmpBytes := TEncoding.UTF8.GetBytes(Value);
Result := base64.EncodeBytes(TIdBytes(tmpBytes));
finally
base64.Free;
end;
end;
function Base64Encode(const Bytes: TBytes): string;
var
base64: TIdEncoderMIME;
begin
base64 := TIdEncoderMIME.Create(nil);
try
base64.FillChar := '=';
Result := base64.EncodeBytes(TIdBytes(Bytes));
finally
base64.Free;
end;
end;
function Base64Decode(const Value: string): string;
var
base64: TIdDeCoderMIME;
tmpBytes: TBytes;
begin
Result := Value;
base64 := TIdDecoderMIME.Create(nil);
try
base64.FillChar := '=';
tmpBytes := TBytes(base64.DecodeBytes(Value));
Result := TEncoding.UTF8.GetString(tmpBytes);
finally
base64.Free;
end;
end;
function Base64DecodeBytes(const Value: string): TBytes;
var
base64: TIdDeCoderMIME;
begin
base64 := TIdDecoderMIME.Create(nil);
try
base64.FillChar := '=';
Result := TBytes(base64.DecodeBytes(Value));
finally
base64.Free;
end;
end;
function AESCbcEncryptBase64(const Value, AKey: string): string;
var
SS, DS: TMemoryStream;
AESKey128: TAESKey128;
ByteContent: TArrayByte;
Base64ByteContent: TBytes;
Key: AnsiString;
InitVector: TAESBuffer;
begin
Result := '';
SS := TMemoryStream.Create;
DS := TMemoryStream.Create;
try
PKCS5_Padding(AnsiString(Value), ByteContent);
SS.WriteBuffer(ByteContent[0], Length(ByteContent));
SS.Position := 0;
Key := AnsiString(AKey);
FillChar(InitVector, SizeOf(InitVector), 0);
Move(PAnsiChar(cInitVector)^, InitVector, Length(cInitVector));
FillChar(AESKey128, SizeOf(AESKey128), 0);
Move(PAnsiChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
EncryptAESStreamCBC(SS, 0, AESKey128, InitVector, DS);
DS.Position := 0;
SetLength(Base64ByteContent, DS.size);
DS.ReadBuffer(Base64ByteContent[0], DS.Size);
Result := Base64Encode(Base64ByteContent);
finally
SS.Free;
DS.Free;
end;
end;
function AESCbcDecryptBase64(const Value, AKey: string): string;
var
SS, DS: TMemoryStream;
AESKey128: TAESKey128;
Base64ByteContent, ByteContent: TBytes;
Key: AnsiString;
InitVector: TAESBuffer;
begin
Result := '';
SS := TStringStream.Create;
DS := TStringStream.Create;
try
Base64ByteContent := Base64DecodeBytes(Value);
SS.WriteBuffer(Base64ByteContent[0], Length(Base64ByteContent));
SS.Position := 0;
Key := AnsiString(AKey);
FillChar(InitVector, SizeOf(InitVector), 0);
Move(PAnsiChar(cInitVector)^, InitVector, Length(cInitVector));
FillChar(AESKey128, SizeOf(AESKey128), 0 );
Move(PAnsiChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
DecryptAESStreamCBC(SS, SS.Size - SS.Position, AESKey128, InitVector, DS);
DS.Position := 0;
SetLength(ByteContent, DS.size);
DS.ReadBuffer(ByteContent[0], DS.size);
Result := string(PKCS5_DePadding(ByteContent));
finally
SS.Free;
DS.Free;
end;
end;
end.
|
unit Options;
interface
uses
Classes, SysUtils,
PxCommandLine, PxSettings;
type
TOptions = class (TPxCommandLineParser)
private
function GetHelp: Boolean;
function GetQuiet: Boolean;
function GetPrintVersion: Boolean;
function GetInputFile: String;
function GetSearchPath: TStrings;
function GetDumpDebugTree: Boolean;
function GetDumpUsesTree: Boolean;
function GetDumpAdvancedUsesTree: Boolean;
function GetDumpCyclomaticComplexity: Boolean;
function GetRecuseIntoUnits: Boolean;
protected
class procedure Initialize;
class procedure Shutdown;
procedure CreateOptions; override;
procedure AfterParseOptions; override;
procedure WriteProgramHeader;
procedure WriteProgramVersion;
public
class function Instance: TOptions;
constructor Create;
property Help: Boolean read GetHelp;
property Quiet: Boolean read GetQuiet;
property PrintVersion: Boolean read GetPrintVersion;
property InputFile: String read GetInputFile;
property SearchPath: TStrings read GetSearchPath;
property DumpDebugTree: Boolean read GetDumpDebugTree;
property DumpUsesTree: Boolean read GetDumpUsesTree;
property DumpAdvancedUsesTree: Boolean read GetDumpAdvancedUsesTree;
property DumpCyclomaticComplexity: Boolean read GetDumpCyclomaticComplexity;
property RecurseIntoUnits: Boolean read GetRecuseIntoUnits;
end;
implementation
uses
OptionsValidator;
{ TOptions }
{ Private declarations }
function TOptions.GetHelp: Boolean;
begin
Result := ByName['help'].Value;
end;
function TOptions.GetQuiet: Boolean;
begin
Result := ByName['quiet'].Value;
end;
function TOptions.GetPrintVersion: Boolean;
begin
Result := ByName['version'].Value;
end;
function TOptions.GetInputFile: String;
begin
Result := ByName['input-file'].Value;
end;
function TOptions.GetSearchPath: TStrings;
begin
Result := TPxPathListOption(ByName['search-path']).Values;
end;
function TOptions.GetDumpDebugTree: Boolean;
begin
Result := ByName['dump-debug-tree'].Value;
end;
function TOptions.GetDumpUsesTree: Boolean;
begin
Result := ByName['dump-uses-tree'].Value;
end;
function TOptions.GetDumpAdvancedUsesTree: Boolean;
begin
Result := ByName['dump-advanced-uses-tree'].Value;
end;
function TOptions.GetDumpCyclomaticComplexity: Boolean;
begin
Result := ByName['dump-cyclomatic-complexity'].Value;
end;
function TOptions.GetRecuseIntoUnits: Boolean;
begin
Result := ByName['recurse-units'].Value;
end;
{ Protected declarations }
var
_Instance: TOptions = nil;
class procedure TOptions.Initialize;
begin
_Instance := TOptions.Create;
_Instance.Parse;
end;
class procedure TOptions.Shutdown;
begin
Assert(Assigned(_Instance), 'Error: TOptions instance not initialized');
FreeAndNil(_Instance);
end;
procedure TOptions.CreateOptions;
begin
with AddOption(TPxBoolOption.Create('h', 'help')) do
Explanation := 'Show help';
with AddOption(TPxBoolOption.Create('q', 'quiet')) do
Explanation := 'Be quiet';
with AddOption(TPxBoolOption.Create(#0, 'version')) do
Explanation := 'Print version information and exit';
with AddOption(TPxStringOption.Create('i', 'input-file')) do
Explanation := 'Input file (unit or delphi project)';
with TPxPathListOption(AddOption(TPxPathListOption.Create(#0, 'search-path'))) do
begin
Explanation := 'Additional search path';
Values.Add('');
end;
with AddOption(TPxBoolOption.Create('d', 'dump-debug-tree')) do
Explanation := 'Dump debug source tree';
with AddOption(TPxBoolOption.Create('u', 'dump-uses-tree')) do
Explanation := 'Dump uses tree';
with AddOption(TPxBoolOption.Create('a', 'dump-advanced-uses-tree')) do
Explanation := 'Dump advanced uses tree';
with AddOption(TPxBoolOption.Create('c', 'dump-cyclomatic-complexity')) do
Explanation := 'Dump Cyclomatic Complexity of methods';
with AddOption(TPxBoolOption.Create(#0, 'recurse-units')) do
Explanation := 'Recurse into units (very slow!)';
end;
procedure TOptions.AfterParseOptions;
begin
with TOptionsValidator.Create do
try
OnWriteProgramHeader := WriteProgramHeader;
OnWriteExplanations := WriteExplanations;
OnWriteProgramVersion := WriteProgramVersion;
Validate;
if ExtractFilePath(InputFile) <> '' then
begin
ChDir(ExtractFilePath(InputFile));
ByName['input-file'].Value := ExtractFileName(InputFile);
end;
finally
Free;
end;
end;
procedure TOptions.WriteProgramHeader;
begin
Writeln(ExtractFileName(ParamStr(0)), ' - Delphi Code Statistics Generator');
Writeln('Copyright (c) 2005-2011 Matthias Hryniszak');
Writeln;
end;
procedure TOptions.WriteProgramVersion;
begin
Writeln('version 1.0');
Writeln;
end;
{ Public declarations }
class function TOptions.Instance: TOptions;
begin
Assert(Assigned(_Instance), 'Error: TOptions instance not initialized');
Result := _Instance;
end;
constructor TOptions.Create;
begin
Assert(not Assigned(_Instance), 'Error: TOptions is a singleton and can only be accessed using TUnitRegistry.Instance method');
inherited Create;
end;
initialization
TOptions.Initialize;
finalization
TOptions.Shutdown;
end.
|
{
DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus
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(DBEBr Framework)
@created(20 Jul 2016)
@author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>)
}
unit dbebr.driver.firedac;
interface
uses
Classes,
DB,
Variants,
StrUtils,
FireDAC.Comp.Client,
FireDAC.Comp.Script,
FireDAC.Comp.ScriptCommands,
FireDAC.DApt,
FireDAC.Stan.Param,
// DBEBr
dbebr.driver.connection,
dbebr.factory.interfaces;
type
// Classe de conexão concreta com FireDAC
TDriverFireDAC = class(TDriverConnection)
protected
FConnection: TFDConnection;
FSQLScript: TFDScript;
public
constructor Create(const AConnection: TComponent;
const ADriverName: TDriverName); override;
destructor Destroy; override;
procedure Connect; override;
procedure Disconnect; override;
procedure ExecuteDirect(const ASQL: string); override;
procedure ExecuteDirect(const ASQL: string; const AParams: TParams); override;
procedure ExecuteScript(const ASQL: string); override;
procedure AddScript(const ASQL: string); override;
procedure ExecuteScripts; override;
function IsConnected: Boolean; override;
function InTransaction: Boolean; override;
function CreateQuery: IDBQuery; override;
function CreateResultSet(const ASQL: string): IDBResultSet; override;
function ExecuteSQL(const ASQL: string): IDBResultSet; override;
end;
TDriverQueryFireDAC = class(TDriverQuery)
private
FFDQuery: TFDQuery;
protected
procedure SetCommandText(ACommandText: string); override;
function GetCommandText: string; override;
public
constructor Create(AConnection: TFDConnection);
destructor Destroy; override;
procedure ExecuteDirect; override;
function ExecuteQuery: IDBResultSet; override;
end;
TDriverResultSetFireDAC = class(TDriverResultSet<TFDQuery>)
public
constructor Create(ADataSet: TFDQuery); override;
destructor Destroy; override;
function NotEof: Boolean; override;
function GetFieldValue(const AFieldName: string): Variant; overload; override;
function GetFieldValue(const AFieldIndex: Integer): Variant; overload; override;
function GetFieldType(const AFieldName: string): TFieldType; overload; override;
function GetField(const AFieldName: string): TField; override;
end;
implementation
{ TDriverFireDAC }
constructor TDriverFireDAC.Create(const AConnection: TComponent;
const ADriverName: TDriverName);
begin
inherited;
FConnection := AConnection as TFDConnection;
FDriverName := ADriverName;
FSQLScript := TFDScript.Create(nil);
try
FSQLScript.Connection := FConnection;
FSQLScript.SQLScripts.Add;
FSQLScript.ScriptOptions.Reset;
FSQLScript.ScriptOptions.BreakOnError := True;
FSQLScript.ScriptOptions.RaisePLSQLErrors := True;
FSQLScript.ScriptOptions.EchoCommands := ecAll;
FSQLScript.ScriptOptions.CommandSeparator := ';';
FSQLScript.ScriptOptions.CommitEachNCommands := 9999999;
FSQLScript.ScriptOptions.DropNonexistObj := True;
except
FSQLScript.Free;
raise;
end;
end;
destructor TDriverFireDAC.Destroy;
begin
FConnection := nil;
FSQLScript.Free;
inherited;
end;
procedure TDriverFireDAC.Disconnect;
begin
inherited;
FConnection.Connected := False;
end;
procedure TDriverFireDAC.ExecuteDirect(const ASQL: string);
begin
inherited;
FConnection.ExecSQL(ASQL);
end;
procedure TDriverFireDAC.ExecuteDirect(const ASQL: string; const AParams: TParams);
var
LExeSQL: TFDQuery;
LFor: Integer;
begin
LExeSQL := TFDQuery.Create(nil);
try
LExeSQL.Connection := FConnection;
LExeSQL.SQL.Text := ASQL;
for LFor := 0 to AParams.Count - 1 do
begin
LExeSQL.ParamByName(AParams[LFor].Name).DataType := AParams[LFor].DataType;
LExeSQL.ParamByName(AParams[LFor].Name).Value := AParams[LFor].Value;
end;
try
LExeSQL.Prepare;
LExeSQL.ExecSQL;
except
raise;
end;
finally
LExeSQL.Free;
end;
end;
procedure TDriverFireDAC.ExecuteScript(const ASQL: string);
begin
inherited;
if ASQL = '' then
Exit;
FSQLScript.SQLScripts[0].SQL.Clear;
try
FSQLScript.SQLScripts[0].SQL.Add(ASQL);
if FSQLScript.ValidateAll then
FSQLScript.ExecuteAll;
finally
FSQLScript.SQLScripts[0].SQL.Clear;
end;
end;
procedure TDriverFireDAC.ExecuteScripts;
begin
inherited;
if FSQLScript.SQLScripts.Count = 0 then
Exit;
try
if FSQLScript.ValidateAll then
FSQLScript.ExecuteAll;
finally
FSQLScript.SQLScripts[0].SQL.Clear;
end;
end;
procedure TDriverFireDAC.AddScript(const ASQL: string);
begin
inherited;
FSQLScript.SQLScripts[0].SQL.Add(ASQL);
end;
procedure TDriverFireDAC.Connect;
begin
inherited;
FConnection.Connected := True;
end;
function TDriverFireDAC.InTransaction: Boolean;
begin
Result := FConnection.InTransaction;
end;
function TDriverFireDAC.IsConnected: Boolean;
begin
inherited;
Result := FConnection.Connected;
end;
function TDriverFireDAC.CreateQuery: IDBQuery;
begin
Result := TDriverQueryFireDAC.Create(FConnection);
end;
function TDriverFireDAC.ExecuteSQL(const ASQL: string): IDBResultSet;
var
LDBQuery: IDBQuery;
begin
LDBQuery := TDriverQueryFireDAC.Create(FConnection);
LDBQuery.CommandText := ASQL;
Result := LDBQuery.ExecuteQuery;
end;
function TDriverFireDAC.CreateResultSet(const ASQL: string): IDBResultSet;
var
LDBQuery: IDBQuery;
begin
LDBQuery := TDriverQueryFireDAC.Create(FConnection);
LDBQuery.CommandText := ASQL;
Result := LDBQuery.ExecuteQuery;
end;
{ TDriverDBExpressQuery }
constructor TDriverQueryFireDAC.Create(AConnection: TFDConnection);
begin
if AConnection = nil then
Exit;
FFDQuery := TFDQuery.Create(nil);
try
FFDQuery.Connection := AConnection;
except
FFDQuery.Free;
raise;
end;
end;
destructor TDriverQueryFireDAC.Destroy;
begin
FFDQuery.Free;
inherited;
end;
function TDriverQueryFireDAC.ExecuteQuery: IDBResultSet;
var
LResultSet: TFDQuery;
LFor: Integer;
begin
LResultSet := TFDQuery.Create(nil);
try
LResultSet.Connection := FFDQuery.Connection;
LResultSet.SQL.Text := FFDQuery.SQL.Text;
for LFor := 0 to FFDQuery.Params.Count - 1 do
begin
LResultSet.Params[LFor].DataType := FFDQuery.Params[LFor].DataType;
LResultSet.Params[LFor].Value := FFDQuery.Params[LFor].Value;
end;
LResultSet.Open;
except
LResultSet.Free;
raise;
end;
Result := TDriverResultSetFireDAC.Create(LResultSet);
if LResultSet.RecordCount = 0 then
Result.FetchingAll := True;
end;
function TDriverQueryFireDAC.GetCommandText: string;
begin
Result := FFDQuery.SQL.Text;
end;
procedure TDriverQueryFireDAC.SetCommandText(ACommandText: string);
begin
inherited;
FFDQuery.SQL.Text := ACommandText;
end;
procedure TDriverQueryFireDAC.ExecuteDirect;
begin
FFDQuery.ExecSQL;
end;
{ TDriverResultSetFireDAC }
constructor TDriverResultSetFireDAC.Create(ADataSet: TFDQuery);
begin
FDataSet:= ADataSet;
inherited;
end;
destructor TDriverResultSetFireDAC.Destroy;
begin
FDataSet.Free;
inherited;
end;
function TDriverResultSetFireDAC.GetFieldValue(const AFieldName: string): Variant;
var
LField: TField;
begin
LField := FDataSet.FieldByName(AFieldName);
Result := GetFieldValue(LField.Index);
end;
function TDriverResultSetFireDAC.GetField(const AFieldName: string): TField;
begin
Result := FDataSet.FieldByName(AFieldName);
end;
function TDriverResultSetFireDAC.GetFieldType(const AFieldName: string): TFieldType;
begin
Result := FDataSet.FieldByName(AFieldName).DataType;
end;
function TDriverResultSetFireDAC.GetFieldValue(const AFieldIndex: Integer): Variant;
begin
if AFieldIndex > FDataSet.FieldCount -1 then
Exit(Variants.Null);
if FDataSet.Fields[AFieldIndex].IsNull then
Result := Variants.Null
else
Result := FDataSet.Fields[AFieldIndex].Value;
end;
function TDriverResultSetFireDAC.NotEof: Boolean;
begin
if not FFirstNext then
FFirstNext := True
else
FDataSet.Next;
Result := not FDataSet.Eof;
end;
end.
|
unit TBGUnidacDriver.Model.Query;
interface
uses
TBGConnection.Model.Interfaces, Data.DB, System.Classes,
System.SysUtils, MemDS, DBAccess, Uni,
TBGConnection.Model.DataSet.Interfaces,
TBGConnection.Model.DataSet.Proxy,
TBGConnection.Model.DataSet.Observer, System.Generics.Collections;
Type
TUnidacModelQuery = class(TInterfacedObject, iQuery)
private
FConexao: TUniConnection;
FKey : Integer;
FiConexao : iConexao;
FDriver : iDriver;
FQuery: TList<TUniQuery>;
FDataSource: TDataSource;
FDataSet: TDictionary<integer, iDataSet>;
FChangeDataSet: TChangeDataSet;
FSQL : String;
FGetDataSet: iDataSet;
FParams : TParams;
procedure InstanciaQuery;
function GetDataSet : iDataSet;
function GetQuery : TUniQuery;
public
constructor Create(Conexao: TUniConnection; Driver : iDriver);
destructor Destroy; override;
class function New(Conexao: TUniConnection; Driver : iDriver): iQuery;
//iObserver
procedure ApplyUpdates(DataSet : TDataSet);
// iQuery
function Open(aSQL: String): iQuery;
function ExecSQL(aSQL: String): iQuery; overload;
function DataSet: TDataSet; overload;
function DataSet(Value: TDataSet): iQuery; overload;
function DataSource(Value: TDataSource): iQuery;
function Fields: TFields;
function ChangeDataSet(Value: TChangeDataSet): iQuery;
function &End: TComponent;
function Tag(Value: Integer): iQuery;
function LocalSQL(Value: TComponent): iQuery;
function Close : iQuery;
function SQL : TStrings;
function Params : TParams;
function ExecSQL : iQuery; overload;
function ParamByName(Value : String) : TParam;
function UpdateTableName(Tabela : String) : iQuery;
end;
implementation
{ TUnidacModelQuery }
function TUnidacModelQuery.&End: TComponent;
begin
Result := GetQuery;
end;
function TUnidacModelQuery.ExecSQL: iQuery;
begin
Result := Self;
GetQuery.ExecSQL;
ApplyUpdates(nil);
end;
function TUnidacModelQuery.ExecSQL(aSQL: String): iQuery;
begin
GetQuery.SQL.Clear;
GetQuery.SQL.Add(aSQL);
GetQuery.ExecSQL;
ApplyUpdates(nil);
end;
function TUnidacModelQuery.Fields: TFields;
begin
Result := GetQuery.Fields;
end;
function TUnidacModelQuery.GetDataSet : iDataSet;
begin
Result := FDataSet.Items[FKey];
end;
function TUnidacModelQuery.GetQuery: TUniQuery;
begin
Result := FQuery.Items[Pred(FQuery.Count)];
end;
procedure TUnidacModelQuery.InstanciaQuery;
var
Query : TUniQuery;
begin
Query := TUniQuery.Create(nil);
Query.Connection := FConexao;
Query.AfterPost := ApplyUpdates;
Query.AfterDelete := ApplyUpdates;
FQuery.Add(Query);
end;
function TUnidacModelQuery.LocalSQL(Value: TComponent): iQuery;
begin
Result := Self;
raise Exception.Create('Função não suportada por este driver');
end;
procedure TUnidacModelQuery.ApplyUpdates(DataSet: TDataSet);
begin
FDriver.Cache.ReloadCache('');
end;
function TUnidacModelQuery.ChangeDataSet(Value: TChangeDataSet): iQuery;
begin
Result := Self;
FChangeDataSet := Value;
end;
function TUnidacModelQuery.Close: iQuery;
begin
Result := Self;
GetQuery.Close;
end;
constructor TUnidacModelQuery.Create(Conexao: TUniConnection; Driver : iDriver);
begin
FDriver := Driver;
FConexao := Conexao;
FQuery := TList<TUniQuery>.Create;
FDataSet := TDictionary<integer, iDataSet>.Create;
InstanciaQuery;
end;
function TUnidacModelQuery.DataSet: TDataSet;
begin
Result := TDataSet(GetQuery);
end;
function TUnidacModelQuery.DataSet(Value: TDataSet): iQuery;
begin
Result := Self;
GetDataSet.DataSet(Value);
end;
function TUnidacModelQuery.DataSource(Value: TDataSource): iQuery;
begin
Result := Self;
FDataSource := Value;
end;
destructor TUnidacModelQuery.Destroy;
begin
FreeAndNil(FQuery);
FreeAndNil(FDataSet);
inherited;
end;
class function TUnidacModelQuery.New(Conexao: TUniConnection; Driver : iDriver): iQuery;
begin
Result := Self.Create(Conexao, Driver);
end;
function TUnidacModelQuery.Open(aSQL: String): iQuery;
var
Query : TUniQuery;
DataSet : iDataSet;
begin
Result := Self;
FSQL := aSQL;
if not FDriver.Cache.CacheDataSet(FSQL, DataSet) then
begin
InstanciaQuery;
DataSet.SQL(FSQL);
DataSet.DataSet(GetQuery);
GetQuery.Close;
GetQuery.SQL.Text := FSQL;
GetQuery.Open;
FDriver.Cache.AddCacheDataSet(DataSet.GUUID, DataSet);
end;
FDataSource.DataSet := DataSet.DataSet;
Inc(FKey);
FDataSet.Add(FKey, DataSet);
end;
function TUnidacModelQuery.ParamByName(Value: String): TParam;
begin
Result := GetQuery.ParamByName(Value);
end;
function TUnidacModelQuery.Params: TParams;
begin
Result := GetQuery.Params;
end;
function TUnidacModelQuery.SQL: TStrings;
begin
Result := GetQuery.SQL;
end;
function TUnidacModelQuery.Tag(Value: Integer): iQuery;
begin
Result := Self;
GetQuery.Tag := Value;
end;
function TUnidacModelQuery.UpdateTableName(Tabela: String): iQuery;
begin
Result := Self;
end;
end.
|
PROGRAM CopyPrgm(INPUT, OUTPUT);
PROCEDURE RCopy(VAR ReadFile, WriteFile: TEXT);
VAR
Ch: CHAR;
BEGIN
IF NOT EOLN(ReadFile)
THEN
BEGIN
READ(ReadFile, Ch);
WRITE(WriteFile, Ch);
RCopy(ReadFile, WriteFile)
END
END;
BEGIN
RCopy(INPUT, OUTPUT);
WRITELN(OUTPUT)
END.
|
unit ce_editor;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, lcltype, Graphics, SynEditKeyCmds,
ComCtrls, SynEditHighlighter, ExtCtrls, Menus, SynMacroRecorder, dialogs,
SynPluginSyncroEdit, SynEdit, SynHighlighterMulti, ce_dialogs,
ce_widget, ce_interfaces, ce_synmemo, ce_dlang, ce_common, ce_dcd, ce_observer,
ce_sharedres, ce_controls, ce_writableComponent;
type
TCEEditorWidget = class;
TCEPagesOptions = class(TWritableLfmTextComponent, ICEEditableOptions)
private
fEditorWidget: TCEEditorWidget;
fPageButtons: TCEPageControlButtons;
fPageOptions: TCEPageControlOptions;
function optionedWantCategory(): string;
function optionedWantEditorKind: TOptionEditorKind;
function optionedWantContainer: TPersistent;
procedure optionedEvent(anEvent: TOptionEditorEvent);
function optionedOptionsModified: boolean;
published
property pageButtons: TCEPageControlButtons read fPageButtons write fPageButtons;
property pageOptions: TCEPageControlOptions read fPageOptions write fPageOptions;
public
procedure Assign(Source: TPersistent); override;
procedure AssignTo(Target: TPersistent); override;
constructor construct(editorWidg: TCEEditorWidget);
destructor Destroy; override;
end;
TCEEditorWidget = class(TCEWidget, ICEMultiDocObserver, ICEMultiDocHandler, ICEProjectObserver)
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem5: TMenuItem;
mnuedRename: TMenuItem;
mnuedInvAllNone: TMenuItem;
mnuedComm: TMenuItem;
mnuedPrev: TMenuItem;
mnuedNext: TMenuItem;
mnuedCallTip: TMenuItem;
mnuedDdoc: TMenuItem;
mnuedCopy: TMenuItem;
mnuedCut: TMenuItem;
mnuedPaste: TMenuItem;
MenuItem4: TMenuItem;
mnuedUndo: TMenuItem;
mnuedRedo: TMenuItem;
MenuItem7: TMenuItem;
mnuedJum2Decl: TMenuItem;
macRecorder: TSynMacroRecorder;
editorStatus: TStatusBar;
mnuEditor: TPopupMenu;
procedure MenuItem5Click(Sender: TObject);
procedure mnuedRenameClick(Sender: TObject);
procedure mnuedInvAllNoneClick(Sender: TObject);
procedure mnuedCommClick(Sender: TObject);
procedure mnuedPrevClick(Sender: TObject);
procedure mnuedNextClick(Sender: TObject);
procedure mnuedCallTipClick(Sender: TObject);
procedure mnuedCopyClick(Sender: TObject);
procedure mnuedCutClick(Sender: TObject);
procedure mnuedDdocClick(Sender: TObject);
procedure mnuEditorPopup(Sender: TObject);
procedure mnuedPasteClick(Sender: TObject);
procedure mnuedUndoClick(Sender: TObject);
procedure mnuedRedoClick(Sender: TObject);
procedure mnuedJum2DeclClick(Sender: TObject);
procedure PageControlChanged(Sender: TObject);
procedure PageControlChanging(Sender: TObject; var AllowChange: Boolean);
protected
procedure updateDelayed; override;
procedure updateImperative; override;
private
fOptions: TCEPagesOptions;
pageControl: TCEPageControl;
fKeyChanged: boolean;
fDoc: TCESynMemo;
fProj: ICECommonProject;
fTokList: TLexTokenList;
fModStart: boolean;
fLastCommand: TSynEditorCommand;
procedure updateStatusBar;
procedure updatePageCaption;
procedure pageBtnAddCLick(Sender: TObject);
procedure pageCloseBtnClick(Sender: TObject);
procedure lexFindToken(const aToken: PLexToken; out doStop: boolean);
procedure memoKeyPress(Sender: TObject; var Key: char);
procedure memoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure memoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure memoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure memoCtrlClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure memoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure getSymbolLoc;
procedure focusedEditorChanged;
procedure memoCmdProcessed(Sender: TObject; var Command: TSynEditorCommand; var AChar: TUTF8Char; Data: pointer);
//
procedure docNew(aDoc: TCESynMemo);
procedure docClosing(aDoc: TCESynMemo);
procedure docFocused(aDoc: TCESynMemo);
procedure docChanged(aDoc: TCESynMemo);
//
procedure projNew(aProject: ICECommonProject);
procedure projChanged(aProject: ICECommonProject);
procedure projClosing(aProject: ICECommonProject);
procedure projFocused(aProject: ICECommonProject);
procedure projCompiling(aProject: ICECommonProject);
procedure projCompiled(aProject: ICECommonProject; success: boolean);
//
function SingleServiceName: string;
function documentCount: Integer;
function getDocument(index: Integer): TCESynMemo;
function findDocument(aFilename: string): TCESynMemo;
procedure openDocument(aFilename: string);
function closeDocument(index: Integer): boolean;
function closeDocument(doc: TCESynMemo): boolean;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
function closeQuery: boolean; override;
end;
implementation
{$R *.lfm}
uses
ce_lcldragdrop;
const
optname = 'editorpages.txt';
{$REGION TCEPagesOptions -------------------------------------------------------}
constructor TCEPagesOptions.construct(editorWidg: TCEEditorWidget);
var
fname: string;
begin
fEditorWidget := editorWidg;
inherited create(editorWidg);
EntitiesConnector.addObserver(self);
//
fname := getCoeditDocPath + optname;
if fname.fileExists then
begin
loadFromFile(fname);
assignTo(fEditorWidget);
end
else Assign(fEditorWidget);
end;
destructor TCEPagesOptions.Destroy;
begin
saveToFile(getCoeditDocPath + optname);
EntitiesConnector.removeObserver(self);
inherited;
end;
procedure TCEPagesOptions.Assign(Source: TPersistent);
begin
if Source = fEditorWidget then
begin
fPageButtons := fEditorWidget.pageControl.buttons;
fPageOptions := fEditorWidget.pageControl.options;
end
else inherited;
end;
procedure TCEPagesOptions.AssignTo(Target: TPersistent);
begin
if Target = fEditorWidget then
begin
fEditorWidget.pageControl.buttons := fPageButtons;
fEditorWidget.pageControl.options := fPageOptions;
end
else inherited;
end;
function TCEPagesOptions.optionedWantCategory(): string;
begin
exit('Editor pages')
end;
function TCEPagesOptions.optionedWantEditorKind: TOptionEditorKind;
begin
exit(oekGeneric);
end;
function TCEPagesOptions.optionedWantContainer: TPersistent;
begin
exit(self);
end;
procedure TCEPagesOptions.optionedEvent(anEvent: TOptionEditorEvent);
begin
case anEvent of
oeeAccept: assignTo(fEditorWidget);
oeeCancel: Assign(fEditorWidget);
end;
end;
function TCEPagesOptions.optionedOptionsModified: boolean;
begin
exit(false);
end;
{$ENDREGION}
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEEditorWidget.create(aOwner: TComponent);
begin
inherited;
//
pageControl := TCEPageControl.Create(self);
pageControl.Parent := Content;
pageControl.align := alClient;
pageControl.onChanged:= @PageControlChanged;
pageControl.onChanging:=@PageControlChanging;
pageControl.closeButton.OnClick:=@pageCloseBtnClick;
pageControl.addButton.OnClick:=@pageBtnAddCLick;
pageControl.OnDragDrop:= @ddHandler.DragDrop;
pageControl.OnDragOver:= @ddHandler.DragOver;
AssignPng(pageControl.moveLeftButton, 'go_previous');
AssignPng(pageControl.moveRightButton, 'go_next');
AssignPng(pageControl.addButton, 'document_add');
AssignPng(pageControl.closeButton, 'document_delete');
AssignPng(pageControl.splitButton, 'splitter');
fTokList := TLexTokenList.Create;
//
AssignPng(mnuedCopy.Bitmap, 'copy');
AssignPng(mnuedCut.Bitmap, 'cut');
AssignPng(mnuedPaste.Bitmap, 'paste');
AssignPng(mnuedUndo.Bitmap, 'arrow_undo');
AssignPng(mnuedRedo.Bitmap, 'arrow_redo');
AssignPng(mnuedJum2Decl.Bitmap, 'arrow_shoe');
AssignPng(mnuedCopy.Bitmap, 'copy');
AssignPng(mnuedNext.Bitmap, 'go_next');
AssignPng(mnuedPrev.Bitmap, 'go_previous');
AssignPng(mnuedRename.Bitmap, 'pencil');
//
EntitiesConnector.addObserver(self);
EntitiesConnector.addSingleService(self);
//
fOptions:= TCEPagesOptions.construct(self);
end;
destructor TCEEditorWidget.destroy;
var
i: integer;
begin
EntitiesConnector.removeObserver(self);
for i := PageControl.PageCount-1 downto 0 do
if PageControl.Pages[i].ControlCount > 0 then
if (PageControl.Pages[i].Controls[0] is TCESynMemo) then
PageControl.Pages[i].Controls[0].Free;
fTokList.Free;
fOptions.Free;
inherited;
end;
function TCEEditorWidget.closeQuery: boolean;
begin
result := inherited and Parent.isNil;
end;
{$ENDREGION}
{$REGION ICEMultiDocObserver ---------------------------------------------------}
procedure TCEEditorWidget.docNew(aDoc: TCESynMemo);
var
pge: TCEPage;
begin
pge := pageControl.addPage;
//
aDoc.Align := alClient;
aDoc.Parent := pge;
//
aDoc.OnKeyDown := @memoKeyDown;
aDoc.OnKeyUp := @memoKeyUp;
aDoc.OnKeyPress := @memoKeyPress;
aDoc.OnMouseDown := @memoMouseDown;
aDoc.OnMouseMove := @memoMouseMove;
aDoc.OnClickLink := @memoCtrlClick;
aDoc.OnCommandProcessed:= @memoCmdProcessed;
//
fDoc := aDoc;
focusedEditorChanged;
updateImperative;
end;
procedure TCEEditorWidget.docClosing(aDoc: TCESynMemo);
begin
if aDoc.isNil then
exit;
aDoc.Parent := nil;
if aDoc = fDoc then
fDoc := nil;
pageControl.deletePage(pageControl.pageIndex);
updateImperative;
end;
procedure TCEEditorWidget.docFocused(aDoc: TCESynMemo);
begin
if fDoc.isNotNil and pageControl.currentPage.isNotNil and
(pageControl.currentPage.Caption = '<new document>') then
updatePageCaption;
if aDoc = fDoc then exit;
fDoc := aDoc;
focusedEditorChanged;
updateImperative;
end;
procedure TCEEditorWidget.docChanged(aDoc: TCESynMemo);
begin
if fDoc <> aDoc then
exit;
fKeyChanged := true;
beginDelayedUpdate;
end;
{$ENDREGION}
{$REGION ICECommonProject ------------------------------------------------------}
procedure TCEEditorWidget.projNew(aProject: ICECommonProject);
begin
end;
procedure TCEEditorWidget.projChanged(aProject: ICECommonProject);
begin
end;
procedure TCEEditorWidget.projClosing(aProject: ICECommonProject);
begin
if fProj = aProject then
fProj := nil;
end;
procedure TCEEditorWidget.projFocused(aProject: ICECommonProject);
begin
fProj := aProject;
end;
procedure TCEEditorWidget.projCompiling(aProject: ICECommonProject);
begin
end;
procedure TCEEditorWidget.projCompiled(aProject: ICECommonProject; success: boolean);
begin
end;
{$ENDREGION}
{$REGION ICEMultiDocHandler ----------------------------------------------------}
function TCEEditorWidget.SingleServiceName: string;
begin
exit('ICEMultiDocHandler');
end;
function TCEEditorWidget.documentCount: Integer;
begin
exit(PageControl.PageCount);
end;
function TCEEditorWidget.getDocument(index: Integer): TCESynMemo;
begin
exit(TCESynMemo(pageControl.Pages[index].Controls[0]));
end;
function TCEEditorWidget.findDocument(aFilename: string): TCESynMemo;
var
i: Integer;
begin
for i := 0 to PageControl.PageCount-1 do
begin
result := getDocument(i);
if result.fileName = aFilename then
exit;
end;
result := nil;
end;
procedure TCEEditorWidget.openDocument(aFilename: string);
var
doc: TCESynMemo;
begin
doc := findDocument(aFilename);
if doc.isNotNil then begin
PageControl.currentPage := TCEPage(doc.Parent);
exit;
end;
doc := TCESynMemo.Create(nil);
fDoc.loadFromFile(aFilename);
if assigned(fProj) and (fProj.filename = fDoc.fileName) then
begin
if fProj.getFormat = pfNative then
fDoc.Highlighter := LfmSyn
else
fDoc.Highlighter := JsSyn;
end;
end;
function TCEEditorWidget.closeDocument(index: Integer): boolean;
var
doc: TCESynMemo;
begin
doc := getDocument(index);
if doc.isNil then exit(false);
if (doc.modified or (doc.fileName = doc.tempFilename)) and
(dlgFileChangeClose(doc.fileName) = mrCancel) then exit(false);
doc.disableFileDateCheck:=true;
pageControl.pageIndex:=index;
doc.Free;
result := true;
end;
function TCEEditorWidget.closeDocument(doc: TCESynMemo): boolean;
var
page: TCEPage = nil;
begin
page := TCEPage(doc.Parent);
if page.isNil then
exit(false);
exit(closeDocument(page.index));
end;
{$ENDREGION}
{$REGION PageControl/Editor things ---------------------------------------------}
procedure TCEEditorWidget.pageCloseBtnClick(Sender: TObject);
begin
closeDocument(PageControl.PageIndex);
end;
procedure TCEEditorWidget.pageBtnAddCLick(Sender: TObject);
begin
TCESynMemo.Create(nil);
pageControl.currentPage.Caption:='<new document>';
end;
procedure TCEEditorWidget.focusedEditorChanged;
begin
if fDoc.isNil then exit;
//
macRecorder.Editor:= fDoc;
fDoc.PopupMenu := mnuEditor;
fDoc.hideCallTips;
fDoc.hideDDocs;
if (pageControl.currentPage.Caption = '') or
(pageControl.currentPage.Caption ='<new document>') then
begin
fKeyChanged := true;
beginDelayedUpdate;
end;
end;
procedure TCEEditorWidget.PageControlChanged(Sender: TObject);
begin
if fDoc.isNil then exit;
fDoc.hideCallTips;
fDoc.hideDDocs;
end;
procedure TCEEditorWidget.PageControlChanging(Sender: TObject; var AllowChange: Boolean);
begin
if fDoc.isNil then exit;
fDoc.hideCallTips;
fDoc.hideDDocs;
end;
procedure TCEEditorWidget.memoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_CLEAR,VK_RETURN,VK_BACK : fKeyChanged := true;
VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT:
begin
if Shift <> [ssCtrl, ssAlt, ssShift] then
updateImperative
else begin
if Key = VK_LEFT then pageControl.pageIndex := pageControl.pageIndex -1
else if Key = VK_RIGHT then pageControl.pageIndex := pageControl.pageIndex +1;
end;
end;
end;
if fKeyChanged then
beginDelayedUpdate;
end;
procedure TCEEditorWidget.memoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case fLastCommand of
ecSelectionStart..ecSelectionEnd: updateImperative;
ecLeft..ecHalfWordRight: updateImperative;
end;
end;
procedure TCEEditorWidget.memoCmdProcessed(Sender: TObject; var Command: TSynEditorCommand; var AChar: TUTF8Char; Data: pointer);
begin
fLastCommand := Command;
//
case Command of
ecJumpToDeclaration:
getSymbolLoc;
ecRecordMacro:
begin
if macRecorder.State = msStopped then
macRecorder.RecordMacro(fDoc)
else
macRecorder.Stop;
updateImperative;
end;
ecPlayMacro:
begin
macRecorder.Stop;
macRecorder.PlaybackMacro(fDoc);
updateImperative;
end;
end;
end;
procedure TCEEditorWidget.memoKeyPress(Sender: TObject; var Key: char);
begin
fKeyChanged := true;
beginDelayedUpdate;
end;
procedure TCEEditorWidget.memoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
updateImperative;
end;
procedure TCEEditorWidget.memoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if not (ssLeft in Shift) then exit;
beginDelayedUpdate;
end;
procedure TCEEditorWidget.memoCtrlClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
getSymbolLoc;
end;
procedure TCEEditorWidget.getSymbolLoc;
var
page: TCEPage;
srcpos, i, sum, linelen: Integer;
fname: string;
len: byte;
begin
if not DcdWrapper.available then exit;
//
DcdWrapper.getDeclFromCursor(fname, srcpos);
if (fname <> fDoc.fileName) and fname.fileExists then
begin
page := pageControl.splitPage;
if assigned(page) then
begin
fDoc := TCESynMemo(page.Controls[0]);
if fDoc.fileName <> fname then
openDocument(fname);
end
else openDocument(fname);
end;
if srcpos <> -1 then
begin
sum := 0;
len := getLineEndingLength(fDoc.fileName);
for i := 0 to fDoc.Lines.Count-1 do
begin
linelen := fDoc.Lines[i].length;
if sum + linelen + len > srcpos then
begin
fDoc.CaretY := i + 1;
fDoc.CaretX := srcpos - sum + len;
fDoc.SelectWord;
fDoc.EnsureCursorPosVisible;
break;
end;
sum += linelen;
sum += len;
end;
end;
end;
procedure TCEEditorWidget.updateStatusBar;
const
modstr: array[boolean] of string = ('...', 'MODIFIED');
begin
if fDoc = nil then
begin
editorStatus.Panels[0].Text := '';
editorStatus.Panels[1].Text := '';
editorStatus.Panels[2].Text := '';
editorStatus.Panels[3].Text := '';
editorStatus.Panels[4].Text := '';
end else
begin
editorStatus.Panels[0].Text := format('%d : %d | %d', [fDoc.CaretY, fDoc.CaretX, fDoc.SelEnd - fDoc.SelStart]);
editorStatus.Panels[1].Text := modstr[fDoc.modified];
if macRecorder.State = msRecording then
editorStatus.Panels[2].Text := 'recording macro'
else if macRecorder.IsEmpty then
editorStatus.Panels[2].Text := 'no macro'
else
editorStatus.Panels[2].Text := 'macro ready';
if fDoc.ReadOnly then
begin
editorStatus.Panels[3].Width:= 120;
editorStatus.Panels[3].Text := '(read-only)';
end else
editorStatus.Panels[3].Width:= 0;
editorStatus.Panels[4].Text := fDoc.fileName;
end;
end;
procedure TCEEditorWidget.updatePageCaption;
var
md: string = '<new document>';
begin
if fDoc.isNotNil then
begin
if fDoc.isDSource then
begin
lex(fDoc.Lines.Text, fTokList, @lexFindToken);
md := getModuleName(fTokList);
fTokList.Clear;
if md.isEmpty then
md := fDoc.fileName.extractFileName;
end
else if fDoc.fileName.fileExists then
md := fDoc.fileName.extractFileName
end;
pageControl.currentPage.Caption := md;
end;
procedure TCEEditorWidget.updateImperative;
begin
updateStatusBar;
if fDoc.isNotNil then
updatePageCaption;
end;
procedure TCEEditorWidget.updateDelayed;
begin
if fDoc = nil then
exit;
updateStatusBar;
if not fKeyChanged then
exit;
if fDoc.isNotNil then
updatePageCaption;
end;
procedure TCEEditorWidget.lexFindToken(const aToken: PLexToken; out doStop: boolean);
begin
if (aToken^.kind = ltkKeyword) and (aToken^.data = 'module') then
begin
fModStart := true;
exit;
end;
if fModStart and (aToken^.kind = ltkSymbol) and (aToken^.data = ';') then
begin
doStop := true;
fModStart := false;
end;
end;
{$ENDREGION}
{$REGION Editor context menu ---------------------------------------------------}
procedure TCEEditorWidget.mnuedCopyClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.ExecuteCommand(ecCopy, '', nil);
end;
procedure TCEEditorWidget.mnuedCallTipClick(Sender: TObject);
begin
if fDoc.isNil then exit;
mnuEditor.Close;
fDoc.hideDDocs;
fDoc.showCallTips;
end;
procedure TCEEditorWidget.mnuedCommClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.CommandProcessor(ecCommentSelection, '', nil);
end;
procedure TCEEditorWidget.mnuedPrevClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.CommandProcessor(ecPreviousLocation, '', nil);
end;
procedure TCEEditorWidget.mnuedNextClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.CommandProcessor(ecNextLocation, '', nil);
end;
procedure TCEEditorWidget.mnuedInvAllNoneClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.CommandProcessor(ecSwapVersionAllNone, '', nil);
end;
procedure TCEEditorWidget.MenuItem5Click(Sender: TObject);
begin
if fDoc.isNil then
exit;
with TSaveDialog.Create(nil) do
try
if execute then
begin
fTokList.Clear;
lex(fDoc.Text, fTokList, nil);
fTokList.saveToFile(FileName);
fTokList.Clear;
end;
finally
free;
end;
end;
procedure TCEEditorWidget.mnuedRenameClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.CommandProcessor(ecRenameIdentifier, '', nil);
end;
procedure TCEEditorWidget.mnuedCutClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.ExecuteCommand(ecCut, '', nil);
end;
procedure TCEEditorWidget.mnuedDdocClick(Sender: TObject);
begin
if fDoc.isNil then exit;
mnuEditor.Close;
fDoc.hideCallTips;
fDoc.showDDocs;
end;
procedure TCEEditorWidget.mnuedPasteClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.ExecuteCommand(ecPaste, '', nil);
end;
procedure TCEEditorWidget.mnuedUndoClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.ExecuteCommand(ecUndo, '', nil);
end;
procedure TCEEditorWidget.mnuedRedoClick(Sender: TObject);
begin
if fDoc.isNotNil then
fDoc.ExecuteCommand(ecRedo, '', nil);
end;
procedure TCEEditorWidget.mnuedJum2DeclClick(Sender: TObject);
begin
if fDoc.isNotNil then
getSymbolLoc;
end;
procedure TCEEditorWidget.mnuEditorPopup(Sender: TObject);
begin
if fDoc.isNil then exit;
//
mnuedCut.Enabled:=fDOc.SelAvail;
mnuedPaste.Enabled:=fDoc.CanPaste;
mnuedCopy.Enabled:=fDoc.SelAvail;
mnuedUndo.Enabled:=fDoc.CanUndo;
mnuedRedo.Enabled:=fDoc.CanRedo;
mnuedJum2Decl.Enabled:=fDoc.isDSource;
end;
{$ENDREGION}
end.
|
{ Модуль статистики операций }
unit StatsForAdmin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms, Dialogs, Grids, StdCtrls, Menus, ComCtrls, ToolWin;
type
TStatsForm = class(TForm)
StatsGrid: TStringGrid;
btnDeleteRec: TButton;
btnEditRec: TButton;
btnDeleteUser: TButton;
btnSaveInfo: TButton;
edtDelUser: TEdit;
cbbSortBy: TComboBoxEx;
btnSearchRec: TButton;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnEditRecClick(Sender: TObject);
procedure rbUserLoginMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btnDeleteRecClick(Sender: TObject);
procedure btnSaveInfoClick(Sender: TObject);
procedure btnDeleteUserClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbbSortBySelect(Sender: TObject);
procedure btnSearchRecClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TUserStats = record
Login: string[16];
Action: string[12];
OldName, NewName: string[20];
Time: TDateTime;
OldSize, NewSize: cardinal;
ProcVal: real;
end;
TList = ^TRoll; //Тип-указатель на запись
TRoll = record //Тип-запись
Rec: TUserStats; //Инфо
Next: TList; //Адрес следующего звена списка
end;
procedure WriteInfo;
procedure SaveField;
procedure ShowStatsInfo;
var
StatsForm: TStatsForm; //Форма статистики
NextAct: TUserStats; //Статистика
implementation
uses
HuffPackage,
AdmEditForm,
SearchRecords;
{$R *.dfm}
const
StatsDir='D:\Huffman Package\UserStats';
var
StatsFile: file of TUserStats; //Файл статистики
FirstEl,LastEl: TList; //Первый/последний элемент списка
ColPos,RowPos: integer; //Позиции в таблице
EdtPos: TList; //Строка редактирования
{ Запись статистики в файл }
procedure WriteInfo;
begin
Assign(StatsFile,StatsDir);
if FileExists(StatsDir) then
begin
Reset(StatsFile);
Seek(StatsFile,FileSize(StatsFile));
end
else Rewrite(StatsFile);
Write(StatsFile,NextAct);
Close(StatsFile);
end;
{ Считывание статистики из файла в однонаправленный список}
procedure ReadUserInfo;
begin
Assign(StatsFile,StatsDir);
if FileExists(StatsDir) then Reset(StatsFile)
else Rewrite(StatsFile);
New(FirstEl);
LastEl:=FirstEl;
{Добавление звеньев с записями в список}
while not(Eof(StatsFile)) do
begin
New(LastEl.Next);
LastEl:=LastEl.Next;
Read(StatsFile,LastEl.Rec);
end;
Close(StatsFile);
end;
{ Отображение статистики }
procedure ShowStatsInfo;
var
Pointer: TList; //Элемент списка
i: word; //Счётчик
begin
Pointer:=FirstEl.Next;
StatsForm.StatsGrid.RowCount:=2;
{ Проход по списку информации }
while Pointer<>LastEl.Next do
begin
with StatsForm.StatsGrid do
with Pointer.Rec do
begin
i:=RowCount-1;
Cells[0,i]:=Login;
Cells[1,i]:=Action;
Cells[2,i]:=OldName;
Cells[3,i]:=NewName;
Cells[4,i]:=TimeToStr(Time);
Cells[5,i]:=DateToStr(Time);
Cells[6,i]:=FloatToStr(OldSize/1024);
Cells[7,i]:=FloatToStr(NewSize/1024);
Cells[8,i]:=FloatToStr(ProcVal);
Cells[9,i]:=IntToStr(i);
RowCount:=RowCount+1;
end;
Pointer:=Pointer.Next;
end;
StatsForm.StatsGrid.RowCount:=StatsForm.StatsGrid.RowCount-1;
end;
{ Сохранение информации списка в файл }
procedure SaveInfo;
var
Pointer:TList; //Элемент списка
begin
Assign(StatsFile,StatsDir);
Rewrite(StatsFile);
Pointer:=FirstEl.Next;
while Pointer<>LastEl.Next do
begin
Write(StatsFile,Pointer.Rec);
Pointer:=Pointer.Next;
end;
Close(StatsFile);
end;
{ Действия при отображении формы статистики }
procedure TStatsForm.FormShow(Sender: TObject);
begin
ReadUserInfo;
ShowStatsInfo;
end;
{ Действия при закрытии формы статистики }
procedure TStatsForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
MainForm.Show;
end;
{ Действия при редактировании записи }
procedure TStatsForm.btnEditRecClick(Sender: TObject);
var
i,RecNum: word; //Счётчики
begin
if (FirstEl<>nil) and (StatsGrid.Row<>0) then
begin
EdtPos:=FirstEl;
RecNum:=StrToInt(StatsGrid.Cells[9,StatsGrid.Row]);
for i:=1 to RecNum do EdtPos:=EdtPos.Next;
{ Получение текущей информации в поля формы }
with AdmEditForm.EditForm do
with EdtPos.Rec do
begin
edtChLogin.Text:=Login;
edtChAction.Text:=Action;
edtChOldName.Text:=OldName;
edtChNewName.Text:=NewName;
edtChProcVal.text:=FloatToStr(ProcVal);
StatsForm.Enabled:=False;
EditForm.Show;
end;
end;
end;
{ Сохранение записи после редактирования }
procedure SaveField;
begin
with AdmEditForm.EditForm do
with EdtPos.Rec do
begin
Login:=edtChLogin.Text;
Action:=edtChAction.Text;
OldName:=edtChOldName.Text;
NewName:=edtChOldName.Text;
ProcVal:=StrToFloat(edtChProcVal.Text);
end;
StatsForm.StatsGrid.Enabled:=True;
ShowStatsInfo;
end;
{ Удаление записи }
procedure TStatsForm.rbUserLoginMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{ Получение координат }
with StatsGrid do
begin
MouseToCell(X,Y,ColPos,RowPos);
Col:=ColPos;
Row:=RowPos;
end
end;
{ Действия при удалении записи }
procedure TStatsForm.btnDeleteRecClick(Sender: TObject);
var
Pos,Pointer: TList; //Элемент списка
i,RecNum: word; //Счётчики
begin
if (FirstEl<>nil) and (StatsGrid.Row<>0) then
begin
RecNum:=StrToInt(StatsGrid.Cells[9,StatsGrid.Row]);
StatsGrid.Rows[StatsGrid.Row].Clear;
Pointer:=FirstEl;
for i:=1 to RecNum-1 do Pointer:=Pointer.Next;
Pos:=Pointer.Next;
Pointer.Next:=Pos.Next;
Dispose(Pos);
cbbSortBy.ItemIndex:=-1;
ShowStatsInfo;
end
else ShowMessage('Отсутствуют или не выбрана информация для удаления');
end;
{ Действия при сохранении статистики }
procedure TStatsForm.btnSaveInfoClick(Sender: TObject);
begin
if (FirstEl<>nil) then SaveInfo
else ShowMessage('Информация для сохранения отсутствует');
end;
{ Действия при удалении пользователя }
procedure TStatsForm.btnDeleteUserClick(Sender: TObject);
var
FileName: string;
begin
if edtDelUser.Text<>'' then
begin
FileName:='D:\Huffman Package\Пользователи\'+edtDelUser.Text;
if DeleteFile(FileName)
then ShowMessage('Пользователь '+edtDelUser.Text+' был удалён')
else ShowMessage('Ошибка. Файл не был удален');
end
else ShowMessage('Ввелидте логин пользователя');
end;
{ Действия при создании формы статистики }
procedure TStatsForm.FormCreate(Sender: TObject);
begin
{$I GridCreate.txt}
end;
{ Сравнение полей при сортировке в порядке возрастания }
function CompareUp(Col: byte; Cur,Next: word):boolean;
begin
Result:=(StatsForm.StatsGrid.Cells[Col,Cur]>StatsForm.StatsGrid.Cells[Col,Next]);
end;
{ Сравнение полей при сортировке в порядке убывания }
function CompareDown(Col: byte; Cur,Next: word):boolean;
begin
Result:=(StatsForm.StatsGrid.Cells[Col,Cur]<StatsForm.StatsGrid.Cells[Col,Next])
end;
{ Сортировка записей }
procedure TStatsForm.cbbSortBySelect(Sender: TObject);
type
TComptAct = function(Col: byte; Cur,Next: word):boolean;
var
i,j,k,n: word;
Temp: string;
Col: byte;
Condition: TComptAct;
begin
Col:=0;
Condition:=nil;
{ Выбор критерия сортировки }
case cbbSortBy.ItemIndex of
0:
begin
Col:=5;
Condition:=CompareUp;
end;
1:
begin
Col:=5;
Condition:=CompareDown;
end;
2:
begin
Col:=3;
Condition:=CompareUp;
end;
3:
begin
Col:=3;
Condition:=CompareDown;
end;
4:
begin
Col:=8;
Condition:=CompareDown;
end;
5:
begin
Col:=8;
Condition:=CompareUp;
end;
6:
begin
Col:=0;
Condition:=CompareUp;
end;
7:
begin
Col:=0;
Condition:=CompareDown;
end
end;
{ Сортировка записей полей StatsGrid }
n:=StatsGrid.RowCount;
for i:=1 to n-2 do
for j:=i+1 to n-1 do
if Condition(Col,i,j) then
for k:=0 to StatsGrid.ColCount do
begin
Temp:=StatsGrid.Cells[k,i];
StatsGrid.Cells[k,i]:=StatsGrid.Cells[k,j];
StatsGrid.Cells[k,j]:=Temp;
end
end;
{ Действия при нажатии кнопки "Поиск"}
procedure TStatsForm.btnSearchRecClick(Sender: TObject);
begin
SearchForm.Show;
end;
end.
|
unit DebugUtilities;
{$DEFINE INLINE_THIS_UNIT}
interface
uses
SysUtils,
DebugInterfaces;
function PointerToText(const aPointer: pointer): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
function InterfaceActualObjectPointerToString(const aInterface: IUnknown): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
function IAOPTS(const aFace: IUnknown): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
implementation
function PointerToText(const aPointer: pointer): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
begin
result := '';
{$IFDEF WIN32}
result := '$' + IntToHex(DWord(aPointer), 2 * SizeOf(pointer));
{$ENDIF}
{$IFDEF WIN64}
result := '$' + IntToHex(QWord(aPointer), 2 * SizeOf(pointer));
{$ENDIF}
end;
function InterfaceActualObjectPointerToString(const aInterface: IUnknown): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
var
reversible: IReversibleCOM;
begin
if aInterface = nil then
exit('NIL');
if aInterface is IReversibleCOM then
result := PointerToText((aInterface as IReversibleCOM).Reverse) + ' (DAO@SS)'
else
result := 'Not reversible';
end;
function IAOPTS(const aFace: IUnknown): string;
{$IFDEF INLINE_THIS_UNIT} inline; {$ENDIF}
begin
result := InterfaceActualObjectPointerToString(aFace);
end;
end.
|
//---------------------------------------------------------------------------------------------
//
// Archivo: HiloDescarga.pas
//
// Propósito:
// Se trata de un descendiente de la clase THiloDescarga, que sobrescribe los métodos
// virtuales "OnXXX" para reaccionar ante los eventos producidos por la descarga.
// En estos eventos se accede (de forma sincronizada a través de una sección crítica)
// a los distintos componentes de la ventana.
//
// Autor: José Manuel Navarro - http://www.lawebdejm.com
// Fecha: 01/05/2004
// Observaciones: Unidad creada en Delphi 5.
// Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre que
// SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos comentarios
// o de cualquier otro modo.
//
//---------------------------------------------------------------------------------------------
unit HiloDescargaEventos;
interface
uses HiloDescarga, Windows, MainFrm, Classes;
type
THiloDescargaEventos = class(THiloDescarga)
private
FProtegerVCL: RTL_CRITICAL_SECTION;
FVentana: TMainForm;
function getIniFile: string;
protected
//
// eventos
//
function onBeginDownload(var byteIni: DWORD; var byteFin: DWORD; size: DWORD): boolean; override;
procedure onEndDownload(totalBytes: DWORD); override;
function onProcessDownload(currentBytes: DWORD): boolean; override;
procedure onCancelDownload(currentByte: DWORD); override;
public
constructor Create;
destructor Destroy; override;
function getDescargasPendientes(lista: TStrings): integer;
function getDatosDescarga(url: string; var filename: string; var size: DWORD; var lastByte: DWORD): boolean;
property Ventana: TMainForm read FVentana write FVentana;
end;
implementation
uses IniFiles, Forms, SysUtils, ShellAPI;
constructor THiloDescargaEventos.Create;
begin
inherited;
InitializeCriticalSection(FProtegerVCL);
end;
destructor THiloDescargaEventos.Destroy;
begin
DeleteCriticalSection(FProtegerVCL);
inherited;
end;
function THiloDescargaEventos.getIniFile: string;
begin
result := ExtractFilePath(Application.ExeName);
result := IncludeTrailingBackslash(result) + 'descarga.ini';
end;
//
// eventos
//
function THiloDescargaEventos.onBeginDownload(var byteIni: DWORD; var byteFin: DWORD; size: DWORD): boolean;
var
ultimoByte: DWORD;
msg: string;
ini: TIniFile;
begin
msg := Format('Inicio de descarga [%d - %d]', [byteIni, byteFin]);
EnterCriticalSection(FProtegerVCL);
try
ini := TIniFile.Create(getIniFile);
try
ultimoByte := ini.ReadInteger(URL, 'lastByte', 0);
finally
ini.Free;
end;
if ultimoByte > 0 then
begin
byteIni := ultimoByte;
byteFin := 0; // hasta el final
end;
FVentana.progreso.Min := 0;
FVentana.progreso.Max := size;
FVentana.lb_log.ItemIndex := ventana.lb_log.Items.Add(msg);
finally
LeaveCriticalSection(FProtegerVCL);
end;
result := true;
end;
procedure THiloDescargaEventos.onEndDownload(totalBytes: DWORD);
var
msg: string;
ini: TIniFile;
ind: integer;
begin
msg := Format('Fin de descarga [%d]', [totalBytes]);
EnterCriticalSection(FProtegerVCL);
try
FVentana.lb_log.ItemIndex := FVentana.lb_log.Items.Add(msg);
FVentana.ParadaDescarga();
ini := TIniFile.Create(getIniFile);
try
ini.EraseSection(URL);
finally
ini.Free;
end;
if totalBytes > 0 then
begin
ind := FVentana.lb_url.Items.IndexOf(URL);
if ind <> -1 then
FVentana.lb_url.Items.Delete(ind);
MessageBox(FVentana.Handle, 'Descarga finalizada correctamente.'#10#13'A continuación se abrirá la carpeta donde se ha guardado del archivo descargado.', PChar(ventana.Caption), MB_ICONINFORMATION);
ShellExecute(GetForegroundWindow(), nil, PChar(FVentana.e_carpeta.Text),
nil, nil, SW_NORMAL);
end
else
MessageBox(FVentana.Handle, 'No se ha descargando el recurso. Comprueba que la conexión esté activa y la URL sea correcta.', PChar(ventana.Caption), MB_ICONINFORMATION);
finally
LeaveCriticalSection(FProtegerVCL);
end;
end;
function THiloDescargaEventos.onProcessDownload(currentBytes: DWORD): boolean;
var
msg: string;
begin
msg := Format('Progreso [%d]', [currentBytes]);
EnterCriticalSection(FProtegerVCL);
try
FVentana.progreso.Position := currentBytes;
if FVentana.lb_log.Items.Count >= 100 then
FVentana.lb_log.Items.Delete(0);
FVentana.lb_log.ItemIndex := FVentana.lb_log.Items.Add(msg);
finally
LeaveCriticalSection(FProtegerVCL);
end;
result := true;
end;
procedure THiloDescargaEventos.onCancelDownload(currentByte: DWORD);
var
msg: string;
ini: TIniFile;
begin
EnterCriticalSection(FProtegerVCL);
try
ini := TIniFile.Create(getIniFile);
try
if currentByte > 0 then
begin
ini.WriteString(URL, 'filename', Destino);
ini.WriteInteger(URL, 'lastByte', currentByte);
end;
if FVentana.lb_url.Items.IndexOf(URL) = -1 then
FVentana.lb_url.Items.Add(URL);
finally
ini.Free;
end;
msg := Format('Descarga cancelada [%d]', [currentByte]);
FVentana.lb_log.ItemIndex := FVentana.lb_log.Items.Add(msg);
FVentana.ParadaDescarga();
finally
LeaveCriticalSection(FProtegerVCL);
end;
end;
function THiloDescargaEventos.getDescargasPendientes(lista: TStrings): integer;
var
ini: TIniFile;
begin
result := lista.Count;
ini := TIniFile.Create(getIniFile);
try
ini.ReadSections(lista);
finally
ini.Free;
end;
result := (lista.Count - result);
end;
function THiloDescargaEventos.getDatosDescarga(url: string; var filename: string; var size: DWORD; var lastByte: DWORD): boolean;
var
ini: TIniFile;
hFile: THandle;
begin
ini := TIniFile.Create(getIniFile);
try
filename := ini.ReadString(url, 'filename', '');
lastByte := ini.ReadInteger(url, 'lastByte', 0);
finally
ini.Free;
end;
if filename = '' then
size := 0
else
begin
hFile := CreateFile(PChar(filename), GENERIC_READ, FILE_SHARE_READ,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
size := GetFileSize(hFile, nil);
if size = $FFFFFFFF then
size := 0;
CloseHandle(hFile);
end;
result := (filename <> '');
end;
end. |
unit debug;
interface
Procedure DebugPrint(Sender: TObject; Info : String); Overload; Forward;
Procedure DebugPrint(Info : String); overload; Forward;
Procedure DebugPrint; overload; Forward;
implementation
Uses
Dialogs,
SysUtils;
Procedure DebugPrint(Sender: TObject; Info : String); overload;
Var
MyFile : TextFile;
MyInfo : String;
DateTime : TDateTime;
DebugFile : String;
Begin
DebugFile := ExtractFileName(ParamStr(0)) + '.log';
If Not FileExists(ExtractFilePath(ParamStr(0)) + DebugFile) Then
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Rewrite(MyFile);
CloseFile(MyFile);
End;
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Append(MyFile);
DateTime := Time; // store the current date and time
MyInfo := DateToStr(Date) + ' ' + TimeToStr(DateTime) + ' Unit : ' + Sender.ClassName + ' ' + Info;
Writeln(MyFile, MyInfo);
Flush(MyFile); { ensures that the text was actually written to file }
CloseFile(MyFile);
End;
End;
Procedure DebugPrint(Info : String); overload;
//Write a string to the debug file
Var
MyFile : TextFile;
MyInfo : String;
DateTime : TDateTime;
DebugFile : String;
Begin
DebugFile := ExtractFileName(ParamStr(0)) + '.log';
If Not FileExists(ExtractFilePath(ParamStr(0)) + DebugFile) Then
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Rewrite(MyFile);
CloseFile(MyFile);
End;
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Append(MyFile);
DateTime := Time; // store the current date and time
MyInfo := DateToStr(Date) + ' ' + TimeToStr(DateTime) + ' ' + Info;
Writeln(MyFile, MyInfo);
Flush(MyFile); { ensures that the text was actually written to file }
CloseFile(MyFile);
End;
End;
Procedure DebugPrint; overload;
//Write an empty line to the debug file
Var
MyFile : TextFile;
DebugFile : String;
Begin
DebugFile := ExtractFileName(ParamStr(0)) + '.log';
If Not FileExists(ExtractFilePath(ParamStr(0)) + DebugFile) Then
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Rewrite(MyFile);
CloseFile(MyFile);
End;
Begin
AssignFile(MyFile, ExtractFilePath(ParamStr(0)) + DebugFile);
Append(MyFile);
Writeln(MyFile, '');
Flush(MyFile); { ensures that the text was actually written to file }
CloseFile(MyFile);
End;
End;
end.
|
unit UNotification;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms;
type
TCard = record
FTableTag: integer;
FCardId: integer;
FBringToFront: TNotifyEvent;
end;
{ TNotifier }
TNotifier = class
procedure Subscribe(AMethod: TNotifyEvent);
procedure Update;
function isCardOpened(ATableTag, ACardId: Integer): Boolean;
procedure CloseCard(ATableTag, ACardId: Integer);
procedure RegisterCard(ATableTag, ACardId: Integer; ABringCardToFront: TNotifyEvent);
private
FSubscibers: array of TNotifyEvent;
FOpenedCards: array of TCard;
end;
var
Notifier: TNotifier;
implementation
{ TNotifier }
procedure TNotifier.Subscribe(AMethod: TNotifyEvent);
begin
SetLength(FSubscibers, Length(FSubscibers) + 1);
FSubscibers[High(FSubscibers)] := AMethod;
end;
procedure TNotifier.Update;
var
i: integer;
begin
if Length(FSubscibers) <> 0 then
for i := 0 to High(FSubscibers) do
FSubscibers[i](nil);
end;
function TNotifier.isCardOpened(ATableTag, ACardId: Integer): Boolean;
var
i: integer;
begin
Result := False;
for i := 0 to High(FOpenedCards) do
if (FOpenedCards[i].FCardId = ACardId) and
(FOpenedCards[i].FTableTag = ATableTag) then
begin
FOpenedCards[i].FBringToFront(nil);
Result := True;
Break;
end;
end;
procedure TNotifier.CloseCard(ATableTag, ACardId: Integer);
var
i, j: integer;
begin
for i := 0 to High(FOpenedCards) do
if (FOpenedCards[i].FTableTag = ATableTag) and
(FOpenedCards[i].FCardId = ACardId) then
for j := i + 1 to High(FOpenedCards) do
FOpenedCards[j - 1] := FOpenedCards[j];
SetLength(FOpenedCards, Length(FOpenedCards) - 1);
end;
procedure TNotifier.RegisterCard(ATableTag, ACardId: Integer;
ABringCardToFront: TNotifyEvent);
begin
SetLength(FOpenedCards, Length(FOpenedCards) + 1);
with FOpenedCards[High(FOpenedCards)] do
begin
FTableTag := ATableTag;
FCardId := ACardId;
FBringToFront := ABringCardToFront;
end;
end;
initialization
Notifier := TNotifier.Create;
end.
|
unit Aurelius.Drivers.SQLite;
{$I Aurelius.inc}
interface
uses
Classes, DB, Variants, Generics.Collections,
Aurelius.Drivers.SQLite.Classes,
Aurelius.Drivers.Base,
Aurelius.Drivers.Interfaces;
type
TSQLiteNativeResultSetAdapter = class(TInterfacedObject, IDBResultSet)
private
FStatement: TSQLiteStatement;
public
constructor Create(AStatement: TSQLiteStatement);
destructor Destroy; override;
function Next: boolean;
function GetFieldValue(FieldIndex: Integer): Variant; overload;
function GetFieldValue(FieldName: string): Variant; overload;
end;
TSQLiteNativeStatementAdapter = class(TInterfacedObject, IDBStatement)
private
FDB: TSQLiteDatabase;
FSQL: string;
FParams: TObjectList<TDBParam>;
function PrepareStatement: TSQLiteStatement;
public
constructor Create(ADB: TSQLiteDatabase);
destructor Destroy; override;
procedure SetSQLCommand(SQLCommand: string);
procedure SetParams(Params: TEnumerable<TDBParam>);
procedure Execute;
function ExecuteQuery: IDBResultSet;
end;
TSQLiteNativeConnectionAdapter = class(TInterfacedObject, IDBConnection)
strict private
FDatabase: TSQLiteDatabase;
FFileName: string;
procedure Execute(const SQL: string);
public
constructor Create(AFileName: string);
destructor Destroy; override;
procedure EnableForeignKeys;
procedure DisableForeignKeys;
procedure Connect;
procedure Disconnect;
function IsConnected: Boolean;
function CreateStatement: IDBStatement;
function BeginTransaction: IDBTransaction;
function SqlDialect: string;
end;
TSQLiteNativeTransactionAdapter = class(TInterfacedObject, IDBTransaction)
private
FDatabase: TSQLiteDatabase;
public
constructor Create(ADatabase: TSQLiteDatabase);
procedure Commit;
procedure Rollback;
end;
implementation
{ TSQLiteNativeStatementAdapter }
uses
Aurelius.Drivers.Exceptions,
Aurelius.Global.Utils;
constructor TSQLiteNativeStatementAdapter.Create(ADB: TSQLiteDatabase);
begin
FDB := ADB;
FParams := TObjectList<TDBParam>.Create(true);
end;
destructor TSQLiteNativeStatementAdapter.Destroy;
begin
FParams.Free;
inherited;
end;
procedure TSQLiteNativeStatementAdapter.Execute;
var
Statement: TSqliteStatement;
begin
Statement := PrepareStatement;
try
Statement.Execute;
finally
Statement.Free;
end;
end;
function TSQLiteNativeStatementAdapter.ExecuteQuery: IDBResultSet;
var
Statement: TSqliteStatement;
begin
Statement := PrepareStatement;
Result := TSQLiteNativeResultSetAdapter.Create(Statement);
end;
function TSQLiteNativeStatementAdapter.PrepareStatement: TSQLiteStatement;
var
Statement: TSQLiteStatement;
Param: TDBParam;
ParamIdx: integer;
begin
Statement := FDB.Prepare(FSQL);
try
for Param in FParams do
begin
if VarIsNull(Param.ParamValue) then
Continue;
ParamIdx := Statement.BindParameterIndex(':' + Param.ParamName);
case Param.ParamType of
ftInteger, ftShortint, ftSmallint, ftLargeint:
Statement.BindInt64(ParamIdx, Param.ParamValue);
ftFloat, ftCurrency, ftExtended:
Statement.BindDouble(ParamIdx, Param.ParamValue);
ftString, ftWideString, ftFixedChar, ftMemo, ftWideMemo:
Statement.BindText(ParamIdx, Param.ParamValue);
ftBlob:
Statement.BindBlob(ParamIdx, TUtils.VariantToBytes(Param.ParamValue));
else
Statement.BindText(ParamIdx, Param.ParamValue);
end;
end;
Result := Statement;
except
Statement.Free;
raise;
end;
end;
procedure TSQLiteNativeStatementAdapter.SetParams(Params: TEnumerable<TDBParam>);
var
P: TDBParam;
begin
FParams.Clear;
for P in Params do
FParams.Add(TDBParam.Create(P.ParamName, P.ParamType, P.ParamValue));
end;
procedure TSQLiteNativeStatementAdapter.SetSQLCommand(SQLCommand: string);
begin
FSQL := SQLCommand;
end;
{ TSQLiteNativeConnectionAdapter }
function TSQLiteNativeConnectionAdapter.BeginTransaction: IDBTransaction;
begin
if not IsConnected then
Connect;
if not FDatabase.InTransaction then
begin
FDatabase.BeginTransaction;
Result := TSQLiteNativeTransactionAdapter.Create(FDatabase);
end else
Result := TSQLiteNativeTransactionAdapter.Create(nil);
end;
procedure TSQLiteNativeConnectionAdapter.Connect;
begin
if not IsConnected then
FDatabase := TSQLiteDatabase.Create(FFileName);
end;
constructor TSQLiteNativeConnectionAdapter.Create(AFileName: string);
begin
FFilename := AFileName;
end;
function TSQLiteNativeConnectionAdapter.CreateStatement: IDBStatement;
begin
if not IsConnected then
Connect;
Result := TSQLiteNativeStatementAdapter.Create(FDatabase);
end;
destructor TSQLiteNativeConnectionAdapter.Destroy;
begin
Disconnect;
inherited;
end;
procedure TSQLiteNativeConnectionAdapter.DisableForeignKeys;
begin
Execute('PRAGMA foreign_keys = off');
end;
procedure TSQLiteNativeConnectionAdapter.Disconnect;
begin
if FDatabase <> nil then
begin
FDatabase.Free;
FDatabase := nil;
end;
end;
procedure TSQLiteNativeConnectionAdapter.EnableForeignKeys;
begin
Execute('PRAGMA foreign_keys = on');
end;
procedure TSQLiteNativeConnectionAdapter.Execute(const SQL: string);
var
Statement: IDBStatement;
begin
Statement := CreateStatement;
Statement.SetSQLCommand(SQL);
Statement.Execute;
end;
function TSQLiteNativeConnectionAdapter.IsConnected: Boolean;
begin
Result := FDatabase <> nil;
end;
function TSQLiteNativeConnectionAdapter.SqlDialect: string;
begin
Result := 'SQLite';
end;
{ TSQLiteNativeTransactionAdapter }
procedure TSQLiteNativeTransactionAdapter.Commit;
begin
if (FDatabase = nil) then
Exit;
FDatabase.Commit;
end;
constructor TSQLiteNativeTransactionAdapter.Create(ADatabase: TSQLiteDatabase);
begin
FDatabase := ADatabase;
end;
procedure TSQLiteNativeTransactionAdapter.Rollback;
begin
if (FDatabase = nil) then
Exit;
FDatabase.Rollback;
end;
{ TSQLiteNativeResultSetAdapter }
constructor TSQLiteNativeResultSetAdapter.Create(AStatement: TSQLiteStatement);
begin
FStatement := AStatement;
end;
destructor TSQLiteNativeResultSetAdapter.Destroy;
begin
FStatement.Free;
inherited;
end;
function TSQLiteNativeResultSetAdapter.GetFieldValue(FieldIndex: Integer): Variant;
begin
case FStatement.ColumnType(FieldIndex) of
TSQLiteFieldType.stInteger:
Result := FStatement.ColumnInt64(FieldIndex);
TSQLiteFieldType.stFloat:
Result := FStatement.ColumnDouble(FieldIndex);
TSQLiteFieldType.stText:
Result := FStatement.ColumnText(FieldIndex);
TSQLiteFieldType.stBlob:
Result := FStatement.ColumnBlob(FieldIndex);
TSQLiteFieldType.stNull:
Result := Variants.Null;
else
//sftUnknown:
// ERROR!
end;
end;
function TSQLiteNativeResultSetAdapter.GetFieldValue(FieldName: string): Variant;
var
FieldIndex: integer;
begin
FieldIndex := FStatement.ColumnIndex(FieldName);
Result := GetFieldValue(FieldIndex);
end;
function TSQLiteNativeResultSetAdapter.Next: boolean;
begin
Result := FStatement.Next;
end;
end.
|
program problem404;
{Kamus Global}
var
found: boolean;
length,i, x : integer;
cars: array of integer;
function min(numbers: array of integer; length: integer): integer;
{Menerima input berupa array of integer, dan length yang merupakan panjang dari array tersebut
mengembalikan nilai minimum yang ada di array tersebut, array tidak kosong.}
{Kamus Lokal}
var
i : integer;
{Algoritma Lokal}
begin
{Inisialisai nilai minimal}
min:= numbers[0];
for i:= 0 to (length-1) do
begin
if (numbers[i] <= min) then
begin
min:= numbers[i];
end
else
begin
min:= min
end;
end;
end;
function iFind(numbers: array of integer; x, length: integer): integer;
{Menerima input berupa array of integer, x yang merupakan bilangan yang akan dicari
dan length yang merupakan panjang dari array tersebut. akan mengembalikan indeks dimana
bilangan x ditemukan, jika tidak ada mengembalikan nilai -1, array tidak kosong.}
{Kamus Lokal}
var
i: integer;
found: boolean;
{Algoritma Lokal}
begin
i:= 0;
found := false;
while ((not found) and (i < length)) do
begin
if (numbers[i] = x) then
begin
found := true;
end
else
begin
i := i+1;
end;
end;
if (found) then
iFind := i
else
iFind := -1;
end;
{Algoritma Utama}
begin
{Menerima masukan jumlah mobil yang ada}
write('Masukkan jumlah mobil : ');
readln(length);
{Jika jumlah mobil yang dimasukkan lebih dari 0}
if(length > 0 ) then
begin
SetLength(cars, length);
write('Masukkan ');
write(length);
writeln(' nomor mobil yang ada:');
{Input nomor/ nomor-nomor ke dalam array}
for i := 0 to (length-1) do
begin
readln(x);
cars[i] := x;
end;
found:= false;
{Mencari apakah ada nomor yang dilompat}
i := min(cars, length);
while((not found) and (i <= (min(cars, length)+length-1))) do
begin
if (iFind(cars, i, length) = -1) then
begin
found := true;
end
else
begin
i := i+1;
end;
end;
if (found) then
begin
write('Mobil Charlie adalah mobil dengan nomor ');
writeln(i);
end
else
begin
writeln('Tidak ada mobil yang merupakan mobil Charlie');
end;
end
{Jika jumlah mobil yang dimasukkan <= 0}
else
begin
writeln('Tidak ada mobil yang merupakan mobil Charlie');
end;
end. |
(**
* $Id: dco.transport.np.NamedPipeTransportImpl.pas 845 2014-05-25 17:42:00Z 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.transport.np.NamedPipeTransportImpl;
interface
uses
dco.transport.AbstractTransportImpl,
dco.transport.Pdu,
dco.util.ThreadedConsumer,
Cromis.Comm.Custom,
Cromis.Comm.IPC;
type
/// <summary>The class implements a transport resource via named pipe.</summary>
TNamedPipeTransportImpl = class(TAbstractTransportImpl)
private
FReceivingServer: TIPCServer;
FSenderClient: TIPCClient;
FSenderThread: TThreadedConsumer<TPdu>;
procedure HandleExecuteRequest(const Context: ICommContext; const Request: IMessageData;
const Response: IMessageData);
public
function WriteEnsured(const Pdu: TPdu): Boolean; override;
function GetUri: string; override;
private
procedure SendMessage(const Pdu: TPdu);
function SendMessageAwait(const Pdu: TPdu): Boolean;
public
constructor Create(const Name: string);
destructor Destroy; override;
end;
implementation
uses
{$IFDEF LOGGING}
Log4D,
{$ENDIF}
System.SysUtils,
dco.transport.Uri;
const
IPC_RECIPIENT = 'r';
IPC_MESSAGE = 'm';
constructor TNamedPipeTransportImpl.Create(const Name: string);
begin
inherited Create;
FSenderClient := TIPCClient.Create;
FSenderThread := TThreadedConsumer<TPdu>.Create(FOutboundQueue, SendMessage);
FSenderThread.NameThreadForDebugging('dco.system.sender <np>', FSenderThread.ThreadID);
FReceivingServer := TIPCServer.Create;
FReceivingServer.MinPoolSize := 1;
//FReceivingServer.NameThreadForDebugging('dco.system.receiver <np>', FReceiverThread.ThreadID);
FReceivingServer.ServerName := Name;
FReceivingServer.OnExecuteRequest := HandleExecuteRequest;
FSenderThread.Start;
FReceivingServer.Start;
end;
destructor TNamedPipeTransportImpl.Destroy;
begin
FReceivingServer.Free;
FSenderThread.Free;
FSenderClient.Free;
inherited;
end;
procedure TNamedPipeTransportImpl.HandleExecuteRequest(const Context: ICommContext; const Request: IMessageData;
const Response: IMessageData);
var
Pdu: TPdu;
begin
try
Pdu := TPdu.Create(
TUri.FromString(Request.Data.ReadString(IPC_RECIPIENT)).ToString,
TUri.FromString(Request.ID).ToString,
Request.Data.ReadString(IPC_MESSAGE)
);
except
Exit; // Unexpected message
end;
FInboundQueue.Put(Pdu);
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Trace('<-%s: %s', [Pdu.Sender, Pdu.Message_]);
{$ENDIF}
end;
function TNamedPipeTransportImpl.WriteEnsured(const Pdu: TPdu): Boolean;
begin
// This message is expected to be sent immediately with ensurance, so we call the static method directly!
Result := SendMessageAwait(Pdu);
end;
function TNamedPipeTransportImpl.GetUri: string;
begin
Result := FReceivingServer.ServerName;
end;
procedure TNamedPipeTransportImpl.SendMessage(const Pdu: TPdu);
begin
SendMessageAwait(Pdu);
end;
function TNamedPipeTransportImpl.SendMessageAwait(const Pdu: TPdu): Boolean;
var
Recipient: TUri;
Sender: TUri;
Data: IIPCData;
begin
try
Recipient := TUri.FromString(Pdu.Recipient);
Sender := TUri.FromString(Pdu.Sender);
except
on E: Exception do
begin
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Error(E.ToString);
{$ENDIF}
Exit(False);
end;
end;
if Recipient.Id <> Sender.Id then
begin
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Error(
Format('Untrusted message header detected: Recipient=%s, Sender=%s, Message=%s',
[Pdu.Recipient, Pdu.Sender, Pdu.Message_]));
{$ENDIF}
Exit(False);
end;
Data := AcquireIPCData;
Data.ID := Pdu.Sender;
Data.Data.WriteString(IPC_RECIPIENT, Pdu.Recipient);
Data.Data.WriteString(IPC_MESSAGE, Pdu.Message_);
Result := False;
try
FSenderClient.ServerName := Recipient.Domain;
FSenderClient.ExecuteRequest(Data);
if FSenderClient.AnswerValid then
Result := True;
except
end;
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Trace('->%s: %s', [Pdu.Recipient, Pdu.Message_]);
{$ENDIF}
end;
end.
|
unit Stack;
interface
uses
SysUtils, StdCtrls;
type
PTField = ^TField;
TField = record
Ch: char;
SP: PTField;
end;
TStack = class
constructor Create;
procedure Push(Ch: char);
function Pop: char;
function IsEmpty: boolean;
destructor Destroy; override;
private
ESP: PTField;
end;
implementation
constructor TStack.Create;
begin
Inherited Create;
ESP := nil;
end;
procedure TStack.Push;
var
ETP: PTField;
begin
New(ETP);
ETP^.Ch := Ch;
ETP^.SP := ESP;
ESP := ETP;
end;
function TStack.Pop: char;
var
ETP: PTField;
begin
if ESP <> nil then
begin
Result := ESP^.Ch;
ETP := ESP;
ESP := ESP^.SP;
Dispose(ETP);
end
else
Result := '!';
end;
function TStack.IsEmpty: boolean;
begin
if ESP <> nil then
Result := false
else
Result := true;
end;
destructor TStack.Destroy;
var
ETP: PTField;
begin
if ESP = nil then Exit;
while ESP <> nil do
begin
ETP := ESP;
ESP := ESP^.SP;
Dispose(ETP);
end;
Inherited Destroy;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.