text stringlengths 14 6.51M |
|---|
inherited dmValePedagio: TdmValePedagio
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWOPETVALEPED'
' (NR_MANIFVALEPED, CNPJFORNVALEPED, RESPPAGAMENTOVALEPED, COMPR' +
'OVANTEVALEPED, VALORVALEPED, DT_ALTERACAO, OPERADOR)'
'VALUES'
' (:NR_MANIFVALEPED, :CNPJFORNVALEPED, :RESPPAGAMENTOVALEPED, :C' +
'OMPROVANTEVALEPED, :VALORVALEPED, :DT_ALTERACAO, :OPERADOR)')
SQLDelete.Strings = (
'DELETE FROM STWOPETVALEPED'
'WHERE'
' NR_MANIFVALEPED = :Old_NR_MANIFVALEPED AND CNPJFORNVALEPED = :' +
'Old_CNPJFORNVALEPED AND RESPPAGAMENTOVALEPED = :Old_RESPPAGAMENT' +
'OVALEPED AND COMPROVANTEVALEPED = :Old_COMPROVANTEVALEPED')
SQLUpdate.Strings = (
'UPDATE STWOPETVALEPED'
'SET'
' NR_MANIFVALEPED = :NR_MANIFVALEPED, CNPJFORNVALEPED = :CNPJFOR' +
'NVALEPED, RESPPAGAMENTOVALEPED = :RESPPAGAMENTOVALEPED, COMPROVA' +
'NTEVALEPED = :COMPROVANTEVALEPED, VALORVALEPED = :VALORVALEPED, ' +
'DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR'
'WHERE'
' NR_MANIFVALEPED = :Old_NR_MANIFVALEPED AND CNPJFORNVALEPED = :' +
'Old_CNPJFORNVALEPED AND RESPPAGAMENTOVALEPED = :Old_RESPPAGAMENT' +
'OVALEPED AND COMPROVANTEVALEPED = :Old_COMPROVANTEVALEPED')
SQLRefresh.Strings = (
'SELECT NR_MANIFVALEPED, CNPJFORNVALEPED, RESPPAGAMENTOVALEPED, C' +
'OMPROVANTEVALEPED, VALORVALEPED, DT_ALTERACAO, OPERADOR FROM STW' +
'OPETVALEPED'
'WHERE'
' NR_MANIFVALEPED = :Old_NR_MANIFVALEPED AND CNPJFORNVALEPED = :' +
'Old_CNPJFORNVALEPED AND RESPPAGAMENTOVALEPED = :Old_RESPPAGAMENT' +
'OVALEPED AND COMPROVANTEVALEPED = :Old_COMPROVANTEVALEPED')
SQLLock.Strings = (
'SELECT NULL FROM STWOPETVALEPED'
'WHERE'
'NR_MANIFVALEPED = :Old_NR_MANIFVALEPED AND CNPJFORNVALEPED = :Ol' +
'd_CNPJFORNVALEPED AND RESPPAGAMENTOVALEPED = :Old_RESPPAGAMENTOV' +
'ALEPED AND COMPROVANTEVALEPED = :Old_COMPROVANTEVALEPED'
'FOR UPDATE WITH LOCK')
SQLRecCount.Strings = (
'SELECT COUNT(*) FROM ('
'SELECT 1 AS C FROM STWOPETVALEPED'
''
') q')
SQL.Strings = (
'SELECT * FROM STWOPETVALEPED VPED')
Left = 64
object qryManutencaoNR_MANIFVALEPED: TStringField
FieldName = 'NR_MANIFVALEPED'
Required = True
Size = 18
end
object qryManutencaoCNPJFORNVALEPED: TStringField
FieldName = 'CNPJFORNVALEPED'
Required = True
Size = 18
end
object qryManutencaoRESPPAGAMENTOVALEPED: TStringField
FieldName = 'RESPPAGAMENTOVALEPED'
Required = True
Size = 18
end
object qryManutencaoCOMPROVANTEVALEPED: TStringField
FieldName = 'COMPROVANTEVALEPED'
Required = True
end
object qryManutencaoVALORVALEPED: TFloatField
FieldName = 'VALORVALEPED'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT * FROM STWOPETVALEPED VPED')
object qryLocalizacaoNR_MANIFVALEPED: TStringField
FieldName = 'NR_MANIFVALEPED'
Required = True
Size = 18
end
object qryLocalizacaoCNPJFORNVALEPED: TStringField
FieldName = 'CNPJFORNVALEPED'
Required = True
Size = 18
end
object qryLocalizacaoRESPPAGAMENTOVALEPED: TStringField
FieldName = 'RESPPAGAMENTOVALEPED'
Required = True
Size = 18
end
object qryLocalizacaoCOMPROVANTEVALEPED: TStringField
FieldName = 'COMPROVANTEVALEPED'
Required = True
end
object qryLocalizacaoVALORVALEPED: TFloatField
FieldName = 'VALORVALEPED'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
end
end
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品调价
*******************************************************************************}
unit UFormProductPrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, StdCtrls,
UImageButton, Grids, UGridExPainter, cxCheckBox, cxMaskEdit,
cxDropDownEdit;
type
TfFormProductPrice = class(TSkinFormBase)
LabelHint: TLabel;
GridList: TDrawGridEx;
Panel1: TPanel;
BtnOK: TImageButton;
BtnExit: TImageButton;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Panel1Resize(Sender: TObject);
private
{ Private declarations }
FPainter: TGridExPainter;
//绘制对象
FSaleSame: Boolean;
//标志
procedure LoadProductList(const nStyleID: string);
//商品信息
procedure OnComboChanged(Sender: TObject);
//下拉框
procedure OnCheckClick(Sender: TObject);
//复选
procedure OnEditExit(Sender: TObject);
//数据生效
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowProductPriceForm(const nStyleID: string): Boolean;
//添加账户
implementation
{$R *.dfm}
uses
ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule, FZSale_Intf;
function ShowProductPriceForm(const nStyleID: string): Boolean;
begin
with TfFormProductPrice.Create(Application) do
begin
LoadProductList(nStyleID);
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormProductPrice.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormProductPrice.FormCreate(Sender: TObject);
var nIdx: Integer;
begin
FSaleSame := False;
for nIdx:=ComponentCount-1 downto 0 do
if Components[nIdx] is TImageButton then
LoadFixImageButton(TImageButton(Components[nIdx]));
//xxxxx
FPainter := TGridExPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('款式名称', 50, True);
AddHeader('颜色', 50, True);
AddHeader('尺码', 50);
AddHeader('现有库存', 50);
AddHeader('进货价', 50);
AddHeader('零售价', 50);
AddHeader('调整价', 50);
end;
LoadFormConfig(Self);
LoadDrawGridConfig(Name, GridList);
end;
procedure TfFormProductPrice.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveFormConfig(Self);
SaveDrawGridConfig(Name, GridList);
FPainter.Free;
end;
procedure TfFormProductPrice.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 调整按钮位置
procedure TfFormProductPrice.Panel1Resize(Sender: TObject);
var nW,nL: Integer;
begin
nW := BtnOK.Width + 65 + BtnExit.Width;
nL := Trunc((Panel1.Width - nW) / 2);
BtnOk.Left := nL;
BtnExit.Left := nL + BtnOK.Width + 65;
end;
//------------------------------------------------------------------------------
//Desc: 载入执行产品信息
procedure TfFormProductPrice.LoadProductList(const nStyleID: string);
var nStr,nHint: string;
nInt,nNum: Integer;
nDS: TDataSet;
nLabel: TLabel;
nCombo: TcxComboBox;
nCheck: TcxCheckBox;
nEdit: TcxTextEdit;
nRow: TGridExDataArray;
nCol: TGridExColDataArray;
begin
nStr := 'Select pt.*,p.StyleID,StyleName,ColorName,SizeName From $PT pt' +
' Left Join (Select ProductID,StyleName,dpt.StyleID From $DPT dpt' +
' Left Join $ST st On st.StyleID=dpt.StyleID' +
' ) p On ProductID=pt.P_ID' +
' Left Join $CR cr On cr.ColorID=P_Color ' +
' Left Join $SZ sz on sz.SizeID=P_Size ' +
'Where P_TerminalID=''$ID'' And p.StyleID=''$SID'' ' +
'Order By ColorName,SizeName';
//xxxxx
nStr := MacroValue(nStr, [MI('$PT', sTable_Product), MI('$DPT', sTable_DL_Product),
MI('$ST', sTable_DL_Style), MI('$CR', sTable_DL_Color),
MI('$SZ', sTable_DL_Size), MI('$ID', gSysParam.FTerminalID),
MI('$SID', nStyleID)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
SetLength(nRow, 5);
for nInt:=0 to 2 do
with nRow[nInt] do
begin
FText := '';
FCtrls := nil;
end;
with nRow[3] do
begin
FText := '';
FAlign := taCenter;
FCtrls := TList.Create;
nLabel := TLabel.Create(Self);
FCtrls.Add(nLabel);
nLabel.Transparent := True;
nLabel.Caption := '折扣';
nCombo := TcxComboBox.Create(Self);
FCtrls.Add(nCombo);
with nCombo do
begin
Width := 50;
Height := 22;
Properties.DropDownRows := 15;
Properties.OnEditValueChanged := OnComboChanged;
with Properties.Items do
begin
Add('9.9');
Add('9.5');
Add('9.0');
Add('8.0');
Add('7.5');
Add('7.0');
Add('6.5');
Add('5.0');
end;
end;
end;
with nRow[4] do
begin
FText := '';
FAlign := taCenter;
FCtrls := TList.Create;
nLabel := TLabel.Create(Self);
FCtrls.Add(nLabel);
nLabel.Transparent := True;
nLabel.Caption := '相同';
nCheck := TcxCheckBox.Create(Self);
FCtrls.Add(nCheck);
with nCheck do
begin
Width := 32;
Height := 22;
Transparent := True;
OnClick := OnCheckClick;
end;
end;
FPainter.AddRowData(nRow);
//添加首行控制
//------------------------------------------------------------------------
First;
nStr := FieldByName('StyleName').AsString;
LabelHint.Caption := Format('%s款式价格调整', [nStr]);
SetLength(nCol, 1);
with nCol[0] do
begin
FCol := 0;
FRows := RecordCount + 1;
FAlign := taCenter;
FText := FieldByName('StyleName').AsString;
end;
FPainter.AddColData(nCol);
nHint := '';
nNum := 1;
while not Eof do
begin
SetLength(nRow, 8);
for nInt:=Low(nRow) to High(nRow) do
begin
nRow[nInt].FCtrls := nil;
nRow[nInt].FAlign := taCenter;
end;
nRow[0].FText := FieldByName('SizeName').AsString;
nRow[1].FText := IntToStr(FieldByName('P_Number').AsInteger);
nRow[2].FText := Format('%.2f', [FieldByName('P_InPrice').AsFloat]);
nRow[3].FText := Format('%.2f', [FieldByName('P_Price').AsFloat]);
with nRow[4] do
begin
FText := '';
FAlign := taCenter;
FCtrls := TList.Create;
nLabel := TLabel.Create(Self);
nLabel.Transparent := True;
nLabel.Caption := '¥';
FCtrls.Add(nLabel);
nEdit := TcxTextEdit.Create(Self);
FCtrls.Add(nEdit);
with nEdit do
begin
Text := '0';
Width := 52;
Height := 18;
OnExit := OnEditExit;
end;
nLabel := TLabel.Create(Self);
nLabel.Transparent := True;
nLabel.Caption := '元';
FCtrls.Add(nLabel);
end;
nRow[5].FText := FieldByName('P_Color').AsString;
nRow[6].FText := FieldByName('P_Size').AsString;
nRow[7].FText := FieldByName('P_ID').AsString;
FPainter.AddRowData(nRow);
//添加行数据
//----------------------------------------------------------------------
if nHint = '' then
nHint := FieldByName('ColorName').AsString;
//first time
if nHint = FieldByName('ColorName').AsString then
begin
Inc(nNum);
Next; Continue;
end;
SetLength(nCol, 1);
with nCol[0] do
begin
FCol := 1;
FRows := nNum;
FAlign := taCenter;
FText := nHint;
nNum := 1;
nHint := FieldByName('ColorName').AsString;
end;
FPainter.AddColData(nCol);
Next;
end;
end;
if nNum > 0 then
begin
SetLength(nCol, 1);
with nCol[0] do
begin
FCol := 1;
FRows := nNum;
FAlign := taCenter;
FText := nHint;
end;
FPainter.AddColData(nCol);
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 下拉框折扣
procedure TfFormProductPrice.OnComboChanged(Sender: TObject);
var nStr: string;
nIdx: Integer;
nVal,nTmp: Double;
begin
nStr := TcxComboBox(Sender).Text;
if not IsNumber(nStr, True) then
begin
ActiveControl := TcxComboBox(Sender);
ShowMsg('折扣无效', sHint); Exit;
end;
nVal := StrToFloat(nStr);
if nVal <= 0 then
begin
ActiveControl := TcxComboBox(Sender);
ShowMsg('折扣为">0"的小数', sHint); Exit;
end;
for nIdx:=1 to FPainter.DataCount - 1 do
begin
nTmp := StrToFloat(FPainter.Data[nIdx][3].FText);
nTmp := RegularMoney(nTmp * nVal / 10);
nStr := Format('%.2f', [nTmp]);
TcxTextEdit(FPainter.Data[nIdx][4].FCtrls[1]).Text := nStr;
end;
GridList.Invalidate;
end;
//Desc: 复选
procedure TfFormProductPrice.OnCheckClick(Sender: TObject);
begin
with TcxCheckBox(Sender) do
begin
FSaleSame := Checked;
end;
end;
//Desc: 焦点退出,内容生效
procedure TfFormProductPrice.OnEditExit(Sender: TObject);
var nStr: string;
nIdx: Integer;
nEdit: TcxTextEdit;
begin
with TcxTextEdit(Sender) do
begin
if (not IsNumber(Text, True)) or (StrToFloat(Text) < 0) then
begin
SetFocus;
ShowMsg('请填写有效单价', sHint); Exit;
end;
if not FSaleSame then Exit;
nStr := Format('%.2f', [StrToFloat(Text)]);
for nIdx:=1 to FPainter.DataCount - 1 do
begin
nEdit := TcxTextEdit(FPainter.Data[nIdx][4].FCtrls[1]);
nEdit.Text := nStr;
end;
end;
end;
//Desc: 保存
procedure TfFormProductPrice.BtnOKClick(Sender: TObject);
var nStr, nHint: string;
nIdx: Integer;
nSQLList: SQLItems;
begin
ActiveControl := nil;
nSQLList := SQLItems.Create;
try
for nIdx:=1 to FPainter.DataCount - 1 do
begin
nStr := TcxTextEdit(FPainter.Data[nIdx][4].FCtrls[1]).Text;
if (not IsNumber(nStr, True)) or (StrToFloat(nStr) <= 0) then Continue;
nHint := 'P_TerminalId=''$TER'' And P_ID=''$ID'' And P_Size=''$SZ'' And ' +
'P_Color=''$CR''';
nHint := MacroValue(nHint, [MI('$TER', gSysParam.FTerminalID),
MI('$CR', FPainter.Data[nIdx][5].FText),
MI('$SZ', FPainter.Data[nIdx][6].FText),
MI('$ID', FPainter.Data[nIdx][7].FText)]);
//where
nStr := MakeSQLByStr([SF('R_Sync', sFlag_SyncW),
SF('P_OldPrice', 'P_Price', sfVal),
SF('P_Price', TcxTextEdit(FPainter.Data[nIdx][4].FCtrls[1]).Text)
], sTable_Product, nHint, False);
//insert sql
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
end;
if FDM.SQLUpdates(nSQLList, True, nHint) > -1 then
begin
ShowMsg('调价完毕', sHint);
ModalResult := mrOk;
end else ShowDlg(nHint, sWarn);
finally
//nSQLList.Free;
end;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StCRC.pas 4.04 *}
{*********************************************************}
{* SysTools: Cyclic redundancy check unit for SysTools *}
{*********************************************************}
{$I StDefine.inc}
{
Note: CRC routines rely on overflows for their results,
so these need to be off:
}
{$R-}
{$Q-}
unit StCRC;
interface
uses
Windows, SysUtils, Classes,
StBase;
const
CrcBufSize = 2048;
CrcFileMode = fmOpenRead or fmShareDenyWrite;
function Adler32Prim(var Data; DataSize : Cardinal; CurCrc : Integer) : Integer;
function Adler32OfStream(Stream : TStream; CurCrc : Integer) : Integer;
function Adler32OfFile(FileName : String) : Integer;
function Crc16Prim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
function Crc16OfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
function Crc16OfFile(FileName : String) : Cardinal;
function Crc32Prim(var Data; DataSize : Cardinal; CurCrc : Integer) : Integer;
function Crc32OfStream(Stream : TStream; CurCrc : Integer) : Integer;
function Crc32OfFile(FileName : String) : Integer;
function InternetSumPrim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
function InternetSumOfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
function InternetSumOfFile(FileName : String) : Cardinal;
function Kermit16Prim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
function Kermit16OfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
function Kermit16OfFile(FileName : String) : Cardinal;
const
{ Cardinal takes more space, but is about 10% faster in 32-bit }
CrcTable: array[0..255] of Cardinal = (
$0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7,
$8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef,
$1231, $0210, $3273, $2252, $52b5, $4294, $72f7, $62d6,
$9339, $8318, $b37b, $a35a, $d3bd, $c39c, $f3ff, $e3de,
$2462, $3443, $0420, $1401, $64e6, $74c7, $44a4, $5485,
$a56a, $b54b, $8528, $9509, $e5ee, $f5cf, $c5ac, $d58d,
$3653, $2672, $1611, $0630, $76d7, $66f6, $5695, $46b4,
$b75b, $a77a, $9719, $8738, $f7df, $e7fe, $d79d, $c7bc,
$48c4, $58e5, $6886, $78a7, $0840, $1861, $2802, $3823,
$c9cc, $d9ed, $e98e, $f9af, $8948, $9969, $a90a, $b92b,
$5af5, $4ad4, $7ab7, $6a96, $1a71, $0a50, $3a33, $2a12,
$dbfd, $cbdc, $fbbf, $eb9e, $9b79, $8b58, $bb3b, $ab1a,
$6ca6, $7c87, $4ce4, $5cc5, $2c22, $3c03, $0c60, $1c41,
$edae, $fd8f, $cdec, $ddcd, $ad2a, $bd0b, $8d68, $9d49,
$7e97, $6eb6, $5ed5, $4ef4, $3e13, $2e32, $1e51, $0e70,
$ff9f, $efbe, $dfdd, $cffc, $bf1b, $af3a, $9f59, $8f78,
$9188, $81a9, $b1ca, $a1eb, $d10c, $c12d, $f14e, $e16f,
$1080, $00a1, $30c2, $20e3, $5004, $4025, $7046, $6067,
$83b9, $9398, $a3fb, $b3da, $c33d, $d31c, $e37f, $f35e,
$02b1, $1290, $22f3, $32d2, $4235, $5214, $6277, $7256,
$b5ea, $a5cb, $95a8, $8589, $f56e, $e54f, $d52c, $c50d,
$34e2, $24c3, $14a0, $0481, $7466, $6447, $5424, $4405,
$a7db, $b7fa, $8799, $97b8, $e75f, $f77e, $c71d, $d73c,
$26d3, $36f2, $0691, $16b0, $6657, $7676, $4615, $5634,
$d94c, $c96d, $f90e, $e92f, $99c8, $89e9, $b98a, $a9ab,
$5844, $4865, $7806, $6827, $18c0, $08e1, $3882, $28a3,
$cb7d, $db5c, $eb3f, $fb1e, $8bf9, $9bd8, $abbb, $bb9a,
$4a75, $5a54, $6a37, $7a16, $0af1, $1ad0, $2ab3, $3a92,
$fd2e, $ed0f, $dd6c, $cd4d, $bdaa, $ad8b, $9de8, $8dc9,
$7c26, $6c07, $5c64, $4c45, $3ca2, $2c83, $1ce0, $0cc1,
$ef1f, $ff3e, $cf5d, $df7c, $af9b, $bfba, $8fd9, $9ff8,
$6e17, $7e36, $4e55, $5e74, $2e93, $3eb2, $0ed1, $1ef0
);
const
Crc32Table : array[0..255] of DWORD = (
$00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535,
$9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd,
$e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d,
$6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec,
$14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4,
$a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c,
$dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac,
$51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f,
$2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab,
$b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f,
$9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb,
$086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e,
$6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea,
$fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce,
$a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a,
$346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9,
$5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409,
$ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81,
$b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739,
$9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8,
$e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268,
$6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0,
$10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8,
$a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b,
$d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef,
$4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703,
$220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7,
$b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a,
$9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae,
$0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242,
$68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6,
$ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45,
$a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d,
$3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5,
$47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605,
$cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94,
$b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d
);
implementation
{$IFDEF TRIALRUN}
uses
StTrial;
{$ENDIF}
type
CRCByteArray = array[0..Pred(High(Integer))] of Byte;
function Adler32Prim(var Data; DataSize : Cardinal; CurCrc : Integer) : Integer;
{ Calculates the Adler 32-bit CRC of a block }
var
S1, S2, I : Integer;
begin
if DataSize > 0 then begin
S1 := CurCrc and $FFFF;
S2 := (CurCrc shr 16) and $FFFF;
for I := 0 to (DataSize-1) do begin
S1 := (S1 + CRCByteArray(Data)[I]) mod 65521;
S2 := (S2 + S1) mod 65521;
end;
Result := (S2 shl 16) + S1;
end else
Result := CurCrc;
end;
function Adler32OfStream(Stream : TStream; CurCrc : Integer) : Integer;
{ Calculates the Adler 32-bit CRC of a stream }
var
BufArray : array[0..(CrcBufSize-1)] of Byte;
Res : Integer;
begin
{Initialize Crc}
Result := CurCrc;
repeat
Res := Stream.Read(BufArray, CrcBufSize);
Result := Adler32Prim(BufArray, Res, Result);
until (Res <> CrcBufSize);
end;
function Adler32OfFile(FileName : String) : Integer;
{ Calculates the Adler 32-bit CRC of a file }
var
FileSt : TFileStream;
begin
FileSt := TFileStream.Create(FileName, CrcFileMode);
try
Result := Adler32OfStream(FileSt, 1);
finally
FileSt.Free;
end;
end;
function Crc16Prim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
{ Calculates the 16-bit CRC of a block }
var
I : Integer;
begin
Result := CurCrc;
for I := 0 to (DataSize-1) do
Result := (CrcTable[((Result shr 8) and 255)] xor (Result shl 8) xor
CRCByteArray(Data)[I]) and $FFFF;
end;
function Crc16OfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
{ Calculates the 16-bit CRC of a stream }
var
BufArray : array[0..(CrcBufSize-1)] of Byte;
Res : Integer;
begin
{Initialize Crc}
Result := CurCrc;
repeat
Res := Stream.Read(BufArray, CrcBufSize);
Result := Crc16Prim(BufArray, Res, Result);
until (Res <> CrcBufSize);
end;
function Crc16OfFile(FileName : String) : Cardinal;
{ Calculates the 16-bit CRC of a file }
var
FileSt : TFileStream;
begin
FileSt := TFileStream.Create(FileName, CrcFileMode);
try
Result := Crc16OfStream(FileSt, 0);
finally
FileSt.Free;
end;
end;
function Crc32Prim(var Data; DataSize : Cardinal; CurCrc : Integer) : Integer;
{ Calculates the 32-bit CRC of a block }
var
I : Integer;
begin
Result := CurCrc;
for I := 0 to (DataSize-1) do
Result := Crc32Table[Byte(Result xor CRCByteArray(Data)[I])] xor
DWord((Result shr 8) and $00FFFFFF);
end;
function Crc32OfStream(Stream : TStream; CurCrc : Integer) : Integer;
{ Calculates the 32-bit CRC of a stream }
var
BufArray : array[0..(CrcBufSize-1)] of Byte;
Res : Integer;
begin
{Initialize Crc}
Result := CurCrc;
repeat
Res := Stream.Read(BufArray, CrcBufSize);
Result := Crc32Prim(BufArray, Res, Result);
until (Res <> CrcBufSize);
end;
function Crc32OfFile(FileName : String) : Integer;
{ Calculates the 32-bit CRC of a file }
var
FileSt : TFileStream;
begin
FileSt := TFileStream.Create(FileName, CrcFileMode);
try
Result := not Crc32OfStream(FileSt, Integer($FFFFFFFF));
finally
FileSt.Free;
end;
end;
function InternetSumPrim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
{ Calculates the Internet Checksum of a block }
var
I : Integer;
begin
Result := CurCrc;
if DataSize = 0 then Exit;
for I := 0 to (DataSize - 1) do begin
if Odd(I) then
Result := Result + (CRCByteArray(Data)[I] shl 8)
else
Result := Result + CRCByteArray(Data)[I];
end;
Result := (not((Result and $FFFF) + (Result shr 16))) and $FFFF;
end;
function InternetSumOfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
{ Calculates the Internet Checksum of a stream }
var
BufArray : array[0..(CrcBufSize-1)] of Byte;
Res : Integer;
begin
{Initialize Crc}
Result := CurCrc;
repeat
Res := Stream.Read(BufArray, CrcBufSize);
Result := InternetSumPrim(BufArray, Res, Result);
until (Res <> CrcBufSize);
end;
function InternetSumOfFile(FileName : String) : Cardinal;
{ Calculates the Internet Checksum of a file }
var
FileSt : TFileStream;
begin
FileSt := TFileStream.Create(FileName, CrcFileMode);
try
Result := InternetSumOfStream(FileSt, 0);
finally
FileSt.Free;
end;
end;
function Kermit16Prim(var Data; DataSize, CurCrc : Cardinal) : Cardinal;
{ Calculates the Kermit 16-bit CRC of a block }
var
I, J : Integer;
Temp : Cardinal;
CurrByte : Byte;
begin
for I := 0 to (DataSize-1) do begin
CurrByte := CRCByteArray(Data)[I];
for J := 0 to 7 do begin
Temp := CurCrc xor CurrByte;
CurCrc := CurCrc shr 1;
if Odd(Temp) then
CurCrc := CurCrc xor $8408;
CurrByte := CurrByte shr 1;
end;
end;
Result := CurCrc;
end;
function Kermit16OfStream(Stream : TStream; CurCrc : Cardinal) : Cardinal;
{ Calculates the Kermit 16-bit CRC of a stream }
var
BufArray : array[0..(CrcBufSize-1)] of Byte;
Res : Integer;
begin
{Initialize Crc}
Result := CurCrc;
repeat
Res := Stream.Read(BufArray, CrcBufSize);
Result := Kermit16Prim(BufArray, Res, Result);
until (Res <> CrcBufSize);
end;
function Kermit16OfFile(FileName : String) : Cardinal;
{ Calculates the Kermit 16-bit CRC of a file }
var
FileSt : TFileStream;
begin
FileSt := TFileStream.Create(FileName, CrcFileMode);
try
Result := Kermit16OfStream(FileSt, 0);
finally
FileSt.Free;
end;
end;
end.
|
{ Subroutine SST_SCOPE_UNUSED_SHOW (SCOPE)
*
* List the unused symbols in the indicated scope. Only those symbols will
* be listed that are unused, obey the -SHOW_UNUSED command line option,
* and are not intrinsic to the front end.
}
module sst_SCOPE_UNUSED_SHOW;
define sst_scope_unused_show;
%include 'sst2.ins.pas';
procedure sst_scope_unused_show ( {write names of unused symbols in a scope}
in scope: sst_scope_t); {scope to list unused symbols in}
const
max_msg_parms = 3; {max parameters we can pass to a message}
var
pos: string_hash_pos_t; {position handle into hash table}
found: boolean; {TRUE if hash table entry was found}
name_p: univ_ptr; {unused subroutine argument}
sym_p: sst_symbol_p_t; {pointer to to current symbol to write out}
sym_pp: sst_symbol_pp_t; {pointer to hash table user data area}
dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor}
level: sys_int_machine_t; {source file nesting level of symbol}
fnam: string_treename_t; {file name passed to a message}
lnum: sys_int_machine_t; {line number passed to a message}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
label
next_sym;
begin
if sst_level_unused = 0 then return; {not supposed to write any unused symbols ?}
fnam.max := sizeof(fnam.str); {init local var string}
string_hash_pos_first (sst_scope_p^.hash_h, pos, found); {get pos for first symbol}
while found do begin {once for each symbol at this scope}
string_hash_ent_atpos (pos, name_p, sym_pp); {get pointer to this hash entry}
sym_p := sym_pp^; {get pointer to symbol descriptor}
if sst_symflag_used_k in sym_p^.flags {symbol is used ?}
then goto next_sym;
if sst_symflag_intrinsic_in_k in sym_p^.flags {intrinsic to front end ?}
then goto next_sym;
if sym_p^.char_h.crange_p = nil {didn't come from input stream ?}
then goto next_sym;
if sym_p^.symtype = sst_symtype_dtype_k then begin {could be undefined dtype ?}
dt_p := sym_p^.dtype_dtype_p; {resolve base data type}
while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p;
if dt_p^.dtype = sst_dtype_undef_k {data type is undefined ?}
then goto next_sym;
end;
if {variable in common block declared here ?}
(sym_p^.symtype = sst_symtype_var_k) and {symbol is a variable ?}
(sym_p^.var_com_p <> nil) and then {variable is in a common block ?}
(not (sst_symflag_extern_k in sym_p^.var_com_p^.flags)) {com defined here ?}
then goto next_sym;
if sst_level_unused <> sst_level_unused_all_k then begin {don't list some syms ?}
syo_get_char_flevel (sym_p^.char_h, level); {get source file nesting level}
if level >= sst_level_unused {symbol declared too deep in nested files ?}
then goto next_sym;
end;
{
* This symbol needs to be listed.
}
if
(sym_p^.symtype = sst_symtype_var_k) and
(sym_p^.var_arg_p <> nil)
then begin {unused symbol is routine argument}
sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^);
sys_msg_parm_vstr (msg_parm[2], sym_p^.var_proc_p^.sym_p^.name_in_p^);
sys_message_parms ('sst', 'symbol_arg_unused', msg_parm, 2);
end
else begin {unused symbol is not arg to this routine}
sst_charh_info (sym_p^.char_h, fnam, lnum);
sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^);
sys_msg_parm_int (msg_parm[2], lnum);
sys_msg_parm_vstr (msg_parm[3], fnam);
sys_message_parms ('sst', 'symbol_unused', msg_parm, 3);
end
;
next_sym: {jump here to advance to next symbol in scope}
string_hash_pos_next (pos, found); {advance to next hash table entry}
end; {back and do this new hash table entry}
end;
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clPop3FileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, Windows, SysUtils, SyncObjs,
{$ELSE}
System.Classes, Winapi.Windows, System.SysUtils, System.SyncObjs,
{$ENDIF}
clPop3Server;
type
TclPop3LoadMessageEvent = procedure (Sender: TObject; AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean) of object;
TclPop3FileMessageItem = class(TclPop3MessageItem)
private
FPath: string;
public
constructor Create(const AUID: string; ASize: Integer; const APath: string);
property Path: string read FPath write FPath;
end;
TclPop3FileHandler = class(TComponent)
private
FServer: TclPop3Server;
FMailBoxDir: string;
FAccessor: TCriticalSection;
FOnLoadMessage: TclPop3LoadMessageEvent;
procedure SetServer(const Value: TclPop3Server);
procedure SetMailBoxDir(const Value: string);
procedure DoStateChanged(Sender: TObject; AConnection: TclPop3CommandConnection);
procedure DoMailBoxInfo(Sender: TObject; AConnection: TclPop3CommandConnection;
AMailBox: TclPop3MessageList);
procedure DoRetrieve(Sender: TObject; AConnection: TclPop3CommandConnection;
AMessageNo: Integer; AMessage: TStrings; var Success: Boolean);
function GetMailBoxPath(const AUserName: string): string;
function GetMessageUid(const AFileName: string; AFileSize: Integer): string;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
procedure DoLoadMessage(AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean); virtual;
property Accessor: TCriticalSection read FAccessor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: TclPop3Server read FServer write SetServer;
property MailBoxDir: string read FMailBoxDir write SetMailBoxDir;
property OnLoadMessage: TclPop3LoadMessageEvent read FOnLoadMessage write FOnLoadMessage;
end;
implementation
uses
clUtils;
{ TclPop3FileHandler }
procedure TclPop3FileHandler.CleanEventHandlers;
begin
Server.OnMailBoxInfo := nil;
Server.OnRetrieve := nil;
Server.OnStateChanged := nil;
end;
constructor TclPop3FileHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
end;
destructor TclPop3FileHandler.Destroy;
begin
FAccessor.Free();
inherited Destroy();
end;
procedure TclPop3FileHandler.InitEventHandlers;
begin
Server.OnMailBoxInfo := DoMailBoxInfo;
Server.OnRetrieve := DoRetrieve;
Server.OnStateChanged := DoStateChanged;
end;
procedure TclPop3FileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclPop3FileHandler.SetMailBoxDir(const Value: string);
begin
FAccessor.Enter();
try
FMailBoxDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclPop3FileHandler.SetServer(const Value: TclPop3Server);
begin
if (FServer <> Value) then
begin
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
function TclPop3FileHandler.GetMailBoxPath(const AUserName: string): string;
begin
FAccessor.Enter();
try
Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName);
finally
FAccessor.Leave();
end;
end;
function TclPop3FileHandler.GetMessageUid(const AFileName: string; AFileSize: Integer): string;
begin
Result := UpperCase(StringReplace(AFileName, '.', ':', [rfReplaceAll])) + ':' + IntToStr(AFileSize);
Result := StringReplace(Result, #32, '_', [rfReplaceAll]);
end;
procedure TclPop3FileHandler.DoMailBoxInfo(Sender: TObject;
AConnection: TclPop3CommandConnection; AMailBox: TclPop3MessageList);
var
path: string;
searchRec: TSearchRec;
canLoad: Boolean;
begin
path := GetMailBoxPath(AConnection.UserName);
AMailBox.Clear();
if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(path + '*.MSG', 0, searchRec) = 0 then
begin
repeat
canLoad := True;
DoLoadMessage(AConnection, path, searchRec.Name, canLoad);
if canLoad then
begin
AMailBox.Add(TclPop3FileMessageItem.Create(
GetMessageUid(searchRec.Name, searchRec.Size), searchRec.Size, path + searchRec.Name));
end;
until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(searchRec) <> 0);
{$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(searchRec);
end;
end;
procedure TclPop3FileHandler.DoRetrieve(Sender: TObject; AConnection: TclPop3CommandConnection;
AMessageNo: Integer; AMessage: TStrings; var Success: Boolean);
var
s: string;
begin
try
s := TclPop3FileMessageItem(AConnection.MailBox.Items[AMessageNo - 1]).Path;
AMessage.Clear();
TclStringsUtils.LoadStrings(s, AMessage, '');
Success := True;
except
AMessage.Clear();
Success := False;
end;
end;
procedure TclPop3FileHandler.DoStateChanged(Sender: TObject; AConnection: TclPop3CommandConnection);
var
i: Integer;
begin
if (AConnection.ConnectionState <> csPop3Update) then Exit;
for i := 0 to AConnection.MailBox.Count - 1 do
begin
if AConnection.MailBox[i].IsDeleted then
begin
DeleteFile(TclPop3FileMessageItem(AConnection.MailBox[i]).Path);
end;
end;
end;
procedure TclPop3FileHandler.DoLoadMessage(AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean);
begin
if Assigned(OnLoadMessage) then
begin
OnLoadMessage(Self, AConnection, AMailBoxPath, AMessageFile, ACanLoad);
end;
end;
{ TclPop3FileMessageItem }
constructor TclPop3FileMessageItem.Create(const AUID: string; ASize: Integer; const APath: string);
begin
inherited Create(AUID, ASize);
FPath := APath;
end;
end.
|
unit MiscEditors;
interface
uses
Classes, Forms, Dialogs, ExtDlgs, DsgnIntf, TypInfo, SysUtils;
type
TFilenameProperty =
class( TStringProperty )
public
procedure Edit; override;
function GetAttributes : TPropertyAttributes; override;
end;
procedure Register;
implementation
uses
CommRez;
// TFilename
procedure TFilenameProperty.Edit;
var
OpenDialog : TOpenDialog;
begin
OpenDialog := TOpenDialog.Create( Application );
with OpenDialog do
try
Options := [ofFileMustExist, ofHideReadOnly];
Title := SFileToLoad;
Filter := SAllFilesMask;
DefaultExt := '';
if Execute
then SetValue( Filename );
finally
OpenDialog.Free;
end;
end;
function TFilenameProperty.GetAttributes : TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
// VCL Registration
procedure Register;
begin
RegisterPropertyEditor( TypeInfo( string ), nil, 'Filename', TFilenameProperty );
end;
end.
|
{
This file is part of the Free Component Library (FCL)
Copyright (c) 2018 by Michael Van Canneyt
Unit tests for Pascal-to-Javascript converter class.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************
Examples:
./testpas2js --suite=TTestCLI_Precompile
./testpas2js --suite=TTestModule.TestEmptyUnit
}
unit TCPrecompile;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
fpcunit, testregistry, Pas2jsFileUtils, Pas2JsFiler, Pas2jsCompiler,
TCUnitSearch, TCModules;
type
{ TCustomTestCLI_Precompile }
TCustomTestCLI_Precompile = class(TCustomTestCLI)
private
FPCUFormat: TPas2JSPrecompileFormat;
FUnitOutputDir: string;
protected
procedure SetUp; override;
procedure CheckPrecompile(MainFile, UnitPaths: string;
SharedParams: TStringList = nil;
FirstRunParams: TStringList = nil;
SecondRunParams: TStringList = nil; ExpExitCode: integer = 0);
function GetJSFilename(ModuleName: string): string; virtual;
public
constructor Create; override;
property PCUFormat: TPas2JSPrecompileFormat read FPCUFormat write FPCUFormat;
property UnitOutputDir: string read FUnitOutputDir write FUnitOutputDir;
end;
{ TTestCLI_Precompile }
TTestCLI_Precompile = class(TCustomTestCLI_Precompile)
published
procedure TestPCU_EmptyUnit;
procedure TestPCU_UTF8BOM;
procedure TestPCU_ParamNS;
procedure TestPCU_Overloads;
procedure TestPCU_Overloads_MDelphi_ModeObjFPC;
procedure TestPCU_UnitCycle;
procedure TestPCU_Class_Forward;
procedure TestPCU_Class_Constructor;
procedure TestPCU_Class_ClassConstructor;
procedure TestPCU_ClassInterface;
procedure TestPCU_Namespace;
procedure TestPCU_CheckVersionMain;
procedure TestPCU_CheckVersionMain2;
procedure TestPCU_CheckVersionSystem;
end;
function LinesToList(const Lines: array of string): TStringList;
implementation
function LinesToList(const Lines: array of string): TStringList;
var
i: Integer;
begin
Result:=TStringList.Create;
for i:=Low(Lines) to High(Lines) do Result.Add(Lines[i]);
end;
{ TCustomTestCLI_Precompile }
procedure TCustomTestCLI_Precompile.SetUp;
begin
inherited SetUp;
UnitOutputDir:='units';
end;
procedure TCustomTestCLI_Precompile.CheckPrecompile(MainFile,
UnitPaths: string; SharedParams: TStringList; FirstRunParams: TStringList;
SecondRunParams: TStringList; ExpExitCode: integer);
var
JSFilename, OrigSrc, NewSrc, s: String;
JSFile: TCLIFile;
begin
try
AddDir(UnitOutputDir);
// compile, create .pcu files
{$IFDEF VerbosePCUFiler}
writeln('TTestCLI_Precompile.CheckPrecompile create pcu files=========================');
{$ENDIF}
Params.Clear;
Params.Add('-Jminclude');
Params.Add('-Jc');
if SharedParams<>nil then
Params.AddStrings(SharedParams);
if FirstRunParams<>nil then
Params.AddStrings(FirstRunParams);
Compile([MainFile,'-Fu'+UnitPaths,'-JU'+PCUFormat.Ext,'-FU'+UnitOutputDir]);
AssertFileExists(UnitOutputDir+'/system.'+PCUFormat.Ext);
JSFilename:=GetJSFilename(MainFile);
AssertFileExists(JSFilename);
JSFile:=FindFile(JSFilename);
OrigSrc:=JSFile.Source;
// compile, using .pcu files
//for i:=0 to FileCount-1 do
// writeln('TCustomTestCLI_Precompile.CheckPrecompile ',i,' ',Files[i].Filename);
{$IFDEF VerbosePCUFiler}
writeln('TTestCLI_Precompile.CheckPrecompile compile using pcu files==================');
{$ENDIF}
JSFile.Source:='';
Compiler.Reset;
Params.Clear;
Params.Add('-Jminclude');
Params.Add('-Jc');
if SharedParams<>nil then
Params.AddStrings(SharedParams);
if SecondRunParams<>nil then
Params.AddStrings(SecondRunParams);
Compile([MainFile,'-FU'+UnitOutputDir],ExpExitCode);
if ExpExitCode=0 then
begin
NewSrc:=JSFile.Source;
if not CheckSrcDiff(OrigSrc,NewSrc,s) then
begin
WriteSources;
writeln('TCustomTestCLI_Precompile.CheckPrecompile OrigSrc==================');
writeln(OrigSrc);
writeln('TCustomTestCLI_Precompile.CheckPrecompile NewSrc==================');
writeln(NewSrc);
Fail('test1.js: '+s);
end;
end;
finally
SharedParams.Free;
FirstRunParams.Free;
SecondRunParams.Free;
end;
end;
function TCustomTestCLI_Precompile.GetJSFilename(ModuleName: string): string;
begin
Result:=UnitOutputDir+PathDelim+ExtractFilenameOnly(ModuleName)+'.js';
end;
constructor TCustomTestCLI_Precompile.Create;
begin
inherited Create;
FPCUFormat:=PrecompileFormats[0];
end;
{ TTestCLI_Precompile }
procedure TTestCLI_Precompile.TestPCU_EmptyUnit;
begin
AddUnit('src/system.pp',[''],['']);
AddFile('test1.pas',[
'begin',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_UTF8BOM;
var
aFile: TCLIFile;
begin
aFile:=AddUnit('src/system.pp',
['var',
' s: string = ''aaaäö'';',
' s2: string = ''😊'';', // 1F60A
''],
['']);
aFile.Source:=UTF8BOM+aFile.Source;
aFile:=AddFile('test1.pas',[
'begin',
' s:=''ö😊'';',
'end.']);
aFile.Source:=UTF8BOM+aFile.Source;
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_ParamNS;
begin
AddUnit('src/system.pp',[''],['']);
AddUnit('src/foo.unit1.pp',['var i: longint;'],['']);
AddFile('test1.pas',[
'uses unit1;',
'begin',
' i:=3;',
'end.']);
CheckPrecompile('test1.pas','src',LinesToList(['-FNfoo']));
end;
procedure TTestCLI_Precompile.TestPCU_Overloads;
begin
AddUnit('src/system.pp',['type integer = longint;'],['']);
AddUnit('src/unit1.pp',
['var i: integer;',
'procedure DoIt(j: integer); overload;',
'procedure DoIt(b: boolean);'],
['procedure DoIt(j: integer);',
'begin',
' i:=j;',
'end;',
'procedure DoIt(b: boolean);',
'begin',
' i:=3;',
'end;']);
AddUnit('src/unit2.pp',
['uses unit1;',
'procedure DoIt(s: string); overload;'],
['procedure DoIt(s: string);',
'begin',
' unit1.i:=length(s);',
'end;']);
AddFile('test1.pas',[
'uses unit1, unit2;',
'procedure DoIt(d: double); overload;',
'begin',
' unit1.i:=4;',
'end;',
'begin',
' DoIt(3);',
' DoIt(''abc'');',
' DoIt(true);',
' DoIt(3.3);',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_Overloads_MDelphi_ModeObjFPC;
var
SharedParams: TStringList;
begin
AddUnit('src/system.pp',[
'type',
' integer = longint;',
' TDateTime = type double;'],
['']);
AddFile('src/unit1.pp',
LinesToStr([
'unit unit1;',
'{$mode objfpc}',
'interface',
'function DoIt(i: integer): TDateTime;', // no overload needed in ObjFPC
'function DoIt(i, j: integer): TDateTime;',
'implementation',
'function DoIt(i: integer): TDateTime;',
'begin',
' Result:=i;',
'end;',
'function DoIt(i, j: integer): TDateTime;',
'begin',
' Result:=i+j;',
'end;',
'end.']));
AddFile('test1.pas',[
'uses unit1;',
'var d: TDateTime;',
'begin',
' d:=DoIt(3);',
' d:=DoIt(4,5);',
'end.']);
SharedParams:=TStringList.Create;
SharedParams.Add('-MDelphi');
CheckPrecompile('test1.pas','src',SharedParams);
end;
procedure TTestCLI_Precompile.TestPCU_UnitCycle;
begin
AddUnit('src/system.pp',['type integer = longint;'],['']);
AddUnit('src/unit1.pp',
['var i: integer;',
'procedure Do1(j: integer);'],
['uses unit2;',
'procedure Do1(j: integer);',
'begin',
' Do2(j);',
'end;']);
AddUnit('src/unit2.pp',
['uses unit1;',
'procedure Do2(j: integer);'],
['procedure Do2(j: integer);',
'begin',
' unit1.i:=j;',
'end;']);
AddFile('test1.pas',[
'uses unit1;',
'begin',
' Do1(3);',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_Class_Forward;
begin
AddUnit('src/system.pp',[
'type integer = longint;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddUnit('src/unit1.pp',
['type',
' TClass = class of TObject;',
' TBirdClass = class of TBird;',
' TObject = class',
' FBirdClass: TBirdClass;',
' constructor Create;',
' constructor Create(Id: integer);',
' property BirdClass: TBirdClass read FBirdClass;',
' end;',
' TBird = class',
' constructor Create(d: double); overload;',
' end;',
''],
['constructor TObject.Create; begin end;',
'constructor TObject.Create(Id: integer); begin end;',
'constructor TBird.Create(d: double); begin end;']);
AddFile('test1.pas',[
'uses unit1;',
'var',
' b: TBird;',
' c: TClass;',
'begin',
' c:=TObject;',
' c:=TBird;',
' c:=b.BirdClass;',
' b:=TBird.Create;',
' b:=TBird.Create(1);',
' b:=TBird.Create(3.3);',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_Class_Constructor;
begin
AddUnit('src/system.pp',[
'type integer = longint;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddUnit('src/unit1.pp',[
'type',
' TObject = class',
' constructor Create;',
' end;',
' TBird = class',
' constructor Create; reintroduce;',
' end;',
' TCow = class',
' constructor Create; reintroduce;',
' end;',
''],[
'constructor TObject.Create; begin end;',
'constructor TBird.Create; begin end;',
'constructor TCow.Create; begin end;',
'']);
AddUnit('src/unit2.pp',[
'uses unit1;',
'procedure DoIt;',
''],[
'procedure DoIt;',
'begin',
' TBird.Create;',
' TCow.Create;',
'end;',
'']);
AddFile('test1.pas',[
'uses unit2;',
'begin',
' DoIt;',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_Class_ClassConstructor;
begin
AddUnit('src/system.pp',[
'type integer = longint;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddUnit('src/unit1.pp',[
'type',
' TObject = class',
' constructor Create;',
' end;',
' TBird = class',
' class constructor InitBird;',
' end;',
''],[
'constructor TObject.Create; begin end;',
'class constructor TBird.InitBird;',
'begin',
' exit;',
'end;',
'']);
AddUnit('src/unit2.pp',[
'uses unit1;',
'procedure DoIt;',
''],[
'procedure DoIt;',
'begin',
' TBird.Create;',
'end;',
'']);
AddFile('test1.pas',[
'uses unit2;',
'begin',
' DoIt;',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_ClassInterface;
begin
AddUnit('src/system.pp',[
'{$interfaces corba}',
'type',
' integer = longint;',
' IUnknown = interface',
' end;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddUnit('src/unit1.pp',[
'type',
' IIntf = interface',
' function GetItems(Index: longint): longint;',
' procedure SetItems(Index: longint; Value: longint);',
' property Items[Index: longint]: longint read GetItems write SetItems; default;',
' end;',
''],[
'']);
AddUnit('src/unit2.pp',[
'uses unit1;',
'type',
' IAlias = IIntf;',
' TObject = class end;',
' TBird = class(IIntf)',
' strict private',
' function IIntf.GetItems = FetchItems;',
' function FetchItems(Index: longint): longint; virtual; abstract;',
' procedure SetItems(Index: longint; Value: longint); virtual; abstract;',
' end;',
''],[
'']);
AddUnit('src/unit3.pp',[
'uses unit2;',
'type',
' TEagle = class(TBird)',
' function FetchItems(Index: longint): longint; override;',
' procedure SetItems(Index: longint; Value: longint); override;',
' end;',
' TFlying = class(IAlias)',
' strict private',
' FEagle: TEagle;',
' property Eagle: TEagle read FEagle implements IAlias;',
' public',
' constructor Create;',
' end;',
''],[
'function TEagle.FetchItems(Index: longint): longint; begin end;',
'procedure TEagle.SetItems(Index: longint; Value: longint); begin end;',
'constructor TFlying.Create;',
'begin',
' FEagle:=nil;',
'end;',
'']);
AddFile('test1.pas',[
'uses unit2, unit3;',
'type IAlias2 = IAlias;',
'var',
' f: TFlying;',
' i: IAlias2;',
'begin',
' f:=TFlying.Create;',
' i:=f;',
' i[2]:=i[3];',
'end.']);
CheckPrecompile('test1.pas','src');
end;
procedure TTestCLI_Precompile.TestPCU_Namespace;
begin
AddUnit('src/system.pp',[
'type integer = longint;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddUnit('src/Web.Unit1.pp',[
'var i: integer;',
''],[
'']);
AddUnit('src/Unit2.pp',[
'uses WEB.uNit1;',
'procedure DoIt;',
''],[
'procedure DoIt;',
'begin',
' writeln(i);',
'end;',
'']);
AddFile('test1.pas',[
'uses unIT2;',
'begin',
' DoIt;',
'end.']);
CheckPrecompile('test1.pas','src');
AssertFileExists(UnitOutputDir+'/Unit2.'+PCUFormat.Ext);
AssertFileExists(UnitOutputDir+'/Web.Unit1.'+PCUFormat.Ext);
end;
procedure TTestCLI_Precompile.TestPCU_CheckVersionMain;
var
aFile: TCLIFile;
s, JSFilename, ExpectedSrc: string;
begin
AddUnit('src/system.pp',[
'type integer = longint;'],
['']);
AddFile('test1.pas',[
'begin',
'end.']);
CheckPrecompile('test1.pas','src',LinesToList(['-JoCheckVersion=Main','-Jm-','-Jc-']));
JSFilename:=GetJSFilename('test1.js');
aFile:=FindFile(JSFilename);
AssertNotNull('File not found '+JSFilename,aFile);
ExpectedSrc:=LinesToStr([
UTF8BOM+'rtl.module("program",["system"],function () {',
' "use strict";',
' var $mod = this;',
' $mod.$main = function () {',
' rtl.checkVersion('+IntToStr((VersionMajor*100+VersionMinor)*100+VersionRelease)+');',
' };',
'});']);
if not CheckSrcDiff(ExpectedSrc,aFile.Source,s) then
Fail('TTestCLI_Precompile.TestPCU_CheckVersionMain src diff: '+s);
end;
procedure TTestCLI_Precompile.TestPCU_CheckVersionMain2;
var
aFile: TCLIFile;
s, JSFilename, ExpectedSrc: string;
begin
AddUnit('src/system.pp',[
'type integer = longint;',
'procedure Writeln; varargs;'],
['procedure Writeln; begin end;']);
AddFile('test1.pas',[
'begin',
' Writeln;',
'end.']);
CheckPrecompile('test1.pas','src',LinesToList(['-JoCheckVersion=Main','-Jm-','-Jc-']));
JSFilename:=GetJSFilename('test1.js');
aFile:=FindFile(JSFilename);
AssertNotNull('File not found '+JSFilename,aFile);
ExpectedSrc:=LinesToStr([
UTF8BOM+'rtl.module("program",["system"],function () {',
' "use strict";',
' var $mod = this;',
' $mod.$main = function () {',
' rtl.checkVersion('+IntToStr((VersionMajor*100+VersionMinor)*100+VersionRelease)+');',
' pas.system.Writeln();',
' };',
'});']);
if not CheckSrcDiff(ExpectedSrc,aFile.Source,s) then
Fail('TTestCLI_Precompile.TestPCU_CheckVersionMain src diff: '+s);
end;
procedure TTestCLI_Precompile.TestPCU_CheckVersionSystem;
var
aFile: TCLIFile;
s, JSFilename, ExpectedSrc, VerStr: string;
begin
AddUnit('src/system.pp',[
'type integer = longint;'],
['']);
AddFile('test1.pas',[
'begin',
'end.']);
CheckPrecompile('test1.pas','src',LinesToList(['-JoCheckVersion=system','-Jm-','-Jc-']));
JSFilename:=GetJSFilename('system.js');
aFile:=FindFile(JSFilename);
AssertNotNull('File not found '+JSFilename,aFile);
writeln('TTestCLI_Precompile.TestPCU_CheckVersionMain ',aFile.Source);
VerStr:=IntToStr((VersionMajor*100+VersionMinor)*100+VersionRelease);
ExpectedSrc:=LinesToStr([
UTF8BOM+'rtl.module("system",[],function () {',
' "use strict";',
' rtl.checkVersion('+VerStr+');',
' var $mod = this;',
'});']);
if not CheckSrcDiff(ExpectedSrc,aFile.Source,s) then
Fail('TTestCLI_Precompile.TestPCU_CheckVersionMain src diff: '+s);
end;
Initialization
RegisterTests([TTestCLI_Precompile]);
RegisterPCUFormat;
end.
|
{ Subroutine SST_R_PAS_STATEMENTS
*
* Build a chain of opcodes from the STATEMENTS syntax. All the opcodes on the
* chain will be of "executable" type.
}
module sst_r_pas_STATEMENTS;
define sst_r_pas_statements;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_statements; {build opcodes from STATEMENTS syntax}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
label
tag_loop;
begin
sst_scope_p^.flag_ref_used := true; {referenced symbols will be flagged as used}
syo_level_down; {down into STATEMENTS syntax level}
tag_loop: {back here each new RAW_STATEMENT syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
case tag of
{
* Hit end of STATMENTS syntax.
}
syo_tag_end_k: begin
syo_level_up; {up from STATEMENTS syntax}
return;
end;
{
* Tag is a new RAW_STATEMENT syntax.
}
1: begin
sst_r_pas_raw_sment; {add RAW_STATEMENT onto opcodes chain}
end;
{
* Unexpected tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of tag value cases}
goto tag_loop; {back for next syntax tag in STATEMENTS}
end;
|
unit BufferDraw;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, Buffer, SpeedBmp;
// if you don't want any clipping pass nil as ClipArea:
procedure BufferCopyGDI( Source, Dest : TSpeedBitmap; aX, aY : integer; ClipArea : PRect );
procedure BufferCopyOpaque( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
// Warning: These are intended only for 8-bpp and 24-bpp bitmaps
procedure BufferCopyTrans( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
procedure BufferCopyGlassed( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
procedure BufferCopyShaded( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
// These 2 are only for 8-bit bitmaps
procedure BufferCopySourceCTT( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; Table : pointer );
procedure BufferCopyDestCTT( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; Table : pointer );
// Clipping engine ================================================================
type
TClipResults =
record
ImageRect : TRect;
Size : TPoint;
x, y : integer;
dx, dy : integer;
SrcWidth : integer;
DstWidth : integer;
end;
function DoClipping( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; var Results : TClipResults ) : boolean;
implementation
uses
Rects, BitBlt;
function DoClipping( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; var Results : TClipResults ) : boolean;
var
ClipRect : TRect;
begin
with Results do
begin
if not Assigned( ClipArea )
then
begin
ClipArea := @ClipRect;
ClipArea^ := Dest.ClientRect;
end;
Result := IntersectRect( ImageRect, RectFromBounds( aX, aY, Source.Width, Source.Height ), ClipArea^ );
if Result
then
begin
Size := RectSize( ImageRect );
if aX < ImageRect.Left
then
begin
dx := ImageRect.Left - aX;
x := ImageRect.Left;
end
else
begin
dx := 0;
x := aX;
end;
if aY < ImageRect.Top
then
begin
dy := ImageRect.Top - aY;
y := ImageRect.Top;
end
else
begin
dy := 0;
y := aY;
end;
if Source.TopDown
then SrcWidth := Source.StorageWidth
else SrcWidth := -Source.StorageWidth;
if Dest.TopDown
then DstWidth := Dest.StorageWidth
else DstWidth := -Dest.StorageWidth;
end;
end;
end;
procedure BufferCopyGDI( Source, Dest : TSpeedBitmap; aX, aY : integer; ClipArea : PRect );
begin
with Dest.Canvas do
if Assigned( ClipArea )
then Source.DrawOnDC( Handle, aX, aY, CopyMode )
else Source.ClipDrawOnDC( Handle, aX, aY, ClipArea^, CopyMode );
end;
procedure BufferCopyOpaque( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
var
Results : TClipResults;
begin
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then // In this case we don't have to bother with bitmap bits per pixel
BltCopyOpaque( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y],
Size.x, Size.y, SrcWidth, DstWidth );
end;
procedure BufferCopyTrans( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
var
Results : TClipResults;
begin
assert( ( Source.BitCount = Dest.BitCount ) and
( Source.BitCount in [8, 16, 24] ) and
( Dest.BitCount in [8, 24] ), 'Invalid bits per pixel in BufferDraw.BufferCopyTrans!!' );
assert( Source.BitCount in [8, 24], 'Only 8 and 24 bits-per-pixel supported in BufferDraw.BufferCopyTrans!!' );
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then
case Source.BitCount of
8: BltCopyTrans( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx, Size.x, Size.y, SrcWidth, DstWidth );
24: BltCopyTrans24( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.Width, Source.Height, Source.TransparentColor, 0, SrcWidth, DstWidth );
end;
end;
procedure BufferCopyGlassed( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
var
Results : TClipResults;
begin
assert( ( Source.BitCount = Dest.BitCount ) and
( Source.BitCount in [8, 16, 24] ) and
( Dest.BitCount in [8, 16, 24] ), 'Invalid bits per pixel in BufferDraw.BufferCopyGlassed!!' );
assert( Source.BitCount in [8, 16, 24], 'Only 8 and 24 bits-per-pixel supported in BufferDraw.BufferCopyGlassed!!' );
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then
case Source.BitCount of
8:
BltCopyGlassed( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
Size.x, Size.y, SrcWidth, DstWidth, nil );
16:
BltCopyGlassedCTT16( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.Width, Source.Height,
Source.TransparentIndx, SrcWidth, DstWidth, nil);
{ 24: BltCopyGlassed24( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentColor,
Size.x, Size.y, SrcWidth, DstWidth, nil );}
end;
end;
procedure BufferCopyShaded( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect );
var
Results : TClipResults;
begin
assert( ( Source.BitCount = Dest.BitCount ) and
( Source.BitCount in [8] ), 'Invalid bits per pixel in BufferDraw.BufferCopyShaded!!' );
assert( Source.BitCount in [8, 24], 'Only 8 and 24 bits-per-pixel supported in BufferDraw.BufferCopyShaded!!' );
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then
if Source.BitCount = 8
then //BltCopyDestCTT( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
// Size.x, Size.y, SrcWidth, DstWidth, Dest.BufferPalette.MixTable )
else BltCopyShaded24( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentColor,
Size.x, Size.y, SrcWidth, DstWidth, nil );
end;
procedure BufferCopySourceCTT( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; Table : pointer );
var
Results : TClipResults;
begin
assert( Source.BitCount = 8, 'Only 8 bits-per-pixel source bitmaps supported in BufferDraw.BufferCopySourceCTT!!' );
assert( Dest.BitCount in [8, 16, 24], 'Only 8, 16 or 24 bits-per-pixel dest bitmaps supported in BufferDraw.BufferCopySourceCTT!!' );
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then
case Dest.BitCount of
8 :
BltCopySourceCTT( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
Size.x, Size.y, SrcWidth, DstWidth, Table );
16 :
BltCopySourceCTT16( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
Size.x, Size.y, SrcWidth, DstWidth, Table );
{ 24 :
BltCopySourceCTT24( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
Size.x, Size.y, SrcWidth, DstWidth, Table );}
end;
end;
procedure BufferCopyDestCTT( Source, Dest : TBuffer; aX, aY : integer; ClipArea : PRect; Table : pointer );
var
Results : TClipResults;
begin
assert( ( Source.BitCount = Dest.BitCount ) and
( Source.BitCount = 8 ), 'Only 8 bits-per-pixel supported in BufferDraw.BufferCopyDestCTT!!' );
with Results do
if DoClipping( Source, Dest, aX, aY, ClipArea, Results )
then BltCopyDestCTT( Source.PixelAddr[dx, dy], Dest.PixelAddr[x, y], Source.TransparentIndx,
Size.x, Size.y, SrcWidth, DstWidth, Table );
end;
end.
|
unit CleanArch_EmbrConf.Adapter.interfaces;
interface
uses
CleanArch_EmbrConf.Core.Entity.Interfaces;
type
iParkingLotAdapter = interface
function Code(Value : String) : iParkingLotAdapter; overload;
function Code : String; overload;
function Capacity(Value : Integer) : iParkingLotAdapter; overload;
function Capacity : Integer; overload;
function OpenHour(Value : Integer) : iParkingLotAdapter; overload;
function OpenHour : Integer; overload;
function CloseHour(Value : Integer) : iParkingLotAdapter; overload;
function CloseHour : Integer; overload;
function OccupiedSpaces(Value : Integer) : iParkingLotAdapter; overload;
function OccupiedSpaces : Integer; overload;
function ParkingLot : iParkingLot;
end;
implementation
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2017 * }
{ *********************************************************** }
unit tfHashServ;
interface
{$I TFL.inc}
uses tfRecords, tfTypes, tfAlgServ, tfByteVectors,
tfMD5, tfSHA1, tfSHA256, tfSHA512,
tfCRC32, tfJenkinsOne,
tfHMAC;
function GetHashServerInstance(var A: IHashServer): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
function GetHashInstance(AlgID: TF_AlgID; var Alg: IHash): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
implementation
(*
type
PAlgItem = ^TAlgItem;
TAlgItem = record
Name: array[0..15] of Byte;
Getter: Pointer;
end;
*)
type
PHashServer = ^THashServer;
THashServer = record
public const
TABLE_SIZE = 64;
public
// !! inherited from TAlgServer
FVTable: PPointer;
FCapacity: Integer;
FCount: Integer;
FAlgTable: array[0..TABLE_SIZE - 1] of TAlgItem;
(*
FVTable: PPointer;
FAlgTable: array[0..63] of TAlgItem;
FCount: Integer;
class function GetByAlgID(Inst: PHashServer; AlgID: Integer;
var Alg: IHashAlgorithm): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
*)
class function GetHMAC(Inst: PHashServer; var HMACAlg: IHMACAlgorithm;
// Key: Pointer; KeySize: Cardinal;
const HashAlg: IHash): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function PBKDF1(Inst: PHashServer; HashAlg: IHash;
Password: Pointer; PassLen: Cardinal; Salt: Pointer; SaltLen: Cardinal;
Rounds, dkLen: Cardinal; var Key: PByteVector): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
(*
class function GetByName(Inst: PHashServer; AName: Pointer; CharSize: Integer;
var Alg: IHashAlgorithm): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetByIndex(Inst: PHashServer; Index: Integer;
var Alg: IHashAlgorithm): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetName(Inst: PHashServer; Index: Integer;
var Name: PByteVector): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetCount(Inst: PHashServer): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
*)
// class function RegisterHash(Inst: PHashServer; Name: Pointer; CharSize: Integer;
// Getter: THashGetter; var Index: Integer): TF_RESULT;
// {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
const
VTable: array[0..9] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeSingleton.Addref,
@TForgeSingleton.Release,
@TAlgServer.GetID,
@TAlgServer.GetName,
@TAlgServer.GetCount,
@TAlgServer.GetIDByName,
@TAlgServer.GetNameByID,
@THashServer.GetHMAC,
@THashServer.PBKDF1
// @THashServer.RegisterHash,
);
var
Instance: THashServer;
const
MD5_LITERAL: UTF8String = 'MD5';
SHA1_LITERAL: UTF8String = 'SHA1';
SHA256_LITERAL: UTF8String = 'SHA256';
SHA512_LITERAL: UTF8String = 'SHA512';
SHA224_LITERAL: UTF8String = 'SHA224';
SHA384_LITERAL: UTF8String = 'SHA384';
CRC32_LITERAL: UTF8String = 'CRC32';
JENKINS1_LITERAL: UTF8String = 'JENKINS1';
(*
procedure AddTableItem(const AName: RawByteString; AGetter: Pointer);
var
P: PAlgItem;
L: Integer;
begin
P:= @Instance.FAlgTable[Instance.FCount];
FillChar(P^.Name, SizeOf(P^.Name), 0);
L:= Length(AName);
if L > SizeOf(P^.Name) then L:= SizeOf(P^.Name);
Move(Pointer(AName)^, P^.Name, L);
P^.Getter:= AGetter;
Inc(Instance.FCount);
end;
*)
procedure InitInstance;
begin
Instance.FVTable:= @VTable;
Instance.FCapacity:= THashServer.TABLE_SIZE;
// Instance.FCount:= 0;
TAlgServer.AddTableItem(@Instance, Pointer(MD5_LITERAL), TF_ALG_MD5);
TAlgServer.AddTableItem(@Instance, Pointer(SHA1_LITERAL), TF_ALG_SHA1);
TAlgServer.AddTableItem(@Instance, Pointer(SHA256_LITERAL), TF_ALG_SHA256);
TAlgServer.AddTableItem(@Instance, Pointer(SHA512_LITERAL), TF_ALG_SHA512);
TAlgServer.AddTableItem(@Instance, Pointer(SHA224_LITERAL), TF_ALG_SHA224);
TAlgServer.AddTableItem(@Instance, Pointer(SHA384_LITERAL), TF_ALG_SHA384);
TAlgServer.AddTableItem(@Instance, Pointer(CRC32_LITERAL), TF_ALG_CRC32);
TAlgServer.AddTableItem(@Instance, Pointer(JENKINS1_LITERAL), TF_ALG_JENKINS1);
end;
function GetHashServerInstance(var A: IHashServer): TF_RESULT;
begin
if Instance.FVTable = nil then InitInstance;
// IHashServer is implemented by a singleton, no need for releasing old instance
Pointer(A):= @Instance;
Result:= TF_S_OK;
end;
{ THashServer }
class function THashServer.PBKDF1(Inst: PHashServer; HashAlg: IHash;
Password: Pointer; PassLen: Cardinal; Salt: Pointer; SaltLen: Cardinal;
Rounds, dkLen: Cardinal; var Key: PByteVector): TF_RESULT;
const
MAX_DIGEST_SIZE = 128; // = 1024 bits
var
hLen: Cardinal;
Digest: array[0 .. MAX_DIGEST_SIZE - 1] of Byte;
begin
hLen:= HashAlg.GetDigestSize;
if dkLen = 0 then dkLen:= hLen;
if (hLen < dkLen) or (hLen > MAX_DIGEST_SIZE) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
HashAlg.Init;
HashAlg.Update(Password, PassLen);
HashAlg.Update(Salt, SaltLen);
HashAlg.Done(@Digest);
while Rounds > 1 do begin
HashAlg.Init;
HashAlg.Update(@Digest, hLen);
HashAlg.Done(@Digest);
Dec(Rounds);
end;
Result:= ByteVectorFromPByte(Key, @Digest, dkLen);
end;
function GetStdInstance(AlgID: TF_AlgID; var Alg: IHash): TF_RESULT;
begin
case AlgID of
TF_ALG_MD5: Result:= GetMD5Algorithm(PMD5Alg(Alg));
TF_ALG_SHA1: Result:= GetSHA1Algorithm(PSHA1Alg(Alg));
TF_ALG_SHA256: Result:= GetSHA256Algorithm(PSHA256Alg(Alg));
TF_ALG_SHA512: Result:= GetSHA512Algorithm(PSHA512Alg(Alg));
TF_ALG_SHA224: Result:= GetSHA224Algorithm(PSHA224Alg(Alg));
TF_ALG_SHA384: Result:= GetSHA384Algorithm(PSHA384Alg(Alg));
else
case AlgID of
TF_ALG_CRC32: Result:= GetCRC32Algorithm(PCRC32Alg(Alg));
TF_ALG_JENKINS1: Result:= GetJenkinsOneAlgorithm(PJenkinsOneAlg(Alg));
else
Result:= TF_E_INVALIDARG;
end;
end;
end;
function GetOSSLInstance(AlgID: TF_AlgID; var Alg: IHash): TF_RESULT;
begin
Result:= TF_E_INVALIDARG;
end;
function GetHashInstance(AlgID: TF_AlgID; var Alg: IHash): TF_RESULT;
begin
case AlgID and TF_ENGINE_MASK of
TF_ENGINE_STD: Result:= GetStdInstance(AlgID and not TF_ENGINE_MASK, Alg);
TF_ENGINE_OSSL: Result:= GetOSSLInstance(AlgID and not TF_ENGINE_MASK, Alg);
else
Result:= TF_E_INVALIDARG;
end;
end;
class function THashServer.GetHMAC(Inst: PHashServer; var HMACAlg: IHMACAlgorithm;
const HashAlg: IHash): TF_RESULT;
begin
Result:= GetHMACAlgorithm(PHMACAlg(HMACAlg), HashAlg);
end;
(*
class function THashServer.GetByName(Inst: PHashServer; AName: Pointer;
CharSize: Integer; var Alg: IHashAlgorithm): TF_RESULT;
const
ANSI_a = Ord('a');
var
I: Integer;
PItem, Sentinel: PAlgItem;
P1, P2: PByte;
Found: Boolean;
UP2: Byte;
begin
PItem:= @Inst.FAlgTable;
Sentinel:= PItem;
Inc(Sentinel, Inst.FCount);
while PItem <> Sentinel do begin
P1:= @PItem.Name;
P2:= AName;
Found:= True;
I:= SizeOf(PItem.Name);
repeat
UP2:= P2^;
if UP2 >= ANSI_a then
UP2:= UP2 and not $20; { upcase }
if P1^ <> UP2 then begin
Found:= False;
Break;
end;
if P1^ = 0 then Break;
Inc(P1);
Inc(P2, CharSize);
Dec(I);
until I = 0;
if Found then begin
Result:= THashGetter(PItem.Getter)(Alg);
// Result:= TF_S_OK;
Exit;
end;
Inc(PItem);
end;
Result:= TF_E_INVALIDARG;
end;
class function THashServer.GetByIndex(Inst: PHashServer; Index: Integer;
var Alg: IHashAlgorithm): TF_RESULT;
begin
if Cardinal(Index) >= Cardinal(Length(Inst.FAlgTable)) then
Result:= TF_E_INVALIDARG
else
Result:= THashGetter(Inst.FAlgTable[Index].Getter)(Alg);
end;
class function THashServer.GetCount(Inst: PHashServer): Integer;
begin
Result:= Inst.FCount;
end;
class function THashServer.GetName(Inst: PHashServer; Index: Integer;
var Name: PByteVector): TF_RESULT;
var
Tmp: PByteVector;
P, P1: PByte;
I: Integer;
begin
if Cardinal(Index) >= Cardinal(Length(Instance.FAlgTable)) then
Result:= TF_E_INVALIDARG
else begin
P:= @Inst.FAlgTable[Index].Name;
P1:= P;
I:= 0;
repeat
if P1^ = 0 then Break;
Inc(P1);
Inc(I);
until I = 16;
if I = 0 then
Result:= TF_E_UNEXPECTED
else begin
Tmp:= nil;
Result:= ByteVectorAlloc(Tmp, I);
if Result = TF_S_OK then begin
Move(P^, Tmp.FData, I);
if Name <> nil then TtfRecord.Release(Name);
Name:= Tmp;
end;
end;
end;
end;
*)
{
class function THashServer.RegisterHash(Inst: PHashServer; Name: Pointer;
CharSize: Integer; Getter: THashGetter; var Index: Integer): TF_RESULT;
begin
// todo:
end;
}
end.
|
unit BusVal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, AdoDb, Db, CurrEdit, Mask, ToolEdit;
type
tcControl = ( tcDate, tcNumber, tcFloat, tcString );
TBusValDlg = class(TForm)
GroupBox1: TGroupBox;
cbCampos: TComboBox;
GroupBox2: TGroupBox;
edBuscar: TEdit;
GroupBox3: TGroupBox;
cbCaseSensitive: TCheckBox;
rbExacto: TRadioButton;
rbComienza: TRadioButton;
rbContiene: TRadioButton;
bbBuscar: TBitBtn;
bbSig: TBitBtn;
BitBtn3: TBitBtn;
Fecha: TDateEdit;
ceValor: TCurrencyEdit;
procedure FormCreate(Sender: TObject);
procedure bbBuscarClick(Sender: TObject);
procedure bbSigClick(Sender: TObject);
procedure cbCamposChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FDataSet: TAdoDataSet;
FCampos: TStringList;
FControl: tcControl;
procedure SetDataSet(const Value: TAdoDataSet);
procedure CargarCampos;
function BuscarValor( DesdeInicio: boolean ): boolean;
procedure Verificar;
public
{ Public declarations }
property DataSet: TAdoDataSet read FDataSet write SetDataSet;
procedure SetCampos( const aCampos: array of string );
end;
var
BusValDlg: TBusValDlg;
implementation
{$R *.DFM}
procedure TBusValDlg.FormCreate(Sender: TObject);
begin
if cbCampos.Items.Count = 0 then
begin
FCampos := TStringlist.create;
CargarCampos;
end;
end;
procedure TBusValDlg.bbBuscarClick(Sender: TObject);
var
Opciones: TLocateOptions;
begin
Verificar;
Opciones := [];
if not ( cbCaseSensitive.checked ) then
Opciones := [ loCaseInsensitive ];
if rbComienza.checked then
Opciones := Opciones + [ loPartialKey ];
if rbContiene.checked then
bbSig.Enabled := BuscarValor( true )
else
begin
if FControl = tcDate then
bbSig.Enabled := FDataSet.Locate( FCampos[ cbCampos.ItemIndex ], Fecha.date, Opciones )
else if FControl = tcNumber then
bbSig.Enabled := FDataSet.Locate( FCampos[ cbCampos.ItemIndex ], ceValor.value, Opciones )
else if FControl = tcFloat then
bbSig.Enabled := BuscarValor( true )
else
bbSig.Enabled := FDataSet.Locate( FCampos[ cbCampos.ItemIndex ], edBuscar.text, Opciones );
end;
end;
procedure TBusValDlg.SetDataSet(const Value: TAdoDataSet);
begin
FDataSet := Value;
if Value <> nil then
Self.FreeNotification( Value );
CargarCampos;
end;
procedure TBusValDlg.CargarCampos;
var
x: integer;
begin
cbCampos.Items.Clear;
if Assigned( FDataSet ) then
for x:=0 to FDataSet.FieldCount-1 do
if ( FDataSet.Fields[ x ].FieldKind = fkData ) and
( FDataSet.Fields[ x ].Visible ) then
begin
cbCampos.Items.Add( FDataSet.Fields[ x ].DisplayLabel );
FCampos.Add( FDataSet.Fields[ x ].FieldName );
end;
end;
procedure TBusValDlg.bbSigClick(Sender: TObject);
begin
Verificar;
bbSig.enabled := BuscarValor( false );
end;
function TBusValDlg.BuscarValor(DesdeInicio: boolean): boolean;
var
nPos: integer;
FBuscar, FBuscado: string;
begin
FDataSet.DisableControls;
try
Result := true;
if ( FControl = tcString ) and not ( cbCaseSensitive.checked ) then
FBuscar := AnsiUpperCase( edBuscar.text )
else
FBuscar := edBuscar.text;
if DesdeInicio then
FDataSet.first
else
FDataSet.next;
while not FDataSet.eof do
begin
if FControl = tcDate then
begin
if Fecha.date = FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]] then
exit;
end
else if FControl = tcNumber then
begin
if ceValor.Value = FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]] then
exit;
end
else if FControl = tcFloat then
begin
try
if FloatToStr( ceValor.Value ) = FloatToStr( FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]]) then
exit;
except
end;
end
else
begin
if not ( cbCaseSensitive.checked ) then
FBuscado := UpperCase( FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]])
else
FBuscado := FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]];
nPos := Pos( FBuscar, FBuscado );
if nPos = 1 then
begin
if not ( rbExacto.checked ) or
( FBuscar=FDataSet.FieldValues[ FCampos[ cbCampos.ItemIndex ]] ) then
exit
end
else if ( nPos > 1 ) and ( rbContiene.checked ) then
exit;
end;
FDataSet.next;
end;
Result := false;
finally
FDataSet.EnableControls;
end;
end;
procedure TBusValDlg.Verificar;
begin
if (( edBuscar.text = '' ) and ( FControl = tcString )) then
raise exception.create( 'Por favor, complete dato a buscar' );
if cbCampos.itemindex = -1 then
raise exception.create( 'Por favor, indique campo de busqueda' );
end;
procedure TBusValDlg.cbCamposChange(Sender: TObject);
var
FNombre: string;
ACampo: TField;
begin
if cbCampos.ItemIndex > -1 then
begin
FNombre := FCampos[ cbCampos.ItemIndex ];
ACampo := FDataSet.FindField( FNombre );
if ( ACampo <> nil ) then
begin
Case( ACampo.DataType ) of
ftDate, ftDateTime:
begin
edBuscar.Visible := false;
ceValor.Visible := false;
Fecha.Visible := true;
FControl := tcDate;
end;
ftFloat, ftCurrency, ftBCD:
begin
edBuscar.Visible := false;
ceValor.Visible := true;
Fecha.Visible := false;
FControl := tcFloat;
end;
ftSmallint, ftInteger, ftWord:
begin
edBuscar.Visible := false;
ceValor.Visible := true;
Fecha.Visible := false;
FControl := tcNumber;
end
else
begin
edBuscar.Visible := true;
Fecha.Visible := false;
ceValor.Visible := false;
FControl := tcString;
end;
end;
end;
end;
end;
procedure TBusValDlg.FormDestroy(Sender: TObject);
begin
FCampos.free;
end;
procedure TBusValDlg.SetCampos(const aCampos: array of string);
var
x, FPos: integer;
begin
cbCampos.Items.Clear;
FCampos.clear;
if Assigned( FDataSet ) then
for x:=0 to High( aCampos ) do
begin
FPos := FDataSet.FieldList.IndexOf( aCampos[ x ] );
if FPos > 0 then
if ( FDataSet.Fields[ FPos ].FieldKind = fkData ) and
( FDataSet.Fields[ FPos ].Visible ) then
begin
cbCampos.Items.Add( FDataSet.Fields[ FPos ].DisplayLabel );
FCampos.Add( FDataSet.Fields[ FPos ].FieldName );
end;
end;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraQuota;
interface
uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable;
type
Quota = record
USERNAME,
TABLESPACE_NAME: string;
UNLIMITID: boolean;
UNITS: string;
AMOUNT: Integer;
end;
TQuota = ^Quota;
TQuotaList = class(TObject)
private
FQuotaList: TList;
FOraSession: TOraSession;
FDSQuotaList: TVirtualTable;
FUSER: String;
function GetQuota(Index: Integer): TQuota;
procedure SetQuota(Index: Integer; Quota: TQuota);
function GetQuotaCount: Integer;
public
procedure QuotaAdd(Quota: TQuota);
procedure QuotaDelete(Index: Integer);
property QuotaCount: Integer read GetQuotaCount;
property QuotaItems[Index: Integer]: TQuota read GetQuota write SetQuota;
procedure CopyFrom(QuotaList: TQuotaList);
property USER: String read FUSER write FUSER;
property DSQuotaList: TVirtualTable read FDSQuotaList;
property OraSession: TOraSession read FOraSession write FOraSession;
constructor Create;
destructor Destroy; override;
procedure SetDDL;
function GetDDL: string;
function Quota(QuotaScript: string) : boolean;
end;
function GetQuotas: string;
implementation
uses util, frmSchemaBrowser;
{********************** TQuota ***********************************}
function GetQuotas: string;
begin
result :=
'select username, T.tablespace_name, '
+' decode(mod(max_bytes,1048576), -1, ''YES'', ''NO'') UNL, '
+' decode(mod(max_bytes,1048576), 0, max_bytes / 1048576, -1, 0, max_bytes / 1024) amt, '
+' decode(mod(max_bytes,1048576), 0, ''MB'', -1, '''', null, null, ''KB'') unit '
+' from dba_ts_quotas q, dba_tablespaces t '
+' where q.TABLESPACE_NAME (+) = t.TABLESPACE_NAME '
+' AND username (+) = :pName ';
end;
constructor TQuotaList.Create;
begin
FQuotaList := TList.Create;
FDSQuotaList := TVirtualTable.Create(nil);
end;
destructor TQuotaList.Destroy;
var
i : Integer;
FQuota: TQuota;
begin
try
if FQuotaList.Count > 0 then
begin
for i := FQuotaList.Count - 1 downto 0 do
begin
FQuota := FQuotaList.Items[i];
Dispose(FQuota);
end;
end;
finally
FQuotaList.Free;
end;
FDSQuotaList.Free;
inherited;
end;
procedure TQuotaList.QuotaAdd(Quota: TQuota);
begin
FQuotaList.Add(Quota);
end;
procedure TQuotaList.QuotaDelete(Index: Integer);
begin
TObject(FQuotaList.Items[Index]).Free;
FQuotaList.Delete(Index);
end;
function TQuotaList.GetQuota(Index: Integer): TQuota;
begin
Result := FQuotaList.Items[Index];
end;
procedure TQuotaList.SetQuota(Index: Integer; Quota: TQuota);
begin
if Assigned(Quota) then
FQuotaList.Items[Index] := Quota;
end;
function TQuotaList.GetQuotaCount: Integer;
begin
Result := FQuotaList.Count;
end;
procedure TQuotaList.CopyFrom(QuotaList: TQuotaList);
var
i: integer;
begin
FOraSession := QuotaList.OraSession;
FUSER := QuotaList.USER;
for i := 0 to QuotaList.QuotaCount -1 do
FQuotaList.Add(TQuota(QuotaList.QuotaItems[i]));
end;
procedure TQuotaList.SetDDL;
var
FQuota: TQuota;
q: TOraQuery;
begin
q := TOraQuery.Create(nil);
q.Session := FOraSession;
q.SQL.Text := GetQuotas;
q.ParamByName('pName').AsString := FUSER;
q.Open;
CopyDataSet(q, FDSQuotaList);
while not q.Eof do
begin
if q.FieldByName('USERNAME').AsString = FUSER then
begin
new(FQuota);
FQuota^.USERNAME := q.FieldByName('USERNAME').AsString;
FQuota^.TABLESPACE_NAME := q.FieldByName('TABLESPACE_NAME').AsString;
FQuota^.UNLIMITID := q.FieldByName('UNL').AsString = 'YES';
FQuota^.UNITS := q.FieldByName('UNIT').AsString;
FQuota^.AMOUNT := q.FieldByName('AMT').AsInteger;
QuotaAdd(FQuota);
end;
q.Next;
end;
q.close;
end;
function TQuotaList.GetDDL: string;
var
i: integer;
FQuota: TQuota;
begin
result := '';
with self do
begin
for i := 0 to GetQuotaCount -1 do
begin
FQuota := QuotaItems[i];
if FQuota.UNLIMITID then
result := result + ln + 'ALTER USER '+FQuota.USERNAME +' ' + 'QUOTA UNLIMITED ON '+ FQuota.TABLESPACE_NAME+ ';';
if FQuota.AMOUNT > 0 then
result := result + ln + 'ALTER USER '+FQuota.USERNAME +' ' + 'QUOTA '+IntToStr(FQuota.AMOUNT)+FQuota.UNITS+ ' ON '+ FQuota.TABLESPACE_NAME +';';
end;
end; //with self
end;
function TQuotaList.Quota(QuotaScript: string) : boolean;
begin
result := ExecSQL(QuotaScript, '', FOraSession);
end;
end.
|
unit LUX.Map.D1;
interface //#################################################################### ■
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TArray1D<T_Item>
TArray1D<T_Item> = class
private
_AllX :Integer;
///// メソッド
procedure MakeArray;
function XtoI( const X_:Integer ) :Integer; inline;
protected
_Item :array of T_Item;
_CountX :Integer;
_MarginX :Integer;
///// アクセス
function GetItem( const X_:Integer ) :T_Item; virtual;
procedure SetItem( const X_:Integer; const Item_:T_Item ); virtual;
procedure SetCountX( const CountX_:Integer ); virtual;
procedure SetMarginX( const MarginX_:Integer ); virtual;
public
constructor Create; overload;
constructor Create( const CountX_:Integer ); overload;
constructor Create( const CountX_,MarginX_:Integer ); overload;
procedure AfterConstruction; override;
destructor Destroy; override;
///// プロパティ
property Item[ const X_:Integer ] :T_Item read GetItem write SetItem; default;
property Count :Integer read _CountX write SetCountX;
property CountX :Integer read _CountX write SetCountX;
property Margin :Integer read _MarginX write SetMarginX;
property MarginX :Integer read _MarginX write SetMarginX;
///// メソッド
class procedure Swap( var Array0_,Array1_:TArray1D<T_Item> ); static;
procedure MakeEdgeLoop;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TBricArray1D<T_Item>
TBricArray1D<T_Item> = class( TArray1D<T_Item> )
private
protected
///// アクセス
function GetGridX :Integer;
procedure SetGridX( const GridX_:Integer );
public
///// プロパティ
property Bric[ const X_:Integer ] :T_Item read GetItem write SetItem; default;
property BricN :Integer read _CountX write SetCountX;
property BricX :Integer read _CountX write SetCountX;
property GridN :Integer read GetGridX write SetGridX;
property GridX :Integer read GetGridX write SetGridX;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGridArray1D<T_Item>
TGridArray1D<T_Item> = class( TArray1D<T_Item> )
private
protected
///// アクセス
function GetBricX :Integer;
procedure SetBricX( const BricX_:Integer );
public
constructor Create; overload;
constructor Create( const BricX_:Integer ); overload;
constructor Create( const BricX_,MarginX_:Integer ); overload;
destructor Destroy; override;
///// プロパティ
property Grid[ const X_:Integer ] :T_Item read GetItem write SetItem; default;
property GridN :Integer read _CountX write SetCountX;
property GridX :Integer read _CountX write SetCountX;
property BricN :Integer read GetBricX write SetBricX;
property BricX :Integer read GetBricX write SetBricX;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TArray1D<T_Item>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// メソッド
procedure TArray1D<T_Item>.MakeArray;
begin
_AllX := _MarginX + _CountX + _MarginX;
SetLength( _Item, _AllX );
end;
function TArray1D<T_Item>.XtoI( const X_:Integer ) :Integer;
begin
Result := _MarginX + X_;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
procedure TArray1D<T_Item>.SetCountX( const CountX_:Integer );
begin
_CountX := CountX_; MakeArray;
end;
procedure TArray1D<T_Item>.SetMarginX( const MarginX_:Integer );
begin
_MarginX := MarginX_; MakeArray;
end;
function TArray1D<T_Item>.GetItem( const X_:Integer ) :T_Item;
begin
Result := _Item[ XtoI( X_ ) ];
end;
procedure TArray1D<T_Item>.SetItem( const X_:Integer; const Item_:T_Item );
begin
_Item[ XtoI( X_ ) ] := Item_;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TArray1D<T_Item>.Create;
begin
Create( 0, 0 );
end;
constructor TArray1D<T_Item>.Create( const CountX_:Integer );
begin
Create( CountX_, 0 );
end;
constructor TArray1D<T_Item>.Create( const CountX_,MarginX_:Integer );
begin
inherited Create;
_CountX := CountX_;
_MarginX := MarginX_;
end;
procedure TArray1D<T_Item>.AfterConstruction;
begin
MakeArray;
end;
destructor TArray1D<T_Item>.Destroy;
begin
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
class procedure TArray1D<T_Item>.Swap( var Array0_,Array1_:TArray1D<T_Item> );
var
A :TArray1D<T_Item>;
begin
A := Array0_; Array0_ := Array1_; Array1_ := A;
end;
procedure TArray1D<T_Item>.MakeEdgeLoop;
var
X :Integer;
begin
for X := -_MarginX to -1 do Item[ X ] := Item[ X + _CountX ];
for X := _CountX to _CountX+_MarginX-1 do Item[ X ] := Item[ X - _CountX ];
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TBricArray1D<T_Item>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TBricArray1D<T_Item>.GetGridX :Integer;
begin
Result := BricX + 1;
end;
procedure TBricArray1D<T_Item>.SetGridX( const GridX_:Integer );
begin
BricX := GridX_ - 1;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGridArray1D<T_Item>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGridArray1D<T_Item>.GetBricX :Integer;
begin
Result := _CountX - 1;
end;
procedure TGridArray1D<T_Item>.SetBricX( const BricX_:Integer );
begin
_CountX := BricX_ + 1; MakeArray;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGridArray1D<T_Item>.Create;
begin
Create( 0, 0 );
end;
constructor TGridArray1D<T_Item>.Create( const BricX_:Integer );
begin
Create( BricX_, 0 );
end;
constructor TGridArray1D<T_Item>.Create( const BricX_,MarginX_:Integer );
begin
inherited;
_CountX := BricX_ + 1;
end;
destructor TGridArray1D<T_Item>.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit ResUpdate;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Resource update functions used by both Setup and the compiler
$jrsoftware: issrc/Projects/ResUpdate.pas,v 1.4 2009/03/20 13:49:17 mlaan Exp $
}
interface
{$I VERSION.INC}
uses
Windows, SysUtils, FileClass;
function ReadSignatureAndChecksumFields(const F: TCustomFile;
var ASignatureAddress, ASignatureSize, AChecksum: DWORD): Boolean;
function SeekToResourceData(const F: TCustomFile; const ResType, ResId: Cardinal): Cardinal;
function UpdateSignatureAndChecksumFields(const F: TCustomFile;
const ASignatureAddress, ASignatureSize, AChecksum: DWORD): Boolean;
procedure UpdateManifestRequestedExecutionLevel(const F: TCustomFile;
const RequireAdministrator: Boolean);
implementation
uses
Int64Em;
const
IMAGE_NT_SIGNATURE = $00004550;
IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
IMAGE_SIZEOF_SHORT_NAME = 8;
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2;
IMAGE_DIRECTORY_ENTRY_SECURITY = 4;
type
PImageFileHeader = ^TImageFileHeader;
TImageFileHeader = packed record
Machine: Word;
NumberOfSections: Word;
TimeDateStamp: DWORD;
PointerToSymbolTable: DWORD;
NumberOfSymbols: DWORD;
SizeOfOptionalHeader: Word;
Characteristics: Word;
end;
PImageDataDirectory = ^TImageDataDirectory;
TImageDataDirectory = record
VirtualAddress: DWORD;
Size: DWORD;
end;
PImageOptionalHeader = ^TImageOptionalHeader;
TImageOptionalHeader = packed record
{ Standard fields. }
Magic: Word;
MajorLinkerVersion: Byte;
MinorLinkerVersion: Byte;
SizeOfCode: DWORD;
SizeOfInitializedData: DWORD;
SizeOfUninitializedData: DWORD;
AddressOfEntryPoint: DWORD;
BaseOfCode: DWORD;
BaseOfData: DWORD;
{ NT additional fields. }
ImageBase: DWORD;
SectionAlignment: DWORD;
FileAlignment: DWORD;
MajorOperatingSystemVersion: Word;
MinorOperatingSystemVersion: Word;
MajorImageVersion: Word;
MinorImageVersion: Word;
MajorSubsystemVersion: Word;
MinorSubsystemVersion: Word;
Win32VersionValue: DWORD;
SizeOfImage: DWORD;
SizeOfHeaders: DWORD;
CheckSum: DWORD;
Subsystem: Word;
DllCharacteristics: Word;
SizeOfStackReserve: DWORD;
SizeOfStackCommit: DWORD;
SizeOfHeapReserve: DWORD;
SizeOfHeapCommit: DWORD;
LoaderFlags: DWORD;
NumberOfRvaAndSizes: DWORD;
DataDirectory: packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of TImageDataDirectory;
end;
TISHMisc = packed record
case Integer of
0: (PhysicalAddress: DWORD);
1: (VirtualSize: DWORD);
end;
PImageSectionHeader = ^TImageSectionHeader;
TImageSectionHeader = packed record
Name: packed array[0..IMAGE_SIZEOF_SHORT_NAME-1] of Byte;
Misc: TISHMisc;
VirtualAddress: DWORD;
SizeOfRawData: DWORD;
PointerToRawData: DWORD;
PointerToRelocations: DWORD;
PointerToLinenumbers: DWORD;
NumberOfRelocations: Word;
NumberOfLinenumbers: Word;
Characteristics: DWORD;
end;
TImageResourceDirectory = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
NumberOfNamedEntries: Word;
NumberOfIdEntries: Word;
end;
TImageResourceDirectoryEntry = packed record
Id: DWORD;
Offset: DWORD;
end;
TImageResourceDataEntry = packed record
OffsetToData: DWORD;
Size: DWORD;
CodePage: DWORD;
Reserved: DWORD;
end;
procedure Error(const Msg: String);
begin
raise Exception.Create('Resource update error: ' + Msg);
end;
function SeekToPEHeader(const F: TCustomFile): Boolean;
var
DosHeader: packed record
Sig: array[0..1] of AnsiChar;
Other: array[0..57] of Byte;
PEHeaderOffset: LongWord;
end;
Sig: DWORD;
begin
Result := False;
F.Seek(0);
if F.Read(DosHeader, SizeOf(DosHeader)) = SizeOf(DosHeader) then begin
if (DosHeader.Sig[0] = 'M') and (DosHeader.Sig[1] = 'Z') and
(DosHeader.PEHeaderOffset <> 0) then begin
F.Seek(DosHeader.PEHeaderOffset);
if F.Read(Sig, SizeOf(Sig)) = SizeOf(Sig) then
if Sig = IMAGE_NT_SIGNATURE then
Result := True;
end;
end;
end;
function SeekToAndReadPEOptionalHeader(const F: TCustomFile;
var OptHeader: TImageOptionalHeader; var OptHeaderOffset: Integer64): Boolean;
var
Header: TImageFileHeader;
begin
Result := False;
if SeekToPEHeader(F) then begin
if (F.Read(Header, SizeOf(Header)) = SizeOf(Header)) and
(Header.SizeOfOptionalHeader = SizeOf(OptHeader)) then begin
OptHeaderOffset := F.Position;
if F.Read(OptHeader, SizeOf(OptHeader)) = SizeOf(OptHeader) then
if OptHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC then
Result := True;
end;
end;
end;
procedure FindResourceSection(const F: TCustomFile;
var SectionVirtualAddr, SectionPhysOffset, SectionPhysSize: Cardinal);
var
EXESig: Word;
PEHeaderOffset, PESig: Cardinal;
PEHeader: TImageFileHeader;
PEOptHeader: TImageOptionalHeader;
PESectionHeader: TImageSectionHeader;
I: Integer;
begin
{ Read DOS header }
F.Seek(0);
F.ReadBuffer(EXESig, SizeOf(EXESig));
if EXESig <> $5A4D {'MZ'} then
Error('File isn''t an EXE file (1)');
F.Seek($3C);
F.ReadBuffer(PEHeaderOffset, SizeOf(PEHeaderOffset));
if PEHeaderOffset = 0 then
Error('File isn''t a PE file (1)');
{ Read PE header & optional header }
F.Seek(PEHeaderOffset);
F.ReadBuffer(PESig, SizeOf(PESig));
if PESig <> $00004550 {'PE'#0#0} then
Error('File isn''t a PE file (2)');
F.ReadBuffer(PEHeader, SizeOf(PEHeader));
if PEHeader.SizeOfOptionalHeader <> SizeOf(PEOptHeader) then
Error('File isn''t a PE file (3)');
F.ReadBuffer(PEOptHeader, SizeOf(PEOptHeader));
if PEOptHeader.Magic <> IMAGE_NT_OPTIONAL_HDR32_MAGIC then
Error('File isn''t a PE file (4)');
{ Scan section headers for resource section }
if (PEOptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = 0) or
(PEOptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = 0) then
Error('No resources (1)');
SectionVirtualAddr := PEOptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
SectionPhysOffset := 0;
for I := 0 to PEHeader.NumberOfSections-1 do begin
F.ReadBuffer(PESectionHeader, SizeOf(PESectionHeader));
if (PESectionHeader.VirtualAddress = SectionVirtualAddr) and
(PESectionHeader.SizeOfRawData <> 0) then begin
SectionPhysOffset := PESectionHeader.PointerToRawData;
SectionPhysSize := PESectionHeader.SizeOfRawData;
Break;
end;
end;
if SectionPhysOffset = 0 then
Error('No resources (2)');
end;
function FindResOffset(const F: TCustomFile; const AnyId: Boolean;
const Id: Cardinal; const FindSubdir: Boolean; var Offset: Cardinal): Boolean;
var
Dir: TImageResourceDirectory;
Entry: TImageResourceDirectoryEntry;
I: Integer;
begin
F.ReadBuffer(Dir, SizeOf(Dir));
{ Skip over named entries }
for I := 0 to Dir.NumberOfNamedEntries-1 do
F.ReadBuffer(Entry, SizeOf(Entry));
{ Now process ID entries }
Result := False;
for I := 0 to Dir.NumberOfIdEntries-1 do begin
F.ReadBuffer(Entry, SizeOf(Entry));
if (AnyId or (Entry.Id = Id)) and
((Entry.Offset and $80000000 <> 0) = FindSubdir) then begin
Offset := Entry.Offset and $7FFFFFFF;
Result := True;
Break;
end;
end;
end;
function SeekToResourceData(const F: TCustomFile; const ResType, ResId: Cardinal): Cardinal;
{ Seeks to the specified resource's data, and returns its size. Raises an
exception if the resource cannot be found. }
var
SectionVirtualAddr, SectionPhysOffset, SectionPhysSize, Ofs: Cardinal;
DataEntry: TImageResourceDataEntry;
begin
FindResourceSection(F, SectionVirtualAddr, SectionPhysOffset, SectionPhysSize);
{ Scan the resource directory }
F.Seek(SectionPhysOffset);
if not FindResOffset(F, False, ResType, True, Ofs) then
Error('Can''t find resource (1)');
F.Seek(SectionPhysOffset + Ofs);
if not FindResOffset(F, False, ResId, True, Ofs) then
Error('Can''t find resource (2)');
F.Seek(SectionPhysOffset + Ofs);
if not FindResOffset(F, True, 0, False, Ofs) then
Error('Can''t find resource (3).');
F.Seek(SectionPhysOffset + Ofs);
F.ReadBuffer(DataEntry, SizeOf(DataEntry));
{ Sanity check: DataEntry.OffsetToData is an RVA. It's technically possible
for the RVA to point to a different section, but we don't support that. }
if Cardinal(DataEntry.OffsetToData) < SectionVirtualAddr then
Error('Invalid resource (1)');
if Cardinal(DataEntry.OffsetToData - SectionVirtualAddr + DataEntry.Size) > SectionPhysSize then
Error('Invalid resource (2)');
{ Seek to the resource }
F.Seek(SectionPhysOffset + (DataEntry.OffsetToData - SectionVirtualAddr));
Result := DataEntry.Size;
end;
procedure UpdateManifestRequestedExecutionLevel(const F: TCustomFile;
const RequireAdministrator: Boolean);
const
ElementText: AnsiString = '<requestedExecutionLevel level="';
Levels: array[Boolean] of AnsiString = (
'highestAvailable" ',
'requireAdministrator"');
var
S: AnsiString;
Offset: Integer64;
P: Integer;
begin
{ Read the manifest resource into a string }
SetString(S, nil, SeekToResourceData(F, 24, 1));
Offset := F.Position;
F.ReadBuffer(S[1], Length(S));
{ Locate and update the requestedExecutionLevel element }
P := Pos(ElementText, S);
if P = 0 then
Error('Element not found');
Inc(P, Length(ElementText));
if Copy(S, P+21, 10) <> ' uiAccess=' then
Error('Level too short');
Inc64(Offset, P-1);
F.Seek64(Offset);
F.WriteAnsiString(Levels[RequireAdministrator]);
end;
function ReadSignatureAndChecksumFields(const F: TCustomFile;
var ASignatureAddress, ASignatureSize, AChecksum: DWORD): Boolean;
{ Reads the signature and checksum fields in the specified file's header.
If the file is not a valid PE executable, False is returned. }
var
OptHeader: TImageOptionalHeader;
OptHeaderOffset: Integer64;
begin
Result := SeekToAndReadPEOptionalHeader(F, OptHeader, OptHeaderOffset);
if Result then begin
ASignatureAddress := OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;
ASignatureSize := OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
AChecksum := OptHeader.CheckSum;
end;
end;
function UpdateSignatureAndChecksumFields(const F: TCustomFile;
const ASignatureAddress, ASignatureSize, AChecksum: DWORD): Boolean;
{ Sets the signature and checksum fields in the specified file's header.
If the file is not a valid PE executable, False is returned. }
var
OptHeader: TImageOptionalHeader;
OptHeaderOffset: Integer64;
begin
Result := SeekToAndReadPEOptionalHeader(F, OptHeader, OptHeaderOffset);
if Result then begin
OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress := ASignatureAddress;
OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size := ASignatureSize;
OptHeader.CheckSum := AChecksum;
F.Seek64(OptHeaderOffset);
F.WriteBuffer(OptHeader, SizeOf(OptHeader));
end;
end;
end.
|
unit elCustomEdit_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Forms"
// Модуль: "w:/common/components/gui/Garant/Daily/Forms/elCustomEdit_Form.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::Everest::elCustomEdit
//
// Форма для тестирования TelCustomEdit
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
vcmInterfaces,
elCustomEdit,
vcmEntityForm,
vcmUserControls,
l3StringIDEx
{$If not defined(NoScripts)}
,
tfwScriptingInterfaces
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwInteger
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
elCustomEdit_ut_elCustomEdit_UserType,
Classes {a},
l3InterfacedComponent {a},
vcmComponent {a},
vcmBaseEntities {a},
vcmEntities {a},
vcmExternalInterfaces {a}
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
const
{ elCustomEditIDs }
fm_elCustomEditForm : TvcmFormDescriptor = (rFormID : (rName : 'elCustomEditForm'; rID : 0); rFactory : nil);
{ Идентификатор формы TelCustomEditForm }
type
elCustomEditFormDef = interface(IUnknown)
{* Идентификатор формы elCustomEdit }
['{83F3F220-AFBC-45DC-8C59-16D7972E06BB}']
end;//elCustomEditFormDef
TelCustomEditForm = {final form} class(TvcmEntityForm, elCustomEditFormDef)
{* Форма для тестирования TelCustomEdit }
Entities : TvcmEntities;
private
// private fields
f_Edit : TelCustomEdit;
{* Поле для свойства Edit}
protected
procedure MakeControls; override;
protected
// overridden protected methods
procedure InitControls; override;
{* Процедура инициализации контролов. Для перекрытия в потомках }
public
// public properties
property Edit: TelCustomEdit
read f_Edit;
end;//TelCustomEditForm
{$IfEnd} //nsTest AND not NoVCM
implementation
{$R *.DFM}
{$If defined(nsTest) AND not defined(NoVCM)}
uses
Forms
{$If not defined(NoScripts)}
,
tfwScriptEngine
{$IfEnd} //not NoScripts
,
l3MessageID
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
var
{ Локализуемые строки ut_elCustomEditLocalConstants }
str_ut_elCustomEditCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_elCustomEditCaption'; rValue : 'Форма для тестирования TelCustomEdit');
{ Заголовок пользовательского типа "Форма для тестирования TelCustomEdit" }
type
Tkw_elCustomEdit_Component_Edit = class(TtfwControlString)
{* Слово словаря для идентификатора компонента Edit
----
*Пример использования*:
[code]
компонент::Edit TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_elCustomEdit_Component_Edit
// start class Tkw_elCustomEdit_Component_Edit
{$If not defined(NoScripts)}
function Tkw_elCustomEdit_Component_Edit.GetString: AnsiString;
{-}
begin
Result := 'Edit';
end;//Tkw_elCustomEdit_Component_Edit.GetString
{$IfEnd} //not NoScripts
type
Tkw_Form_elCustomEdit = class(TtfwControlString)
{* Слово словаря для идентификатора формы elCustomEdit
----
*Пример использования*:
[code]
'aControl' форма::elCustomEdit TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_Form_elCustomEdit
// start class Tkw_Form_elCustomEdit
{$If not defined(NoScripts)}
function Tkw_Form_elCustomEdit.GetString: AnsiString;
{-}
begin
Result := 'elCustomEditForm';
end;//Tkw_Form_elCustomEdit.GetString
{$IfEnd} //not NoScripts
type
Tkw_elCustomEdit_Edit_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола Edit формы elCustomEdit }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_elCustomEdit_Edit_ControlInstance
// start class Tkw_elCustomEdit_Edit_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_elCustomEdit_Edit_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TelCustomEditForm).Edit);
end;//Tkw_elCustomEdit_Edit_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
procedure TelCustomEditForm.InitControls;
//#UC START# *4A8E8F2E0195_4BCE9D210265_var*
//#UC END# *4A8E8F2E0195_4BCE9D210265_var*
begin
//#UC START# *4A8E8F2E0195_4BCE9D210265_impl*
inherited;
WindowState := wsMaximized;
Edit.Left := 0;
Edit.Top := 0;
//#UC END# *4A8E8F2E0195_4BCE9D210265_impl*
end;//TelCustomEditForm.InitControls
procedure TelCustomEditForm.MakeControls;
begin
inherited;
f_Edit := TelCustomEdit.Create(Self);
f_Edit.Name := 'Edit';
with AddUsertype(ut_elCustomEditName,
str_ut_elCustomEditCaption,
str_ut_elCustomEditCaption,
false,
-1,
-1,
'',
nil,
nil,
nil,
vcm_ccNone) do
begin
end;//with AddUsertype(ut_elCustomEditName
end;
{$IfEnd} //nsTest AND not NoVCM
initialization
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_elCustomEdit_Component_Edit
Tkw_elCustomEdit_Component_Edit.Register('компонент::Edit', TelCustomEdit);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация фабрики формы elCustomEdit
fm_elCustomEditForm.SetFactory(TelCustomEditForm.Make);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_Form_elCustomEdit
Tkw_Form_elCustomEdit.Register('форма::elCustomEdit', TelCustomEditForm);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_elCustomEdit_Edit_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TelCustomEditForm.Edit', Tkw_elCustomEdit_Edit_ControlInstance);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Инициализация str_ut_elCustomEditCaption
str_ut_elCustomEditCaption.Init;
{$IfEnd} //nsTest AND not NoVCM
end. |
unit MultiLineButton;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Windows;
type
TMultiLineButton = class(TButton)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
procedure CreateParams(var Params : TCreateParams); override;
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('componenteOW', [TMultiLineButton]);
end;
{ TMultiLineButton }
procedure TMultiLineButton.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or bs_Multiline;
end;
end.
|
unit DaoFireDac;
interface
uses Base, Rtti, Atributos,FireDAC.Comp.UI,FireDAC.Comp.Client{uib}, system.SysUtils;
type
//TDaoUib antigamente, agora correponde aos componetes do TFireDac
TDaoFDac = class(TDaoBase)
private
FDatabase: TFDConnection;
FDTransaction: TFDTransaction;
// Este método configura os parâmetros da AQuery.
protected
// métodos responsáveis por setar os parâmetros
procedure QryParamInteger(ARecParams: TRecParams); override;
procedure QryParamString(ARecParams: TRecParams); override;
procedure QryParamDate(ARecParams: TRecParams); override;
procedure QryParamCurrency(ARecParams: TRecParams); override;
procedure QryParamVariant(ARecParams: TRecParams); override;
//métodos para setar os variados tipos de campos
procedure SetaCamposInteger(ARecParams: TRecParams); override;
procedure SetaCamposString(ARecParams: TRecParams); override;
procedure SetaCamposDate(ARecParams: TRecParams); override;
procedure SetaCamposCurrency(ARecParams: TRecParams); override;
function ExecutaQuery: Integer; override;
procedure FechaQuery; override;
public
Qry: TFDQuery;
constructor Create(ADatabase: TFDConnection ; ATransacao: TFDTransaction);
function Inserir(ATabela: TTabela): Integer; override;
function Salvar(ATabela: TTabela): Integer; override;
function Excluir(ATabela: TTabela): Integer; override;
function Buscar(ATabela:TTabela): Integer; override;
function InTransaction: Boolean; override;
procedure StartTransaction; override;
procedure Commit; override;
procedure RollBack; override;
end;
implementation
{ TDaoFDac }
uses Vcl.forms, dialogs, System.TypInfo;
constructor TDaoFDac.Create(ADatabase: TFDConnection; ATransacao: TFDTransaction);
begin
inherited Create;
if not Assigned(ADatabase) then
raise Exception.Create('TFDConnection não informado!');
if not Assigned(ATransacao) then
raise Exception.Create('TFDTransaction não informado!');
FDatabase := ADatabase;
FDTransaction := ATransacao;
Qry := TFDQuery.Create(Application);
Qry.Connection := FDatabase;
Qry.Transaction := FDTransaction;
end;
function TDaoFDac.InTransaction: Boolean;
begin
Result := FDTransaction.Connection.Connected;
end;
procedure TDaoFDac.QryParamCurrency(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).Params.ParamByName(Campo).AsCurrency := Prop.GetValue(Tabela).AsCurrency;
end;
end;
procedure TDaoFDac.QryParamDate(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).Params.ParamByName(Campo).AsDateTime := Prop.GetValue(Tabela).AsType<TDateTime>;
end;
end;
procedure TDaoFDac.QryParamInteger(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).Params.ParamByName(Campo).AsInteger := Prop.GetValue(Tabela).AsInteger;
end;
end;
procedure TDaoFDac.QryParamString(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).Params.ParamByName(Campo).AsString := Prop.GetValue(Tabela).AsString;
end;
end;
procedure TDaoFDac.QryParamVariant(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).Params.ParamValues[Campo] := Prop.GetValue(Tabela).AsVariant;
end;
end;
procedure TDaoFDac.StartTransaction;
begin
FDTransaction.StartTransaction;
end;
procedure TDaoFDac.RollBack;
begin
FDTransaction.RollBack;
end;
function TDaoFDac.Buscar(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
Dados: TFDQuery;
begin
Dados := TFDQuery.Create(nil);
try
//crio uma variável do tipo TFuncReflexao - um método anônimo
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Dados do
begin
Connection := FDatabase;
Transaction := FDTransaction;
sql.Text := GerarSqlSelect(ATabela);
for Campo in ACampos.PKs do
begin
// setando os parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Dados);
end;
end;
Open;
Result := Fields.Count;
if Result > 0 then
begin
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
SetaDadosTabela(PropRtti, Campo, ATabela, Dados);
end;
end;
end;
end;
//reflection da tabela e abertura da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
finally
Dados.Free;
end;
end;
procedure TDaoFDac.Commit;
begin
FDTransaction.Commit;
end;
procedure TDaoFDac.FechaQuery;
begin
Qry.Close;
Qry.SQL.Clear;
end;
function TDaoFDac.ExecutaQuery: Integer;
begin
with Qry do
begin
Prepare();
ExecSQL;
Result := RowsAffected;
end;
end;
function TDaoFDac.Excluir(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
//crio uma variável do tipo TFuncReflexao - um método anônimo
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
Qry.Close;
Qry.SQL.Clear;
Qry.SQL.Text := GerarSqlDelete(ATabela);
//percorrer todos os campos da chave primária
for Campo in PegaPks(ATabela) do
begin
// setando os parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
//reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
end;
function TDaoFDac.Inserir(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
Result := 0;
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Qry do
begin
close;
SQL.clear;
SQL.Text := GerarSqlInsert(ATabela, ACampos.TipoRtti);
//valor dos parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
//reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
end;
function TDaoFDac.Salvar(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
Result := 0;
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Qry do
begin
close;
sql.Clear;
sql.Text := GerarSqlUpdate(ATabela, Acampos.TipoRtti);
//valor dos parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
//reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
end;
procedure TDaoFDac.SetaCamposCurrency(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).Fields.FieldByName(Campo).AsCurrency);
end;
end;
procedure TDaoFDac.SetaCamposDate(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).Fields.FieldByName(Campo).AsDateTime);
end;
end;
procedure TDaoFDac.SetaCamposInteger(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela,TFDQuery(Qry).FieldByName(Campo).AsInteger);
end;
end;
procedure TDaoFDac.SetaCamposString(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).Fields.FieldByName(Campo).AsString);
end;
end;
end.
|
unit Unbound.Game.Serialization;
interface
uses
System.SysUtils,
System.Classes,
System.IOUtils,
System.Math,
Pengine.Utility,
Pengine.ICollections,
Pengine.IntMaths,
Pengine.Vector,
Pengine.Color,
Pengine.Formatting;
type
// TODO: Don't create a new serializer object for nested types
// - Use the existing one and keep a stack of UBSParents
EUBSError = class(Exception);
TUBSTag = (
// Nil type
utNil,
// Basic/Nested structures
utMap,
utList,
// Common Primitives
utInteger,
utSingle,
utBoolean,
utString,
utByteArray,
// Utility
utGUID,
// Integer math
utIntBounds1,
utIntBounds2,
utIntBounds3,
utIntVector2,
utIntVector3,
// Vector math
utBounds1,
utBounds2,
utBounds3,
utVector2,
utVector3,
// Color
utColorRGB,
utColorRGBA
);
TUBSClass = class of TUBSValue;
TUBSValue = class
public const
// BinaryFileSignature: array [0 .. 3] of Byte = (27, Ord('U'), Ord('B'), Ord('S'));
BinaryFileSignature: array [0 .. 3] of AnsiChar = #27'UBS';
public type
TUBSFormatMode = (
ufPretty,
ufInline,
ufMinify
);
IFormatter = interface(IFormatter<TUBSValue>)
function GetMode: TUBSFormatMode;
procedure SetMode(const Value: TUBSFormatMode);
function GetIndentWidth: Integer;
procedure SetIndentWidth(const Value: Integer);
property Mode: TUBSFormatMode read GetMode write SetMode;
property IndentWidth: Integer read GetIndentWidth write SetIndentWidth;
end;
TFormatter = class(TFormatter<TUBSValue>, IFormatter)
public const
DefaultMode = ufPretty;
DefaultIndentWidth = 2;
private
FBuilder: TStringBuilder;
FIndentLevel: Integer;
// Format-Settings
FMode: TUBSFormatMode;
FIndentWidth: Integer;
function GetMode: TUBSFormatMode;
procedure SetMode(const Value: TUBSFormatMode);
function GetIndentWidth: Integer;
procedure SetIndentWidth(const Value: Integer);
public
constructor Create; override;
function Format: string; override;
property Mode: TUBSFormatMode read GetMode write SetMode;
property IndentWidth: Integer read GetIndentWidth write SetIndentWidth;
property Builder: TStringBuilder read FBuilder;
procedure Indent; inline;
procedure Unindent; inline;
procedure AddIndentation; inline;
procedure NewLine; inline;
property IndentLevel: Integer read FIndentLevel;
end;
protected
procedure FormatInternal(AFormatter: TFormatter); virtual; abstract;
procedure SaveInternal(AWriter: TBinaryWriter); virtual; abstract;
procedure LoadInternal(AReader: TBinaryReader); virtual; abstract;
public
constructor Create; virtual;
class function CreateTyped(ATag: TUBSTag): TUBSValue; static;
class function GetTag: TUBSTag; virtual; abstract;
class function GetTagName: string;
procedure Save(AWriter: TBinaryWriter);
class function Load(AReader: TBinaryReader): TUBSValue; static;
procedure SaveToFile(const AFilename: string);
class function LoadFromFile(const AFilename: string): TUBSValue; static;
function Cast<T: TUBSValue>: T;
function Formatter: IFormatter;
function Format(AMode: TUBSFormatMode = TFormatter.DefaultMode): string;
function ToString: string; override;
end;
TUBSNil = class(TUBSValue)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSParent = class(TUBSValue);
TUBSMap = class(TUBSParent)
private
FMap: IToObjectMap<string, TUBSValue>;
FOrder: IList<TPair<string, TUBSValue>>;
function GetMap: IReadonlyMap<string, TUBSValue>;
function GetOrder: IReadonlyList<TPair<string, TUBSValue>>;
function GetItem(AKey: string): TUBSValue;
procedure SetItem(AKey: string; const Value: TUBSValue);
function GetCount: Integer;
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
constructor Create; override;
class function GetTag: TUBSTag; override;
property Count: Integer read GetCount;
property Map: IReadonlyMap<string, TUBSValue> read GetMap;
property Order: IReadonlyList < TPair < string, TUBSValue >> read GetOrder;
property Items[AKey: string]: TUBSValue read GetItem write SetItem; default;
procedure Remove(AKey: string);
function Extract(AKey: string): TUBSValue;
function GetEnumerator: IIterator<TPair<string, TUBSValue>>;
end;
TUBSList = class(TUBSParent)
private
FItems: IObjectList<TUBSValue>;
function GetItem(AIndex: Integer): TUBSValue;
procedure SetItem(AIndex: Integer; const Value: TUBSValue);
function GetItems: IReadonlyList<TUBSValue>;
function GetCount: Integer;
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
constructor Create; override;
class function GetTag: TUBSTag; override;
property Count: Integer read GetCount;
property Items: IReadonlyList<TUBSValue> read GetItems;
property Values[AIndex: Integer]: TUBSValue read GetItem write SetItem; default;
procedure Add(AValue: TUBSValue);
procedure Remove(AValue: TUBSValue);
procedure RemoveAt(AIndex: Integer);
function Extract(AIndex: Integer): TUBSValue;
function GetEnumerator: IIterator<TUBSValue>;
end;
TUBSValue<T> = class(TUBSValue)
private
FValue: T;
protected
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
constructor Create; overload; override;
constructor Create(AValue: T); reintroduce; overload;
property Value: T read FValue write FValue;
end;
TUBSInteger = class(TUBSValue<Integer>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSSingle = class(TUBSValue<Single>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSBoolean = class(TUBSValue<Boolean>)
public const
BoolStrings: array [Boolean] of string = ('false', 'true');
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSString = class(TUBSValue<string>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSByteArray = class(TUBSValue)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
procedure SaveInternal(AWriter: TBinaryWriter); override;
procedure LoadInternal(AReader: TBinaryReader); override;
public
Data: TBytes;
class function GetTag: TUBSTag; override;
end;
TUBSGUID = class(TUBSValue<TGUID>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSIntBounds1 = class(TUBSValue<TIntBounds1>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSIntBounds2 = class(TUBSValue<TIntBounds2>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSIntBounds3 = class(TUBSValue<TIntBounds3>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSIntVector2 = class(TUBSValue<TIntVector2>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSIntVector3 = class(TUBSValue<TIntVector3>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSBounds1 = class(TUBSValue<TBounds1>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSBounds2 = class(TUBSValue<TBounds2>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSBounds3 = class(TUBSValue<TBounds3>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSVector2 = class(TUBSValue<TVector2>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSVector3 = class(TUBSValue<TVector3>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSColorRGB = class(TUBSValue<TColorRGB>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
TUBSColorRGBA = class(TUBSValue<TColorRGBA>)
protected
procedure FormatInternal(AFormatter: TUBSValue.TFormatter); override;
public
class function GetTag: TUBSTag; override;
end;
ISerializable = interface;
TSerializer = class
public type
TMode = (
smSerialize,
smUnserialize
);
private
FMode: TMode;
FValue: TUBSMap;
public
class function Serialize(ASerializable: ISerializable): TUBSMap;
class procedure Unserialize(ASerializable: ISerializable; AValue: TUBSMap);
property Mode: TMode read FMode;
property Value: TUBSMap read FValue;
procedure Define(const AName: string; const ASerializable: ISerializable); overload;
procedure Define<T: ISerializable>(const AName: string; var ASerializable: T;
const AInstantiator: TFunc<T>); overload;
procedure Define<T: ISerializable>(const AName: string; var ASerializable: T;
const AInstantiator: TFunc<TUBSMap, T>); overload;
procedure Define<T: ISerializable>(const AName: string; const ACollection: ICollection<T>;
const AInstantiator: TFunc<T>); overload;
procedure Define<T: ISerializable>(const AName: string; const ACollection: ICollection<T>;
const AInstantiator: TFunc<TUBSMap, T>); overload;
procedure Define<T: ISerializable, constructor>(const AName: string; const ACollection: ICollection<T>); overload;
procedure Define(const AName: string; var AValue: Integer); overload;
procedure Define(const AName: string; var AValue: Single); overload;
procedure Define(const AName: string; var AValue: Boolean); overload;
procedure Define(const AName: string; var AValue: string); overload;
procedure Define(const AName: string; var AValue: TGUID); overload;
procedure Define(const AName: string; const ACollection: ICollection<TGUID>); overload;
procedure Define(const AName: string; var AValue: TIntBounds1); overload;
procedure Define(const AName: string; var AValue: TIntBounds2); overload;
procedure Define(const AName: string; var AValue: TIntBounds3); overload;
procedure Define(const AName: string; var AValue: TIntVector2); overload;
procedure Define(const AName: string; var AValue: TIntVector3); overload;
procedure Define(const AName: string; var AValue: TBounds1); overload;
procedure Define(const AName: string; var AValue: TBounds2); overload;
procedure Define(const AName: string; var AValue: TBounds3); overload;
procedure Define(const AName: string; var AValue: TVector2); overload;
procedure Define(const AName: string; var AValue: TVector3); overload;
procedure Define(const AName: string; var AValue: TColorRGB); overload;
procedure Define(const AName: string; var AValue: TColorRGBA); overload;
procedure WriteOnly(const AName: string; const AValue: Integer); overload;
procedure WriteOnly(const AName: string; const AValue: Single); overload;
procedure WriteOnly(const AName: string; const AValue: Boolean); overload;
procedure WriteOnly(const AName: string; const AValue: string); overload;
procedure WriteOnly(const AName: string; const AValue: TGUID); overload;
procedure WriteOnly(const AName: string; const AValue: TIntBounds1); overload;
procedure WriteOnly(const AName: string; const AValue: TIntBounds2); overload;
procedure WriteOnly(const AName: string; const AValue: TIntBounds3); overload;
procedure WriteOnly(const AName: string; const AValue: TIntVector2); overload;
procedure WriteOnly(const AName: string; const AValue: TIntVector3); overload;
procedure WriteOnly(const AName: string; const AValue: TBounds1); overload;
procedure WriteOnly(const AName: string; const AValue: TBounds2); overload;
procedure WriteOnly(const AName: string; const AValue: TBounds3); overload;
procedure WriteOnly(const AName: string; const AValue: TVector2); overload;
procedure WriteOnly(const AName: string; const AValue: TVector3); overload;
procedure WriteOnly(const AName: string; const AValue: TColorRGB); overload;
procedure WriteOnly(const AName: string; const AValue: TColorRGBA); overload;
end;
ISerializable = interface
procedure Serialize(ASerializer: TSerializer);
end;
const
UBSClasses: array [TUBSTag] of TUBSClass = (
// Nil type
TUBSNil,
// Basic/Nested structures
TUBSMap,
TUBSList,
// Common Primitives
TUBSInteger,
TUBSSingle,
TUBSBoolean,
TUBSString,
TUBSByteArray,
// Utility
TUBSGUID,
// Integer math
TUBSIntBounds1,
TUBSIntBounds2,
TUBSIntBounds3,
TUBSIntVector2,
TUBSIntVector3,
// Vector math
TUBSBounds1,
TUBSBounds2,
TUBSBounds3,
TUBSVector2,
TUBSVector3,
// Color
TUBSColorRGB,
TUBSColorRGBA
);
UBSTagNames: array [TUBSTag] of string = (
// Nil type
'nil',
// Basic/Nested structures
'map',
'list',
// Common Primitives
'integer',
'single',
'boolean',
'string',
'bytes',
// Utility
'guid',
// Integer math
'ibounds1',
'ibounds2',
'ibounds3',
'ivec2',
'ivec3',
// Vector math
'bound1',
'bound2',
'bound3',
'vec2',
'vec3',
// Color
'rgb',
'rgba'
);
implementation
type
TBinaryWriterHelper = class helper for TBinaryWriter
procedure Write7BitEncodedInt(Value: Integer);
end;
TBinaryReaderHelper = class helper for TBinaryReader
function Read7BitEncodedInt: Integer;
end;
{ TBinaryWriterHelper }
procedure TBinaryWriterHelper.Write7BitEncodedInt(Value: Integer);
begin
inherited Write7BitEncodedInt(Value);
end;
{ TBinaryReaderHelper }
function TBinaryReaderHelper.Read7BitEncodedInt: Integer;
begin
Result := inherited Read7BitEncodedInt;
end;
{ TUBSNil }
procedure TUBSNil.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('nil');
end;
class function TUBSNil.GetTag: TUBSTag;
begin
Result := utNil;
end;
procedure TUBSNil.LoadInternal(AReader: TBinaryReader);
begin
// nothing
end;
procedure TUBSNil.SaveInternal(AWriter: TBinaryWriter);
begin
// nothing
end;
{ TUBSMap }
function TUBSMap.GetMap: IReadonlyMap<string, TUBSValue>;
begin
Result := FMap.ReadonlyMap;
end;
function TUBSMap.GetOrder: IReadonlyList<TPair<string, TUBSValue>>;
begin
Result := FOrder.ReadonlyList;
end;
function TUBSMap.GetCount: Integer;
begin
Result := Map.Count;
end;
function TUBSMap.GetEnumerator: IIterator<TPair<string, TUBSValue>>;
begin
Result := FOrder.GetEnumerator;
end;
function TUBSMap.GetItem(AKey: string): TUBSValue;
begin
Result := FMap[AKey];
end;
procedure TUBSMap.SetItem(AKey: string; const Value: TUBSValue);
begin
if FMap.ContainsKey(AKey) then
raise EUBSError.Create('UBS-Key exists already.');
FMap[AKey] := Value;
FOrder.Add(TPair<string, TUBSValue>.Create(AKey, Value));
end;
function TUBSMap.Extract(AKey: string): TUBSValue;
var
I: Integer;
begin
Result := FMap.Extract(AKey);
for I := 0 to FOrder.MaxIndex do
if FOrder[I].Value = Result then
begin
FOrder.RemoveAt(I);
Break;
end;
end;
procedure TUBSMap.FormatInternal(AFormatter: TUBSValue.TFormatter);
procedure FormatIndex(AIndex: Integer);
begin
AFormatter.Builder.Append(Order[AIndex].Key);
AFormatter.Builder.Append(':');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
Order[AIndex].Value.FormatInternal(AFormatter);
end;
var
I: Integer;
begin
AFormatter.Builder.Append('{');
if not Map.Empty then
begin
AFormatter.Indent;
FormatIndex(0);
for I := 1 to Order.MaxIndex do
begin
AFormatter.Builder.Append(',');
if AFormatter.Mode = ufInline then
AFormatter.Builder.Append(' ');
AFormatter.NewLine;
FormatIndex(I);
end;
AFormatter.Unindent;
end;
AFormatter.Builder.Append('}');
end;
procedure TUBSMap.SaveInternal(AWriter: TBinaryWriter);
var
Item: TPair<string, TUBSValue>;
begin
AWriter.Write7BitEncodedInt(Count);
for Item in Order do
begin
AWriter.Write(Item.Key);
Item.Value.Save(AWriter);
end;
end;
procedure TUBSMap.LoadInternal(AReader: TBinaryReader);
var
I: Integer;
Key: string;
Value: TUBSValue;
begin
for I := 1 to AReader.Read7BitEncodedInt do
begin
Key := AReader.ReadString;
Value := Load(AReader);
Items[Key] := Value;
end;
end;
procedure TUBSMap.Remove(AKey: string);
begin
Extract(AKey).Free;
end;
constructor TUBSMap.Create;
begin
FMap := TToObjectMap<string, TUBSValue>.Create;
FOrder := TList < TPair < string, TUBSValue >>.Create;
end;
class function TUBSMap.GetTag: TUBSTag;
begin
Result := utMap;
end;
{ IUBSList }
function TUBSList.GetItem(AIndex: Integer): TUBSValue;
begin
Result := FItems[AIndex];
end;
procedure TUBSList.SetItem(AIndex: Integer; const Value: TUBSValue);
begin
FItems[AIndex] := Value;
end;
function TUBSList.GetItems: IReadonlyList<TUBSValue>;
begin
Result := FItems.ReadonlyList;
end;
function TUBSList.GetCount: Integer;
begin
Result := Items.Count;
end;
procedure TUBSList.FormatInternal(AFormatter: TUBSValue.TFormatter);
var
I: Integer;
begin
AFormatter.Builder.Append('[');
if not Items.Empty then
begin
AFormatter.Indent;
Items.First.FormatInternal(AFormatter);
for I := 1 to Items.MaxIndex do
begin
AFormatter.Builder.Append(',');
if AFormatter.Mode = ufInline then
AFormatter.Builder.Append(' ');
AFormatter.NewLine;
Items[I].FormatInternal(AFormatter);
end;
AFormatter.Unindent;
end;
AFormatter.Builder.Append(']');
end;
procedure TUBSList.SaveInternal(AWriter: TBinaryWriter);
var
Item: TUBSValue;
begin
AWriter.Write7BitEncodedInt(Count);
for Item in Items do
Item.Save(AWriter);
end;
procedure TUBSList.LoadInternal(AReader: TBinaryReader);
var
I: Integer;
begin
for I := 1 to AReader.Read7BitEncodedInt do
Add(Load(AReader));
end;
constructor TUBSList.Create;
begin
FItems := TObjectList<TUBSValue>.Create;
end;
class function TUBSList.GetTag: TUBSTag;
begin
Result := utList;
end;
procedure TUBSList.Add(AValue: TUBSValue);
begin
FItems.Add(AValue);
end;
procedure TUBSList.Remove(AValue: TUBSValue);
begin
FItems.Remove(AValue);
end;
procedure TUBSList.RemoveAt(AIndex: Integer);
begin
FItems.RemoveAt(AIndex);
end;
function TUBSList.Extract(AIndex: Integer): TUBSValue;
begin
Result := FItems.Extract(AIndex);
end;
function TUBSList.GetEnumerator: IIterator<TUBSValue>;
begin
Result := FItems.GetEnumerator;
end;
{ TUBSInteger }
procedure TUBSInteger.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append(Value);
end;
class function TUBSInteger.GetTag: TUBSTag;
begin
Result := utInteger;
end;
{ TUBSSingle }
procedure TUBSSingle.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append(PrettyFloat(Value));
if not IsInfinite(Value) and not IsNan(Value) then
AFormatter.Builder.Append('f');
end;
class function TUBSSingle.GetTag: TUBSTag;
begin
Result := utSingle;
end;
{ TUBSBoolean }
procedure TUBSBoolean.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append(BoolStrings[Value]);
end;
class function TUBSBoolean.GetTag: TUBSTag;
begin
Result := utBoolean;
end;
{ TUBSString }
procedure TUBSString.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append(Value.QuotedString('"'));
end;
procedure TUBSString.SaveInternal(AWriter: TBinaryWriter);
begin
AWriter.Write(Value);
end;
procedure TUBSString.LoadInternal(AReader: TBinaryReader);
begin
Value := AReader.ReadString;
end;
class function TUBSString.GetTag: TUBSTag;
begin
Result := utString;
end;
{ TUBSByteArray }
procedure TUBSByteArray.FormatInternal(AFormatter: TUBSValue.TFormatter);
var
I: Integer;
begin
AFormatter.Builder.Append('bytes(');
for I := 0 to Length(Data) - 1 do
AFormatter.Builder.Append(IntToHex(Data[I]));
AFormatter.Builder.Append(')');
end;
procedure TUBSByteArray.SaveInternal(AWriter: TBinaryWriter);
begin
AWriter.Write7BitEncodedInt(Length(Data));
AWriter.Write(Data);
end;
procedure TUBSByteArray.LoadInternal(AReader: TBinaryReader);
var
Count: Integer;
begin
Count := AReader.Read7BitEncodedInt;
SetLength(Data, Count);
AReader.Read(Data, 0, Count);
end;
class function TUBSByteArray.GetTag: TUBSTag;
begin
Result := utByteArray;
end;
{ TUBSGUID }
procedure TUBSGUID.FormatInternal(AFormatter: TUBSValue.TFormatter);
var
Text: string;
begin
Text := Value.ToString;
Text[1] := '<';
Text[38] := '>';
AFormatter.Builder.Append(Text);
end;
class function TUBSGUID.GetTag: TUBSTag;
begin
Result := utGUID;
end;
{ TUBSIntBounds1 }
procedure TUBSIntBounds1.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('ibounds1(');
AFormatter.Builder.Append(Value.C1);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2);
AFormatter.Builder.Append(')');
end;
class function TUBSIntBounds1.GetTag: TUBSTag;
begin
Result := utIntBounds1;
end;
{ TUBSIntBounds2 }
procedure TUBSIntBounds2.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('ibounds2(');
AFormatter.Builder.Append(Value.C1.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C1.Y);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2.Y);
AFormatter.Builder.Append(')');
end;
class function TUBSIntBounds2.GetTag: TUBSTag;
begin
Result := utIntBounds2;
end;
{ TUBSIntBounds3 }
procedure TUBSIntBounds3.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('ibounds3(');
AFormatter.Builder.Append(Value.C1.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C1.Y);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C1.Z);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2.Y);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.C2.Z);
AFormatter.Builder.Append(')');
end;
class function TUBSIntBounds3.GetTag: TUBSTag;
begin
Result := utIntBounds3;
end;
{ TUBSIntVector2 }
procedure TUBSIntVector2.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('ivec2(');
AFormatter.Builder.Append(Value.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.Y);
AFormatter.Builder.Append(')');
end;
class function TUBSIntVector2.GetTag: TUBSTag;
begin
Result := utIntVector2;
end;
{ TUBSIntVector3 }
procedure TUBSIntVector3.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('ivec3(');
AFormatter.Builder.Append(Value.X);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.Y);
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(Value.Z);
AFormatter.Builder.Append(')');
end;
class function TUBSIntVector3.GetTag: TUBSTag;
begin
Result := utIntVector3;
end;
{ TUBSBounds1 }
procedure TUBSBounds1.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('bounds1(');
AFormatter.Builder.Append(PrettyFloat(Value.C1));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2));
AFormatter.Builder.Append(')');
end;
class function TUBSBounds1.GetTag: TUBSTag;
begin
Result := utBounds1;
end;
{ TUBSBounds2 }
procedure TUBSBounds2.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('bounds2(');
AFormatter.Builder.Append(PrettyFloat(Value.C1.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C1.Y));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2.Y));
AFormatter.Builder.Append(')');
end;
class function TUBSBounds2.GetTag: TUBSTag;
begin
Result := utBounds2;
end;
{ TUBSBounds3 }
procedure TUBSBounds3.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('bounds3(');
AFormatter.Builder.Append(PrettyFloat(Value.C1.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C1.Y));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C1.Z));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2.Y));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.C2.Z));
AFormatter.Builder.Append(')');
end;
class function TUBSBounds3.GetTag: TUBSTag;
begin
Result := utBounds3;
end;
{ TUBSVector2 }
procedure TUBSVector2.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('vec2(');
AFormatter.Builder.Append(PrettyFloat(Value.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.Y));
AFormatter.Builder.Append(')');
end;
class function TUBSVector2.GetTag: TUBSTag;
begin
Result := utVector2;
end;
{ TUBSVector3 }
procedure TUBSVector3.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('vec3(');
AFormatter.Builder.Append(PrettyFloat(Value.X));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.Y));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.Z));
AFormatter.Builder.Append(')');
end;
class function TUBSVector3.GetTag: TUBSTag;
begin
Result := utVector3;
end;
{ TUBSColorRGB }
procedure TUBSColorRGB.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('rgb(');
AFormatter.Builder.Append(PrettyFloat(Value.R));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.G));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.B));
AFormatter.Builder.Append(')');
end;
class function TUBSColorRGB.GetTag: TUBSTag;
begin
Result := utColorRGB;
end;
{ TUBSColorRGBA }
procedure TUBSColorRGBA.FormatInternal(AFormatter: TUBSValue.TFormatter);
begin
AFormatter.Builder.Append('rgba(');
AFormatter.Builder.Append(PrettyFloat(Value.R));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.G));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.B));
AFormatter.Builder.Append(',');
if AFormatter.Mode <> ufMinify then
AFormatter.Builder.Append(' ');
AFormatter.Builder.Append(PrettyFloat(Value.A));
AFormatter.Builder.Append(')');
end;
class function TUBSColorRGBA.GetTag: TUBSTag;
begin
Result := utColorRGBA;
end;
{ TSerializer }
class function TSerializer.Serialize(ASerializable: ISerializable): TUBSMap;
var
Serializer: TSerializer;
begin
Serializer := TSerializer.Create;
Serializer.FMode := smSerialize;
Serializer.FValue := TUBSMap.Create;
try
ASerializable.Serialize(Serializer);
Result := Serializer.FValue;
finally
Serializer.Free;
end;
end;
class procedure TSerializer.Unserialize(ASerializable: ISerializable; AValue: TUBSMap);
var
Serializer: TSerializer;
begin
Serializer := TSerializer.Create;
Serializer.FMode := smUnserialize;
Serializer.FValue := AValue;
try
ASerializable.Serialize(Serializer);
finally
Serializer.Free;
end;
end;
procedure TSerializer.Define(const AName: string; const ASerializable: ISerializable);
begin
case Mode of
smSerialize:
Value[AName] := Serialize(ASerializable);
smUnserialize:
Unserialize(ASerializable, Value[AName].Cast<TUBSMap>);
end;
end;
procedure TSerializer.Define<T>(const AName: string; var ASerializable: T; const AInstantiator: TFunc<T>);
begin
case Mode of
smSerialize:
Value[AName] := Serialize(ASerializable);
smUnserialize:
begin
ASerializable := AInstantiator;
Unserialize(ASerializable, Value[AName].Cast<TUBSMap>);
end;
end;
end;
procedure TSerializer.Define<T>(const AName: string; var ASerializable: T; const AInstantiator: TFunc<TUBSMap, T>);
var
UBSMap: TUBSMap;
begin
case Mode of
smSerialize:
Value[AName] := Serialize(ASerializable);
smUnserialize:
begin
UBSMap := Value[AName].Cast<TUBSMap>;
ASerializable := AInstantiator(UBSMap);
Unserialize(ASerializable, UBSMap);
end;
end;
end;
procedure TSerializer.Define<T>(const AName: string; const ACollection: ICollection<T>; const AInstantiator: TFunc<T>);
var
List: TUBSList;
Item: T;
UBSValue: TUBSValue;
begin
case Mode of
smSerialize:
begin
List := TUBSList.Create;
for Item in ACollection do
List.Add(Serialize(Item));
Value[AName] := List;
end;
smUnserialize:
begin
ACollection.Clear;
for UBSValue in Value[AName].Cast<TUBSList> do
begin
Item := AInstantiator;
Unserialize(Item, UBSValue.Cast<TUBSMap>);
ACollection.Add(Item);
end;
end;
end;
end;
procedure TSerializer.Define<T>(const AName: string; const ACollection: ICollection<T>;
const AInstantiator: TFunc<TUBSMap, T>);
var
List: TUBSList;
Item: T;
UBSValue: TUBSValue;
UBSMap: TUBSMap;
begin
case Mode of
smSerialize:
begin
List := TUBSList.Create;
for Item in ACollection do
List.Add(Serialize(Item));
Value[AName] := List;
end;
smUnserialize:
begin
ACollection.Clear;
for UBSValue in Value[AName].Cast<TUBSList> do
begin
UBSMap := UBSValue.Cast<TUBSMap>;
Item := AInstantiator(UBSMap);
Unserialize(Item, UBSMap);
ACollection.Add(Item);
end;
end;
end;
end;
procedure TSerializer.Define<T>(const AName: string; const ACollection: ICollection<T>);
begin
Define<T>(AName, ACollection,
function: T
begin
Result := T.Create;
end);
end;
procedure TSerializer.Define(const AName: string; var AValue: Integer);
begin
case Mode of
smSerialize:
Value[AName] := TUBSInteger.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSInteger>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: Single);
begin
case Mode of
smSerialize:
Value[AName] := TUBSSingle.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSSingle>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: Boolean);
begin
case Mode of
smSerialize:
Value[AName] := TUBSBoolean.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSBoolean>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: string);
begin
case Mode of
smSerialize:
Value[AName] := TUBSString.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSString>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TGUID);
begin
case Mode of
smSerialize:
Value[AName] := TUBSGUID.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSGUID>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TIntBounds1);
begin
case Mode of
smSerialize:
Value[AName] := TUBSIntBounds1.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSIntBounds1>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TIntBounds2);
begin
case Mode of
smSerialize:
Value[AName] := TUBSIntBounds2.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSIntBounds2>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TIntBounds3);
begin
case Mode of
smSerialize:
Value[AName] := TUBSIntBounds3.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSIntBounds3>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TIntVector2);
begin
case Mode of
smSerialize:
Value[AName] := TUBSIntVector2.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSIntVector2>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TIntVector3);
begin
case Mode of
smSerialize:
Value[AName] := TUBSIntVector3.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSIntVector3>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TBounds1);
begin
case Mode of
smSerialize:
Value[AName] := TUBSBounds1.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSBounds1>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TBounds2);
begin
case Mode of
smSerialize:
Value[AName] := TUBSBounds2.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSBounds2>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TBounds3);
begin
case Mode of
smSerialize:
Value[AName] := TUBSBounds3.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSBounds3>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TVector2);
begin
case Mode of
smSerialize:
Value[AName] := TUBSVector2.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSVector2>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TVector3);
begin
case Mode of
smSerialize:
Value[AName] := TUBSVector3.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSVector3>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TColorRGB);
begin
case Mode of
smSerialize:
Value[AName] := TUBSColorRGB.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSColorRGB>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; var AValue: TColorRGBA);
begin
case Mode of
smSerialize:
Value[AName] := TUBSColorRGBA.Create(AValue);
smUnserialize:
AValue := Value[AName].Cast<TUBSColorRGBA>.Value;
end;
end;
procedure TSerializer.Define(const AName: string; const ACollection: ICollection<TGUID>);
var
List: TUBSList;
GUID: TGUID;
UBSValue: TUBSValue;
begin
case Mode of
smSerialize:
begin
List := TUBSList.Create;
for GUID in ACollection do
List.Add(TUBSGUID.Create(GUID));
Value[AName] := List;
end;
smUnserialize:
begin
ACollection.Clear;
for UBSValue in Value[AName].Cast<TUBSList> do
ACollection.Add(UBSValue.Cast<TUBSGUID>.Value);
end;
end;
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: Integer);
begin
if Mode = smSerialize then
Value[AName] := TUBSInteger.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: Single);
begin
if Mode = smSerialize then
Value[AName] := TUBSSingle.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: Boolean);
begin
if Mode = smSerialize then
Value[AName] := TUBSBoolean.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName, AValue: string);
begin
if Mode = smSerialize then
Value[AName] := TUBSString.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TGUID);
begin
if Mode = smSerialize then
Value[AName] := TUBSGUID.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TIntBounds1);
begin
if Mode = smSerialize then
Value[AName] := TUBSIntBounds1.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TIntBounds2);
begin
if Mode = smSerialize then
Value[AName] := TUBSIntBounds2.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TIntBounds3);
begin
if Mode = smSerialize then
Value[AName] := TUBSIntBounds3.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TIntVector2);
begin
if Mode = smSerialize then
Value[AName] := TUBSIntVector2.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TIntVector3);
begin
if Mode = smSerialize then
Value[AName] := TUBSIntVector3.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TBounds1);
begin
if Mode = smSerialize then
Value[AName] := TUBSBounds1.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TBounds2);
begin
if Mode = smSerialize then
Value[AName] := TUBSBounds2.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TBounds3);
begin
if Mode = smSerialize then
Value[AName] := TUBSBounds3.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TVector2);
begin
if Mode = smSerialize then
Value[AName] := TUBSVector2.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TVector3);
begin
if Mode = smSerialize then
Value[AName] := TUBSVector3.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TColorRGB);
begin
if Mode = smSerialize then
Value[AName] := TUBSColorRGB.Create(AValue);
end;
procedure TSerializer.WriteOnly(const AName: string; const AValue: TColorRGBA);
begin
if Mode = smSerialize then
Value[AName] := TUBSColorRGBA.Create(AValue);
end;
{ TUBSValue }
procedure TUBSValue.Save(AWriter: TBinaryWriter);
begin
AWriter.Write7BitEncodedInt(Ord(GetTag));
SaveInternal(AWriter);
end;
class function TUBSValue.Load(AReader: TBinaryReader): TUBSValue;
var
Tag: TUBSTag;
begin
Tag := TUBSTag(AReader.Read7BitEncodedInt);
if not(Tag in [Low(TUBSTag) .. High(TUBSTag)]) then
raise EUBSError.Create('Unknown UBS-Tag, newer version or corrupted data.');
Result := CreateTyped(Tag);
Result.LoadInternal(AReader);
end;
constructor TUBSValue.Create;
begin
// nothing
end;
class function TUBSValue.CreateTyped(ATag: TUBSTag): TUBSValue;
begin
Result := UBSClasses[ATag].Create;
end;
procedure TUBSValue.SaveToFile(const AFilename: string);
var
Writer: TBinaryWriter;
begin
Writer := TBinaryWriter.Create(AFilename, False, TEncoding.UTF8);
try
Writer.Write(Cardinal(BinaryFileSignature));
Save(Writer);
finally
Writer.Free;
end;
end;
class function TUBSValue.LoadFromFile(const AFilename: string): TUBSValue;
var
Reader: TBinaryReader;
begin
Reader := TBinaryReader.Create(AFilename, TEncoding.UTF8);
try
try
if Reader.ReadCardinal <> Cardinal(BinaryFileSignature) then
raise EUBSError.Create('Loading non-binary UBS file not supported.');
Result := Load(Reader);
except
raise EUBSError.Create('Invalid UBS file.');
end;
finally
Reader.Free;
end;
end;
function TUBSValue.Cast<T>: T;
begin
if Self.ClassType = T then
Exit(T(Self));
raise EUBSError.Create('Invalid cast of UBS-Type.');
end;
function TUBSValue.Formatter: IFormatter;
begin
Result := TFormatter.Create(Self);
end;
class function TUBSValue.GetTagName: string;
begin
Result := UBSTagNames[GetTag];
end;
function TUBSValue.Format(AMode: TUBSFormatMode): string;
begin
with Formatter do
begin
Mode := AMode;
Result := Format;
end;
end;
function TUBSValue.ToString: string;
begin
Result := Format(ufInline);
end;
{ TUBSValue.TFormatter }
function TUBSValue.TFormatter.GetMode: TUBSFormatMode;
begin
Result := FMode;
end;
procedure TUBSValue.TFormatter.SetMode(const Value: TUBSFormatMode);
begin
FMode := Value;
end;
function TUBSValue.TFormatter.GetIndentWidth: Integer;
begin
Result := FIndentWidth;
end;
procedure TUBSValue.TFormatter.SetIndentWidth(const Value: Integer);
begin
FIndentWidth := Value;
end;
constructor TUBSValue.TFormatter.Create;
begin
FMode := DefaultMode;
FIndentWidth := DefaultIndentWidth;
end;
function TUBSValue.TFormatter.Format: string;
begin
FBuilder := TStringBuilder.Create;
try
Value.FormatInternal(Self);
Result := FBuilder.ToString;
finally
Builder.Free;
end;
end;
procedure TUBSValue.TFormatter.Indent;
begin
Inc(FIndentLevel);
NewLine;
end;
procedure TUBSValue.TFormatter.Unindent;
begin
Dec(FIndentLevel);
NewLine;
end;
procedure TUBSValue.TFormatter.AddIndentation;
begin
Builder.Append(' ', IndentLevel * IndentWidth);
end;
procedure TUBSValue.TFormatter.NewLine;
begin
if Mode = ufPretty then
begin
Builder.AppendLine;
AddIndentation;
end;
end;
{ TUBSValue<T> }
procedure TUBSValue<T>.SaveInternal(AWriter: TBinaryWriter);
begin
AWriter.BaseStream.Write(Value, SizeOf(T));
end;
procedure TUBSValue<T>.LoadInternal(AReader: TBinaryReader);
begin
AReader.BaseStream.ReadData<T>(FValue);
end;
constructor TUBSValue<T>.Create;
begin
inherited;
end;
constructor TUBSValue<T>.Create(AValue: T);
begin
Create;
FValue := AValue;
end;
end.
|
unit UFrontUI;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Objects,
System.Actions, FMX.ActnList, FMX.Edit, FireDAC.Comp.Client;
type
TFormMainUI = class(TForm)
MainUILoginGrid: TGridPanelLayout;
MainUIAction: TActionList;
actLogin: TAction;
actCreateProfile: TAction;
EdUsername: TEdit;
EdPassword: TEdit;
MainUILogo: TImage;
btLogin: TButton;
txtForgotPassword: TText;
txtCreateNewProfile: TText;
orSeparatorGrid: TGridPanelLayout;
orSeparatorGridLeftLine: TGridPanelLayout;
orSeparatorGridRightLine: TGridPanelLayout;
leftLine: TLine;
txtOr: TText;
Line1: TLine;
procedure actCreateProfileExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMainUI: TFormMainUI;
implementation
{$R *.fmx}
uses UCreateNewProfile, UDM;
procedure TFormMainUI.actCreateProfileExecute(Sender: TObject);
var FormCreateNewProfile: TFormCreateNewProfile;
begin
FormCreateNewProfile:= TFormCreateNewProfile.Create(Self);
try
FormCreateNewProfile.Show;
finally
FormCreateNewProfile.Free;
end;
end;
end.
|
unit mnSynHighlighterConfig;
{$mode objfpc}{$H+}
{**
* MiniLib project
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
Classes, Graphics,
SynEditTypes, SynEditHighlighter, mnSynUtils;
type
TtkTokenKind = (tkNone, tkKey, tkSubKey, tkSection, tkText, tkComment, tkDocument, tkNull, tkNumber,
tkSpace, tkString, tkSymbol, tkUnknown);
TSynConfRange = (cnfrNone, cnfrKey, cnfrSubKey, cnfrValue, cnfrSection);
{ TSynConfigSyn }
TSynConfigSyn = class(TSynCustomHighlighter)
private
FLine: PChar;
FProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
FTokenPos: Integer;
FTokenID: TtkTokenKind;
FCommentAttri: TSynHighlighterAttributes;
FDocumentAttri: TSynHighlighterAttributes;
FTextAttri: TSynHighlighterAttributes;
FSectionAttri: TSynHighlighterAttributes;
FKeyAttri: TSynHighlighterAttributes;
FNumberAttri: TSynHighlighterAttributes;
FSpaceAttri: TSynHighlighterAttributes;
FStringAttri: TSynHighlighterAttributes;
FSymbolAttri: TSynHighlighterAttributes;
procedure TextProc;
procedure BracketSectionOpenProc;
procedure BSSectionOpenProc;
procedure LFProc;
procedure NullProc;
procedure CRProc;
procedure SpaceProc;
procedure CommentProc;
procedure DocumentProc;
procedure KeyProc;
procedure EqualProc;
procedure ParamProc;
procedure DotProc;
procedure NumberProc;
procedure DQStringProc; // ""
procedure SQStringProc; // ''
procedure MakeMethodTables;
protected
FRange: TSynConfRange;
function GetIdentChars: TSynIdentChars; override;
function GetSampleSource: String; override;
function IsFilterStored: Boolean; override;
public
procedure SetRange(Value: Pointer); override;
function GetRange: Pointer; override;
procedure ResetRange; override;
class function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
function GetEol: Boolean; override;
function GetTokenID: TtkTokenKind;
procedure SetLine(const NewValue: String; LineNumber:Integer); override;
function GetToken: String; override;
procedure GetTokenEx(out TokenStart: PChar; out TokenLength: integer); override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: Integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
published
property SpaceAttri : TSynHighlighterAttributes read FSpaceAttri write FSpaceAttri;
property CommentAttri: TSynHighlighterAttributes read FCommentAttri write FCommentAttri;
property DocumentAttri: TSynHighlighterAttributes read FDocumentAttri write FDocumentAttri;
property TextAttri : TSynHighlighterAttributes read FTextAttri write FTextAttri;
property SectionAttri: TSynHighlighterAttributes read FSectionAttri write FSectionAttri;
property KeyAttri : TSynHighlighterAttributes read FKeyAttri write FKeyAttri;
property NumberAttri : TSynHighlighterAttributes read FNumberAttri write FNumberAttri;
property StringAttri : TSynHighlighterAttributes read FStringAttri write FStringAttri;
property SymbolAttri : TSynHighlighterAttributes read FSymbolAttri write FSymbolAttri;
end;
implementation
uses
SynEditStrConst;
procedure TSynConfigSyn.MakeMethodTables;
var
i: Char;
begin
for i := #0 to #255 do
case i of
#0 : FProcTable[i] := @NullProc;
#10 {LF}: FProcTable[i] := @LFProc;
#13 {CR}: FProcTable[i] := @CRProc;
#1..#9, #11, #12, #14..#32: FProcTable[i] := @SpaceProc;
'=' : FProcTable[i] := @EqualProc;
'.' : FProcTable[i] := @DotProc;
'?' : FProcTable[i] := @ParamProc;
'"' : FProcTable[i] := @DQStringProc;
'''' : FProcTable[i] := @SQStringProc;
'#' : FProcTable[i] := @DocumentProc;
';' : FProcTable[i] := @CommentProc;
'[' : FProcTable[i] := @BracketSectionOpenProc;
']' : FProcTable[i] := @BracketSectionOpenProc;
'\' : FProcTable[i] := @BSSectionOpenProc;
'0'..'9': FProcTable[i] := @NumberProc;
else
FProcTable[i] := @TextProc;
end;
end;
constructor TSynConfigSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
FCommentAttri.Style := [];
FCommentAttri.Foreground := clGreen;
AddAttribute(FCommentAttri);
FDocumentAttri := TSynHighlighterAttributes.Create('Document');
FDocumentAttri.Style := [];
FDocumentAttri.Foreground := clGreen;
AddAttribute(FDocumentAttri);
FTextAttri := TSynHighlighterAttributes.Create(SYNS_AttrText);
AddAttribute(FTextAttri);
FSectionAttri := TSynHighlighterAttributes.Create(SYNS_AttrSection);
FSectionAttri.Style := [];
AddAttribute(FSectionAttri);
FKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrKey);
AddAttribute(FKeyAttri);
FNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber);
AddAttribute(FNumberAttri);
FSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace);
AddAttribute(FSpaceAttri);
FStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString);
AddAttribute(FStringAttri);
FSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol);
AddAttribute(FSymbolAttri);
SetAttributesOnChange(@DefHighlightChange);
FDefaultFilter := SYNS_FilterINI;
MakeMethodTables;
end;
procedure TSynConfigSyn.SetLine(const NewValue: String; LineNumber:Integer);
begin
inherited;
FLine := PChar(NewValue);
Run := 0;
FRange := cnfrNone;
FTokenID := tkNone;
Next;
end;
procedure TSynConfigSyn.BracketSectionOpenProc;
begin
FTokenID := tkSection;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
']':
begin
inc(Run);
break
end;
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TSynConfigSyn.BSSectionOpenProc;
begin
if FRange = cnfrNone then
begin
FTokenID := tkSection;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
#10: break;
#13: break;
else
inc(Run);
end;
end
else
begin
FTokenID := tkSymbol;
inc(Run);
end;
end;
procedure TSynConfigSyn.CRProc;
begin
FTokenID := tkSpace;
Case FLine[Run + 1] of
#10: inc(Run, 2);
else inc(Run);
end;
end;
procedure TSynConfigSyn.EqualProc;
begin
if FRange = cnfrValue then
TextProc
else
begin
inc(Run);
FTokenID := tkSymbol;
SetRange(Pointer(cnfrValue));
end;
end;
procedure TSynConfigSyn.ParamProc;
begin
inc(Run);
if FRange = cnfrValue then
FTokenID := tkSymbol;
SetRange(Pointer(cnfrValue));
end;
procedure TSynConfigSyn.DotProc;
begin
if FRange = cnfrValue then
TextProc
else
begin
inc(Run);
FTokenID := tkSymbol;
SetRange(Pointer(cnfrSubKey));
end;
end;
procedure TSynConfigSyn.KeyProc;
begin
FTokenID := tkKey;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
'=': break;
'.': break;
#10: break;
#13: break;
else
inc(Run);
end;
end;
procedure TSynConfigSyn.TextProc;
begin
if FRange <> cnfrValue then
KeyProc
else
begin
FTokenID := tkText;
Inc(Run);
while (FLine[Run] in [#128..#191]) OR // continued utf8 subcode
((FLine[Run] <> #0) and (FProcTable[FLine[Run]] = @TextProc)) do
Inc(Run);
end;
end;
procedure TSynConfigSyn.LFProc;
begin
FTokenID := tkSpace;
inc(Run);
end;
procedure TSynConfigSyn.NullProc;
begin
FTokenID := tkNull;
end;
procedure TSynConfigSyn.NumberProc;
begin
if FRange <> cnfrValue then
KeyProc
else begin
inc(Run);
FTokenID := tkNumber;
while FLine[Run] in ['0'..'9', '.', 'e', 'E'] do inc(Run);
if FLine[Run] in ['a'..'z','A'..'Z'] then TextProc;
end;
end;
// ;
procedure TSynConfigSyn.CommentProc;
begin
FTokenID := tkComment;
inc(Run);
if (FLine[Run] <> #0) and (FLine[Run] in ['#', ';', '*']) then
DocumentProc
else
while FLine[Run] <> #0 do
case FLine[Run] of
#10: break;
#13: break;
else inc(Run);
end;
end;
// #
procedure TSynConfigSyn.DocumentProc;
begin
FTokenID := tkDocument;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TSynConfigSyn.SpaceProc;
begin
inc(Run);
FTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do
inc(Run);
end;
// ""
procedure TSynConfigSyn.DQStringProc;
begin
if FRange in [cnfrNone, cnfrKey] then
FTokenID := tkKey
else if FRange = cnfrSubKey then
FTokenID := tkSubKey
else
FTokenID := tkString;
inc(Run);
while not (FLine[Run] in [#0, #10, #13]) do
begin
if (FLine[Run] = '"') then
begin
inc(Run);
//FTokenID := tkText;
break;
end;
Inc(Run);
end;
end;
// ''
procedure TSynConfigSyn.SQStringProc;
begin
if FRange in [cnfrNone, cnfrKey] then
FTokenID := tkKey
else if FRange = cnfrSubKey then
FTokenID := tkSubKey
else
FTokenID := tkString;
inc(Run);
while not (FLine[Run] in [#0, #10, #13]) do
begin
if (FLine[Run] = '''') then
begin
inc(Run);
//FTokenID := tkText;
break;
end;
Inc(Run);
end;
end;
procedure TSynConfigSyn.Next;
begin
FTokenPos := Run;
fProcTable[fLine[Run]];
end;
function TSynConfigSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
SYN_ATTR_NUMBER: Result := fNumberAttri;
SYN_ATTR_DIRECTIVE: Result := FSectionAttri;
else
Result := nil;
end;
end;
function TSynConfigSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function TSynConfigSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - FTokenPos;
SetString(Result, (FLine + FTokenPos), Len);
end;
procedure TSynConfigSyn.GetTokenEx(out TokenStart: PChar; out TokenLength: integer);
begin
TokenLength := Run - FTokenPos;
TokenStart := FLine + FTokenPos;
end;
function TSynConfigSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynConfigSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case FTokenID of
tkComment: Result := FCommentAttri;
tkDocument: Result := FDocumentAttri;
tkText : Result := FTextAttri;
tkSection: Result := FSectionAttri;
tkKey : Result := FKeyAttri;
tkSubKey : Result := FKeyAttri;
tkNumber : Result := FNumberAttri;
tkSpace : Result := FSpaceAttri;
tkString : Result := FStringAttri;
tkSymbol : Result := FSymbolAttri;
tkUnknown: Result := FTextAttri;
else
Result := nil;
end;
end;
function TSynConfigSyn.GetTokenKind: Integer;
begin
Result := Ord(FTokenId);
end;
function TSynConfigSyn.GetTokenPos: Integer;
begin
Result := FTokenPos;
end;
function TSynConfigSyn.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
end;
function TSynConfigSyn.IsFilterStored: Boolean;
begin
Result := FDefaultFilter <> SYNS_FilterINI;
end;
procedure TSynConfigSyn.SetRange(Value: Pointer);
begin
inherited;
FRange := TSynConfRange(PtrInt(Value));
end;
function TSynConfigSyn.GetRange: Pointer;
begin
Result := Pointer(PtrInt(FRange));
end;
procedure TSynConfigSyn.ResetRange;
begin
inherited;
FRange := cnfrNone;
end;
class function TSynConfigSyn.GetLanguageName: string;
begin
Result := 'INI';
end;
function TSynConfigSyn.GetSampleSource: String;
begin
Result := '# Syntax highlighting'#13#10+
'[Options]'#13#10+
'Visible = true'+#13#10+
'Protected = false'+#13#10+
'Port = 80'#13#10+
'Host = "server"'#13#10+
';End of INI'#13#10;
end;
initialization
RegisterPlaceableHighlighter(TSynConfigSyn);
end.
|
unit uSprites;
interface
uses Graphics, uUtils;
const
TilesetCount = 2;
SpritesCount = 50;
spObj = 0;
spCrt = 1;
var
Sprite: array [0..TilesetCount - 1, 0..SpritesCount - 1] of TBitmap;
implementation
uses SysUtils;
procedure Load;
var
I, J: Byte;
Tileset: TBitmap;
begin
for J := 0 to TilesetCount - 1 do
begin
Tileset := TBitmap.Create;
Tileset.LoadFromFile('Sprite' + IntToStr(J) + '.bmp');
for I := 0 to SpritesCount - 1 do
begin
Sprite[J][I] := TBitmap.Create;
BitmapFromTileset(Sprite[J][I], Tileset, I, 64);
Sprite[J][I].Transparent := True;
end;
Tileset.Free;
end;
end;
procedure Free;
var
I, J: Byte;
begin
for J := 0 to TilesetCount - 1 do
for I := 0 to SpritesCount - 1 do
Sprite[J][I].Free;
end;
initialization
Load;
finalization
Free;
end.
|
PROGRAM d7b;
USES sysutils, classes, fgl, math;
CONST
FILESYSTEM_SIZE = 70000000;
FREE_SPACE_NEEDED = 30000000;
FUNCTION answer(filename:string) : longint;
TYPE
FSizeMap = specialize TFPGMap<string, longint>;
VAR
files: TStringList;
sizes: FSizeMap;
PROCEDURE parse_input;
VAR
curdir: TStringList;
f: text;
l: string;
arg: string;
sizecol: string;
BEGIN
curdir := TStringList.Create;
curdir.delimiter := '/';
assign(f, filename);
reset(f);
REPEAT
readln(f, l);
IF l[1] = '$' THEN{a command}
CASE copy(l, 3, 2) OF
'cd':
BEGIN
arg := copy(l, 6, length(l)-5);
IF arg = '..' THEN curdir.Delete(curdir.Count-1)
ELSE curdir.Add(trim(arg));
END;
'ls': ;
END
ELSE {not a command. ls-output}
BEGIN
sizecol := copy(l, 1, pos(' ', l)-1);
IF sizecol <> 'dir' THEN files.add(curdir.DelimitedText + ',' + l);
END;
UNTIL eof(f);
close(f);
curdir.Free();
END;
VAR
f: string;
d_string: string;
d: string;
size: longint;
min_dir_size_needed,
free_space: longint;
i: integer;
curdir: TStringList;
BEGIN{answer}
files := TStringList.Create;
sizes := FSizeMap.Create;
parse_input();
curdir := TStringList.Create;
curdir.delimiter := '/';
FOR f IN files DO
BEGIN
d_string := copy(f, 1, pos(',', f)-1);
size := strToInt64(copy(f, pos(',', f)+1, pos(' ', f)-pos(',', f)-1));
{load list from delimited string} curdir.DelimitedText := d_string;
WHILE curdir.count > 0 DO
BEGIN
d := curdir.DelimitedText;
IF sizes.IndexOf(d) = -1 THEN sizes[d] := 0;
sizes[d] := sizes[d] + size;
{go up one dir} curdir.Delete(curdir.Count-1);
END;
END;
free_space := FILESYSTEM_SIZE - sizes['"/"'];
writeln('current free space ', free_space);
min_dir_size_needed := FREE_SPACE_NEEDED - free_space;
writeln('need to free additional ', min_dir_size_needed);
answer := FILESYSTEM_SIZE;
FOR i:=0 TO sizes.Count-1 DO
IF sizes.data[i] >= min_dir_size_needed THEN
answer := min(answer, sizes.data[i]);
files.Free();
sizes.Free();
curdir.Free();
END;
CONST
testfile1 = 'd7.test.1';
filename = 'd7.input';
VAR
a: longint;
BEGIN{d7b}
assert(answer(testfile1) = 24933642, 'test 1 faal');
a := answer(filename);
writeln('');
writeln('answer: ', a);
END.
|
//==================================================================//
// 网上支付接口实现单元:
// 功能描述:为了实现考生从网上自助缴费而设置的接口。
// 接口名称:Ijxgzl
// 接口引用:http://url/jxgzl/jxgzlWebSrv.dll/soap/Ijxgzl
// 或者:http://url/jxgzl/jxgzlWebSrv.dll/wsdl/Ijxgzl
//==================================================================//
{ Invokable implementation File for TjxgzlSrv which implements IjxgzlSrv }
unit uJxgzlImpl;
interface
uses InvokeRegistry, SysUtils, Types, uJxgzlIntf, DB, ADODB, DBClient, WebBrokerSOAP;
type
{ TjxgzlSrv }
Tjxgzl = class(TInvokableClass, Ijxgzl)
private
function RecordIsExists(const sqlstr:string):Boolean;
function ExecSql(const sqlstr:string):Boolean;
function WriteSysLog(const UserId,sWhat:string):Boolean;
function WriteLoginLog(const UserId,sVer:string):Boolean;
function WriteLogoutLog(const UserId:string):Boolean;
function TeacherIsExistsByNo(const sNo,sXnxq: string): Boolean;
public
function RegIsOK:Boolean;stdcall;//系统是否注册
function SrvIsOK:Boolean;stdcall; //服务器是否准备好/是否可用
//判断WEB Server是否为合法的用户接入服务器IP(即WEB服务器IP验证)
function IsValidIP:Boolean;stdcall;
//判断服务器当前是否可以进行网上报名,如果允许网上报名则返回字符串:OK ;如果不允许,则返回不允许的原因,如服务关闭、IP不正确、不在报名时间内等等
function IsCanNetPrintZKZ:Boolean;stdcall;
function GetXnXqList:string;stdcall;
//通过职工号和学年学期获取工作量信息,返回XML格式的DataSet值
function GetJxgzlInfo(const sNo,sXnxq:string;const iRecCount,iPage:Integer):string;stdcall;
function GetJxgzlRecordCount(const sNo,sXnxq:string):Integer;stdcall;
//得到教学工作量信息
function GetJxgzlDelta(const id:string):string;stdcall;
function TeacherLoginByNo(const sNo,sXM:string):Boolean;stdcall;//通过职工号登录
function TeacherLoginBySfzh(const sfzh,sXM:string):Boolean;stdcall;//通过身份证号登录
//获取公告通知,RecCount为希望获取的记录数目,结果返回XML格式的DataSet值。
function GetBullitInfo(const RecCount:Integer=5):string;stdcall;
//获取帮助信息,返回结果为一个多行的字符串值。行与行之间用回车换行符分隔,即通常的#13#10符
function GetHelpInfo:string;stdcall;
//获取用户的网银配置信息:UserDM:商户代码 UserAccount:商户帐号,BankSrvUrl:网银支付接口地址,BankWapSrvUrl:手机支付接口地址
//获取成功返回True,否则返回False
function GetUserNetBankInfo(out UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string):Boolean;stdcall;
//得到用户(商户)代码
function GetUserDM:string;stdcall;
//得到用户(商户)帐号
function GetUserAccount:string;stdcall;
//得到网银支付接口网址
function GetBankSrvUrl:string;stdcall;
//得到手机支付接口网址
function GetBankWapSrvUrl:string;stdcall;
end;
implementation
uses uJxgzlSoapDM;
const
gbSplitChar :string = '<|>';
function Tjxgzl.ExecSql(const sqlstr: string): Boolean;
var
dm:TJxgzlSoapDM;
begin
dm := TJxgzlSoapDM.Create(nil);
try
Result := dm.ExecSqlCmd(sqlstr);
finally
dm.Free;
end;
end;
function Tjxgzl.GetBankSrvUrl: string;
var
UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string;
begin
GetUserNetBankInfo(UserDM, UserAccount, BankSrvUrl, BankWapSrvUrl);
Result := BankSrvUrl;
end;
function Tjxgzl.GetBankWapSrvUrl: string;
var
UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string;
begin
GetUserNetBankInfo(UserDM, UserAccount, BankSrvUrl, BankWapSrvUrl);
Result := BankWapSrvUrl;
end;
function Tjxgzl.GetBullitInfo(const RecCount: Integer=5): string;
var
dm:TJxgzlSoapDM;
sqlStr:string;
begin
Result := '';
dm := TJxgzlSoapDM.Create(nil);
sqlStr := 'select top '+IntToStr(RecCount)+' ID,内容,ActionTime from 公告通知表 order by 是否置顶 desc,ActionTime desc';
try
dm.cds_Query.Close;
dm.cds_Query.CommandText := sqlStr;
dm.cds_Query.Open;
Result := dm.cds_Query.XMLData;
dm.cds_Query.Close;
finally
dm.Free;
end;
end;
function Tjxgzl.GetHelpInfo: string;
var
dm:TJxgzlSoapDM;
sqlStr:string;
begin
Result := '';
dm := TJxgzlSoapDM.Create(nil);
sqlStr := 'select 帮助信息 from 网站帮助信息表';
try
dm.DataSet_Temp.Close;
dm.DataSet_Temp.CommandText := sqlStr;
dm.DataSet_Temp.Open;
Result := dm.DataSet_Temp.Fields[0].AsString;
dm.DataSet_Temp.Close;
finally
dm.Free;
end;
end;
function Tjxgzl.GetJxgzlDelta(const id: string): string;
var
dm:TJxgzlSoapDM;
sData,sqlstr:string;
iCompressType:Integer;
//ICompressType: -1: Auto, 0: Not Compress, 1: Compress
begin
iCompressType := 0; //不压缩
dm := TJxgzlSoapDM.Create(nil);
try
sqlstr := 'select * from 工作量总表_Web where id='+quotedstr(id);
if dm.Query_Data(sqlstr,iCompressType,sData)=S_OK then
Result := sData
else
Result := '';
finally
dm.Free;
end;
end;
function Tjxgzl.GetJxgzlInfo(const sNo, sXnxq: string;const iRecCount,iPage:Integer): string;
var
dm:TJxgzlSoapDM;
sData,sqlstr,sWhere,sWhere2:string;
iCompressType:Integer;
//ICompressType: -1: Auto, 0: Not Compress, 1: Compress
begin
iCompressType := 0; //不压缩
dm := TJxgzlSoapDM.Create(nil);
try
sWhere := ' where zgh='+quotedstr(sNo);
if sXnxq<>'' then sWhere := sWhere+' and xnxq='+quotedstr(sXnxq);
// iRecordCount := IntToStr(dm.GetRecordCountBySql('select count(*) from 工作量总表_Web '+sWhere));
sqlstr := 'select top '+IntToStr(iRecCount)+' * from 工作量总表_Web'+sWhere;
if iPage>1 then
sWhere2 := ' and id not in (select top '+IntToStr(iRecCount*(iPage-1))+' id from 工作量总表_Web '+sWhere+' order by id)';
sqlstr := sqlstr+sWhere2+' order by id';
if dm.Query_Data(sqlstr,iCompressType,sData)=S_OK then
Result := sData
else
Result := '';
finally
dm.Free;
end;
end;
function Tjxgzl.GetJxgzlRecordCount(const sNo, sXnxq: string): Integer;
var
dm:TJxgzlSoapDM;
sqlstr,sWhere:string;
begin
dm := TJxgzlSoapDM.Create(nil);
try
sWhere := ' where zgh='+quotedstr(sNo);
if sXnxq<>'' then sWhere := sWhere+' and xnxq='+quotedstr(sXnxq);
Result := dm.GetRecordCountBySql('select count(*) from 工作量总表_Web '+sWhere);
finally
dm.Free;
end;
end;
function Tjxgzl.GetUserAccount: string;
var
UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string;
begin
GetUserNetBankInfo(UserDM, UserAccount, BankSrvUrl, BankWapSrvUrl);
Result := UserAccount;
end;
function Tjxgzl.GetUserDM: string;
var
UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string;
begin
GetUserNetBankInfo(UserDM, UserAccount, BankSrvUrl, BankWapSrvUrl);
Result := UserDM;
end;
function Tjxgzl.GetUserNetBankInfo(out UserDM, UserAccount, BankSrvUrl,
BankWapSrvUrl:string): Boolean;
var
dm:TJxgzlSoapDM;
sqlStr:string;
begin
dm := TJxgzlSoapDM.Create(nil);
sqlStr := 'select 商户代码,商户帐号,网站支付URL,手机支付URL from 用户网银信息表';
try
dm.cds_Query.Close;
dm.cds_Query.CommandText := sqlStr;
dm.cds_Query.Open;
UserDM := dm.cds_Query.Fields[0].AsString;
UserAccount := dm.cds_Query.Fields[1].AsString;
BankSrvUrl := dm.cds_Query.Fields[2].AsString;
BankWapSrvUrl := dm.cds_Query.Fields[3].AsString;
Result := dm.cds_Query.RecordCount>0;
dm.cds_Query.Close;
finally
dm.Free;
end;
end;
function Tjxgzl.GetXnXqList: string;
var
dm:TJxgzlSoapDM;
sqlStr:string;
begin
Result := '';
dm := TJxgzlSoapDM.Create(nil);
sqlStr := 'select distinct xnxq from 工作量总表_Web order by xnxq';
try
dm.cds_Query.Close;
dm.cds_Query.CommandText := sqlStr;
dm.cds_Query.Open;
Result := dm.cds_Query.XMLData;
dm.cds_Query.Close;
finally
dm.Free;
end;
end;
function Tjxgzl.IsCanNetPrintZKZ: Boolean;
var
sqlStr:string;
begin
sqlStr := 'select count(*) from 网上报名时间设置表 where (打印准考证=1)';
Result := RecordIsExists(sqlstr);
end;
function Tjxgzl.IsValidIP: Boolean;
var
dm:TJxgzlSoapDM;
begin
//Result := False;
dm := TJxgzlSoapDM.Create(nil);
try
Result := dm.IsValidIP(GetSOAPWebModule.Request.RemoteAddr);
finally
dm.Free;
end;
end;
function Tjxgzl.RecordIsExists(const sqlstr: string): Boolean;
var
dm:TJxgzlSoapDM;
begin
dm := TJxgzlSoapDM.Create(nil);
try
Result := dm.RecordIsExists(sqlstr);
finally
dm.Free;
end;
end;
function Tjxgzl.RegIsOK: Boolean;
var
dm:TJxgzlSoapDM;
begin
dm := TJxgzlSoapDM.Create(nil);
try
Result := dm.RegIsOK;
finally
dm.Free;
end;
end;
function Tjxgzl.SrvIsOK: Boolean;
begin
Result := RegIsOK;
end;
function Tjxgzl.TeacherIsExistsByNo(const sNo, sXnxq: string): Boolean;
var
sqlstr:string;
begin
sqlstr := 'select count(*) from 工作量总表_Web where zgh='+quotedstr(sNo);
if sXnxq<>'' then
sqlstr := sqlstr+' and xnxq='+quotedstr(sXnxq);
Result := RecordIsExists(sqlstr);
end;
function Tjxgzl.TeacherLoginByNo(const sNo, sXM: string): Boolean;
var
sqlstr:string;
begin
//WriteLogoutLog(sNo);
sqlstr := 'select count(*) from 工作量总表 where 教师职工号='+quotedstr(sNo)+' and 教师姓名='+quotedstr(sXM);
Result := RecordIsExists(sqlstr);
{
if Result then
WriteLoginLog(sNo,'Ver: 1.0.0.3')
else
begin
if KsIsExistsByUserName(UserName) then
WriteSysLog(UserName,'Web登录失败!');
end;
}
end;
function Tjxgzl.TeacherLoginBySfzh(const sfzh,sXM: string): Boolean;
var
sqlstr:string;
begin
//WriteLogoutLog(sNo);
sqlstr := 'select count(*) from 工作量总表 where 身份证号='+quotedstr(sfzh)+' and 教师姓名='+quotedstr(sXM);
Result := RecordIsExists(sqlstr);
{
if Result then
WriteLoginLog(sNo,'Ver: 1.0.0.3')
else
begin
if KsIsExistsByUserName(UserName) then
WriteSysLog(UserName,'Web登录失败!');
end;
}
end;
function Tjxgzl.WriteLoginLog(const UserId, sVer: string): Boolean;
var
sIP,sSrvHost,sqlstr:String;
begin
sIP := GetSOAPWebModule.Request.RemoteAddr;
sSrvHost := UserId; //GetSOAPWebModule.Request.RemoteHost;
if Length(sSrvHost)>30 then
sSrvHost := Copy(sSrvHost,1,30);
sqlstr := 'Insert Into 操作员登录表 (操作员编号,登录时间,登录IP,SrvHost,是否在线,客户端版本) values'+
'('+quotedstr('WebUser')+',GetDate(),'+quotedstr(sIP)+','+quotedstr(sSrvHost)+',1,'+quotedstr(sVer)+')';
Result := ExecSql(sqlstr);
end;
function Tjxgzl.WriteLogoutLog(const UserId: string): Boolean;
var
sIP,sqlstr:String;
begin
sIP := GetSOAPWebModule.Request.RemoteAddr;
sqlstr := 'Update 操作员登录表 Set 注销时间=getdate(),注销IP='+quotedstr(sIP)+',是否在线=0 '+
'where 操作员编号='+quotedstr(UserID)+' and 是否在线=1';
Result := ExecSql(sqlstr);
end;
function Tjxgzl.WriteSysLog(const UserId, sWhat: string): Boolean;
var
sIP,sqlstr:String; //sSrvHost,
begin
sIP := GetSOAPWebModule.Request.RemoteAddr;
sqlstr := 'Insert Into 操作日志表 (用户,ActionTime,内容,IP) values'+
'('+quotedstr(UserID)+',GetDate(),'+quotedstr(sWhat)+','+quotedstr(sIP)+')';
Result := ExecSql(sqlstr);
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(Tjxgzl);
end.
|
unit kwLoadFromFile;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Keywords4Daily"
// Модуль: "w:/common/components/rtl/Garant/Keywords4Daily/kwLoadFromFile.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Tests::Keywords4Daily::SupportWords::LoadFromFile
//
// Загружает файл в форму дочернего класса TPrimTextLoadForm.
// *Формат:* имя_файла LoadFromFile
// *Примечание:* Создан специально для тестов DailyTests в результате переделок form:Needs. Имя
// файла можно подавать без пути - будет автоматически добавлен путь к данным для тестов.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoScripts) AND not defined(NoVCM)}
uses
tfwScriptingInterfaces
;
{$IfEnd} //nsTest AND not NoScripts AND not NoVCM
{$If defined(nsTest) AND not defined(NoScripts) AND not defined(NoVCM)}
type
{$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas}
_LoadUnits_Parent_ = _tfwAutoregisteringWord_;
{$Include w:\common\components\gui\Garant\Daily\LoadUnits.imp.pas}
TkwLoadFromFile = {final} class(_LoadUnits_)
{* Загружает файл в форму дочернего класса TPrimTextLoadForm.
*Формат:* имя_файла LoadFromFile
*Примечание:* Создан специально для тестов DailyTests в результате переделок form:Needs. Имя файла можно подавать без пути - будет автоматически добавлен путь к данным для тестов. }
protected
// realized methods
procedure DoDoIt(const aCtx: TtfwContext); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwLoadFromFile
{$IfEnd} //nsTest AND not NoScripts AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoScripts) AND not defined(NoVCM)}
uses
tfwAutoregisteredDiction,
tfwScriptEngine,
PrimTextLoad_Form,
Document_Const
;
{$IfEnd} //nsTest AND not NoScripts AND not NoVCM
{$If defined(nsTest) AND not defined(NoScripts) AND not defined(NoVCM)}
type _Instance_R_ = TkwLoadFromFile;
{$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas}
{$Include w:\common\components\gui\Garant\Daily\LoadUnits.imp.pas}
// start class TkwLoadFromFile
procedure TkwLoadFromFile.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_509A5CCB022A_var*
var
l_Form : TObject;
l_FileName : String;
//#UC END# *4DAEEDE10285_509A5CCB022A_var*
begin
//#UC START# *4DAEEDE10285_509A5CCB022A_impl*
if aCtx.rEngine.IsTopObj then
begin
l_Form := aCtx.rEngine.PopObj;
if aCtx.rEngine.IsTopString then
begin
l_FileName := aCtx.rEngine.PopDelphiString;
l_FileName := aCtx.rCaller.ResolveInputFilePath(l_FileName);
with (l_Form as TPrimTextLoadForm) do
begin
LoadManager.FileName := l_FileName;
LoadManager.Load(TextSource, k2_idDocument);
AfterLoad;
end // with (aForm as TPrimTextLoadForm) do
end
else
Assert(False, 'Не задано название файла!');
end // if aCtx.rEngine.IsTopObj then
else
Assert(False, 'Не задана форма для загрузки текста!');
//#UC END# *4DAEEDE10285_509A5CCB022A_impl*
end;//TkwLoadFromFile.DoDoIt
class function TkwLoadFromFile.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'LoadFromFile';
end;//TkwLoadFromFile.GetWordNameForRegister
{$IfEnd} //nsTest AND not NoScripts AND not NoVCM
initialization
{$If defined(nsTest) AND not defined(NoScripts) AND not defined(NoVCM)}
{$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas}
{$IfEnd} //nsTest AND not NoScripts AND not NoVCM
end. |
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{*
Combines two matrices, by the given operator
*}
function CombineMatrix(Mat1:T2DByteArray; Mat2:T2DByteArray; OP:Char): T2DByteArray; overload;
begin
if not(length(mat1) = length(mat2)) then
NewException('Matrices must have the same size');
if (length(mat1) = 0) then
NewException('Matrices must be initalized');
if not(op in ['*','/','+','-']) then
NewException('Undefined operator: "'+op+'", expected any of "*", "/", "+" or "-"');
if not(length(mat1[0]) = length(mat2[0])) then
NewException('Matrices must have the same size');
case OP of
'*': Result := Mat1*Mat2;
'/': Result := Mat1/Mat2;
'+': Result := Mat1+Mat2;
'-': Result := Mat1-Mat2;
end;
end;
function CombineMatrix(Mat1:T2DIntArray; Mat2:T2DIntArray; OP:Char): T2DIntArray; overload;
begin
if not(length(mat1) = length(mat2)) then
NewException('Matrices must have the same size');
if (length(mat1) = 0) then
NewException('Matrices must be initalized');
if not(op in ['*','/','+','-']) then
NewException('Undefined operator: "'+op+'", expected any of "*", "/", "+" or "-"');
if not(length(mat1[0]) = length(mat2[0])) then
NewException('Matrices must have the same size');
case OP of
'*': Result := Mat1*Mat2;
'/': Result := Mat1/Mat2;
'+': Result := Mat1+Mat2;
'-': Result := Mat1-Mat2;
end;
end;
function CombineMatrix(Mat1:T2DFloatArray; Mat2:T2DFloatArray; OP:Char): T2DFloatArray; overload;
begin
if not(length(mat1) = length(mat2)) then
NewException('Matrices must have the same size');
if (length(mat1) = 0) then
NewException('Matrices must be initalized');
if not(op in ['*','/','+','-']) then
NewException('Undefined operator: "'+op+'", expected any of "*", "/", "+" or "-"');
if not(length(mat1[0]) = length(mat2[0])) then
NewException('Matrices must have the same size');
case OP of
'*': Result := Mat1*Mat2;
'/': Result := Mat1/Mat2;
'+': Result := Mat1+Mat2;
'-': Result := Mat1-Mat2;
end;
end;
function CombineMatrix(Mat1:T2DDoubleArray; Mat2:T2DDoubleArray; OP:Char): T2DDoubleArray; overload;
begin
if not(length(mat1) = length(mat2)) then
NewException('Matrices must have the same size');
if (length(mat1) = 0) then
NewException('Matrices must be initalized');
if not(op in ['*','/','+','-']) then
NewException('Undefined operator: "'+op+'", expected any of "*", "/", "+" or "-"');
if not(length(mat1[0]) = length(mat2[0])) then
NewException('Matrices must have the same size');
case OP of
'*': Result := Mat1*Mat2;
'/': Result := Mat1/Mat2;
'+': Result := Mat1+Mat2;
'-': Result := Mat1-Mat2;
end;
end;
function CombineMatrix(Mat1:T2DExtArray; Mat2:T2DExtArray; OP:Char): T2DExtArray; overload;
begin
if not(length(mat1) = length(mat2)) then
NewException('Matrices must have the same size');
if (length(mat1) = 0) then
NewException('Matrices must be initalized');
if not(op in ['*','/','+','-']) then
NewException('Undefined operator: "'+op+'", expected any of "*", "/", "+" or "-"');
if not(length(mat1[0]) = length(mat2[0])) then
NewException('Matrices must have the same size');
case OP of
'*': Result := Mat1*Mat2;
'/': Result := Mat1/Mat2;
'+': Result := Mat1+Mat2;
'-': Result := Mat1-Mat2;
end;
end;
|
unit ufrmCadPadrao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, ExtCtrls, DBCtrls, DB, StdCtrls, Mask, DBClientActns,
DBActns, ComCtrls, Buttons, Grids, DBGrids, DBClient;
type
TfrmCadastro = class(TForm)
DataSource1: TDataSource;
StatusBar1: TStatusBar;
GroupBox1: TGroupBox;
btnNovo: TBitBtn;
btnExcluir: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnEditar: TBitBtn;
btnSair: TBitBtn;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
Panel1: TPanel;
procedure DataSource1StateChange(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnEditarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnSairClick(Sender: TObject);
procedure LocalizarExAfterSearch(Sender: TObject; AModalResult: Integer);
procedure LocalizarExecute(Sender: TObject);
procedure btnNovoEnter(Sender: TObject);
private
{ Private declarations }
public
procedure EnableDisableControls(Value: Boolean);
function FieldsWrithe(DtSrc: TDataSource): Boolean;
end;
var
frmCadastro: TfrmCadastro;
implementation
uses UDM;
{$R *.dfm}
function TfrmCadastro.FieldsWrithe(DtSrc: TDataSource): Boolean;
var
i: Integer;
// : verifica quais os campos que estão em branco no cadastro
begin
inherited;
Result := True; // : assume que estão todos preenchidos
for i := 0 to DtSrc.DataSet.FieldCount - 1 do
if DtSrc.DataSet.Fields[i].Required then
BEGIN
if (DtSrc.DataSet.Fields[i].IsNull) Or
(DtSrc.DataSet.Fields[i].AsString = '') then
begin
MessageDlg('Preencha o campo " ' + DtSrc.DataSet.Fields[i]
.DisplayLabel + '"', mtWarning, [mbOk], 0);
Result := False;
DtSrc.DataSet.Fields[i].FocusControl; // : coloca o foco no controle
Break;
end;
end;
end;
procedure TfrmCadastro.DataSource1StateChange(Sender: TObject);
var
x: Boolean;
begin
x := True;
btnNovo.Enabled := Not(DataSource1.State in [DSINSERT, DSEDIT]);
btnEditar.Enabled := Not(DataSource1.State in [DSINSERT, DSEDIT]);
btnExcluir.Enabled := Not(DataSource1.State in [DSINSERT, DSEDIT]);
// btnLocalizar.Enabled := Not (DataSource1.State in [DSINSERT,DSEDIT]);
btnGravar.Enabled := DataSource1.State in [DSINSERT, DSEDIT];
btnCancelar.Enabled := DataSource1.State in [DSINSERT, DSEDIT];
btnSair.Enabled := Not(DataSource1.State in [DSINSERT, DSEDIT]);
if not(DataSource1.State in [DSINSERT, DSEDIT]) then
x := False;
EnableDisableControls(x);
end;
procedure TfrmCadastro.btnNovoClick(Sender: TObject);
begin
if not(DataSource1.DataSet.State in [DSINSERT, DSEDIT]) then
begin
DataSource1.DataSet.Insert;
// DataSource1.DataSet.Fields[1].FocusControl;
end;
end;
procedure TfrmCadastro.btnExcluirClick(Sender: TObject);
begin
if (DataSource1.DataSet.Active) and (DataSource1.DataSet.RecordCount > 0) then
begin
if MessageDlg('Tem certeza que deseja excluir o registro ?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
try
DataSource1.DataSet.Delete;
except
ShowMessage('Não foi possível excluir o registro');
end;
end;
end;
end;
procedure TfrmCadastro.btnGravarClick(Sender: TObject);
begin
{ : salvo as dados se os campos estiverem preenchidos }
if FieldsWrithe(DataSource1) and (DataSource1.State in [DSEDIT, DSINSERT])
then
begin
DataSource1.DataSet.Post;
MessageDlg('O registro foi gravado com sucesso .', mtInformation, [mbOk],
0);
end;
end;
procedure TfrmCadastro.btnCancelarClick(Sender: TObject);
begin
if (DataSource1.DataSet.State in [DSINSERT, DSEDIT]) then
DataSource1.DataSet.Cancel;
end;
procedure TfrmCadastro.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if DataSource1.State in [DSEDIT, DSINSERT] then
begin
case MessageDlg('Deseja salvar as alterações realizados no Cadastro ?',
mtConfirmation, [mbYes, mbNo], 0) of
mrYes:
begin
btnGravar.Click;
end;
mrNo:
begin
DataSource1.DataSet.Cancel;
DataSource1.DataSet.Close;
Close;
end;
end;
end
else
begin
DataSource1.DataSet.Close;
end;
end;
procedure TfrmCadastro.FormKeyPress(Sender: TObject; var Key: Char);
begin
{ : troca ENTER por TAB }
if Key = #13 then
begin
Perform(CM_DialogKey, VK_TAB, 0);
Key := #0;
end
end;
procedure TfrmCadastro.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{ : Esc para Sair }
if Key = VK_Escape then
begin
DataSource1.DataSet.Close;
Close;
end;
end;
procedure TfrmCadastro.EnableDisableControls(Value: Boolean);
var
i: Integer;
begin
{ : faz um laço em todos os componentes }
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TDBEdit) then (Components[i] as TDBEdit)
.Enabled := Value;
if (Components[i] is TDBComboBox) then (Components[i] as TDBComboBox)
.Enabled := Value;
if (Components[i] is TDBLookupComboBox) then
(Components[i] as TDBLookupComboBox)
.Enabled := Value;
if (Components[i] is TDBMemo) then (Components[i] as TDBMemo)
.Enabled := Value;
{ if (Components[i] is TDBDateTime) then
(Components[i] as TDBDateTime).Enabled := Value; }
end;
end;
procedure TfrmCadastro.btnEditarClick(Sender: TObject);
begin
DataSource1.DataSet.Edit;
// DataSource1.DataSet.Fields[1].FocusControl;
end;
procedure TfrmCadastro.FormShow(Sender: TObject);
begin
DataSource1.DataSet.Open;
DataSource1.DataSet.First;
end;
procedure TfrmCadastro.btnSairClick(Sender: TObject);
begin
DataSource1.DataSet.Close;
Close;
end;
procedure TfrmCadastro.LocalizarExAfterSearch(Sender: TObject;
AModalResult: Integer);
begin
if AModalResult = mrOK then
begin
EnableDisableControls(True);
end;
end;
procedure TfrmCadastro.LocalizarExecute(Sender: TObject);
begin
{ : verifica se esta em modo de edição ou inserção }
if DataSource1.State in [DSEDIT, DSINSERT] then
case MessageDlg('Deseja salvar as alterações realizados no Cadastro?',
mtConfirmation, [mbYes, mbNo, mbCancel], 0) of
mrYes:
btnGravar.Click;
mrNo:
DataSource1.DataSet.Cancel;
end
else
// LocalizarEx.Execute;
end;
procedure TfrmCadastro.btnNovoEnter(Sender: TObject);
begin
StatusBar1.Panels[0].Text := (Sender as TControl).Hint;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSProtocolVersion.pas }
{ File version: 5.02 }
{ Description: TLS Protocol Version }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ 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. }
{ 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 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/09 5.02 Create flcTLSProtocolVersion unit from flcTLSUtils unit. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSProtocolVersion;
interface
{ }
{ ProtocolVersion }
{ }
type
TTLSProtocolVersion = packed record
major, minor : Byte;
end;
PTLSProtocolVersion = ^TTLSProtocolVersion;
const
TLSProtocolVersionSize = Sizeof(TTLSProtocolVersion);
SSLProtocolVersion20 : TTLSProtocolVersion = (major: 0; minor: 2);
SSLProtocolVersion30 : TTLSProtocolVersion = (major: 3; minor: 0);
TLSProtocolVersion10 : TTLSProtocolVersion = (major: 3; minor: 1);
TLSProtocolVersion11 : TTLSProtocolVersion = (major: 3; minor: 2);
TLSProtocolVersion12 : TTLSProtocolVersion = (major: 3; minor: 3);
TLSProtocolVersion13 : TTLSProtocolVersion = (major: 3; minor: 4);
procedure InitSSLProtocolVersion30(var A: TTLSProtocolVersion);
procedure InitTLSProtocolVersion10(var A: TTLSProtocolVersion);
procedure InitTLSProtocolVersion11(var A: TTLSProtocolVersion);
procedure InitTLSProtocolVersion12(var A: TTLSProtocolVersion);
function IsTLSProtocolVersion(const A, B: TTLSProtocolVersion): Boolean;
function IsSSL2(const A: TTLSProtocolVersion): Boolean;
function IsSSL3(const A: TTLSProtocolVersion): Boolean;
function IsTLS10(const A: TTLSProtocolVersion): Boolean;
function IsTLS11(const A: TTLSProtocolVersion): Boolean;
function IsTLS12(const A: TTLSProtocolVersion): Boolean;
function IsTLS13(const A: TTLSProtocolVersion): Boolean;
function IsTLS10OrLater(const A: TTLSProtocolVersion): Boolean;
function IsTLS11OrLater(const A: TTLSProtocolVersion): Boolean;
function IsTLS12OrLater(const A: TTLSProtocolVersion): Boolean;
function IsPostTLS12(const A: TTLSProtocolVersion): Boolean;
function IsKnownTLSVersion(const A: TTLSProtocolVersion): Boolean; ////
function TLSProtocolVersionToStr(const A: TTLSProtocolVersion): String;
function TLSProtocolVersionName(const A: TTLSProtocolVersion): String;
{ }
{ Tests }
{ }
{$IFDEF TLS_TEST}
procedure Test;
{$ENDIF}
implementation
uses
{ System }
SysUtils;
{ }
{ ProtocolVersion }
{ }
procedure InitSSLProtocolVersion30(var A: TTLSProtocolVersion);
begin
A := SSLProtocolVersion30;
end;
procedure InitTLSProtocolVersion10(var A: TTLSProtocolVersion);
begin
A := TLSProtocolVersion10;
end;
procedure InitTLSProtocolVersion11(var A: TTLSProtocolVersion);
begin
A := TLSProtocolVersion11;
end;
procedure InitTLSProtocolVersion12(var A: TTLSProtocolVersion);
begin
A := TLSProtocolVersion12;
end;
function IsTLSProtocolVersion(const A, B: TTLSProtocolVersion): Boolean;
begin
Result :=
(A.major = B.major) and
(A.minor = B.minor);
end;
function IsSSL2(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, SSLProtocolVersion20);
end;
function IsSSL3(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, SSLProtocolVersion30);
end;
function IsTLS10(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, TLSProtocolVersion10);
end;
function IsTLS11(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, TLSProtocolVersion11);
end;
function IsTLS12(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, TLSProtocolVersion12);
end;
function IsTLS13(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLSProtocolVersion(A, TLSProtocolVersion13);
end;
function IsTLS10OrLater(const A: TTLSProtocolVersion): Boolean;
begin
Result :=
((A.major = TLSProtocolVersion10.major) and
(A.minor >= TLSProtocolVersion10.minor))
or
(A.major > TLSProtocolVersion10.major);
end;
function IsTLS11OrLater(const A: TTLSProtocolVersion): Boolean;
begin
Result :=
((A.major = TLSProtocolVersion11.major) and
(A.minor >= TLSProtocolVersion11.minor))
or
(A.major > TLSProtocolVersion11.major);
end;
function IsTLS12OrLater(const A: TTLSProtocolVersion): Boolean;
begin
Result :=
((A.major = TLSProtocolVersion12.major) and
(A.minor >= TLSProtocolVersion12.minor))
or
(A.major > TLSProtocolVersion12.major);
end;
function IsPostTLS12(const A: TTLSProtocolVersion): Boolean;
begin
Result :=
((A.major = TLSProtocolVersion12.major) and
(A.minor > TLSProtocolVersion12.minor))
or
(A.major > TLSProtocolVersion12.major);
end;
function IsKnownTLSVersion(const A: TTLSProtocolVersion): Boolean;
begin
Result := IsTLS12(A) or IsTLS11(A) or IsTLS10(A) or IsSSL3(A);
end;
function TLSProtocolVersionToStr(const A: TTLSProtocolVersion): String;
begin
Result := IntToStr(A.major) + '.' + IntToStr(A.minor);
end;
function TLSProtocolVersionName(const A: TTLSProtocolVersion): String;
begin
if IsSSL2(A) then
Result := 'SSL2' else
if IsSSL3(A) then
Result := 'SSL3' else
if IsTLS10(A) then
Result := 'TLS1.0' else
if IsTLS11(A) then
Result := 'TLS1.1' else
if IsTLS12(A) then
Result := 'TLS1.2'
else
if IsTLS13(A) then
Result := 'TLS1.3'
else
Result := '[TLS' + TLSProtocolVersionToStr(A) + ']';
end;
{ }
{ Tests }
{ }
{$IFDEF TLS_TEST}
{$ASSERTIONS ON}
procedure Test;
begin
Assert(TLSProtocolVersionSize = 2);
Assert(IsTLS12OrLater(TLSProtocolVersion12));
Assert(not IsTLS12OrLater(TLSProtocolVersion10));
Assert(TLSProtocolVersionToStr(TLSProtocolVersion12) = '3.3');
Assert(TLSProtocolVersionName(SSLProtocolVersion20) = 'SSL2');
Assert(TLSProtocolVersionName(SSLProtocolVersion30) = 'SSL3');
Assert(TLSProtocolVersionName(TLSProtocolVersion10) = 'TLS1.0');
Assert(TLSProtocolVersionName(TLSProtocolVersion11) = 'TLS1.1');
Assert(TLSProtocolVersionName(TLSProtocolVersion12) = 'TLS1.2');
end;
{$ENDIF}
end.
|
unit ChromeLikeThemedWindowCaptionButtons;
// Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeThemedWindowCaptionButtons.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "ChromeLikeThemedWindowCaptionButtons" MUID: (533D1518032F)
interface
{$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)}
uses
l3IntfUses
, ChromeLikeBaseThemedWindowCaptionButton
, l3Interfaces
;
type
TChromeLikeThemedCloseCaptionButton = class(TChromeLikeBaseThemedWindowCaptionButton)
protected
function GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; override;
function GetHintText: Il3CString; override;
end;//TChromeLikeThemedCloseCaptionButton
TChromeLikeThemedMaximizeCaptionButton = class(TChromeLikeBaseThemedWindowCaptionButton)
protected
function GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; override;
function NeedUpdateHint: Boolean; override;
function GetHintText: Il3CString; override;
end;//TChromeLikeThemedMaximizeCaptionButton
TChromeLikeThemedMinimizeCaptionButton = class(TChromeLikeBaseThemedWindowCaptionButton)
protected
function GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; override;
function GetHintText: Il3CString; override;
end;//TChromeLikeThemedMinimizeCaptionButton
{$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)
implementation
{$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)}
uses
l3ImplUses
, UxTheme
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
, ChromeLikeBaseWindowCaptionButton
, ChromeLikeWindowCaptionButtonsRes
{$If NOT Defined(NoScripts)}
, TtfwClassRef_Proxy
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *533D1518032Fimpl_uses*
//#UC END# *533D1518032Fimpl_uses*
;
function TChromeLikeThemedCloseCaptionButton.GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams;
//#UC START# *533D091902B8_533D0B3A02F3_var*
const
cCloseCaptionButtonStateArr: array[TChromeLikeWindowCaptionButtonState] of Integer =
(CBS_DISABLED, CBS_HOT, CBS_NORMAL, CBS_PUSHED);
//#UC END# *533D091902B8_533D0B3A02F3_var*
begin
//#UC START# *533D091902B8_533D0B3A02F3_impl*
Result := inherited GetPaintParams;
with Result do
begin
rPartID := WP_CLOSEBUTTON;
rStateID := cCloseCaptionButtonStateArr[State];
end;//with Result
//#UC END# *533D091902B8_533D0B3A02F3_impl*
end;//TChromeLikeThemedCloseCaptionButton.GetPaintParams
function TChromeLikeThemedCloseCaptionButton.GetHintText: Il3CString;
//#UC START# *5474500600DA_533D0B3A02F3_var*
//#UC END# *5474500600DA_533D0B3A02F3_var*
begin
//#UC START# *5474500600DA_533D0B3A02F3_impl*
Result := str_Close.AsCStr;
//#UC END# *5474500600DA_533D0B3A02F3_impl*
end;//TChromeLikeThemedCloseCaptionButton.GetHintText
function TChromeLikeThemedMaximizeCaptionButton.GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams;
//#UC START# *533D091902B8_533D0B640155_var*
const
cMaximizeRestoreCaptionPartArr: array[Boolean] of Integer = (WP_MAXBUTTON,
WP_RESTOREBUTTON);
//
cMaximizeCaptionButtonStateArr: array[TChromeLikeWindowCaptionButtonState] of Integer =
(MAXBS_DISABLED, MAXBS_HOT, MAXBS_NORMAL, MAXBS_PUSHED);
//
cRestoreCaptionButtonStateArr: array[TChromeLikeWindowCaptionButtonState] of Integer =
(RBS_DISABLED, RBS_HOT, RBS_NORMAL, RBS_PUSHED);
var
l_IsMaximized: Boolean;
l_State: Integer;
//#UC END# *533D091902B8_533D0B640155_var*
begin
//#UC START# *533D091902B8_533D0B640155_impl*
Result := inherited GetPaintParams;
if (ParentForm <> nil) then
begin
// Если окно развернуто на весь экран - рисуем кнопку "Восстановить",
// если нет - "Развернуть"
l_IsMaximized := (ParentForm.WindowState = wsMaximized);
Result.rPartID := cMaximizeRestoreCaptionPartArr[l_IsMaximized];
if not l_IsMaximized then
l_State := cMaximizeCaptionButtonStateArr[State]
else
l_State := cRestoreCaptionButtonStateArr[State];
Result.rStateID := l_State;
end;//if (ParentForm <> nil)
//#UC END# *533D091902B8_533D0B640155_impl*
end;//TChromeLikeThemedMaximizeCaptionButton.GetPaintParams
function TChromeLikeThemedMaximizeCaptionButton.NeedUpdateHint: Boolean;
//#UC START# *54744FED0113_533D0B640155_var*
//#UC END# *54744FED0113_533D0B640155_var*
begin
//#UC START# *54744FED0113_533D0B640155_impl*
Result := True;
//#UC END# *54744FED0113_533D0B640155_impl*
end;//TChromeLikeThemedMaximizeCaptionButton.NeedUpdateHint
function TChromeLikeThemedMaximizeCaptionButton.GetHintText: Il3CString;
//#UC START# *5474500600DA_533D0B640155_var*
//#UC END# *5474500600DA_533D0B640155_var*
begin
//#UC START# *5474500600DA_533D0B640155_impl*
if (ParentForm.WindowState = wsMaximized) then
Result := str_Restore.AsCStr
else
Result := str_Maximize.AsCStr;
//#UC END# *5474500600DA_533D0B640155_impl*
end;//TChromeLikeThemedMaximizeCaptionButton.GetHintText
function TChromeLikeThemedMinimizeCaptionButton.GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams;
//#UC START# *533D091902B8_533D0B4B022A_var*
const
cMinimizeCaptionButtonStateArr: array[TChromeLikeWindowCaptionButtonState] of Integer =
(MINBS_DISABLED, MINBS_HOT, MINBS_NORMAL, MINBS_PUSHED);
//#UC END# *533D091902B8_533D0B4B022A_var*
begin
//#UC START# *533D091902B8_533D0B4B022A_impl*
Result := inherited GetPaintParams;
with Result do
begin
rPartID := WP_MINBUTTON;
rStateID := cMinimizeCaptionButtonStateArr[State];
end;//with Result
//#UC END# *533D091902B8_533D0B4B022A_impl*
end;//TChromeLikeThemedMinimizeCaptionButton.GetPaintParams
function TChromeLikeThemedMinimizeCaptionButton.GetHintText: Il3CString;
//#UC START# *5474500600DA_533D0B4B022A_var*
//#UC END# *5474500600DA_533D0B4B022A_var*
begin
//#UC START# *5474500600DA_533D0B4B022A_impl*
Result := str_Minimize.AsCStr;
//#UC END# *5474500600DA_533D0B4B022A_impl*
end;//TChromeLikeThemedMinimizeCaptionButton.GetHintText
initialization
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(TChromeLikeThemedCloseCaptionButton);
{* Регистрация TChromeLikeThemedCloseCaptionButton }
{$IfEnd} // NOT Defined(NoScripts)
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(TChromeLikeThemedMaximizeCaptionButton);
{* Регистрация TChromeLikeThemedMaximizeCaptionButton }
{$IfEnd} // NOT Defined(NoScripts)
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(TChromeLikeThemedMinimizeCaptionButton);
{* Регистрация TChromeLikeThemedMinimizeCaptionButton }
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)
end.
|
unit xLngManager;
interface
uses
{$IFNDEF NODESIGN}DesignEditors,{$ENDIF}
SysUtils, Classes, IniFiles, Contnrs, xLog;
type
TxStorageType = (stText, stDLL);
TxLngManager = class;
//------------------------------------------------------------
TxLngManItem = class
private
FParent: TxLngManItem;
FText: string;
FKeyName: string;
procedure SetText(const Value: string);
procedure SetKeyName(const Value: string);
public
constructor Create(const AKeyName, AText: string; AParent: TxLngManItem = nil); virtual;
property KeyName: string read FKeyName write SetKeyName;
property Parent: TxLngManItem read FParent write FParent;
property Text: string read FText write SetText;
end;
//------------------------------------------------------------
TxLngFile = class
private
FLngFile: TIniFile;
FItems: TObjectList;
FParent: TxLngManager;
FCfgFile: string;
FFileName: string;
FDesc: string;
FLangName: string;
procedure SetFileName(const Value: string);
procedure SetDesc(const Value: string);
function GetItem(Index: Integer): TxLngManItem;
function GetCount: Integer;
procedure RecreateIniFile;
function GetIndex: Integer;
procedure SetLangName(const Value: string);
protected
function AddItem(const AKeyName, AText: string; AParent: TxLngManItem): TxLngManItem;
public
constructor Create(const ADesc, AFileName, AName, ACfgFile: string); reintroduce;
destructor Destroy; override;
function AddItemEx(const AKeyName, AText: string; AParent: TxLngManItem): TxLngManItem;
procedure Clear;
procedure DropItem(AItem: TxLngManItem);
function GetRS(const ASection, AKeyName: string): string;
procedure Load;
procedure UpdateItem(AItem: TxLngManItem; const AKeyName, AText: string);
function Read(const ASection, AKey: string): string;
procedure Write(const ASection, AKey, AValue: string);
property CfgFile: string read FCfgFile write FCfgFile;
property Count: Integer read GetCount;
property Desc: string read FDesc write SetDesc;
property FileName: string read FFileName write SetFileName;
property LangName: string read FLangName write SetLangName;
property Index: Integer read GetIndex;
property Items[Index: Integer]: TxLngManItem read GetItem;
property Parent: TxLngManager read FParent;
end;
//------------------------------------------------------------
TxLngManager = class(TComponent)
private
FActive: Boolean;
FFiles: TObjectList;
FModifyOnly: Boolean;
FActiveLngIndex: Integer;
FStorageType: TxStorageType;
FCfgFile: TFileName;
FDefaultSection: String;
procedure SetActive(const Value: Boolean);
procedure LoadItems;
procedure SetActiveLngIndex(const Value: Integer);
function GetActiveLngFile: TxLngFile;
procedure SetStorageType(const Value: TxStorageType);
function GetFile(Index: Integer): TxLngFile;
function GetFilesCount: Integer;
procedure SetFile(Index: Integer; const Value: TxLngFile);
procedure SetCfgFile(const Value: TFileName);
function ReadCfgFile: Boolean;
function GetActiveLng: string;
procedure SetActiveLng(const Value: string);
procedure setDefaultSection(const Value: String);
protected
procedure Loaded; override;
public
Logger: TxLog;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddFile: TxLngFile;
procedure DropFile(AIndex: Integer);
function GetRS(const ASection, AKeyName: string; emptyIfMissing: Boolean = False): string;
procedure Clear;
procedure ClearCfg;
procedure Open;
procedure Close;
procedure ShowEditor;
property ActiveLng: TxLngFile read GetActiveLngFile;
property FilesCount: Integer read GetFilesCount;
property Files[Index: Integer]: TxLngFile read GetFile write SetFile;
published
property Active: Boolean read FActive write SetActive;
property ActiveLngIndex: Integer read FActiveLngIndex write SetActiveLngIndex default -1;
property ActiveLngDesc: string read GetActiveLng write SetActiveLng;
property CfgFile: TFileName read FCfgFile write SetCfgFile;
property DefaultSection: String read FDefaultSection write setDefaultSection;
property ModifyOnly: Boolean read FModifyOnly write FModifyOnly default False;
property StorageType: TxStorageType read FStorageType write SetStorageType default stText;
end;
//------------------------------------------------------------
{$IFNDEF NODESIGN}
TxLngManEditor = class(TComponentEditor)
public
function GetVerb(Index: Integer): string; override;
function GetVerbCount: integer; override;
procedure ExecuteVerb(Index: Integer); override;
end;
{$ENDIF}
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
{$IFNDEF NODESIGN}xLngManDsgn,{$ENDIF}
udebug, StrUtils, xStrUtils, ComObj, Dialogs, Controls;
{$IFDEF UDEBUG}var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';{$ENDIF}
//==============================================================================================
//==============================================================================================
//==============================================================================================
//==============================================================================================
{$IFNDEF NODESIGN}
procedure TxLngManEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: with TxLngManager(Component) do begin
if not Active then Active := True;
ShowEditor;
end;
end;
end;
//==============================================================================================
function TxLngManEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Items...';
end;
end;
//==============================================================================================
function TxLngManEditor.GetVerbCount: integer;
begin
Result := 1;
end;
{$ENDIF}
//==============================================================================================
//==============================================================================================
//==============================================================================================
//==============================================================================================
procedure TxLngManager.Clear;
begin
FFiles.Clear;
end;
//==============================================================================================
constructor TxLngManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFiles := TObjectList.Create(True);
FActiveLngIndex := -1;
Logger := nil;
FDefaultSection := '';
end;
//==============================================================================================
destructor TxLngManager.Destroy;
begin
Clear;
FFiles.Destroy;
inherited;
end;
//==============================================================================================
procedure TxLngManager.LoadItems;
var
i: Integer;
begin
for i := 0 to FilesCount - 1 do begin
{$IFDEF UDEBUG}debugInstantLog('TxLngManager.LoadItems: reading lang file ' + Files[i].FileName);{$ENDIF}
Files[i].Clear;
Files[i].Load;
end;
end;
//==============================================================================================
procedure TxLngManager.SetActive(const Value: Boolean);
begin
if FActive = Value then Exit;
FActive := Value;
if FActive then begin
if csLoading in ComponentState then begin
FActive := False;
ActiveLngIndex := -1;
Clear;
Exit;
end;
{$IFDEF UDEBUG}debugInstantLog('TxLngManager.SetActive: reading config ' + FCfgFile);{$ENDIF}
if not ReadCfgFile then begin
if csDesigning in ComponentState
then FActive := False
else raise Exception.Create('TxLngManager.SetActive: Invalid configuration file: "' + FCfgFile + '"! Check CfgFile property.');
end
else LoadItems;
end;
if not FActive then begin
ActiveLngIndex := -1;
Clear;
end;
{$IFDEF UDEBUG}debugInstantLog('TxLngManager.SetActive: set to ' + ifThen(Value, 'ON', 'OFF'));{$ENDIF}
end;
//==============================================================================================
procedure TxLngManager.Loaded;
begin
inherited;
end;
//==============================================================================================
procedure TxLngManager.ShowEditor;
begin
{$IFNDEF NODESIGN}
with TfrmLngManDsgn.Create(nil) do
try
LngManager := Self;
ShowModal;
finally
Free;
end;
{$ENDIF}
end;
//==============================================================================================
function TxLngManager.GetRS(const ASection, AKeyName: string; emptyIfMissing: Boolean = False): string;
var
i: Integer;
sec,key: String;
begin
try // finally
if emptyIfMissing
then Result := ''
else Result := AKeyName + ' of ' + ASection + ' missing!';
sec := AnsiLowerCase(trim(ASection));
if (sec = '') and (FDefaultSection = '') then begin
Result := AKeyName;
Exit;
end;
{$IFDEF PKG}
if FActiveLngindex = -1 then begin // for ready-getting captions @ design time
SetActive(True);
SetActiveLngIndex(0);
end;
{$ENDIF}
if FActiveLngIndex = -1 then Exit; // still bad cfg?
key := AnsiLowerCase(AKeyName);
with ActiveLng do try // except
if sec <> '' then
for i := 0 to Count - 1 do
if (Items[i].Parent <> nil) and (0 = AnsiCompareText(Items[i].Parent.KeyName, sec))
and (0 = AnsiCompareText(Items[i].KeyName, key)) and (Items[i].Text <> '')
then begin
Result := Items[i].Text;
Exit;
end;
if FDefaultSection <> '' then // not found. trying default
for i := 0 to Count - 1 do
if (Items[i].Parent <> nil) and (0 = AnsiCompareText(Items[i].Parent.KeyName, FDefaultSection))
and (0 = AnsiCompareText(Items[i].KeyName, key)) and (Items[i].Text <> '')
then begin
Result := Items[i].Text;
Exit;
end;
except
end; // with ActiveLng
{$IFNDEF PKG}
if Logger <> nil then Logger.Add('langman: ' + Result);
{$ENDIF}
finally
end;
end;
//==============================================================================================
procedure TxLngManager.Close;
begin
Active := False;
end;
//==============================================================================================
procedure TxLngManager.Open;
begin
Active := True;
end;
//==============================================================================================
procedure TxLngManager.SetActiveLngIndex(const Value: Integer);
begin
if ( Value < 0 ) or ( Value > FFiles.Count - 1 )
then FActiveLngIndex := -1
else FActiveLngIndex := Value;
end;
//==============================================================================================
function TxLngManager.GetActiveLngFile: TxLngFile;
begin
Result := TxLngFile(FFiles[FActiveLngIndex]);
end;
//==============================================================================================
procedure TxLngManager.SetStorageType(const Value: TxStorageType);
begin
FStorageType := Value;
end;
//==============================================================================================
procedure TxLngManager.DropFile(AIndex: Integer);
begin
if Files[AIndex].Desc <> '' then
with TIniFile.Create(FCfgFile) do
try
EraseSection(Files[AIndex].Desc);
finally
Free;
end;
FFiles.Delete(AIndex);
if AIndex <= FActiveLngIndex then ActiveLngIndex := 0;
end;
//==============================================================================================
function TxLngManager.AddFile: TxLngFile;
begin
Result := TxLngFile.Create('', '', '', FCfgFile);
Result.FParent := Self;
FFiles.Add(Result);
end;
//==============================================================================================
function TxLngManager.GetFile(Index: Integer): TxLngFile;
begin
Result := TxLngFile(FFiles[Index]);
end;
//==============================================================================================
function TxLngManager.GetFilesCount: Integer;
begin
Result := FFiles.Count;
end;
//==============================================================================================
procedure TxLngManager.SetFile(Index: Integer; const Value: TxLngFile);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
//{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxLngManager.SetFile') else _udebug := nil;{$ENDIF}
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TxLngManager.SetCfgFile(const Value: TFileName);
begin
Active := False;
FCfgFile := Value;
end;
//==============================================================================================
function TxLngManager.ReadCfgFile: Boolean;
var
FCfg: TIniFile;
FSec: TStringList;
i: Integer;
FLngFile: TxLngFile;
FDesc, FName, FLangName: string;
begin
Result := False;
if not FileExists(FCfgFile) then begin
ActiveLngIndex := -1;
Exit;
end;
try //finally
FSec := TStringList.Create;
try
FCfg := TIniFile.Create(FCfgFile);
FCfg.ReadSections(FSec);
FFiles.Clear;
for i := 0 to FSec.Count - 1 do begin
FDesc := DelCharsEx(FSec[i], ['[', ']']);
FName := FCfg.ReadString(FSec[i], 'FileName', '');
if FName[2] <> ':'
then FName := ExtractFilePath(FCfgFile) + FName; // convert relative path to full
FLangName := FCfg.ReadString(FSec[i], 'LangName', '');
FLngFile := TxLngFile.Create(FDesc, FName, FLangName, FCfgFile);
FLngFile.CfgFile := FCfgFile;
FLngFile.FParent := Self;
FFiles.Add(FLngFile);
end;
Result := True;
except
FFiles.Clear;
end;
finally
FSec.Free;
end;
if FFiles.Count > 0 then ActiveLngIndex := 0;
end;
//==============================================================================================
function TxLngManager.GetActiveLng: string;
begin
if FActiveLngIndex <> -1
then Result := TxLngFile(FFiles[FActiveLngIndex]).Desc
else Result := '<not defined>';
end;
//==============================================================================================
procedure TxLngManager.SetActiveLng(const Value: string);
var
i: Integer;
begin
for i := 0 to FilesCount - 1 do
if Files[i].Desc = Value then begin
ActiveLngIndex := i;
Exit;
end;
end;
//==============================================================================================
procedure TxLngManager.ClearCfg;
var
i: Integer;
begin
with TIniFile.Create(FCfgFile) do
try
for i := 0 to FFiles.Count - 1 do
if Files[i].Desc <> '' then EraseSection(Files[i].Desc);
finally
Free;
end;
end;
//==============================================================================================
procedure TxLngManager.setDefaultSection(const Value: String);
begin
if FDefaultSection = AnsiLowerCase(trim(Value)) then Exit;
FDefaultSection := AnsiLowerCase(trim(Value));
end;
//==============================================================================================
//==============================================================================================
// TxLngManItem
//==============================================================================================
//==============================================================================================
constructor TxLngManItem.Create(const AKeyName, AText: string; AParent: TxLngManItem);
begin
FText := AText;
FKeyName := AKeyName;
FParent := AParent;
end;
//==============================================================================================
procedure TxLngManItem.SetKeyName(const Value: string);
begin
FKeyName := Value;
end;
//==============================================================================================
procedure TxLngManItem.SetText(const Value: string);
begin
FText := Value;
end;
//==============================================================================================
//==============================================================================================
// TxLngFile
//==============================================================================================
//==============================================================================================
function TxLngFile.AddItem(const AKeyName, AText: string; AParent: TxLngManItem): TxLngManItem;
begin
Result := TxLngManItem.Create(AKeyName, AText, AParent);
FItems.Add(Result);
end;
//==============================================================================================
function TxLngFile.AddItemEx(const AKeyName, AText: string; AParent: TxLngManItem): TxLngManItem;
begin
Result := AddItem(AKeyName, AText, AParent);
//if AParent <> nil then FLngFile.WriteString(AParent.KeyName, AKeyName, AText);
end;
//==============================================================================================
procedure TxLngFile.Clear;
begin
FItems.Clear;
end;
//==============================================================================================
constructor TxLngFile.Create(const ADesc, AFileName, AName, ACfgFile: string);
begin
inherited Create;
FLngFile := nil;
FItems := TObjectList.Create(True);
FDesc := ADesc;
if AFileName[2] <> ':'
then FFileName := ExtractFilePath(ParamStr(0)) + AFileName
else FFileName := AFileName;
FLangName := AName;
FCfgFile := ACfgFile;
RecreateIniFile;
end;
//==============================================================================================
destructor TxLngFile.Destroy;
begin
if FLngFile <> nil then FreeAndNil(FLngFile);
FItems.Free;
inherited;
end;
//==============================================================================================
procedure TxLngFile.DropItem(AItem: TxLngManItem);
begin
{with FLngFile do
if AItem.Parent = nil
then EraseSection(AItem.KeyName)
else DeleteKey(AItem.Parent.KeyName, AItem.KeyName);
}
end;
//==============================================================================================
function TxLngFile.GetCount: Integer;
begin
Result := FItems.Count;
end;
//==============================================================================================
function TxLngFile.GetIndex: Integer;
begin
Result := FParent.FFiles.IndexOf(Self);
end;
//==============================================================================================
function TxLngFile.GetItem(Index: Integer): TxLngManItem;
begin
Result := TxLngManItem(FItems[Index]);
end;
//==============================================================================================
function TxLngFile.GetRS(const ASection, AKeyName: string): string;
var
i: Integer;
begin
Result := AKeyName + ' of ' + ASection;
for i := 0 to Count - 1 do
if (Items[i].Parent <> nil) and (0 = AnsiCompareText(Items[i].Parent.KeyName, ASection))
and (0 = AnsiCompareText(Items[i].KeyName, AKeyName))
then begin
Result := Items[i].Text;
Exit;
end;
end;
//==============================================================================================
procedure TxLngFile.Load;
var
F: TextFile;
S: string;
p: Integer;
FItem, FCurSection: TxLngManItem;
begin
if FFileName = '' then Exit;
AssignFile(F, FFileName);
try
Reset(F);
FCurSection := nil;
while not Eof(F) do begin
Readln(F, S);
S := Trim(S);
if ( S = '' ) or ( s[1] = ';' ) then Continue;
if S[1] = '[' then begin
FItem := AddItem(AnsiLowerCase(AnsiMidStr(s, 2, length(s) - 2 )), '', nil);
FCurSection := FItem;
end
else if 0 <> AnsiPos('=', s) then begin
p := AnsiPos('=', s);
AddItem( AnsiLowerCase(AnsiMidStr(S, 1, p - 1)), AnsiMidStr(S, p + 1, 999), FCurSection );
end;
end;
CloseFile(F);
except
CloseFile(F);
raise Exception.Create('Error loading resource file!');
end;
{$IFDEF DEBUG}debugInstantLog('TxLngFile.Load for ' + FFileName + ' OK');{$ENDIF}
end;
//==============================================================================================
function TxLngFile.Read(const ASection, AKey: string): string;
begin
if FLngFile <> nil
then Result := FLngFile.ReadString(ASection, AKey, '')
else Result := '';
end;
//==============================================================================================
procedure TxLngFile.RecreateIniFile;
var
FName: string;
begin
if Assigned(FLngFile) then FreeAndNil(FLngFile);
if FFileName = '' then Exit;
FName := FFileName;
if not FileExists(FName)
and (MessageDlg('Resource file "' + FFileName + '" does not exist! Create it?', mtWarning, [mbYes, mbNo], 0) = mrYes)
then FileCreate(FName);
FLngFile := TIniFile.Create(FName);
end;
//==============================================================================================
procedure TxLngFile.SetDesc(const Value: string);
begin
if (FCfgFile <> '') and (FDesc <> Value) and (FDesc <> '') then begin
with TIniFile.Create(FCfgFile) do
try
EraseSection(FDesc);
finally
Free;
end;
end;
FDesc := Value;
end;
//==============================================================================================
procedure TxLngFile.SetFileName(const Value: string);
begin
if (FCfgFile <> '') and (Value <> '') then begin
with TIniFile.Create(FCfgFile) do
try
WriteString(FDesc, 'FileName', Value);
finally
Free;
end;
end;
FFileName := Value;
RecreateIniFile;
end;
//==============================================================================================
procedure TxLngFile.SetLangName(const Value: string);
begin
if (FCfgFile <> '') and (Value <> '') then begin
with TIniFile.Create(FCfgFile) do
try
WriteString(FDesc, 'LangName', Value);
finally
Free;
end;
end;
FLangName := Value;
end;
//==============================================================================================
procedure TxLngFile.UpdateItem(AItem: TxLngManItem; const AKeyName, AText: string);
var
i: Integer;
begin
{
if AItem.Parent = nil then begin
FLngFile.EraseSection(AItem.KeyName);
for i := 1 to Count - 1 do
if Items[i].Parent = AItem
then FLngFile.WriteString(AKeyName, Items[i].KeyName, Items[i].Text);
end
else begin
if AKeyName <> AItem.KeyName then FLngFile.DeleteKey(AItem.Parent.KeyName, AItem.KeyName);
FLngFile.WriteString(AItem.Parent.KeyName, AKeyName, AText);
end;
}
AItem.Text := AText;
AItem.KeyName := AKeyName;
end;
//==============================================================================================
procedure TxLngFile.Write(const ASection, AKey, AValue: string);
begin
//FLngFile.WriteString(ASection, AKey, AValue);
end;
//==============================================================================================
initialization
{$IFDEF UDEBUG}
DEBUG_unit_ID := debugRegisterUnit('xLngManager', @Debugging, DEBUG_group_ID);
Debugging := False;
{$ENDIF}
//==============================================================================================
finalization
{$IFDEF UDEBUG}
//debugUnregisterUnit(DEBUG_unit_ID);
{$ENDIF}
end.
|
unit CleanArch_EmbrConf.Controller.ParkinLot;
interface
uses
CleanArch_EmbrConf.Core.UserCase.Interfaces,
CleanArch_EmbrConf.Core.Repository.Interfaces,
CleanArch_EmbrConf.Infra.Repository.Memory,
CleanArch_EmbrConf.Infra.Repository.SQL,
CleanArch_EmbrConf.Core.UserCase.Impl.EnterParkingLot,
CleanArch_EmbrConf.Core.UserCase.Impl.GetParkingLot;
type
iController = interface
function GetParkingLot : iGetParkingLot;
function EnterParkingLot : iEnterParkingLot;
end;
TController = class(TInterfacedObject, iController)
private
FParkingLotRepositoryMemory : iParkingLotRepository;
FParkingLotRespositorySQL : iParkingLotRepository;
FGetParkingLot: iGetParkingLot;
FEnterParkingLot: iEnterParkingLot;
public
constructor Create;
destructor Destroy; override;
class function New : iController;
function GetParkingLot : iGetParkingLot;
function EnterParkingLot : iEnterParkingLot;
end;
implementation
constructor TController.Create;
begin
FParkingLotRepositoryMemory := TParkingLotRepositoryMemory.New;
FParkingLotRespositorySQL := TParkingLotRepositorySQL.New;
FEnterParkingLot := TEnterParkingLot.New(FParkingLotRespositorySQL);
FGetParkingLot := TGetParkingLot.New(FParkingLotRespositorySQL);
end;
destructor TController.Destroy;
begin
inherited;
end;
function TController.EnterParkingLot: iEnterParkingLot;
begin
Result := FEnterParkingLot;
end;
function TController.GetParkingLot: iGetParkingLot;
begin
Result := FGetParkingLot;
end;
class function TController.New : iController;
begin
Result := Self.Create;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.Objects, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP, IdIntercept, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdGlobal;
type
TMemoryStreamBuffer = class(TMemoryStream)
private
// Events
FOnWrite: TNotifyEvent;
// Event triggering
procedure TriggerOnWrite;
public
// Buffer management
procedure Delete(Amount: Integer);
// Write overrides
function Write(const Buffer; Count: Longint): Longint; override;
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override;
// Events
property OnWrite: TNotifyEvent read FOnWrite write FOnWrite;
end;
TForm1 = class(TForm)
btnGetMJPEG: TButton;
imgCameraImage: TImage;
idHTTP: TIdHTTP;
idIOHandler: TIdIOHandlerStack;
idConnectionIntercept: TIdConnectionIntercept;
procedure btnGetMJPEGClick(Sender: TObject);
procedure idConnectionInterceptReceive(ASender: TIdConnectionIntercept;
var ABuffer: TIdBytes);
private
// Parsing
FReceivedData: TMemoryStreamBuffer;
FParsedData: TMemoryStreamBuffer;
procedure ParseJPEGData;
public
// Constructor and destructor
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$REGION 'TMemoryStreamBuffer'}
////////////////////////////////////////////////////////////////////////////////
// Name: TriggerOnWrite
//
// Description:
// Trigger the OnWrite event
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// None
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
procedure TMemoryStreamBuffer.TriggerOnWrite;
begin
if Assigned(FOnWrite) then
FOnWrite(Self);
end;
////////////////////////////////////////////////////////////////////////////////
// Name: Delete
//
// Description:
// Delete the amount of specified bytes
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// None
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
procedure TMemoryStreamBuffer.Delete(Amount: Integer);
begin
// Check size
if (Amount < 0) then
Amount := 0
else if Amount > Size then
Amount := Size;
// Delete from buffer
CopyMemory(Memory, @TBytes(Memory)[Amount], Size - Amount);
Size := Size - Amount;
end;
////////////////////////////////////////////////////////////////////////////////
// Name: Write
//
// Description:
// Write buffer
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// [IN] Buffer - Data to read
// [IN] Count - Amount of data
//
// Returns:
// [Longint] - Data written
////////////////////////////////////////////////////////////////////////////////
function TMemoryStreamBuffer.Write(const Buffer; Count: Longint): Longint;
begin
Result := inherited;
// Trigger the write event
TriggerOnWrite;
end;
////////////////////////////////////////////////////////////////////////////////
// Name: Write
//
// Description:
// Write data to buffer
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// [IN] Buffer - Source data
// [IN] Offset - Offset from source
// [IN] Count - Amount of bytes to read from
//
// Returns:
// [Longint] - Amount of written data
////////////////////////////////////////////////////////////////////////////////
function TMemoryStreamBuffer.Write(const Buffer: TBytes; Offset, Count: Longint): Longint;
begin
Result := inherited;
// Trigger the write event
TriggerOnWrite;
end;
{$ENDREGION}
////////////////////////////////////////////////////////////////////////////////
// Name: Create
//
// Description:
// Class constructor
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// [IN] AOwner - Component owner
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
// Create buffers
FReceivedData := TMemoryStreamBuffer.Create;
FParsedData := TMemoryStreamBuffer.Create;
end;
////////////////////////////////////////////////////////////////////////////////
// Name: Destroy
//
// Description:
// Class destructor
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// None
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
destructor TForm1.Destroy;
begin
FParsedData.Free;
FReceivedData.Free;
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
// Name: btnGetMJPEGClick
//
// Description:
// Start MJPEG transmission
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// [IN] Sender - Sender object
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.btnGetMJPEGClick(Sender: TObject);
begin
// Request single JPEG from camera
IdHTTP.Request.BasicAuthentication := TRUE;
IdHTTP.Request.Username := 'convidado';
IdHTTP.Request.Password := 'convidado';
IdHTTP.Get('http://10.1.10.10:8601/Interface/Cameras/GetJPEGStream?Camera=40', FReceivedData);
end;
////////////////////////////////////////////////////////////////////////////////
// Name: ParseJPEGData
//
// Description:
// Parse JPEG data
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// None
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.ParseJPEGData;
var
i: Integer;
StartPos, EndPos: Integer;
StartPt: Pointer;
Data, DataNext: PByte;
Amount: Integer;
begin
// Check size
if (FReceivedData.Size < 2) then
Exit;
// Initialize
Amount := 0;
StartPos := -1;
StartPt := nil;
// Data pointers
Data := FReceivedData.Memory;
DataNext := Data;
Inc(DataNext);
try
// Parsing loop
for i := 0 to FReceivedData.Size -2 do
begin
// Check if we have found the start code
if (StartPos = -1) and (Data^ = $FF) and (DataNext^ = $D8) then
begin
StartPos := i;
StartPt := Data;
end
// Check if we have found the JPEG end code
else if (StartPos >= 0) and (Data^ = $FF) and (DataNext^ = $D9) then
begin
// End position
EndPos := i;
// Copy data (Higher performance than passing whole stream to load,
// because FBitmap.LoadFromStream will create a memory stream and copy
// everything if Position <> 0
FReceivedData.Position := StartPos;
FParsedData.SetSize((EndPos + 2) - StartPos);
FParsedData.Position := 0;
CopyMemory(FParsedData.Memory, StartPt, (EndPos + 2) - StartPos);
// Load bitmap on screen
imgCameraImage.Bitmap.LoadFromStream(FParsedData);
Application.ProcessMessages;
// Amount of data to delete
Amount := EndPos + 2;
// Reset
StartPos := -1;
StartPt := nil;
end;
// Next pointer
Inc(Data);
Inc(DataNext);
end;
// Delete the amount of parsed data
FReceivedData.Delete(Amount);
FReceivedData.Position := FReceivedData.Size;
except
FReceivedData.Clear;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Name: idConnectionInterceptReceive
//
// Description:
// Process the event that data has been received
//
// Author: Éric Fleming Bonilha
//
// Parameters List:
// [IN] ASender - Sender object
// [IN] ABuffer - Received data
//
// Returns:
// None
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.idConnectionInterceptReceive(ASender: TIdConnectionIntercept;
var ABuffer: TIdBytes);
begin
ParseJPEGData;
end;
end.
|
program ExampleSimple;
{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
uses
SysUtils, IPConnection, BrickletSegmentDisplay4x7;
type
TExample = class
private
ipcon: TIPConnection;
sd: TBrickletSegmentDisplay4x7;
public
procedure Execute;
end;
const
HOST = 'localhost';
PORT = 4223;
UID = 'XYZ'; { Change to your UID }
DIGITS : array[0..15] of byte = ($3f,$06,$5b,$4f,
$66,$6d,$7d,$07,
$7f,$6f,$77,$7c,
$39,$5e,$79,$71);
var
e: TExample;
procedure TExample.Execute;
var segments: array[0..3] of byte;
begin
{ Create IP connection }
ipcon := TIPConnection.Create;
{ Create device object }
sd := TBrickletSegmentDisplay4x7.Create(UID, ipcon);
{ Connect to brickd }
ipcon.Connect(HOST, PORT);
{ Don't use device before ipcon is connected }
{ Write "4223" to the display with full brightness without colon }
segments[0] := DIGITS[4];
segments[1] := DIGITS[2];
segments[2] := DIGITS[2];
segments[3] := DIGITS[3];
sd.SetSegments(segments, 7, false);
WriteLn('Press key to exit');
ReadLn;
ipcon.Destroy; { Calls ipcon.Disconnect internally }
end;
begin
e := TExample.Create;
e.Execute;
e.Destroy;
end.
|
unit Entidade.TipoCentroCusto;
interface
uses SimpleAttributes;
type
TTIPO_CENTRO_CUSTO = class
private
FDESCRICAO: string;
FID: Integer;
procedure SetDESCRICAO(const Value: string);
procedure SetID(const Value: Integer);
published
[PK,AutoInc]
property ID : Integer read FID write SetID;
property DESCRICAO : string read FDESCRICAO write SetDESCRICAO;
end;
implementation
{ TTIPO_CENTRO_CUSTO }
procedure TTIPO_CENTRO_CUSTO.SetDESCRICAO(const Value: string);
begin
FDESCRICAO := Value;
end;
procedure TTIPO_CENTRO_CUSTO.SetID(const Value: Integer);
begin
FID := Value;
end;
end.
|
unit DataValidators.TDateTimeDataValidator;
interface
uses
System.SysUtils, System.Variants,
Framework.Interfaces;
type
TDateTimeDataValidator = class(TInterfacedObject, IDataValidator)
strict private
FDateFormatSettings: TFormatSettings;
procedure SetDateSeparator(const AValue: Char);
procedure SetDateFormat(const AValue: String);
public
constructor Create(const ADateFormat: String; const ADateSeparator: Char);
destructor Destroy; override;
function Parse(const AValue: Variant): Boolean;
end;
implementation
{ TDateTimeDataValidator }
constructor TDateTimeDataValidator.Create(const ADateFormat: String;
const ADateSeparator: Char);
begin
inherited Create;
SetDateFormat(ADateFormat);
SetDateSeparator(ADateSeparator);
end;
destructor TDateTimeDataValidator.Destroy;
begin
inherited;
end;
function TDateTimeDataValidator.Parse(const AValue: Variant): Boolean;
var
AuxResult: TDateTime;
begin
Result := VarType(AValue) = varDate;
if not Result then
Result := TryStrToDateTime(AValue, AuxResult, FDateFormatSettings);
end;
procedure TDateTimeDataValidator.SetDateSeparator(const AValue: Char);
begin
FDateFormatSettings.DateSeparator := AValue;
end;
procedure TDateTimeDataValidator.SetDateFormat(const AValue: String);
begin
FDateFormatSettings.ShortDateFormat := AValue;
end;
end.
|
{********************************************************************}
{ THTMDialog component }
{ for Delphi & C++Builder }
{ }
{ Written by }
{ TMS Software }
{ Copyright © 2001 - 2012 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{********************************************************************}
unit htmldlgregde;
interface
{$I TMSDEFS.INC}
uses
Classes, HTMLDialog, HTMLDE,
{$IFDEF DELPHI6_LVL}
DesignIntf, DesignEditors
{$ELSE}
DsgnIntf
{$ENDIF}
;
procedure Register;
implementation
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TStringList), THTMLDialog, 'HTMLText', THTMLTextProperty);
end;
end.
|
unit glr_os_win;
interface
uses
glr_core,
glr_utils,
Windows;
type
{ TglrWindow }
TglrWindow = class (TglrAppView)
private
time, startTime, freq: LARGE_INTEGER;
msg: TMSG;
currentTime, lastTime: Integer;
protected
fHandle: THandle;
fDC: HDC;
fRC: HGLRC;
fEvent: TglrInputEvent;
fDeltaTime: Double;
function GetTime(): Integer;
function WndProc(hWnd: HWND; message: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
public
fShouldQuit: Boolean;
constructor Create(aData: Pointer); override;
destructor Destroy(); override;
procedure Loop(); override;
procedure Quit; override;
end;
PglrWindow = ^TglrWindow;
function FileExists(const FileName: AnsiString): Boolean;
function PathExists(const FilePath: AnsiString): Boolean;
procedure FindFiles(const aPath, aExt: AnsiString; var aList: TglrStringList);
function ExtractFileExt(const aFileName: AnsiString): AnsiString;
function ExtractFilePath(const aFileName: AnsiString): AnsiString;
implementation
function FileExists(const FileName: AnsiString): Boolean;
var
Attr: Dword;
begin
Attr := GetFileAttributesA(PAnsiChar(FileName));
if (Attr <> $ffffffff) then
Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0
else
Result := False;
end;
function PathExists(const FilePath: AnsiString): Boolean;
var
Attr: Dword;
begin
Attr := GetFileAttributes(PAnsiChar(FilePath));
if Attr <> $ffffffff then
Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) > 0
else
Result := False;
end;
var
wnd: TglrWindow; //temp variable for WndProc
{ TglrWindow }
function WndProcFirst(hWnd: HWND; message: UINT; wParam: WPARAM;
lParam: LPARAM): LRESULT; stdcall;
begin
wnd := TglrWindow(GetWindowLongPtrA(hwnd, GWL_USERDATA));
if (wnd <> nil) then
Result := wnd.WndProc(hWnd, message, wParam, lParam)
else
Result := DefWindowProcA(hWnd, message, wParam, lParam);
end;
type
TSearchRec = Record
Time : Longint;
Size : Int64;
Attr : Longint;
Name : String;
ExcludeAttr : Longint;
FindHandle : THandle;
FindData : TWin32FindData;
end;
const
{ File attributes }
faDirectory = $00000010;
faAnyFile = $0000003f;
Invalid_Handle_value = HANDLE(-1);
function FindMatch(var f: TSearchRec): Longint;
begin
{ Find file with correct attribute }
while (F.FindData.dwFileAttributes and Cardinal(F.ExcludeAttr)) <> 0 do
if not FindNextFile (F.FindHandle, F.FindData) then
Exit(GetLastError);
{ Convert some attributes back }
// WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
f.size := F.FindData.NFileSizeLow + (QWord(MaxDWord) + 1) * F.FindData.NFileSizeHigh;
f.attr := F.FindData.dwFileAttributes;
f.Name := StrPas(@F.FindData.cFileName[0]);
Result := 0;
end;
function FindFirst(const Path: String; Attr: Longint; out Rslt: TSearchRec): Longint;
begin
Rslt.Name := Path;
Rslt.Attr := attr;
Rslt.ExcludeAttr := (not Attr) and ($1e); { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
{ FindFirstFile is a Win32 Call }
Rslt.FindHandle := FindFirstFile (PChar(Path), Rslt.FindData);
if (Rslt.FindHandle = Invalid_Handle_value) then
Exit(GetLastError);
{ Find file with correct attribute }
Result := FindMatch(Rslt);
end;
function FindNext(var Rslt: TSearchRec): Longint;
begin
if FindNextFile(Rslt.FindHandle, Rslt.FindData) then
Result := FindMatch(Rslt)
else
Result := GetLastError;
end;
procedure FindClose(var F: TSearchrec);
begin
if (F.FindHandle <> INVALID_HANDLE_VALUE) then
Windows.FindClose(F.FindHandle);
end;
function ExtractFileExt(const aFileName: AnsiString): AnsiString;
var
i: Integer;
begin
i := Length(aFileName) - 1;
while ((i > 0) and (not (aFileName[i] in ['.', '/', '\', ':']))) do
i -= 1;
if (aFileName[i] = '.') and (i > 0) then
Result := Copy(aFileName, i, MaxInt);
end;
function ExtractFilePath(const aFileName: AnsiString): AnsiString;
var
i: Integer;
begin
i := Length(aFileName) - 1;
while ((i > 0) and (not (aFileName[i] in ['/', '\']))) do
i -= 1;
if (i > 0) then
Result := Copy(aFileName, 0, i)
else
Result := '';
end;
procedure FindFiles(const aPath, aExt: AnsiString; var aList: TglrStringList);
var
searchResult: TSearchRec;
fPath: AnsiString;
begin
fPath := aPath;
if (fPath <> '') then
if (fPath[Length(fPath)] = '\') then
fPath[Length(fPath)] := '/'
else if (fPath[Length(fPath)] <> '/') then
fPath += '/';
if (FindFirst(fPath + '*', faAnyFile, searchResult) = 0) then
try
repeat
if (searchResult.Attr and faDirectory) = 0 then
begin
if (aExt = '') or (ExtractFileExt(searchResult.Name) = aExt) then
aList.Add((fPath + searchResult.Name));
end
else if (searchResult.Name <> '.') and (searchResult.Name <> '..') then
begin
FindFiles(fPath + searchResult.Name, aExt, aList);
end;
until FindNext(searchResult) <> 0
finally
FindClose(searchResult);
end;
end;
function TglrWindow.GetTime(): Integer;
begin
QueryPerformanceCounter(@time);
Result := round(1000 * (time.QuadPart - startTime.QuadPart) / freq.QuadPart);
end;
function TglrWindow.WndProc(hWnd: HWND; message: UINT; wParam: WPARAM;
lParam: LPARAM): LRESULT; stdcall;
begin
Result := 0;
fEvent._inited := False;
if not Core.IsReady then
Exit(DefWindowProcA(hWnd, message, wParam, lParam));
case (message) of
WM_ACTIVATEAPP:
if (wParam = 0) then
Core.Pause()
else
Core.Resume();
WM_CLOSE, WM_DESTROY:
Self.fShouldQuit := True;
WM_MOUSEMOVE:
if (wParam and MK_LBUTTON <> 0) then
fEvent.Init(itTouchMove, kLeftButton, LOWORD(lParam), HIWORD(lParam), 0)
else if (wParam and MK_RBUTTON <> 0) then
fEvent.Init(itTouchMove, kRightButton, LOWORD(lParam), HIWORD(lParam), 0)
else if (wParam and MK_MBUTTON <> 0) then
fEvent.Init(itTouchMove, kMiddleButton, LOWORD(lParam), HIWORD(lParam), 0)
else
fEvent.Init(itTouchMove, kNoInput, LOWORD(lParam), HIWORD(lParam), 0);
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK:
if (message = WM_LBUTTONUP) then
fEvent.Init(itTouchUp, kLeftButton, LOWORD(lParam), HIWORD(lParam), 0)
else
fEvent.Init(itTouchDown, kLeftButton, LOWORD(lParam), HIWORD(lParam), 0);
WM_RBUTTONDOWN, WM_RBUTTONUP, WM_RBUTTONDBLCLK:
if (message = WM_RBUTTONUP) then
fEvent.Init(itTouchUp, kRightButton, LOWORD(lParam), HIWORD(lParam), 0)
else
fEvent.Init(itTouchDown, kRightButton, LOWORD(lParam), HIWORD(lParam), 0);
WM_KEYDOWN, WM_KEYUP:
if (message = WM_KEYUP) then
fEvent.Init(itKeyUp, TglrKey(wParam), 0, 0, 0)
else
fEvent.Init(itKeyDown, TglrKey(wParam), 0, 0, 0);
WM_MOUSEWHEEL:
if (wParam > 0) then
fEvent.Init(itWheel, kWheelUp, LOWORD(lParam), HIWORD(lParam), 1 * (HIWORD(wParam) div WHEEL_DELTA))
else
fEvent.Init(itWheel, kWheelDown, LOWORD(lParam), HIWORD(lParam), -1 * (HIWORD(-wParam) div WHEEL_DELTA));
else
Exit(DefWindowProcA(hWnd, message, wParam, lParam));
end;
if fEvent._inited then
Core.InputReceived(@fEvent);
end;
constructor TglrWindow.Create(aData: Pointer);
var
p: TglrInitParams;
r: RECT;
pfd: PIXELFORMATDESCRIPTOR;
wStyle: LongWord;
wClass: TWndClass;
begin
p := TglrInitParams(aData^);
ZeroMemory(@wClass, SizeOf(wClass));
with wClass do
begin
style := CS_VREDRAW or CS_HREDRAW or CS_OWNDC;
hInstance := 0;
hIcon := LoadIcon(0, IDI_WINLOGO);
hCursor := LoadCursor(0, IDC_ARROW);
hbrBackground := GetStockObject (White_Brush);
lpfnWndProc := @WndProcFirst;
lpszClassName := 'TglrWindow';
end;
Windows.RegisterClass(wClass);
wStyle := WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_MINIMIZEBOX or WS_CLIPSIBLINGS or WS_CLIPCHILDREN;
SetRect(r, 0, 0, p.Width, p.Height);
AdjustWindowRect(r, wStyle, False);
fHandle := CreateWindow('TglrWindow', PAnsiChar(Utf8ToAnsi(p.Caption)), wStyle, p.X, p.Y, r.Right - r.Left, r.Bottom - r.Top, 0, 0, 0, Self);
SetWindowLongPtrA(fHandle, GWL_USERDATA, LONG_PTR(Self));
fDC := GetDC(fHandle);
ZeroMemory(@pfd, SizeOf(pfd));
pfd.nSize := SizeOf(pfd);
pfd.nVersion := 1;
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
pfd.cColorBits := 32;
pfd.cAlphaBits := 8;
pfd.cDepthBits := 24;
pfd.cStencilBits := 8;
SetPixelFormat(fDC, ChoosePixelFormat(fDC, pfd), @pfd);
fRC := wglCreateContext(fDC);
wglMakeCurrent(fDC, fRC);
QueryPerformanceFrequency(@freq);
QueryPerformanceCounter(@startTime);
ShowWindow(fHandle, SW_SHOW);
fShouldQuit := False;
end;
destructor TglrWindow.Destroy();
begin
wglMakeCurrent(0, 0);
wglDeleteContext(fRC);
ReleaseDC(fHandle, fDC);
CloseWindow(fHandle);
DestroyWindow(fHandle);
end;
procedure TglrWindow.Loop();
begin
repeat
if (PeekMessageA(msg, fHandle, 0, 0, PM_REMOVE)) then
begin
TranslateMessage(msg);
DispatchMessageA(msg);
end
else
begin
currentTime := getTime();
fDeltaTime := (currentTime - lastTime) / 1000.0;
lastTime := currentTime;
if (fDeltaTime > 0.05) then
fDeltaTime := 0.05;
Core.Update(fDeltaTime);
Core.RenderAll();
SwapBuffers(fDC);
end;
until Self.fShouldQuit;
end;
procedure TglrWindow.Quit;
begin
Self.fShouldQuit := True;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uMultiCastEvent.pas }
{ Описание: Событие с множественными обработчиками }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uMultiCastEvent;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs;
type
IMultiCastEvent = interface(IInterface)
['{8D7AB9FF-EF5D-4136-A930-ACF6DFD82C52}']
procedure Broadcast(ASender: TObject); stdcall;
procedure RegisterListener(AListener: TNotifyEvent); stdcall;
procedure UnRegisterListener(AListener: TNotifyEvent); stdcall;
end;
implementation
end.
|
unit PlayerContextControl;
interface
uses
Math, TypeControl, PlayerControl, WorldControl;
type
TPlayerContext = class
private
FPlayer: TPlayer;
FWorld: TWorld;
public
constructor Create(const player: TPlayer; const world: TWorld);
function GetPlayer: TPlayer;
property Player: TPlayer read GetPlayer;
function GetWorld: TWorld;
property World: TWorld read GetWorld;
destructor Destroy; override;
end;
TPlayerContextArray = array of TPlayerContext;
implementation
constructor TPlayerContext.Create(const player: TPlayer; const world: TWorld);
begin
FPlayer := player;
FWorld := world;
end;
function TPlayerContext.GetPlayer: TPlayer;
begin
result := FPlayer;
end;
function TPlayerContext.GetWorld: TWorld;
begin
result := FWorld;
end;
destructor TPlayerContext.Destroy;
begin
if Assigned(FPlayer) then begin
FPlayer.Free;
end;
if Assigned(FWorld) then begin
FWorld.Free;
end;
inherited;
end;
end.
|
unit uXMLParser;
{$mode objfpc}{$H+}
{$notes off}
{ On-the-fly XML parser
Copyright (c) 2012-8, PJ Design Engineering P/L
All rights reserved.
}
interface
uses Classes;
type
{ Token types returned by parser }
TTokens = (toElement, toComment, toText);
{ XML tag types }
TTagTypes = (ttOpening, ttClosing, ttEmpty);
TStages = (stIdle, stTag, stElement, stName, stValue, stDTD, stNonElement, stInstruction, stParams, stComment, stIgnore, stError);
TTokenEvent = procedure (Sender : TObject; Token : TTokens; TokenName : string;
Tag : TTagTypes; Params : TList) of object;
TTokenValueEvent = procedure (Sender : TObject; aName, aValue : string) of object;
TTokenErrorEvent = procedure (Sender: TObject; ErrorMsg : string) of object;
TParam = class (TObject)
Name : string;
Value : string;
function IntName : integer;
function IntValue : integer;
function BoolValue : boolean;
function CharValue : Char;
constructor Create;
end;
TXMLParser = class (TObject)
private
FTagType : TTagTypes;
FStage : TStages;
FParam : TParam;
FText : string;
FOnToken : TTokenEvent;
FOnError : TTokenErrorEvent;
FOnValue : TTokenValueEvent;
protected
Params : TList;
SkipSpaces : boolean;
Quoted : boolean;
TextValue : boolean;
Buffer : TMemoryStream;
TokenString : string;
TokenStack : TStringList;
function GetChar : Char;
procedure DoParsing;
procedure ClearParams;
procedure DoToken (Token : TTokens; var TokenName : string; Tag : TTagTypes; Attributes : TList);
procedure DoError (ErrorMsg : string);
procedure DoValue (aName, aValue : string);
public
Owner : TObject;
Tag, Tag2 : integer; // general purpose integers
constructor Create (anOwner : TObject);
destructor Destroy; override;
procedure Parse (Data : string); overload;
procedure Parse (Data : TStream); overload;
function Depth : integer;
procedure Reset;
property OnToken : TTokenEvent read FOnToken write FOnToken;
property OnError : TTokenErrorEvent read FOnError write FOnError;
property OnValue : TTokenValueEvent read FOnValue write FOnValue;
end;
const
tgt : array [TTagTypes] of string = ('Opening', 'Closing', 'Empty');
tkt : array [TTokens] of string = ('Element', 'Comment', 'Text');
implementation
uses SysUtils;
{$REGION 'TParam' }
{ TParam }
function TParam.BoolValue: boolean;
begin
Result := not ((CharValue = '0') or (CharValue = 'F'));
end;
function TParam.CharValue: Char;
begin
if Length (Value) = 0 then
Result := #0
else
Result := UpCase (Value[1]);
end;
constructor TParam.Create;
begin
Name := '';
Value := '';
end;
function TParam.IntName: integer;
begin
Result := StrToIntDef (string (Name), -1);
end;
function TParam.IntValue: integer;
begin
if UpperCase (string (Value)) = 'TRUE' then
Result := 1
else if UpperCase (string (Value)) = 'FALSE' then
Result := 0
else
Result := StrToIntDef (string (Value), -1);
end;
{$ENDREGION}
{$REGION 'TXMLParser' }
{ TXMLParser }
procedure TXMLParser.ClearParams;
var
i : integer;
begin
for i := 0 to Params.Count - 1 do
TParam (Params[i]).Free;
FParam:= nil;
Params.Clear;
end;
constructor TXMLParser.Create (anOwner: TObject);
begin
inherited Create;
Params := TList.Create;
Owner := anOwner;
FStage := stIdle;
SkipSpaces := false;
FTagType := ttOpening;
FParam := nil;
TextValue := false;
FText := '';
Buffer := TMemoryStream.Create;
TokenStack := TStringList.Create;
FOnToken := nil;
FOnError := nil;
FOnValue := nil;
Tag := 0;
Tag2 := 0;
end;
function TXMLParser.Depth: integer;
begin
Result := TokenStack.Count;
end;
destructor TXMLParser.Destroy;
begin
ClearParams;
Params.Free;
TokenStack.Free;
Buffer.Free;
inherited;
end;
procedure TXMLParser.DoError (ErrorMsg: string);
begin
if Assigned (FOnError) then FOnError (Self, ErrorMsg);
end;
procedure TXMLParser.DoParsing;
const
st : array[TStages] of string =
('Idle', 'Tag', 'Element', 'Name', 'Value', 'DTD', 'NonElement', 'Instruction', 'Params', 'Comment', 'Ignore', 'Error');
var
delims : string;
aChar : Char;
CanLoad : boolean;
function Delim (delims_ : string; chr_ : Char) : boolean;
begin
Result := Pos (chr_, delims_) > 0;
end;
begin
delims := '<';
aChar := GetChar;
while aChar <> #0 do
begin
case FStage of
stIdle : delims := '<';
stIgnore : delims := '<>';
stTag : delims := '!? '#9'/<>';
stName : delims := ' =/<>';
stValue : delims := ' '#9'/<>';
else delims := '<';
end;
CanLoad := (not Delim (delims, aChar)) and (aChar <> #0);
while CanLoad do
begin
if (aChar = #13) and (quoted) then
begin
DoError('Unterminated string');
quoted := false; // error condition
end;
case FStage of
stIdle : TokenString := TokenString + aChar;
stTag :
if CharInSet (aChar, ['?', '!']) then
FStage := stIgnore
else
TokenString := TokenString + aChar;
stName :
begin
if FParam = nil then
begin
FParam := TParam.Create;
Params.Add (FParam);
end;
FParam.Name := FParam.Name + aChar;
end;
stValue :
if aChar = '"' then
begin
if quoted then
begin
CanLoad := false;
quoted := false;
end
else
quoted := true;
aChar := #0;
end
else
if FParam <> nil then FParam.Value := FParam.Value + aChar;
end; // case
if CanLoad then
begin
aChar := GetChar;
CanLoad := (not Delim (delims, aChar)) and (aChar <> #0);
end;
end; // while CanLoad
// delimiters encountered
if aChar = #0 then
begin
// do nothing
end
else if (FStage = stValue) and quoted then
FParam.Value := FParam.Value + aChar
else if aChar = '<' then
begin
ClearParams;
TokenString := string (Trim (string (TokenString)));
if length (TokenString) > 0 then DoToken (toText, TokenString, ttEmpty, Params);
FStage := stTag;
TokenString := '';
FParam := nil;
FTagType := ttOpening;
end
else if aChar = '>' then
begin
if length (TokenString) > 0 then DoToken (toElement, TokenString, FTagType, Params);
ClearParams;
FStage := stIdle;
end
else if aChar = '/' then
begin
case FStage of
stTag :
if length (TokenString) > 0 then
begin
FTagType := ttEmpty;
FStage := stIgnore;
end
else
FTagType := ttClosing;
else
begin
FTagType := ttEmpty;
FStage := stIgnore;
end;
end; // case
end
else
begin
case FStage of
stIgnore :
if aChar = '<' then
begin
FStage := stName;
TokenString := '';
quoted := false;
ClearParams;
FParam := nil;
end;
stName :
if aChar = '=' then
begin
quoted := false;
FStage := stValue;
end;
stValue :
if (aChar = ' ') and quoted then
FParam.Value := FParam.Value + aChar
else
begin
FStage := stName;
FParam := nil;
end;
stTag : FStage := stName;
end; // case
end; // else
aChar := GetChar;
end;
Buffer.Clear;
end;
procedure TXMLParser.DoToken (Token: TTokens; var TokenName: string;
Tag: TTagTypes; Attributes: TList);
begin
if Token = toElement then
case Tag of
ttOpening :
begin
FText := '';
TextValue := false;
TokenStack.Add (string (TokenName));
end;
ttClosing :
if TokenStack.Count = 0 then
begin
DoError ('Orphaned Closing Tag ' + TokenName);
TextValue := false;
end
else
begin
if CompareText (TokenStack[TokenStack.Count - 1], string (TokenName)) <> 0 then
DoError (string ('Unmatched Closing Tag ' + string (TokenName) + ' vs ' + TokenStack[TokenStack.Count - 1]))
else if TextValue then
DoValue (TokenName, FText);
FText := '';
TokenStack.Delete (TokenStack.Count - 1);
TextValue := false;
end;
ttEmpty : TextValue := false;
end // case
else if (Token = toText) and (TokenStack.Count > 0) then
begin
FText := TokenName;
TextValue := true;
end;
try
if Assigned (FOnToken) then
FOnToken (Self, Token, TokenName, Tag, Attributes);
except
end;
ClearParams;
TokenName := '';
end;
procedure TXMLParser.DoValue (aName, aValue: string);
begin
if Assigned (FOnValue) then
FOnValue (Self, aName, aValue);
end;
function TXMLParser.GetChar: Char;
begin
Result := #10; //lf
while Result = #10 do
begin
if Buffer.Position < Buffer.Size then
Buffer.Read (Result, 1)
else
Result := #0;
end;
end;
procedure TXMLParser.Parse (Data: string);
var
loc : cardinal;
begin
loc := Buffer.Position;
Buffer.Seek (0, soFromEnd);
Buffer.Write (Data[1], length (Data));
Buffer.Seek (loc, soFromBeginning);
DoParsing;
end;
procedure TXMLParser.Parse (Data: TStream);
var
loc : cardinal;
begin
loc := Buffer.Position;
Buffer.Seek (0, soFromEnd);
Data.Seek (0, soFromBeginning);
Buffer.CopyFrom (Data, Data.Size);
Buffer.Seek (loc, soFromBeginning);
DoParsing;
end;
procedure TXMLParser.Reset;
begin
Buffer.Clear;
FStage := stIdle;
FTagType := ttOpening;
FParam := nil;
TokenString := '';
ClearParams;
end;
{$ENDREGION}
end.
|
unit iocpLocker;
interface
uses
Windows, SysUtils, Classes;
type
TIocpLocker = class(TObject)
private
FEnterINfo: string;
FName: String;
FSection: TRTLCriticalSection;
function GetEnterCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure lock;
procedure unLock;
property EnterCount: Integer read GetEnterCount;
property EnterINfo: string read FEnterINfo write FEnterINfo;
property Name: String read FName write FName;
end;
implementation
constructor TIocpLocker.Create;
begin
inherited Create;
InitializeCriticalSection(FSection);
end;
destructor TIocpLocker.Destroy;
begin
DeleteCriticalSection(FSection);
inherited Destroy;
end;
function TIocpLocker.GetEnterCount: Integer;
begin
Result := FSection.RecursionCount;
end;
procedure TIocpLocker.lock;
begin
EnterCriticalSection(FSection);
end;
procedure TIocpLocker.unLock;
begin
LeaveCriticalSection(FSection);
//OutputDebugString(PChar(Format('%d:%s unlock', [GetCurrentThreadID, Name])));
//FEnterINfo := '';
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TImportKind = (ikTop, ikNoTop);
TForm2 = class(TForm)
LoadBtn: TButton;
UnloadBtn: TButton;
Label1: TLabel;
LoadEdit: TEdit;
Button1: TButton;
TypeGroup: TRadioGroup;
Label2: TLabel;
Label3: TLabel;
CountEdit: TEdit;
GetNFreeBtn: TButton;
GetEdit: TEdit;
Button3: TButton;
UnloadCheck: TCheckBox;
Label4: TLabel;
TopDateEdit: TEdit;
DefaultDateBtn: TButton;
ProgressLabel: TLabel;
LogMemo: TMemo;
Label5: TLabel;
NoTopDateEdit: TEdit;
OneIterationBtn: TButton;
Button2: TButton;
procedure LoadBtnClick(Sender: TObject);
procedure UnloadBtnClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure GetNFreeBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DefaultDateBtnClick(Sender: TObject);
procedure OneIterationBtnClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
function GetFromDate(anIndex: TImportKind): TDateTime;
procedure SetFromDate(anIndex: TImportKind; const Value: TDateTime);
private
{ Private declarations }
f_DateArr: array [TImportKind] of TEdit;
procedure SetProgress(aCurr, aTotal: Integer);
function DoProcess(aKind: TImportKind; var aMaxCount: Integer): Integer;
property FromDate[anIndex: TImportKind]: TDateTime read GetFromDate write SetFromDate;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses
ArchiAdapter,
GardocsUnit,
IOUnit,
l3DateTimeBox,
Math,
ActiveX,
l3Memory;
{$R *.dfm}
procedure TForm2.LoadBtnClick(Sender: TObject);
begin
TArchiAdapterDll.Make;
end;
procedure TForm2.UnloadBtnClick(Sender: TObject);
begin
try
FreeAdapterSingleton;
except
on E: Exception do
begin
LogMemo.Lines.Add('UNLOAD FAILED!!!');
raise;
end;
end;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
l_IDX: Integer;
begin
for l_IDX := 1 to StrToInt(LoadEdit.Text) do
begin
LoadBtn.Click;
UnloadBtn.Click;
SetProgress(l_IDX, StrToInt(LoadEdit.Text));
end;
ProgressLabel.Caption := '';
ShowMessage('Done');
end;
procedure TForm2.Button3Click(Sender: TObject);
var
l_IDX: Integer;
begin
for l_IDX := 1 to StrToInt(GetEdit.Text) do
begin
GetNFreeBtn.Click;
SetProgress(l_IDX, StrToInt(GetEdit.Text));
end;
ProgressLabel.Caption := '';
UnloadBtn.Click;
ShowMessage('Done');
end;
procedure TForm2.GetNFreeBtnClick(Sender: TObject);
var
l_Count: Integer;
const
cMap: array [0..1] of TImportKind = (ikTop, ikNotop);
begin
LogMemo.Lines.Clear;
Application.ProcessMessages;
l_Count := StrToInt(CountEdit.Text);
DoProcess(cMap[TypeGroup.ItemIndex], l_Count);
if UnloadCheck.Checked then
UnloadBtn.Click;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
f_DateArr[ikTop] := TopDateEdit;
f_DateArr[ikNoTop] := NoTopDateEdit;
DefaultDateBtn.Click;
end;
procedure TForm2.DefaultDateBtnClick(Sender: TObject);
begin
FromDate[ikTop] := Now - 1;
FromDate[ikNoTop] := FromDate[ikTop];
end;
procedure TForm2.SetProgress(aCurr, aTotal: Integer);
begin
ProgressLabel.Caption := Format('%d/%d', [aCurr, aTotal]);
ProgressLabel.Update;
end;
function TForm2.GetFromDate(anIndex: TImportKind): TDateTime;
begin
Result := StrToDateTime(f_DateArr[anIndex].Text)
end;
procedure TForm2.SetFromDate(anIndex: TImportKind; const Value: TDateTime);
begin
f_DateArr[anIndex].Text := FormatDateTime('dd/mm/yyyy hh:nn:ss', Value);
end;
function TForm2.DoProcess(aKind: TImportKind; var aMaxCount: Integer): Integer;
var
l_DLL: IArchiAdapterDll;
l_Searcher: ISearcher2;
l_Date: TDateTimeBox;
l_List: IGardocList;
l_IDX: Integer;
l_NewDate: TDateTime;
l_TickCount: Integer;
l_Doc: TGardoc;
l_ImgIdx: Integer;
l_Image: TImage;
l_TotalSize: Int64;
l_CurrSize: Int64;
l_Stream: Tl3MemoryStream;
l_Dummy: Int64;
l_Str: String;
const
cMap: array [TImportKind] of String = ('Top', 'Notop');
begin
Result := 0;
if aMaxCount <= 0 then
Exit;
l_DLL := TArchiAdapterDll.Make;
try
l_Searcher := l_DLL.GetSearcher2;
try
l3DateTimeToBox(FromDate[aKind], l_Date);
LogMemo.Lines.Add(Format('Receiving %s from %s ', [cMap[aKind], FormatDateTime('dd/mm/yyyy hh:nn:ss', FromDate[aKind])]));
l_TickCount := GetTickCount;
case aKind of
ikTop: l_Searcher.GetTopCreatedSince(l_Date, aMaxCount, '0', l_List);
ikNoTop: l_Searcher.GetNotopCreatedSince(l_Date, aMaxCount, '0', l_List);
end;
try
if (l_List <> nil) and (l_List.Count > 0) then
begin
LogMemo.Lines.Add(Format('Received %d docs in %s msec', [l_List.Count, FormatFLoat('#,##0', GetTickCount - l_TickCount)]));
l_NewDate := 0;
aMaxCount := aMaxCount - l_List.Count;
Result := l_List.Count;
for l_IDX := 0 to l_List.Count - 1 do
begin
l_List.pm_GetItem(l_IDX, l_Doc);
try
l_Str := l_Doc.rTitle.GetData;
if (l_Doc.rImages <> nil) and (l_Doc.rImages.Count > 0 ) then
begin
l_TotalSize := 0;
for l_ImgIdx := 0 to l_Doc.rImages.Count - 1 do
begin
l_Doc.rImages.pm_GetItem(l_ImgIdx, l_Image);
try
if l_Image.rData <> nil then
begin
l_Stream := Tl3MemoryStream.Make;
try
l_Image.rData.CopyTo(l_STream, MaxInt, l_CurrSize, l_Dummy);
finally
FreeAndNil(l_Stream);
end;
l_TotalSize := l_TotalSize + l_CurrSize;
end;
finally
Finalize(l_Image);
end;
end;
LogMemo.Lines.Add(Format(' ImagesCount: %d, Total Size: %s kb', [l_Doc.rImages.Count, FormatFloat('#,##0', l_TotalSize / 1024)]));
end;
l_NewDate := Max(l_NewDate, l3BoxToDateTime(l_Doc.rTimestamp));
finally
Finalize(l_Doc);
end;
end;
LogMemo.Lines.Add(Format('New time is %s', [FormatDateTime('dd/mm/yyyy hh:nn:ss', l_NewDate)]));
FromDate[aKind] := l_NewDate;
end
else
LogMemo.Lines.Add('There isn''t any documents');
finally
l_List := nil;
end;
finally
l_Searcher := nil;
end;
finally
l_DLL := nil;
end;
end;
procedure TForm2.OneIterationBtnClick(Sender: TObject);
var
l_Count: Integer;
begin
LogMemo.Lines.Clear;
Application.ProcessMessages;
l_Count := StrToInt(CountEdit.Text);
DoProcess(ikTop, l_Count);
DoProcess(ikNoTop, l_Count);
if UnloadCheck.Checked then
UnloadBtn.Click;
ShowMessage('Done');
end;
procedure TForm2.Button2Click(Sender: TObject);
var
l_Count: Integer;
l_LoadedCount: Integer;
begin
LogMemo.Lines.Clear;
Application.ProcessMessages;
repeat
l_Count := StrToInt(CountEdit.Text);
l_LoadedCount := DoProcess(ikTop, l_Count);
l_LoadedCount := l_LoadedCount + DoProcess(ikNoTop, l_Count);
if UnloadCheck.Checked then
UnloadBtn.Click;
Application.ProcessMessages;
until l_LoadedCount = 0;
UnloadBtn.Click;
ShowMessage('Done');
end;
end.
|
unit ce_dockoptions;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, AnchorDocking, AnchorDockOptionsDlg, XMLPropStorage,
AnchorDockStr, Forms, Controls, ce_observer, ce_interfaces;
type
(**
* The option frame to edit the docking option, displayed in the option form.
*)
TDockOptionsEditor = class(TAnchorDockOptionsFrame, ICEEditableOptions)
private
fBackup: TXMLConfigStorage;
//
function optionedWantCategory(): string;
function optionedWantEditorKind: TOptionEditorKind;
function optionedWantContainer: TPersistent;
procedure optionedEvent(anEvent: TOptionEditorEvent);
function optionedOptionsModified: boolean;
//
procedure doChanged(Sender: TObject);
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
var
DockOptionsEditor: TDockOptionsEditor;
DockOptionContainer: TScrollBox;
constructor TDockOptionsEditor.Create(TheOwner: TComponent);
begin
inherited;
fBackup := TXMLConfigStorage.Create('', False);
Master := AnchorDocking.DockMaster;
//
HeaderAlignLeftTrackBar.OnChange := @doChanged;
HeaderAlignTopTrackBar.OnChange := @doChanged;
DragThresholdTrackBar.OnChange := @doChanged;
SplitterWidthTrackBar.OnChange := @doChanged;
//
ShowHeaderCaptionCheckBox.OnChange := @doChanged;
HideHeaderCaptionForFloatingCheckBox.OnChange := @doChanged;
FlattenHeaders.OnChange := @doChanged;
FilledHeaders.OnChange := @doChanged;
//
HeaderStyleComboBox.OnChange := @doChanged;
//
EntitiesConnector.addObserver(self);
end;
destructor TDockOptionsEditor.Destroy;
begin
fBackup.Free;
inherited;
end;
function TDockOptionsEditor.optionedWantCategory(): string;
begin
exit('Docking')
end;
function TDockOptionsEditor.optionedWantEditorKind: TOptionEditorKind;
begin
exit(oekControl);
end;
function TDockOptionsEditor.optionedWantContainer: TPersistent;
begin
fBackup.Clear;
DockMaster.SaveSettingsToConfig(fBackup);
LoadFromMaster;
exit(DockOptionContainer);
end;
procedure TDockOptionsEditor.optionedEvent(anEvent: TOptionEditorEvent);
begin
// restores
if anEvent = oeeCancel then
begin
DockMaster.LoadSettingsFromConfig(fBackup);
LoadFromMaster;
fBackup.Clear;
DockMaster.SaveSettingsToConfig(fBackup);
end
// accept and new backup
else if anEvent = oeeAccept then
begin
SaveToMaster;
fBackup.Clear;
DockMaster.SaveSettingsToConfig(fBackup);
end
// reload
else if anEvent = oeeSelectCat then
begin
fBackup.Clear;
DockMaster.SaveSettingsToConfig(fBackup);
LoadFromMaster;
end
//change
else
begin
SaveToMaster;
doChanged(nil);
end;
end;
function TDockOptionsEditor.optionedOptionsModified: boolean;
begin
exit(false);
end;
procedure TDockOptionsEditor.doChanged(Sender: TObject);
var
hasHeaders: boolean;
begin
DragThresholdLabel.Caption := adrsDragThreshold +
' (' + IntToStr(DragThresholdTrackBar.Position) + ')';
HeaderAlignTopLabel.Caption := adrsHeaderAlignTop +
' (' + IntToStr(HeaderAlignTopTrackBar.Position) + ')';
HeaderAlignLeftLabel.Caption := adrsHeaderAlignLeft +
' (' + IntToStr(HeaderAlignLeftTrackBar.Position) + ')';
SplitterWidthLabel.Caption := adrsSplitterWidth +
' (' + IntToStr(SplitterWidthTrackBar.Position) + ')';
//
hasHeaders:=ShowHeaderCheckBox.Checked;
ShowHeaderCaptionCheckBox.Enabled:=HasHeaders;
HideHeaderCaptionForFloatingCheckBox.Enabled:=HasHeaders;
FlattenHeaders.Enabled:=HasHeaders;
FilledHeaders.Enabled:=HasHeaders;
//
DockMaster.HeaderFilled := FilledHeaders.Checked;
DockMaster.HeaderFlatten:= FlattenHeaders.Checked;
DockMaster.ShowHeaderCaption:= ShowHeaderCaptionCheckBox.Checked;
DockMaster.HideHeaderCaptionFloatingControl:= HideHeaderCaptionForFloatingCheckBox.Checked;
//
SaveToMaster;
end;
initialization
DockOptionsEditor := TDockOptionsEditor.Create(nil);
DockOptionContainer:= TScrollBox.Create(nil);
DockOptionsEditor.Parent := DockOptionContainer;
DockOptionContainer.Align:= alClient;
DockOptionsEditor.Align:= alClient;
finalization
DockOptionsEditor.Free;
DockOptionContainer.Free;
end.
|
unit ImageUtils;
interface
uses
Classes, Windows, Graphics, ExtCtrls;
function LoadIconFromFile(Icon : TIcon; FileName : string; const Width, Height : integer) : boolean;
procedure DrawIcon2Image(Image : TImage; Icon : TIcon; const Width, Height : integer; const BkColor : TColor);
implementation
function LoadIconFromFile(Icon : TIcon; FileName : string; const Width, Height : integer) : boolean;
var
IconHandle : HICON;
begin
IconHandle := Windows.LoadImage(0, PCHAR(FileName), IMAGE_ICON, Width, Height, LR_LOADFROMFILE);
if IconHandle <> 0
then
begin
Icon.Handle := IconHandle;
result := true;
end
else result := false;
end;
procedure DrawIcon2Image(Image : TImage; Icon : TIcon; const Width, Height : integer; const BkColor : TColor);
var
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create;
if Icon <> nil
then
begin
Bitmap.Width := Width;
Bitmap.Height := Height;
with Bitmap.Canvas do
begin
Brush.Color := BkColor;
Brush.Style := bsSolid;
FillRect(ClipRect);
end;
DrawIconEx(Bitmap.Canvas.Handle, 0, 0, Icon.Handle, Width, Height, 0, 0, DI_NORMAL);
end;
Image.Picture.Bitmap := Bitmap;
end;
end.
|
unit uAssets;
interface
uses
glr_core,
glr_math,
glr_scene,
glr_render,
glr_render2d;
type
{ TArenaAssets }
TArenaAssets = class
public
MainCamera, GuiCamera: TglrCamera;
MainMaterial, GuiMaterial: TglrMaterial;
SpriteBatch: TglrSpriteBatch;
FontBatch: TglrFontBatch;
FrameBuffer: TglrFrameBuffer;
BloodTexture: TglrTexture;
procedure Init();
procedure DeInit();
end;
var
Assets: TArenaAssets;
implementation
{ TArenaAssets }
procedure TArenaAssets.Init;
begin
MainMaterial := TglrMaterial.Create(Default.SpriteShader);
MainMaterial.AddTexture(Default.BlankTexture, 'uDiffuse');
MainCamera := TglrCamera.Create();
MainCamera.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 100, pmOrtho, pCenter);
MainCamera.SetViewParams(Vec3f(0, 0, 100), Vec3f(0, 0, 0), Vec3f(0, 1, 0));
GuiMaterial := TglrMaterial.Create(Default.SpriteShader);
GuiMaterial.AddTexture(Default.BlankTexture, 'uDiffuse');
GuiCamera := TglrCamera.Create();
GuiCamera.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 100, pmOrtho, pTopLeft);
GuiCamera.SetViewParams(Vec3f(0, 0, 100), Vec3f(0, 0, 0), Vec3f(0, 1, 0));
SpriteBatch := TglrSpriteBatch.Create();
FontBatch := TglrFontBatch.Create(Default.Font);
BloodTexture := TglrTexture.Create(nil, 1024, 1024, tfRGB8);
FrameBuffer := TglrFrameBuffer.Create();
FrameBuffer.AttachTexture(BloodTexture.Id);
end;
procedure TArenaAssets.DeInit;
begin
MainMaterial.Free();
MainCamera.Free();
GuiMaterial.Free();
GuiCamera.Free();
SpriteBatch.Free();
FontBatch.Free();
FrameBuffer.Free();
BloodTexture.Free();
end;
end.
|
unit Collectible;
interface
uses
FMX.Graphics; { Unit containing TBitmap type definition }
type
TLaunchYear = 1965 .. 1995;
TConsState = 0 .. 100;
TCollectible = class abstract
private
Fname : String;
Fyear : TLaunchYear;
Fstate : TConsState;
Fdescription : String;
Fpictures : array of TBitmap;
nPictures : Integer;
{ Methods for internal use }
procedure setName(name: String);
function getPicture(Index: Integer): TBitmap;
procedure extendPictures;
public
{ There is only a constructor. It needs the name of the item }
constructor Create(name: String);
property Name: String read Fname write setName;
{ Access to the remainder data items in the object }
property Year : TLaunchYear read Fyear write Fyear;
property State : TConsState read Fstate write Fstate;
property Description : String read Fdescription write Fdescription;
property NumPictures : Integer read nPictures;
procedure addPicture(picture: TBitmap);
function hasPictures: Boolean;
property Picture[I: Integer] : TBitmap read getPicture;
end;
implementation
const INI_NUM_PICTURES = 1;
{ The constructor needs the name of the object, and
initializes the essential data members }
constructor TCollectible.Create(name: String);
begin
setName(name);
SetLength(Fpictures, INI_NUM_PICTURES);
nPictures := 0;
end;
function TCollectible.hasPictures;
begin
Result := nPictures > 0;
end;
{ Method for modifying the Name property }
procedure TCollectible.setName(name: String);
begin
Fname := name;
end;
{ Provides access to the pictures in the object }
function TCollectible.getPicture(Index: Integer): TBitmap;
begin
if Index < nPictures then
Result := Fpictures[Index]
else
Result := nil;
end;
{ Add a new picture to the list of pictures }
procedure TCollectible.addPicture(picture: TBitmap);
begin
if nPictures = Length(Fpictures) then
extendPictures;
Fpictures[nPictures] := picture;
inc(nPictures);
end;
{ Extend the array doubling its size }
procedure TCollectible.extendPictures;
begin
SetLength(Fpictures, Length(Fpictures) * 2);
end;
end.
|
unit fmuEKLZRep;
interface
uses
// VCL
ComCtrls, StdCtrls, Controls, ExtCtrls, Classes, SysUtils, Buttons, Graphics,
// This
untPages, fmuData, untDriver, TestManager, untUtil;
type
TfmEKLZRep = class(TPage)
rgReportType: TRadioGroup;
edtDepartment: TEdit;
udDepartment: TUpDown;
dtpFirstSessionDate: TDateTimePicker;
dtpLastSessionDate: TDateTimePicker;
lblStartDate: TLabel;
lblEndDate: TLabel;
btnGetEKLZDepartmentReportInDatesRange: TButton;
btnGetEKLZSessionReportInDatesRange: TButton;
Bevel1: TBevel;
lblFirstSessionNumber: TLabel;
edtFirstSessionNumber: TEdit;
lblLastSessionNumber: TLabel;
edtLastSessionNumber: TEdit;
btnGetEKLZDepartmentReportInSessionsRange: TButton;
btnGetEKLZSessionReportInSessionsRange: TButton;
Bevel2: TBevel;
lblStopEKLZDocumentPrinting: TLabel;
lblUDescription: TLabel;
edtUDescription: TEdit;
lblDepartment: TLabel;
Label1: TLabel;
Bevel3: TBevel;
btnShowData: TBitBtn;
btnGetEKLZData: TBitBtn;
Bevel4: TBevel;
procedure btnGetEKLZDepartmentReportInDatesRangeClick(Sender: TObject);
procedure btnGetEKLZDepartmentReportInSessionsRangeClick(Sender: TObject);
procedure btnGetEKLZSessionReportInDatesRangeClick(Sender: TObject);
procedure btnGetEKLZSessionReportInSessionsRangeClick(Sender: TObject);
procedure btnGetEKLZDataClick(Sender: TObject);
procedure btnShowDataClick(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure btnGetEKLZSessionReportInDatesRangeMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
procedure btnGetEKLZDepartmentReportInDatesRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure btnGetEKLZDepartmentReportInSessionsRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure btnGetEKLZSessionReportInSessionsRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
private
fmData: TfmData;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.DFM}
constructor TfmEKLZRep.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fmData := TfmData.Create(Self);
end;
procedure TfmEKLZRep.btnGetEKLZDepartmentReportInDatesRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Driver.ReportType := rgReportType.ItemIndex > 0;
Driver.Department := StrToInt(edtDepartment.Text);
Driver.FirstSessionDate := dtpFirstSessionDate.Date;
Driver.LastSessionDate := dtpLastSessionDate.Date;
if Driver.GetEKLZDepartmentReportInDatesRange = 0 then
edtUDescription.Text := Driver.UDescription
else
edtUDescription.Clear;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZRep.btnGetEKLZDepartmentReportInSessionsRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Driver.ReportType := rgReportType.ItemIndex > 0;
Driver.Department := StrToInt(edtDepartment.Text);
Driver.FirstSessionNumber := StrToInt(edtFirstSessionNumber.Text);
Driver.LastSessionNumber := StrToInt(edtLastSessionNumber.Text);
if Driver.GetEKLZDepartmentReportInSessionsRange = 0 then
edtUDescription.Text := Driver.UDescription
else
edtUDescription.Clear;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZRep.btnGetEKLZSessionReportInDatesRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Driver.ReportType := rgReportType.ItemIndex > 0;
Driver.FirstSessionDate := dtpFirstSessionDate.Date;
Driver.LastSessionDate := dtpLastSessionDate.Date;
if Driver.GetEKLZSessionReportInDatesRange = 0 Then
edtUDescription.Text := Driver.UDescription
else
edtUDescription.Clear;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZRep.btnGetEKLZSessionReportInSessionsRangeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Driver.ReportType := rgReportType.ItemIndex > 0;
Driver.FirstSessionNumber := StrToInt(edtFirstSessionNumber.Text);
Driver.LastSessionNumber := StrToInt(edtLastSessionNumber.Text);
if Driver.GetEKLZSessionReportInSessionsRange=0 Then
edtUDescription.Text := Driver.UDescription
else
edtUDescription.Clear;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZRep.btnGetEKLZDataClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
if Driver.GetEKLZData = 0 then
fmData.Memo.Lines.Add(Driver.EKLZData);
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZRep.btnShowDataClick(Sender: TObject);
begin
fmData.Show;
end;
procedure TfmEKLZRep.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if HighLighting then
begin
rgReportType.Color := clBtnFace;
edtDepartment.Color := clWindow;
dtpFirstSessionDate.Color := clWindow;
dtpLastSessionDate.Color := clWindow;
edtFirstSessionNumber.Color := clWindow;
edtLastSessionNumber.Color := clWindow;
edtUDescription.Color := clBtnFace;
end;
end;
procedure TfmEKLZRep.btnGetEKLZDepartmentReportInDatesRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
begin
rgReportType.Color := InColor;
edtDepartment.Color := InColor;
dtpFirstSessionDate.Color := InColor;
dtpLastSessionDate.Color := InColor;
edtUDescription.Color := OutColor;
end;
end;
procedure TfmEKLZRep.btnGetEKLZSessionReportInDatesRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
begin
rgReportType.Color := InColor;
dtpFirstSessionDate.Color := InColor;
dtpLastSessionDate.Color := InColor;
edtUDescription.Color := OutColor;
end;
end;
procedure TfmEKLZRep.btnGetEKLZDepartmentReportInSessionsRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
begin
rgReportType.Color := InColor;
edtDepartment.Color := InColor;
edtFirstSessionNumber.Color := InColor;
edtLastSessionNumber.Color := InColor;
edtUDescription.Color := OutColor;
end;
end;
procedure TfmEKLZRep.btnGetEKLZSessionReportInSessionsRangeMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
begin
rgReportType.Color := InColor;
edtFirstSessionNumber.Color := InColor;
edtLastSessionNumber.Color := InColor;
edtUDescription.Color := OutColor;
end;
end;
end.
|
unit untCalcImage;
interface
type
TCouleur = record
Rouge, Vert, Bleu : Double; // Le type Double permet de ne pas perdre d'informations après une division ou d'autres opérations
end;
TCouleurHistogramme = record
Rouge, Vert, Bleu : Integer;
end;
type
TCalcImage = class
private
FTailleX : Integer;
FTailleY : Integer;
procedure ChangeTailleX(const Value : Integer);
procedure ChangeTailleY(const Value : Integer);
public
Image : array of array of TCouleur;
Histogramme : array[0..255] of TCouleurHistogramme;
property TailleX : Integer read FTailleX write ChangeTailleX;
property TailleY : Integer read FTailleY write ChangeTailleY;
procedure ChangeDimensions(X, Y : Integer);
procedure CalculerHistogramme;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
untMDIImage, untPrincipale;
{ TCalcImage }
procedure TCalcImage.CalculerHistogramme;
var
X, Y : Integer;
NumCouleur : Integer;
begin
frmPrincipale.ChangeStatus('Calcul de l''histogramme de l''image');
for NumCouleur := 0 to 255 do
begin
Histogramme[NumCouleur].Rouge := 0; // Remet à zero
Histogramme[NumCouleur].Vert := 0; // toutes les valeurs
Histogramme[NumCouleur].Bleu := 0; // des histogrammes
end;
frmPrincipale.ProgressBar.Max := TailleX - 1;
for X := 0 to TailleX - 1 do
begin
frmPrincipale.ProgressBar.Position := X;
for Y := 0 to TailleY - 1 do
begin
Inc(Histogramme[LimiteCouleur(Image[X, Y].Rouge)].Rouge); // "Compte" le nombre
Inc(Histogramme[LimiteCouleur(Image[X, Y].Vert)].Vert); // de points de telle ou
Inc(Histogramme[LimiteCouleur(Image[X, Y].Bleu)].Bleu); // telle couleur
end;
end;
end;
procedure TCalcImage.ChangeDimensions(X, Y: Integer);
begin
FTailleX := X;
FTailleY := Y;
SetLength(Image, FTailleX, FTailleY); // Redimensionne la taille du tableau de données
end;
procedure TCalcImage.ChangeTailleX(const Value: Integer);
begin
FTailleX := Value;
SetLength(Image, FTailleX, FTailleY); // Redimensionne la taille du tableau de données
end;
procedure TCalcImage.ChangeTailleY(const Value: Integer);
begin
FTailleY := Value;
SetLength(Image, FTailleX, FTailleY); // Redimensionne la taille du tableau de données
end;
constructor TCalcImage.Create;
begin
inherited;
end;
destructor TCalcImage.Destroy;
begin
inherited;
end;
end.
|
unit HTMLProcessor;
{$mode objfpc}{$H+}
{**
* Light PHP Edit project
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
SysUtils, Graphics, Controls,
SynEdit, Classes, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc;
type
THTMLRangeState = (rshtmlText, rshtmlAmpersand, rshtmlComment, rshtmlKeyword, rshtmlParam, rshtmlValue, rshtmlStringSQ, rshtmlStringDQ);
{ THTMLProcessor }
THTMLProcessor = class(TSynProcessor)
protected
FRange: THTMLRangeState;
FAndCode: Integer;
function GetIdentChars: TSynIdentChars; override;
procedure ResetRange; override;
function GetRange: Byte; override;
procedure SetRange(Value: Byte); override;
public
procedure BraceOpenProc;
procedure IdentProc; override;
procedure StringProc;
procedure AmpersandProc;
procedure TextProc;
procedure CommentProc;
procedure BraceCloseProc;
procedure CRProc;
procedure EqualProc;
procedure LFProc;
procedure NullProc;
procedure SpaceProc;
procedure Next; override;
procedure Prepare; override;
procedure MakeProcTable; override;
end;
const
{$INCLUDE 'HTMLKeywords.inc'}
MAX_ESCAPEAMPS = 249;
EscapeAmps: array[0..MAX_ESCAPEAMPS - 1] of PChar = (
('Α'), { ? } { greek capital alpha }
('Β'), { ? } { greek capital beta }
('Γ'), { G } { greek capital gamma }
('Δ'), { ? } { greek capital delta }
('Ε'), { ? } { greek capital epsilon }
('Ζ'), { ? } { greek capital zeta }
('Η'), { ? } { greek capital eta }
('Θ'), { T } { greek capital theta }
('Ι'), { ? } { greek capital iota }
('Κ'), { ? } { greek capital kappa }
('Λ'), { ? } { greek capital lambda }
('Μ'), { ? } { greek capital mu }
('Ν'), { ? } { greek capital nu }
('Ξ'), { ? } { greek capital xi }
('Ο'), { ? } { greek capital omicron }
('Π'), { ? } { greek capital pi }
('Ρ'), { ? } { greek capital rho }
('Σ'), { S } { greek capital sigma }
('Τ'), { ? } { greek capital tau }
('Υ'), { ? } { greek capital upsilon }
('Φ'), { F } { greek capital phi }
('Χ'), { ? } { greek capital chi }
('Ψ'), { ? } { greek capital psi }
('Ω'), { O } { greek capital omega }
('α'), { a } { greek small alpha }
('β'), { ß } { greek small beta }
('γ'), { ? } { greek small gamma }
('δ'), { d } { greek small delta }
('ε'), { e } { greek small epsilon }
('ζ'), { ? } { greek small zeta }
('η'), { ? } { greek small eta }
('θ'), { ? } { greek small theta }
('ι'), { ? } { greek small iota }
('κ'), { ? } { greek small kappa }
('λ'), { ? } { greek small lambda }
('μ'), { µ } { greek small mu }
('ν'), { ? } { greek small nu }
('ξ'), { ? } { greek small xi }
('ο'), { ? } { greek small omicron }
('π'), { p } { greek small pi }
('ρ'), { ? } { greek small rho }
('ς'), { ? } { greek small final sigma }
('σ'), { s } { greek small sigma }
('τ'), { t } { greek small tau }
('υ'), { ? } { greek small upsilon }
('φ'), { f } { greek small phi }
('χ'), { ? } { greek small chi }
('ψ'), { ? } { greek small psi }
('ω'), { ? } { greek small omega }
('ϑ'), { ? } { greek small theta symbol }
('ϒ'), { ? } { greek upsilon with hook symbol }
('ϖ'), { ? } { greek pi symbol }
('•'), { • } { bullet }
('…'), { … } { horizontal ellipsis }
('′'), { ' } { prime }
('″'), { " } { double prime }
('‾'), { ? } { overline, = spacing overscore }
('⁄'), { / } { fraction slash }
('℘'), { P } { script capital P }
('ℑ'), { I } { imaginary part }
('ℜ'), { R } { real part }
('™'), { ™ } { trademark sign }
('ℵ'), { ? } { first transfinite cardinal }
('←'), { ? } { leftwards arrow }
('↑'), { ? } { upwards arrow }
('→'), { ? } { rightwards arrow }
('↓'), { ? } { downwards arrow }
('↔'), { ? } { left right arrow }
('↵'), { ? } { carriage return arrow }
('⇐'), { ? } { leftwards double arrow }
('⇑'), { ? } { upwards double arrow }
('⇒'), { ? } { rightwards double arrow }
('⇓'), { ? } { downwards double arrow }
('⇔'), { ? } { left right double arrow }
('∀'), { ? } { for all }
('∂'), { ? } { partial differential }
('∃'), { ? } { there exists }
('∅'), { Ø } { empty set }
('∇'), { ? } { backward difference }
('∈'), { ? } { element of }
('∉'), { ? } { not an element of }
('∋'), { ? } { contains as member }
('∏'), { ? } { n-ary product }
('∑'), { ? } { n-ary sumation }
('−'), { - } { minus sign }
('∗'), { * } { asterisk operator }
('√'), { v } { square root }
('∝'), { ? } { proportional to }
('∞'), { 8 } { infinity }
('∠'), { ? } { angle }
('∧'), { ? } { logical and }
('∨'), { ? } { logical or }
('∩'), { n } { intersection }
('∪'), { ? } { union }
('∫'), { ? } { integral }
('∴'), { ? } { therefore }
('∼'), { ~ } { similar to = tilde operator }
('≅'), { ? } { approximately equal to }
('≈'), { ˜ } { almost euqal to }
('≠'), { ? } { not equal to }
('≡'), { = } { identical to }
('≤'), { = } { less-than or equal to }
('≥'), { = } { greater-than or equal to }
('⊂'), { ? } { subset of }
('⊃'), { ? } { superset of }
('⊄'), { ? } { not a subset of }
('⊆'), { ? } { subset of or equal to }
('⊇'), { ? } { superset of or equal to }
('⊕'), { ? } { circled plus }
('⊗'), { ? } { circled times }
('⊥'), { ? } { orthogonal to = perpendicular }
('⋅'), { · } { dot operator }
('⌈'), { ? } { left ceiling }
('⌉'), { ? } { right ceiling }
('⌊'), { ? } { left floor }
('⌋'), { ? } { right floor }
('⟨'), { < } { left-pointing angle bracket }
('⟩'), { > } { right-pointing angle bracket }
('◊'), { ? } { lozenge }
('♠'), { ? } { black spade suit }
('♣'), { ? } { black club suit }
('♥'), { ? } { black heart suit }
('♦'), { ? } { black diamond suit }
('‘'), { ‘ } { left single quote }
('’'), { ’ } { right single quote }
('‚'), { ‚ } { single low-9 quote }
('“'), { “ } { left double quote }
('”'), { ” } { right double quote }
('„'), { „ } { double low-9 quote }
('†'), { † } { dagger }
('‡'), { ‡ } { double dagger }
('‰'), { ‰ } { per mill sign }
('‹'), { ‹ } { single left-pointing angle quote }
('›'), { › } { single right-pointing angle quote }
('"'), { " " } { double quotation mark }
('&'), { & & } { ampersand }
('<'), { < < } { less-than sign }
('>'), { > } { greater-than sign }
('–'), { – – } { en dash }
('—'), { — — } { em dash }
(' '), {   } { nonbreaking space }
(' '), { } { thin space }
(' '), { } { en space }
(' '), { } { em space }
('¡'), { ¡ ! } { inverted exclamation }
('¢'), { ¢ c } { cent sign }
('£'), { £ L } { pound sterling }
('¤'), { ¤ ¤ } { general currency sign }
('¥'), { ¥ Y } { yen sign }
('¦'), { ¦ ¦ } { broken vertical bar }
('&brkbar;'), { ¦ ¦ } { broken vertical bar }
('§'), { § § } { section sign }
('¨'), { ¨ ¨ } { umlaut }
('¨'), { ¨ ¨ } { umlaut }
('©'), { © © } { copyright }
('ª'), { ª a } { feminine ordinal }
('«'), { « « } { left angle quote }
('¬'), { ¬ ¬ } { not sign }
('­'), { ­ } { soft hyphen }
('®'), { ® ® } { registered trademark }
('¯'), { ¯ — } { macron accent }
('&hibar;'), { ¯ — } { macron accent }
('°'), { ° ° } { degree sign }
('±'), { ± ± } { plus or minus }
('²'), { ² 2 } { superscript two }
('³'), { ³ 3 } { superscript three }
('´'), { ´ ´ } { acute accent }
('µ'), { µ µ } { micro sign }
('¶'), { ¶ ¶ } { paragraph sign }
('·'), { · · } { middle dot }
('¸'), { ¸ ¸ } { cedilla }
('¹'), { ¹ 1 } { superscript one }
('º'), { º o } { masculine ordinal }
('»'), { » » } { right angle quote }
('¼'), { ¼ 1 } { one-fourth }
('½'), { ½ 1 } { one-half }
('¾'), { ¾ 3 } { three-fourths }
('¿'), { ¿ ? } { inverted question mark }
('À'), { À A } { uppercase A, grave accent }
('Á'), { Á Á } { uppercase A, acute accent }
('Â'), { Â Â } { uppercase A, circumflex accent }
('Ã'), { Ã A } { uppercase A, tilde }
('Ä'), { Ä Ä } { uppercase A, umlaut }
('Å'), { Å A } { uppercase A, ring }
('Æ'), { Æ A } { uppercase AE }
('Ç'), { Ç Ç } { uppercase C, cedilla }
('È'), { È E } { uppercase E, grave accent }
('É'), { É É } { uppercase E, acute accent }
('Ê'), { Ê E } { uppercase E, circumflex accent }
('Ë'), { Ë Ë } { uppercase E, umlaut }
('Ì'), { Ì I } { uppercase I, grave accent }
('Í'), { Í Í } { uppercase I, acute accent }
('Î'), { Î Î } { uppercase I, circumflex accent }
('Ï'), { Ï I } { uppercase I, umlaut }
('Ð'), { Ð ? } { uppercase Eth, Icelandic }
('Ñ'), { Ñ N } { uppercase N, tilde }
('Ò'), { Ò O } { uppercase O, grave accent }
('Ó'), { Ó Ó } { uppercase O, acute accent }
('Ô'), { Ô Ô } { uppercase O, circumflex accent }
('Õ'), { Õ O } { uppercase O, tilde }
('Ö'), { Ö Ö } { uppercase O, umlaut }
('×'), { × × } { multiplication sign }
('Ø'), { Ø O } { uppercase O, slash }
('Ù'), { Ù U } { uppercase U, grave accent }
('Ú'), { Ú Ú } { uppercase U, acute accent }
('Û'), { Û U } { uppercase U, circumflex accent }
('Ü'), { Ü Ü } { uppercase U, umlaut }
('Ý'), { Ý Ý } { uppercase Y, acute accent }
('Þ'), { Þ ? } { uppercase THORN, Icelandic }
('ß'), { ß ß } { lowercase sharps, German }
('à'), { à à } { lowercase a, grave accent }
('á'), { á á } { lowercase a, acute accent }
('â'), { â â } { lowercase a, circumflex accent }
('ã'), { ã ã } { lowercase a, tilde }
('ä'), { ä ä } { lowercase a, umlaut }
('å'), { å å } { lowercase a, ring }
('æ'), { æ a } { lowercase ae }
('ç'), { ç ç } { lowercase c, cedilla }
('è'), { è e } { lowercase e, grave accent }
('é'), { é é } { lowercase e, acute accent }
('ê'), { ê ê } { lowercase e, circumflex accent }
('ë'), { ë ë } { lowercase e, umlaut }
('ì'), { ì i } { lowercase i, grave accent }
('í'), { í í } { lowercase i, acute accent }
('î'), { î î } { lowercase i, circumflex accent }
('ï'), { ï i } { lowercase i, umlaut }
('ð'), { ð ? } { lowercase eth, Icelandic }
('ñ'), { ñ ñ } { lowercase n, tilde }
('ò'), { ò o } { lowercase o, grave accent }
('ó'), { ó ó } { lowercase o, acute accent }
('ô'), { ô ô } { lowercase o, circumflex accent }
('õ'), { õ o } { lowercase o, tilde }
('ö'), { ö ö } { lowercase o, umlaut }
('÷'), { ÷ ÷ } { division sign }
('ø'), { ø o } { lowercase o, slash }
('ù'), { ù u } { lowercase u, grave accent }
('ú'), { ú ú } { lowercase u, acute accent }
('û'), { û u } { lowercase u, circumflex accent }
('ü'), { ü ü } { lowercase u, umlaut }
('ý'), { ý ý } { lowercase y, acute accent }
('þ'), { þ ? } { lowercase thorn, Icelandic }
('ÿ'), { ÿ y } { lowercase y, umlaut }
('€'), { € } { euro sign }
('Œ'), { Œ } { capital ligature OE }
('œ'), { œ } { small ligature oe }
('š'), { š } { small S with caron }
('Š'), { Š } { capital S with caron }
('ƒ'), { ƒ } { function }
('ˆ') { ˆ } { circumflex accent }
);
implementation
{ THTMLProcessor }
procedure THTMLProcessor.MakeProcTable;
var
I: char;
begin
for I := #0 to #255 do
begin
case I of
#0: ProcTable[I] := @NullProc;
#10: ProcTable[I] := @LFProc;
#13: ProcTable[I] := @CRProc;
#1..#9, #11, #12, #14..#32: ProcTable[I] := @SpaceProc;
'&': ProcTable[I] := @AmpersandProc;
'"', '''': ProcTable[I] := @StringProc;
'<': ProcTable[I] := @BraceOpenProc;
'>': ProcTable[I] := @BraceCloseProc;
'=': ProcTable[I] := @EqualProc;
else
ProcTable[I] := @IdentProc;
end;
end;
end;
procedure THTMLProcessor.Next;
begin
Parent.fTokenPos := Parent.Run;
case fRange of
rshtmlText:
TextProc;
rshtmlComment:
CommentProc;
rshtmlStringSQ, rshtmlStringDQ:
if Parent.fLine[Parent.Run] in [#0, #10, #13] then
ProcTable[Parent.fLine[Parent.Run]]
else
StringProc;
else
ProcTable[Parent.FLine[Parent.Run]];
end;
end;
procedure THTMLProcessor.AmpersandProc;
begin
if fRange <> rshtmlAmpersand then
begin
if fRange = rshtmlKeyword then
begin
Inc(Parent.Run);
fRange := rshtmlText;
Parent.fTokenID := tkKeyword;
end
else
IdentProc;
Exit;
end;
case fAndCode of
Low(EscapeAmps)..High(EscapeAmps):
begin
Parent.fTokenID := tkVariable;
Inc(Parent.Run, StrLen(EscapeAmps[fAndCode]));
end;
else
begin
if (Parent.FLine[Parent.Run + 1] = '#') then
begin
fAndCode := -1;
inc(Parent.Run, 2);
if Parent.FLine[Parent.Run] in ['X', 'x'] then
begin
inc(Parent.Run);
while (Parent.FLine[Parent.Run] in ['0'..'9', 'A'..'F', 'a'..'f']) do
inc(Parent.Run);
end
else
while (Parent.FLine[Parent.Run] in ['0'..'9']) do
inc(Parent.Run);
if (Parent.FLine[Parent.Run] = ';') then
begin
inc(Parent.Run);
Parent.FTokenID := tkVariable;
end
else
Parent.FTokenID := tkUnknown;
end;
end;
end;
fAndCode := -1;
fRange := rshtmlText;
end;
procedure THTMLProcessor.BraceCloseProc;
begin
fRange := rshtmlText;
Parent.fTokenId := tkSymbol;
Inc(Parent.Run);
end;
procedure THTMLProcessor.BraceOpenProc;
var
aProcessor: string;
begin
Inc(Parent.Run);
aProcessor := '';
if (Parent.FLine[Parent.Run] = '?') then
begin
Inc(Parent.Run);
while Parent.FLine[Parent.Run] in ['a'..'z', 'A'..'Z', '0'..'9', '_', '-'] do
begin
aProcessor := aProcessor + Parent.FLine[Parent.Run];
Inc(Parent.Run);
end;
Parent.fTokenID := tkProcessor;
Parent.Processors.Switch(aProcessor);
end
else if (Parent.FLine[Parent.Run] = '!') and (Parent.FLine[Parent.Run + 1] = '-') and (Parent.FLine[Parent.Run + 2] = '-') then
begin
fRange := rshtmlComment;
Parent.fTokenID := tkComment;
Inc(Parent.Run, 3);
end
else if (Parent.FLine[Parent.Run] = '/') then
begin
fRange := rshtmlKeyword;
Parent.fTokenID := tkSymbol;
Inc(Parent.Run);
end
else
begin
fRange := rshtmlKeyword;
Parent.fTokenID := tkSymbol;
end;
end;
procedure THTMLProcessor.CommentProc;
begin
Parent.fTokenID := tkComment;
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else
while not (Parent.FLine[Parent.Run] in [#0, #10, #13]) do
begin
if (Parent.FLine[Parent.Run] = '>') and (Parent.FLine[Parent.Run - 1] = '-') and (Parent.FLine[Parent.Run - 2] = '-') then
begin
fRange := rshtmlText;
Inc(Parent.Run);
break;
end;
Inc(Parent.Run);
end;
end;
procedure THTMLProcessor.CRProc;
begin
Parent.fTokenID := tkSpace;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = #10 then
Inc(Parent.Run);
end;
procedure THTMLProcessor.EqualProc;
begin
fRange := rshtmlValue;
Parent.fTokenID := tkSymbol;
Inc(Parent.Run);
end;
function THTMLProcessor.GetRange: Byte;
begin
Result := Byte(FRange);
end;
procedure THTMLProcessor.IdentProc;
begin
case FRange of
rshtmlKeyword:
begin
FRange := rshtmlParam;
inherited;
end;
rshtmlValue:
begin
FRange := rshtmlParam;
Parent.FTokenID := tkString;
repeat
Inc(Parent.Run);
until (Parent.FLine[Parent.Run] in [#0..#32, '>']);
end;
else
begin
Parent.FTokenID := ScanIdent(Parent.FLine + Parent.Run);//check here maybe no need to inc(run)
//Inc(Parent.Run);
while not (Parent.FLine[Parent.Run] in [#0..#32, '=', '"', '>']) do
Inc(Parent.Run);
end;
end;
end;
procedure THTMLProcessor.LFProc;
begin
Parent.fTokenID := tkSpace;
Inc(Parent.Run);
end;
procedure THTMLProcessor.NullProc;
begin
Parent.fTokenID := tkNull;
end;
procedure THTMLProcessor.ResetRange;
begin
inherited;
FRange := rshtmlText;
end;
procedure THTMLProcessor.SetRange(Value: Byte);
begin
FRange := THTMLRangeState(Value);
end;
procedure THTMLProcessor.SpaceProc;
begin
Inc(Parent.Run);
Parent.fTokenID := tkSpace;
while Parent.FLine[Parent.Run] <= #32 do
begin
if Parent.FLine[Parent.Run] in [#0, #9, #10, #13] then
break;
Inc(Parent.Run);
end;
end;
procedure THTMLProcessor.StringProc;
var
iOpenChar: Char;
begin
case fRange of
rshtmlStringSQ:
begin
iOpenChar := '''';
Parent.fTokenID := tkString;
end;
rshtmlStringDQ:
begin
iOpenChar := '"';
Parent.fTokenID := tkString;
end;
rshtmlValue:
begin
iOpenChar := Parent.FLine[Parent.Run];
if iOpenChar = '"' then
fRange := rshtmlStringDQ
else
fRange := rshtmlStringSQ;
Parent.fTokenID := tkString;
Inc(Parent.Run); { jumps over the opening char }
end
else
begin
iOpenChar := Parent.FLine[Parent.Run];
IdentProc;
Inc(Parent.Run); { jumps over the opening char }
Exit;
end;
end;
while not (Parent.FLine[Parent.Run] in [#0, #10, #13]) do
begin
if Parent.FLine[Parent.Run] = iOpenChar then
begin
Inc(Parent.Run); { jumps over the closing char }
if fRange in [rshtmlStringDQ, rshtmlStringSQ] then
fRange := rshtmlParam
else
fRange := rshtmlText;
break;
end;
Inc(Parent.Run);
end;
end;
procedure THTMLProcessor.TextProc;
const
StopSet = [#0..#31, '<', '&'];
var
i: Integer;
begin
if Parent.FLine[Parent.Run] in (StopSet - ['&']) then
begin
ProcTable[Parent.FLine[Parent.Run]];
end
else
begin
Parent.fTokenID := tkUnknown;
while True do
begin
while not (Parent.FLine[Parent.Run] in StopSet) do
Inc(Parent.Run);
if (Parent.FLine[Parent.Run] = '&') then
begin
if (Parent.FLine[Parent.Run + 1] = '#') then
begin
fAndCode := -1;
i := Parent.Run;
inc(Parent.Run, 2);
if Parent.FLine[Parent.Run] in ['X', 'x'] then
begin
inc(Parent.Run);
while (Parent.FLine[Parent.Run] in ['0'..'9', 'A'..'F', 'a'..'f']) do
inc(Parent.Run);
end
else
while (Parent.FLine[Parent.Run] in ['0'..'9']) do
inc(Parent.Run);
if (Parent.FLine[Parent.Run] = ';') then
begin
inc(Parent.Run);
Parent.Run := i;
fRange := rshtmlAmpersand;
end;
BREAK;
end
else
begin
for i := Low(EscapeAmps) to High(EscapeAmps) do
begin
if (StrLComp((Parent.FLine + Parent.Run), PChar(EscapeAmps[i]), StrLen(EscapeAmps[i])) = 0) then
begin
fAndCode := i;
fRange := rshtmlAmpersand;
Exit;
end;
end;
end;
Inc(Parent.Run);
end
else
begin
Break;
end;
end;
end;
end;
procedure THTMLProcessor.Prepare;
begin
inherited;
EnumerateKeywords(Ord(tkKeyword), sHTMLKeywords, TSynValidStringChars, @DoAddKeyword);
FRange := rshtmlText;
FAndCode := -1;
end;
function THTMLProcessor.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars + ['&', ';'];
end;
end.
|
unit GraphicMemo;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
LCLIntf;
type
{ TGraphicMemo }
TGraphicMemo = class(TPanel)
private
fback:tpicture;
fbuff:tbitmap;
fcircle:tpicture;
flines:Tstringlist;
ffont:tfont;
findex:integer;
fx,fy,fx1,fy1,fident:integer;
fdown:boolean;
findent:integer;
floaded:boolean;
procedure setback(Value: tpicture);
procedure setcircle(Value: tpicture);
procedure setident(Value: integer);
procedure setlines(value:tstringlist);
procedure loadtextbuffer;
procedure setfont(value:tfont);
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
Procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
destructor Destroy; override;
procedure Paint; override;
published
Procedure LoadFromFile(s:string);
Procedure Apply;
Procedure ScrollBy(y:integer);
Property Background:tpicture read fback write setback;
Property Circle:tpicture read fcircle write setcircle;
Property Indent:integer read findent write setident;
Property Lines:tstringlist read flines write setlines;
Property Font:tfont read ffont write setfont;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Touch',[TGraphicMemo]);
end;
{ TGraphicMemo }
procedure TGraphicMemo.setident(Value: integer);
begin
findent:=value;
invalidate;
end;
procedure TGraphicMemo.setback(Value: tpicture);
begin
fback.assign(value);
end;
procedure TGraphicMemo.setcircle(Value: tpicture);
begin
fcircle.assign(value);
end;
procedure TGraphicMemo.setlines(value: tstringlist);
begin
lines.assign(value);
loadtextbuffer;
invalidate;
end;
procedure TGraphicMemo.loadtextbuffer;
var
i,w:integer;
begin
if flines.count<=0 then exit;
findex:=0;
w:=0;
fbuff.height:=(flines.count*ffont.size)+(height div 2)+(flines.count);
fbuff.width:=width-(findent*2);
fbuff.Canvas.Font.Assign(ffont);
fbuff.Canvas.AntialiasingMode:=amOff;
fbuff.canvas.brush.style:=bsclear;
with fbuff do begin
transparentmode:=tmauto;
transparent:=true;
end;
fbuff.canvas.Clear;
for i:=0 to flines.count-1 do begin
w:=fbuff.canvas.TextWidth(flines[i]);
if alignment=tacenter then fbuff.Canvas.TextOut((fbuff.width div 2)-(w div 2),(i*(ffont.size+2)),flines[i]);;
if alignment=taleftjustify then fbuff.Canvas.TextOut(0,(i*(ffont.size+2)),flines[i]);
if alignment=tarightjustify then fbuff.Canvas.TextOut(fbuff.width-w,(i*(ffont.size+2)),flines[i]);
end;
end;
procedure TGraphicMemo.setfont(value: tfont);
begin
ffont.assign(value);
fbuff.Canvas.Font.assign(value);
end;
constructor TGraphicMemo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fback:= tpicture.Create;
Fbuff:= tbitmap.Create;
fcircle:=tpicture.create;
ffont:=tfont.create;
flines:=tstringlist.create;
fbuff.Width:=1;
fbuff.height:=1;
bevelinner:=bvnone;
bevelouter:=bvnone;
findex:=0;
fx:=0;
floaded:=false;
fy:=0;
findent:=0;
fdown:=false;
end;
procedure TGraphicMemo.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if fdown then scrollby(fy-y);
fy:=y;
fx1:=x;
fy1:=y;
inherited MouseMove(Shift, X, Y);
end;
procedure TGraphicMemo.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
fdown:=false;
invalidate;
inherited MouseUp(Button, Shift, X, Y);
end;
procedure TGraphicMemo.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
fdown:=true;
fx:=y;
inherited MouseDown(Button, Shift, X, Y);
end;
destructor TGraphicMemo.Destroy;
begin
fback.free;
flines.Free;
fbuff.free;
fcircle.free;
ffont.free;
inherited Destroy;
end;
procedure TGraphicMemo.Paint;
begin
if assigned(fback) then canvas.draw(0,0,fback.graphic);
canvas.Draw(findent,-findex+findent,fbuff);
canvas.CopyRect(rect(0,0,width,findent),fback.Bitmap.canvas,rect(0,0,width,findent));
canvas.CopyRect(rect(0,height-findent,width,height+20),fback.Bitmap.canvas,rect(0,height-findent,width,height+20));
if (fdown=true) and (assigned(fcircle)) then canvas.draw(fx1-(fcircle.width div 2),fy1-(fcircle.height div 2),fcircle.graphic);
end;
procedure TGraphicMemo.LoadFromFile(s: string);
begin
lines.clear;
floaded:=true;
lines.LoadFromFile(s);
loadtextbuffer;
invalidate;
end;
procedure TGraphicMemo.Apply;
begin
loadtextbuffer;
invalidate;
end;
procedure TGraphicMemo.ScrollBy(y: integer);
begin
findex:=findex+y;
if (findex+height)>= fbuff.height then findex:=fbuff.height-height;
if findex<=0 then findex:=0;
invalidate;
end;
end.
|
unit Rule_HHV;
interface
uses
BaseRule,
BaseRuleData;
type
TRule_HHV = class(TBaseRule)
protected
fParamN: Word;
fInt64Ret: PArray;
fFloatRet: PArray;
function GetHHVValueF(AIndex: integer): double;
function GetHHVValueI(AIndex: integer): int64;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
procedure ComputeInt64;
procedure ComputeFloat;
public
constructor Create(ADataType: TRuleDataType); override;
destructor Destroy; override;
procedure Execute; override;
property ValueF[AIndex: integer]: double read GetHHVValueF;
property ValueI[AIndex: integer]: int64 read GetHHVValueI;
property ParamN: Word read GetParamN write SetParamN;
end;
TBase_HHV = class(TBaseRule)
protected
fParamN: Word;
procedure Compute; virtual;
public
constructor Create(ADataType: TRuleDataType); override;
procedure Execute; override;
end;
THHV_Int64 = class(TBase_HHV)
protected
fInt64Ret: PArray;
public
end;
THHV_Double = class(TBase_HHV)
protected
fFloatRet: PArray;
public
end;
implementation
{ TRule_HHV }
constructor TRule_HHV.Create(ADataType: TRuleDataType);
begin
inherited;
fParamN := 20;
fInt64Ret := nil;
fFloatRet := nil;
// SetLength(fFloatRet, 0);
// SetLength(fInt64Ret, 0);
end;
destructor TRule_HHV.Destroy;
begin
CheckInArray(fInt64Ret);
CheckInArray(fFloatRet);
inherited;
end;
procedure TRule_HHV.Execute;
begin
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
case fBaseRuleData.DataType of
dtInt64: begin
ComputeInt64;
end;
dtDouble: begin
ComputeFloat;
end;
end;
end;
end;
procedure TRule_HHV.ComputeInt64;
var
tmpInt64_Meta: PArray;
// tmpInt64_MetaNode: PArrayInt64Node;
// tmpInt64RetNode: PArrayInt64Node;
i: integer;
tmpCounter: integer;
tmpValue: Int64;
tmpPreValue: Int64;
begin
if Assigned(OnGetDataI) then
begin
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
tmpInt64_Meta := CheckOutArrayInt64;
try
SetArrayLength(fInt64Ret, fBaseRuleData.DataLength);
SetArrayLength(tmpInt64_Meta, fBaseRuleData.DataLength);
//tmpInt64RetNode := fInt64Ret.FirstValueNode;
//tmpInt64_MetaNode := tmpInt64_Meta.FirstValueNode;
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpValue := OnGetDataI(i);
//tmpInt64_MetaNode.Value[i] := tmpValue;
SetArrayInt64Value(tmpInt64_Meta, i, tmpValue);
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
//tmpPreValue := tmpInt64_MetaNode.Value[i - tmpCounter];
tmpPreValue := GetArrayInt64Value(tmpInt64_Meta, i - tmpCounter);
if tmpValue < tmpPreValue then
begin
tmpValue := tmpPreValue;
end;
end;
Dec(tmpCounter);
end;
//SetArrayInt64NodeValue(tmpInt64RetNode, i, tmpValue);
SetArrayInt64Value(fInt64Ret, i, tmpValue);
end;
finally
CheckInArray(tmpInt64_Meta);
end;
end;
end;
procedure TRule_HHV.ComputeFloat;
var
tmpFloat_Meta: PArray;
i: integer;
tmpCounter: integer;
tmpValue: double;
tmpPreValue: double;
begin
if Assigned(OnGetDataF) then
begin
if fFloatRet = nil then
fFloatRet := CheckOutArrayDouble;
tmpFloat_Meta := CheckOutArrayDouble;
try
SetArrayLength(fFloatRet, fBaseRuleData.DataLength);
SetArrayLength(tmpFloat_Meta, fBaseRuleData.DataLength);
//tmpFloatRetNode := fFloatRet.FirstValueNode;
//tmpFloat_MetaNode := tmpFloat_Meta.FirstValueNode;
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpValue := OnGetDataF(i);
//tmpFloat_MetaNode.Value[i] := tmpValue;
SetArrayDoubleValue(tmpFloat_Meta, i, tmpValue);
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
//tmpPreValue := tmpFloat_MetaNode.Value[i - tmpCounter];
tmpPreValue := GetArrayDoubleValue(tmpFloat_Meta, i - tmpCounter);
if tmpValue < tmpPreValue then
begin
tmpValue := tmpPreValue;
end;
end;
Dec(tmpCounter);
end;
//SetArrayDoubleNodeValue(tmpFloatRetNode, i, tmpValue);
SetArrayDoubleValue(fFloatRet, i, tmpValue);
end;
finally
CheckInArray(tmpFloat_Meta);
end;
end;
end;
function TRule_HHV.GetParamN: Word;
begin
Result := fParamN;
end;
procedure TRule_HHV.SetParamN(const Value: Word);
begin
if Value > 0 then
begin
fParamN := Value;
end;
end;
function TRule_HHV.GetHHVValueF(AIndex: integer): double;
begin
Result := 0;
if fBaseRuleData.DataType = dtDouble then
begin
if nil <> fFloatRet then
Result := GetArrayDoubleValue(fFloatRet, AIndex);
end;
end;
function TRule_HHV.GetHHVValueI(AIndex: integer): int64;
begin
Result := 0;
if fBaseRuleData.DataType = dtInt64 then
begin
if fInt64Ret <> nil then
Result := GetArrayInt64Value(fInt64Ret, AIndex);
end;
end;
{ TBase_HHV }
constructor TBase_HHV.Create(ADataType: TRuleDataType);
begin
inherited;
fParamN := 20;
end;
procedure TBase_HHV.Execute;
begin
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
Compute;
end;
end;
procedure TBase_HHV.Compute;
//var
// i: integer;
begin
if not Assigned(OnGetDataI) then
exit;
(*//
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
SetArrayInt64Length(fInt64Ret, fBaseRuleData.DataLength);
SetArrayInt64Length(tmpInt64_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpInt64_Meta[i] := OnGetDataI(i);
SetArrayInt64Value(fInt64Ret, i, tmpInt64_Meta[i]);
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
if GetArrayInt64Value(fInt64Ret, i) < tmpInt64_Meta[i - tmpCounter] then
begin
SetArrayInt64Value(fInt64Ret, i, tmpInt64_Meta[i - tmpCounter]);
end;
end;
Dec(tmpCounter);
end;
end;
//*)
end;
end.
|
{@html(<hr>)
@abstract(Unit providing routines operating on @code(TelemetryString) type and
routines converting selected binary types to text.)
@author(František Milt <fmilt@seznam.cz>)
@created(2014-04-30)
@lastmod(2014-04-30)
@bold(@NoAutoLink(TelemetryStrings))
©František Milt, all rights reserved.
This unit is intended to provide some basic routines for manipulation and
processing of @code(TelemetryString) type (UTF8 encoded string) and also
routines designed to return human readable (i.e. textual) representation of
binary data stored in variables of selected types.
Last change: 2014-04-30
Change List:@unorderedList(
@item(2014-04-30 - First stable version.)
@item(2014-04-30 - Unit @code(TelemetryRecipientAux) was completely merged
into this unit.))
@html(<hr>)}
unit TelemetryStrings;
interface
{$INCLUDE '.\Telemetry_defs.inc'}
uses
TelemetryCommon,
{$IFDEF UseCondensedHeader}
SCS_Telemetry_Condensed;
{$ELSE}
scssdk,
scssdk_value,
scssdk_telemetry_event;
{$ENDIF}
{==============================================================================}
{ Unit Functions and procedures declarations }
{==============================================================================}
{
@abstract(Compares strings based on the current locale with case sensitivity.)
Since the @code(TelemetryString) is UTF8-encoded and there is no function
for comparison of such strings, both strings are converted to WideString
before actual comparison takes place.@br
This function can be slow, so if performance is important, consider using
TelemetrySameStrNoConv instead.
@param S1 First string to compare.
@param S2 Second string to compare.
@returns @True when the strings have the same value, @false otherwise.
}
Function TelemetrySameStr(const S1, S2: TelemetryString): Boolean;
{
@abstract(Compares strings based on the current locale without case
sensitivity.)
Since the @code(TelemetryString) is UTF8-encoded and there is no function
for comparison of such strings, both strings are converted to WideString
before actual comparison takes place.@br
This function can be slow, so if performance is important, consider using
TelemetrySameTextNoConv instead.
@param S1 First string to compare.
@param S2 Second string to compare.
@returns @True when the strings have the same value, @false otherwise.
}
Function TelemetrySameText(const S1, S2: TelemetryString): Boolean;
{
@abstract(Compares strings based on the current locale with case sensitivity
and without internal conversions.)
Unlike TelemetrySameStr, this function does not convert input strings to
WideString before comparison. Instead, both strings are treated as normal
AnsiString. This requires that both strings contains only ASCII characters
(that is, up to #126), otherwise the function can, and probably will, return
wrong result.
@param S1 First string to compare.
@param S2 Second string to compare.
@returns @True when the strings have the same value, @false otherwise.
}
Function TelemetrySameStrNoConv(const S1, S2: TelemetryString): Boolean;
{
@abstract(Compares strings based on the current locale without case
sensitivity and without internal conversions.)
Unlike TelemetrySameText, this function does not convert input strings to
WideString before comparison. Instead, both strings are treated as normal
AnsiString. This requires that both strings contains only ASCII characters
(that is, up to #126), otherwise the function can, and probably will, return
wrong result.
@param S1 First string to compare.
@param S2 Second string to compare.
@returns @True when the strings have the same value, @false otherwise.
}
Function TelemetrySameTextNoConv(const S1, S2: TelemetryString): Boolean;
//==============================================================================
{
@abstract(Returns identifier of given SCS value type.)
Identifiers are not defined by the API, for details about naming individual
types refer to function implementation.
@param SCSValueType Value type.
@returns Textual identifier of given value type.
}
Function SCSValueTypeToStr(SCSValueType: scs_value_type_t): String;
//------------------------------------------------------------------------------
{
@abstract(Returns value type given by identifier.)
If identifier is not recognized, then @code(SCS_VALUE_TYPE_INVALID) is
returned.@br
Function is case-insensitive.@br
Identifiers are not defined by the API, for details about naming individual
types refer to function implementation.
@param Str Textual identifier of value type.
@returns Value type with name corresponding to passed textual identifier.
}
Function SCSValueTypeFromStr(Str: String): scs_value_type_t;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of @code(scs_value_t) structure.)
When type of the value is not known, an empty string is returned.
@param Value Actual value to be converted to text.
@param(TypeName When set, value type identifier is added to output
string.)
@param(ShowDescriptors When set, fileds descriptors are shown for composite
values.)
@returns Textual representation of given value.
}
Function SCSValueToStr(const Value: scs_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of scs_value_localized_t structure.)
@param Value Actual value to be converted to text.
@param(TypeName When set, value type identifier is added to output
string.)
@param(ShowDescriptors When set, fileds descriptors are shown for composite
values.)
@returns Textual representation of given value.
}
Function SCSValueLocalizedToStr(Value: scs_value_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of @code(scs_named_value_t)
structure.)
@param Value Actual value to be converted to text.
@param(TypeName When set, value type identifier is added to output
string.)
@param(ShowDescriptors When set, fileds descriptors are shown for composite
values.)
@returns Textual representation of given value.
}
Function SCSNamedValueToStr(Value: scs_named_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of scs_named_value_localized_t
structure.)
@param Value Actual value to be converted to text.
@param(TypeName When set, value type identifier is added to output
string.)
@param(ShowDescriptors When set, fileds descriptors are shown for composite
values.)
@returns Textual representation of given value.
}
Function SCSNamedValueLocalizedToStr(Value: scs_named_value_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of @code(scs_telemetry_frame_start_t)
structure.)
@param Data Structure to be converted to text.
@param(TypeName When set, value type identifiers for individual fields are
added to output string.)
@returns Textual representation of given structure.
}
Function TelemetryEventFrameStartToStr(const Data: scs_telemetry_frame_start_t; TypeName: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of
@code(scs_telemetry_configuration_t) structure.)
@param Data Structure to be converted to text.
@param(TypeName When set, value type identifiers for individual
attribute values are added to output.)
@param(ShowDescriptors When set, fields descriptors are shown for composite
values.)
@returns Textual representation of given structure.
}
Function TelemetryEventConfigurationToStr(const Data: scs_telemetry_configuration_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
//------------------------------------------------------------------------------
{
@abstract(Returns textual representation of
scs_telemetry_configuration_localized_t structure.)
@param Data Structure to be converted to text.
@param(TypeName When set, value type identifiers for individual
attribute values are added to output.)
@param(ShowDescriptors When set, fields descriptors are shown for composite
values.)
@returns Textual representation of given structure.
}
Function TelemetryEventConfigurationLocalizedToStr(const Data: scs_telemetry_configuration_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
implementation
uses
Windows, SysUtils;
{==============================================================================}
{ Constants, types, variables, etc... }
{==============================================================================}
const
// Table of identifiers for individual value types (scs_value_type_t).
// Index of each string corresponds to value type number this string is
// identifying.
cSCSValueTypeIdentifiers: Array[0..12] of String =
('none','bool','s32','u32','u64','float','double','fvector','dvector',
'euler','fplacement','dplacement','string');
var
// Used for thread safety in conversions dependent on LocaleID.
// Initialized in Initialization section of this unit (with id set to
// LOCALE_USER_DEFAULT).
FormatSettings: TFormatSettings;
{==============================================================================}
{ Unit Functions and procedures implementation }
{==============================================================================}
Function TelemetrySameStr(const S1, S2: TelemetryString): Boolean;
begin
{$IFDEF Unicode}
Result := AnsiSameStr(UTF8Decode(S1),UTF8Decode(S2));
{$ELSE}
Result := WideSameStr(UTF8Decode(S1),UTF8Decode(S2));
{$ENDIF}
end;
//------------------------------------------------------------------------------
Function TelemetrySameText(const S1, S2: TelemetryString): Boolean;
begin
{$IFDEF Unicode}
Result := AnsiSameText(UTF8Decode(S1),UTF8Decode(S2));
{$ELSE}
Result := WideSameText(UTF8Decode(S1),UTF8Decode(S2));
{$ENDIF}
end;
//------------------------------------------------------------------------------
Function TelemetrySameStrNoConv(const S1, S2: TelemetryString): Boolean;
begin
Result := AnsiSameStr(S1,S2);
end;
//------------------------------------------------------------------------------
Function TelemetrySameTextNoConv(const S1, S2: TelemetryString): Boolean;
begin
Result := AnsiSameText(S1,S2);
end;
//==============================================================================
Function SCSValueTypeToStr(SCSValueType: scs_value_type_t): String;
begin
If (Integer(SCSValueType) >= Low(cSCSValueTypeIdentifiers)) and
(Integer(SCSValueType) <= High(cSCSValueTypeIdentifiers)) then
Result := cSCSValueTypeIdentifiers[Integer(SCSValueType)]
else
Result := 'unknown';
end;
//------------------------------------------------------------------------------
Function SCSValueTypeFromStr(Str: String): scs_value_type_t;
var
i: Integer;
begin
Result := SCS_VALUE_TYPE_INVALID;
For i := Low(cSCSValueTypeIdentifiers) to High(cSCSValueTypeIdentifiers) do
If AnsiSameText(cSCSValueTypeIdentifiers[i],Str) then
begin
Result := scs_value_type_t(i);
Break;
end;
end;
//------------------------------------------------------------------------------
Function SCSValueToStr(const Value: scs_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
type
TDescriptorsArray = Array[0..5] of String;
const
cFullDescriptors: TDescriptorsArray = ('X: ','Y: ','Z: ','Heading: ','Pitch: ','Roll: ');
cEmptyDescriptors: TDescriptorsArray = ('','','','','','');
var
Descriptors: TDescriptorsArray;
begin
If ShowDescriptors then Descriptors := cFullDescriptors
else Descriptors := cEmptyDescriptors;
case Value._type of
SCS_VALUE_TYPE_INVALID:
Result := '';
SCS_VALUE_TYPE_bool:
Result := BoolToStr(Value.value_bool.value <> 0,True);
SCS_VALUE_TYPE_s32:
Result := IntToStr(Value.value_s32.value);
SCS_VALUE_TYPE_u32:
Result := IntToStr(Value.value_u32.value);
SCS_VALUE_TYPE_u64:
Result := IntToStr(Value.value_u64.value);
SCS_VALUE_TYPE_float:
Result := FloatToStr(Value.value_float.value,FormatSettings);
SCS_VALUE_TYPE_double:
Result := FloatToStr(Value.value_double.value,FormatSettings);
SCS_VALUE_TYPE_fvector:
Result := '[' + Descriptors[0] + FloatToStr(Value.value_fvector.x,FormatSettings) +
', ' + Descriptors[1] + FloatToStr(Value.value_fvector.y,FormatSettings) +
', ' + Descriptors[2] + FloatToStr(Value.value_fvector.z,FormatSettings) + ']';
SCS_VALUE_TYPE_dvector:
Result := '[' + Descriptors[0] + FloatToStr(Value.value_dvector.x,FormatSettings) +
', ' + Descriptors[1] + FloatToStr(Value.value_dvector.y,FormatSettings) +
', ' + Descriptors[2] + FloatToStr(Value.value_dvector.z,FormatSettings) + ']';
SCS_VALUE_TYPE_euler:
Result := '[' + Descriptors[3] + FloatToStr(Value.value_euler.heading,FormatSettings) +
', ' + Descriptors[4] + FloatToStr(Value.value_euler.pitch,FormatSettings) +
', ' + Descriptors[5] + FloatToStr(Value.value_euler.roll,FormatSettings) + ']';
SCS_VALUE_TYPE_fplacement:
Result := '[' + Descriptors[0] + FloatToStr(Value.value_fplacement.position.x,FormatSettings) +
', ' + Descriptors[1] + FloatToStr(Value.value_fplacement.position.y,FormatSettings) +
', ' + Descriptors[2] + FloatToStr(Value.value_fplacement.position.z,FormatSettings) +
'] [' + Descriptors[3] + FloatToStr(Value.value_fplacement.orientation.heading,FormatSettings) +
', ' + Descriptors[4] + FloatToStr(Value.value_fplacement.orientation.pitch,FormatSettings) +
', ' + Descriptors[5] + FloatToStr(Value.value_fplacement.orientation.roll,FormatSettings) + ']';
SCS_VALUE_TYPE_dplacement:
Result := '[' + Descriptors[0] + FloatToStr(Value.value_dplacement.position.x,FormatSettings) +
', ' + Descriptors[1] + FloatToStr(Value.value_dplacement.position.y,FormatSettings) +
', ' + Descriptors[2] + FloatToStr(Value.value_dplacement.position.z,FormatSettings) +
'] [' + Descriptors[3] + FloatToStr(Value.value_dplacement.orientation.heading,FormatSettings) +
', ' + Descriptors[4] + FloatToStr(Value.value_dplacement.orientation.pitch,FormatSettings) +
', ' + Descriptors[5] + FloatToStr(Value.value_dplacement.orientation.roll,FormatSettings) + ']';
SCS_VALUE_TYPE_string:
Result := TelemetryStringDecode(APIStringToTelemetryString(Value.value_string.value));
else
Result := '';
end;
If TypeName then Result := '(' + SCSValueTypeToStr(Value._type) + ') ' + Result;
end;
//------------------------------------------------------------------------------
Function SCSValueLocalizedToStr(Value: scs_value_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
begin
case Value.ValueType of
SCS_VALUE_TYPE_string:
If TypeName then Result := '(' + SCSValueTypeToStr(Value.ValueType) + ') ' + TelemetryStringDecode(Value.StringData)
else Result := TelemetryStringDecode(Value.StringData);
else
Value.BinaryData._type := Value.ValueType;
Result := SCSValueToStr(Value.BinaryData,TypeName,ShowDescriptors);
end;
end;
//------------------------------------------------------------------------------
Function SCSNamedValueToStr(Value: scs_named_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
begin
Result := TelemetryStringDecode(APIStringToTelemetryString(Value.name));
If Value.index <> SCS_U32_NIL then Result := Result + '[' + IntToStr(Value.index) + ']';
Result := Result + ': ' + SCSValueToStr(Value.value,TypeName,ShowDescriptors);
end;
//------------------------------------------------------------------------------
Function SCSNamedValueLocalizedToStr(Value: scs_named_value_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
begin
Result := Value.Name;
If Value.Index <> SCS_U32_NIL then Result := Result + '[' + IntToStr(Value.Index) + ']';
Result := Result + ': ' + SCSValueLocalizedToStr(Value.Value,TypeName,ShowDescriptors);
end;
//------------------------------------------------------------------------------
Function TelemetryEventFrameStartToStr(const Data: scs_telemetry_frame_start_t; TypeName: Boolean = False): String;
begin
If TypeName then
Result := 'Flags: (u32) ' + IntToHex(Data.flags,SizeOf(Data.flags) * 2) + sLineBreak +
'Render time: (u64) ' + IntToStr(Data.render_time) + sLineBreak +
'Simulation time: (u64) ' + IntToStr(Data.simulation_time) + sLineBreak +
'Pause simulation time: (u64) ' + IntToStr(Data.paused_simulation_time)
else
Result := 'Flags: ' + IntToHex(Data.flags,SizeOf(Data.flags) * 2) + sLineBreak +
'Render time: ' + IntToStr(Data.render_time) + sLineBreak +
'Simulation time: ' + IntToStr(Data.simulation_time) + sLineBreak +
'Pause simulation time: ' + IntToStr(Data.paused_simulation_time);
end;
//------------------------------------------------------------------------------
Function TelemetryEventConfigurationToStr(const Data: scs_telemetry_configuration_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
var
TempAttr: p_scs_named_value_t;
begin
Result := TelemetryStringDecode(APIStringToTelemetryString(Data.id));
TempAttr := Data.attributes;
while Assigned(TempAttr^.name) do
begin
Result := Result + sLineBreak + SCSNamedValueToStr(TempAttr^,TypeName,ShowDescriptors);
Inc(TempAttr);
end;
end;
//------------------------------------------------------------------------------
Function TelemetryEventConfigurationLocalizedToStr(const Data: scs_telemetry_configuration_localized_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
var
i: Integer;
begin
Result := TelemetryStringDecode(Data.ID);
For i := Low(Data.Attributes) to High(Data.Attributes) do
Result := Result + sLineBreak + SCSNamedValueLocalizedToStr(Data.Attributes[i],TypeName,ShowDescriptors);
end;
//------------------------------------------------------------------------------
initialization
GetLocaleFormatSettings(LOCALE_USER_DEFAULT,FormatSettings);
FormatSettings.DecimalSeparator := '.';
end.
|
unit DirUtils;
// Copyright (c) 1997 JRG & Yeti, Merchise
interface
function RemoveEmptyDirs( const Path : string ) : boolean;
// Directory travelling
type
TNotifyProc = procedure ( const ItemFound : string; Attr : integer; Data : integer );
// Travel flags
const
tfNotifyHidden = $01;
tfNotifySystem = $02;
tfNotifyAll = tfNotifyHidden or tfNotifySystem;
tfNotifyFiles = $10;
tfNotifySubdirectories = $20;
tfNotifyBoth = tfNotifyFiles or tfNotifySubdirectories;
procedure Travel( const DirName : string; Flags : integer; Data : integer; Notification : TNotifyProc );
implementation
uses
Windows, SysUtils;
function RemoveEmptyDirs( const Path : string ) : boolean;
var
SearchRec : TSearchRec;
FindResult : integer;
begin
FindResult := FindFirst( Path + '*.*', faDirectory, SearchRec );
while FindResult = 0 do
begin
if ( SearchRec.Name <> '.' ) and ( SearchRec.Name <> '..' )
then RemoveEmptyDirs( Path + SearchRec.Name + '\' );
FindResult := FindNext( SearchRec );
end;
FindClose( SearchRec );
Result := RemoveDirectory( pchar( Copy( Path, 1, pred( Length( Path ) ) ) ) );
end;
// Directory travelling
procedure Travel( const DirName : string; Flags : integer; Data : integer; Notification : TNotifyProc );
procedure TravelSubdirectories( const DirName : string );
var
SearchRec : TSearchRec;
FoundResult : integer;
begin
FoundResult := FindFirst( DirName + '\*.*', faAnyFile, SearchRec );
try
while FoundResult = 0 do
with SearchRec do
begin
if ( Name <> '.' ) and ( Name <> '..' )
then
begin
if ( ( Flags and tfNotifyHidden <> 0 ) or ( Attr and faHidden = 0 ) ) and
( ( Flags and tfNotifySystem <> 0 ) or ( Attr and faSysFile = 0 ) ) and
( ( Flags and tfNotifySubdirectories <> 0 ) or ( Attr and faDirectory = 0 ) )
then Notification( DirName + '\' + Name, Attr, Data );
if Attr and faDirectory <> 0
then TravelSubdirectories( DirName + '\' + Name );
end;
FoundResult := FindNext( SearchRec );
end;
finally
FindClose( SearchRec );
end;
end;
begin
TravelSubdirectories( DirName );
end;
end.
|
unit LUX.GPU.Vulkan.Surfac;
interface //#################################################################### ■
uses WinApi.Windows,
vulkan_core, vulkan_win32,
LUX.Data.List;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TVkSurfacs<TVkInstan_:class> = class;
TVkSurfac<TVkInstan_:class> = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkSurfac
TVkSurfac<TVkInstan_:class> = class( TListChildr<TVkInstan_,TVkSurfacs<TVkInstan_>> )
private
type TVkSurfacs_ = TVkSurfacs<TVkInstan_>;
protected
_Inform :VkWin32SurfaceCreateInfoKHR;
_PxSizeX :Integer;
_PxSizeY :Integer;
_Handle :VkSurfaceKHR;
///// アクセス
function GetWindow :HWND;
procedure SetWindow( const Window_:HWND );
function GetPxSizeX :Integer;
function GetPxSizeY :Integer;
function GetHandle :VkSurfaceKHR;
procedure SetHandle( const Handle_:VkSurfaceKHR );
///// メソッド
procedure CreateHandle;
procedure DestroHandle;
public
constructor Create; override;
constructor Create( const Instan_:TVkInstan_ ); overload; virtual;
constructor Create( const Instan_:TVkInstan_; const Window_:HWND ); overload; virtual;
destructor Destroy; override;
///// プロパティ
property Instan :TVkInstan_ read GetOwnere ;
property Surfacs :TVkSurfacs_ read GetParent ;
property Window :HWND read GetWindow write SetWindow;
property PxSizeX :Integer read GetPxSizeX;
property PxSizeY :Integer read GetPxSizeY;
property Inform :VkWin32SurfaceCreateInfoKHR read _Inform ;
property Handle :VkSurfaceKHR read GetHandle write SetHandle;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkSurfacs
TVkSurfacs<TVkInstan_:class> = class( TListParent<TVkInstan_,TVkSurfac<TVkInstan_>> )
private
type TVkSurfac_ = TVkSurfac<TVkInstan_>;
protected
public
///// プロパティ
property Instan :TVkInstan_ read GetOwnere;
///// メソッド
function Add :TVkSurfac_; overload;
function Add( const HWND_:HWND ) :TVkSurfac_; overload;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils,
FMX.Types,
LUX.GPU.Vulkan;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkSurfac
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TVkSurfac<TVkInstan_>.GetWindow :HWND;
begin
Result := _Inform.hwnd;
end;
procedure TVkSurfac<TVkInstan_>.SetWindow( const Window_:HWND );
var
R :TRect;
begin
_Inform.hwnd := Window_;
GetClientRect( Window, R );
_PxSizeX := R.Width ;
_PxSizeY := R.Height;
_Inform.hinstance := GetWindowLong( Window, GWL_HINSTANCE );
Handle := 0;
end;
function TVkSurfac<TVkInstan_>.GetPxSizeX :Integer;
begin
Result := _PxSizeX;
end;
function TVkSurfac<TVkInstan_>.GetPxSizeY :Integer;
begin
Result := _PxSizeY;
end;
function TVkSurfac<TVkInstan_>.GetHandle :VkSurfaceKHR;
begin
if _Handle = 0 then CreateHandle;
Result := _Handle;
end;
procedure TVkSurfac<TVkInstan_>.SetHandle( const Handle_:VkSurfaceKHR );
begin
if _Handle <> 0 then DestroHandle;
_Handle := Handle_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TVkSurfac<TVkInstan_>.CreateHandle;
begin
Assert( vkCreateWin32SurfaceKHR( TVkInstan( Instan ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS );
end;
procedure TVkSurfac<TVkInstan_>.DestroHandle;
begin
vkDestroySurfaceKHR( TVkInstan( Instan ).Handle, _Handle, nil );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TVkSurfac<TVkInstan_>.Create;
begin
inherited;
_Handle := 0;
with _Inform do
begin
sType := VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
pNext := nil;
flags := 0;
// hinstance
// hwnd
end;
end;
constructor TVkSurfac<TVkInstan_>.Create( const Instan_:TVkInstan_ );
begin
inherited Create( TVkInstan( Instan_ ).Surfacs );
end;
constructor TVkSurfac<TVkInstan_>.Create( const Instan_:TVkInstan_; const Window_:HWND );
begin
Create( Instan_ );
Window := Window_;
end;
destructor TVkSurfac<TVkInstan_>.Destroy;
begin
Handle := 0;
inherited;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkSurfacs
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
/////////////////////////////////////////////////////////////////////// メソッド
function TVkSurfacs<TVkInstan_>.Add :TVkSurfac_;
begin
Result := TVkSurfac_.Create( Instan );
end;
function TVkSurfacs<TVkInstan_>.Add( const HWND_:HWND ) :TVkSurfac_;
begin
Result := TVkSurfac_.Create( Instan, HWND_ );
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
program ejercicio10;
const
dimF = 3;
type
str40= String[40];
fotos = record
tituloFoto: str40;
autorFoto: str40;
cantMegusta: Integer;
cantClick: Integer;
cantComentario: Integer;
end;
vfotos = array[1..dimF] of fotos;
procedure cargarVectorFotos(var v:vfotos; f:fotos);
var
i: Integer;
begin
for i := 1 to dimF do
begin
with f do
begin
write('Ingrese el Titulo de la foto: ');
readln(v[i].tituloFoto);
write('Ingrese Autor de la foto: ');
readln(v[i].autorFoto);
write('Ingrese la cantidad de me gusta de la foto: ');
readln(v[i].cantMegusta);
write('Ingres la cantidad de Click en las fotos: ');
readln(v[i].cantClick);
write('Ingres la cantidad de comentarios: ');
readln(v[i].cantComentario);
writeln('######################################');
end;
end;
end;
procedure informar(v:vfotos; f:fotos);
var
i,max,sumaArt: integer;
fotoMasVista: str40;
begin
max:=-9999;
sumaArt:=0;
for i := 1 to dimF do
begin
if (v[i].cantClick >=max) then {INCISO1}
begin
max:= v[i].cantClick;
fotoMasVista:= f.tituloFoto;
end;
if (v[i].autorFoto = 'Art Vandelay') then {INCISO2}
begin
sumaArt:= sumaArt + v[i].cantMegusta;
end;
writeln('La cantidad de comentarios para la foto: ', v[i].tituloFoto, ' son: ', v[i].cantComentario);
end;
writeln('La cantidad total de Me gusta a las fotos cuyo autos es Art Vandelay es: ',sumaArt);
writeln('La fotos mas vista es: ', fotoMasVista);
end;
procedure imprimirVectorfotos(v:vfotos);
var
i:integer;
begin
for i := 1 to dimF do
begin
writeln(v[i].tituloFoto);
writeln(v[i].autorFoto);
writeln(v[i].cantMegusta);
writeln(v[i].cantClick);
writeln(v[i].cantComentario);
end;
end;
var
v:vfotos;
f:fotos;
begin
cargarVectorFotos(v,f);
informar(v,f);
writeln();
imprimirVectorfotos(v);
readln();
end.
|
unit InfoXINSCOMPTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXINSCOMPRecord = record
PCompanyCode: String[4];
PDraftAccount: String[2];
PTrackingCode: String[2];
PName: String[60];
PAddress: String[30];
PCityState: String[25];
PZip: String[10];
PModCount: SmallInt;
End;
TInfoXINSCOMPClass2 = class
public
PCompanyCode: String[4];
PDraftAccount: String[2];
PTrackingCode: String[2];
PName: String[60];
PAddress: String[30];
PCityState: String[25];
PZip: String[10];
PModCount: SmallInt;
End;
// function CtoRInfoXINSCOMP(AClass:TInfoXINSCOMPClass):TInfoXINSCOMPRecord;
// procedure RtoCInfoXINSCOMP(ARecord:TInfoXINSCOMPRecord;AClass:TInfoXINSCOMPClass);
TInfoXINSCOMPBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXINSCOMPRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXINSCOMP = (InfoXINSCOMPPrimaryKey);
TInfoXINSCOMPTable = class( TDBISAMTableAU )
private
FDFCompanyCode: TStringField;
FDFDraftAccount: TStringField;
FDFTrackingCode: TStringField;
FDFName: TStringField;
FDFAddress: TStringField;
FDFCityState: TStringField;
FDFZip: TStringField;
FDFModCount: TSmallIntField;
procedure SetPCompanyCode(const Value: String);
function GetPCompanyCode:String;
procedure SetPDraftAccount(const Value: String);
function GetPDraftAccount:String;
procedure SetPTrackingCode(const Value: String);
function GetPTrackingCode:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCityState(const Value: String);
function GetPCityState:String;
procedure SetPZip(const Value: String);
function GetPZip:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetEnumIndex(Value: TEIInfoXINSCOMP);
function GetEnumIndex: TEIInfoXINSCOMP;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoXINSCOMPRecord;
procedure StoreDataBuffer(ABuffer:TInfoXINSCOMPRecord);
property DFCompanyCode: TStringField read FDFCompanyCode;
property DFDraftAccount: TStringField read FDFDraftAccount;
property DFTrackingCode: TStringField read FDFTrackingCode;
property DFName: TStringField read FDFName;
property DFAddress: TStringField read FDFAddress;
property DFCityState: TStringField read FDFCityState;
property DFZip: TStringField read FDFZip;
property DFModCount: TSmallIntField read FDFModCount;
property PCompanyCode: String read GetPCompanyCode write SetPCompanyCode;
property PDraftAccount: String read GetPDraftAccount write SetPDraftAccount;
property PTrackingCode: String read GetPTrackingCode write SetPTrackingCode;
property PName: String read GetPName write SetPName;
property PAddress: String read GetPAddress write SetPAddress;
property PCityState: String read GetPCityState write SetPCityState;
property PZip: String read GetPZip write SetPZip;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoXINSCOMP read GetEnumIndex write SetEnumIndex;
end; { TInfoXINSCOMPTable }
TInfoXINSCOMPQuery = class( TDBISAMQueryAU )
private
FDFCompanyCode: TStringField;
FDFDraftAccount: TStringField;
FDFTrackingCode: TStringField;
FDFName: TStringField;
FDFAddress: TStringField;
FDFCityState: TStringField;
FDFZip: TStringField;
FDFModCount: TSmallIntField;
procedure SetPCompanyCode(const Value: String);
function GetPCompanyCode:String;
procedure SetPDraftAccount(const Value: String);
function GetPDraftAccount:String;
procedure SetPTrackingCode(const Value: String);
function GetPTrackingCode:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCityState(const Value: String);
function GetPCityState:String;
procedure SetPZip(const Value: String);
function GetPZip:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXINSCOMPRecord;
procedure StoreDataBuffer(ABuffer:TInfoXINSCOMPRecord);
property DFCompanyCode: TStringField read FDFCompanyCode;
property DFDraftAccount: TStringField read FDFDraftAccount;
property DFTrackingCode: TStringField read FDFTrackingCode;
property DFName: TStringField read FDFName;
property DFAddress: TStringField read FDFAddress;
property DFCityState: TStringField read FDFCityState;
property DFZip: TStringField read FDFZip;
property DFModCount: TSmallIntField read FDFModCount;
property PCompanyCode: String read GetPCompanyCode write SetPCompanyCode;
property PDraftAccount: String read GetPDraftAccount write SetPDraftAccount;
property PTrackingCode: String read GetPTrackingCode write SetPTrackingCode;
property PName: String read GetPName write SetPName;
property PAddress: String read GetPAddress write SetPAddress;
property PCityState: String read GetPCityState write SetPCityState;
property PZip: String read GetPZip write SetPZip;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoXINSCOMPTable }
procedure Register;
implementation
procedure TInfoXINSCOMPTable.CreateFields;
begin
FDFCompanyCode := CreateField( 'CompanyCode' ) as TStringField;
FDFDraftAccount := CreateField( 'DraftAccount' ) as TStringField;
FDFTrackingCode := CreateField( 'TrackingCode' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCityState := CreateField( 'CityState' ) as TStringField;
FDFZip := CreateField( 'Zip' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXINSCOMPTable.CreateFields }
procedure TInfoXINSCOMPTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXINSCOMPTable.SetActive }
procedure TInfoXINSCOMPTable.SetPCompanyCode(const Value: String);
begin
DFCompanyCode.Value := Value;
end;
function TInfoXINSCOMPTable.GetPCompanyCode:String;
begin
result := DFCompanyCode.Value;
end;
procedure TInfoXINSCOMPTable.SetPDraftAccount(const Value: String);
begin
DFDraftAccount.Value := Value;
end;
function TInfoXINSCOMPTable.GetPDraftAccount:String;
begin
result := DFDraftAccount.Value;
end;
procedure TInfoXINSCOMPTable.SetPTrackingCode(const Value: String);
begin
DFTrackingCode.Value := Value;
end;
function TInfoXINSCOMPTable.GetPTrackingCode:String;
begin
result := DFTrackingCode.Value;
end;
procedure TInfoXINSCOMPTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXINSCOMPTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXINSCOMPTable.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoXINSCOMPTable.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoXINSCOMPTable.SetPCityState(const Value: String);
begin
DFCityState.Value := Value;
end;
function TInfoXINSCOMPTable.GetPCityState:String;
begin
result := DFCityState.Value;
end;
procedure TInfoXINSCOMPTable.SetPZip(const Value: String);
begin
DFZip.Value := Value;
end;
function TInfoXINSCOMPTable.GetPZip:String;
begin
result := DFZip.Value;
end;
procedure TInfoXINSCOMPTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXINSCOMPTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoXINSCOMPTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('CompanyCode, String, 4, N');
Add('DraftAccount, String, 2, N');
Add('TrackingCode, String, 2, N');
Add('Name, String, 60, N');
Add('Address, String, 30, N');
Add('CityState, String, 25, N');
Add('Zip, String, 10, N');
Add('ModCount, SmallInt, 0, N');
end;
end;
procedure TInfoXINSCOMPTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, CompanyCode, Y, Y, N, N');
end;
end;
procedure TInfoXINSCOMPTable.SetEnumIndex(Value: TEIInfoXINSCOMP);
begin
case Value of
InfoXINSCOMPPrimaryKey : IndexName := '';
end;
end;
function TInfoXINSCOMPTable.GetDataBuffer:TInfoXINSCOMPRecord;
var buf: TInfoXINSCOMPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCompanyCode := DFCompanyCode.Value;
buf.PDraftAccount := DFDraftAccount.Value;
buf.PTrackingCode := DFTrackingCode.Value;
buf.PName := DFName.Value;
buf.PAddress := DFAddress.Value;
buf.PCityState := DFCityState.Value;
buf.PZip := DFZip.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXINSCOMPTable.StoreDataBuffer(ABuffer:TInfoXINSCOMPRecord);
begin
DFCompanyCode.Value := ABuffer.PCompanyCode;
DFDraftAccount.Value := ABuffer.PDraftAccount;
DFTrackingCode.Value := ABuffer.PTrackingCode;
DFName.Value := ABuffer.PName;
DFAddress.Value := ABuffer.PAddress;
DFCityState.Value := ABuffer.PCityState;
DFZip.Value := ABuffer.PZip;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoXINSCOMPTable.GetEnumIndex: TEIInfoXINSCOMP;
var iname : string;
begin
result := InfoXINSCOMPPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXINSCOMPPrimaryKey;
end;
procedure TInfoXINSCOMPQuery.CreateFields;
begin
FDFCompanyCode := CreateField( 'CompanyCode' ) as TStringField;
FDFDraftAccount := CreateField( 'DraftAccount' ) as TStringField;
FDFTrackingCode := CreateField( 'TrackingCode' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCityState := CreateField( 'CityState' ) as TStringField;
FDFZip := CreateField( 'Zip' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXINSCOMPQuery.CreateFields }
procedure TInfoXINSCOMPQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXINSCOMPQuery.SetActive }
procedure TInfoXINSCOMPQuery.SetPCompanyCode(const Value: String);
begin
DFCompanyCode.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPCompanyCode:String;
begin
result := DFCompanyCode.Value;
end;
procedure TInfoXINSCOMPQuery.SetPDraftAccount(const Value: String);
begin
DFDraftAccount.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPDraftAccount:String;
begin
result := DFDraftAccount.Value;
end;
procedure TInfoXINSCOMPQuery.SetPTrackingCode(const Value: String);
begin
DFTrackingCode.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPTrackingCode:String;
begin
result := DFTrackingCode.Value;
end;
procedure TInfoXINSCOMPQuery.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXINSCOMPQuery.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoXINSCOMPQuery.SetPCityState(const Value: String);
begin
DFCityState.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPCityState:String;
begin
result := DFCityState.Value;
end;
procedure TInfoXINSCOMPQuery.SetPZip(const Value: String);
begin
DFZip.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPZip:String;
begin
result := DFZip.Value;
end;
procedure TInfoXINSCOMPQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXINSCOMPQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
function TInfoXINSCOMPQuery.GetDataBuffer:TInfoXINSCOMPRecord;
var buf: TInfoXINSCOMPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCompanyCode := DFCompanyCode.Value;
buf.PDraftAccount := DFDraftAccount.Value;
buf.PTrackingCode := DFTrackingCode.Value;
buf.PName := DFName.Value;
buf.PAddress := DFAddress.Value;
buf.PCityState := DFCityState.Value;
buf.PZip := DFZip.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXINSCOMPQuery.StoreDataBuffer(ABuffer:TInfoXINSCOMPRecord);
begin
DFCompanyCode.Value := ABuffer.PCompanyCode;
DFDraftAccount.Value := ABuffer.PDraftAccount;
DFTrackingCode.Value := ABuffer.PTrackingCode;
DFName.Value := ABuffer.PName;
DFAddress.Value := ABuffer.PAddress;
DFCityState.Value := ABuffer.PCityState;
DFZip.Value := ABuffer.PZip;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXINSCOMPTable, TInfoXINSCOMPQuery, TInfoXINSCOMPBuffer ] );
end; { Register }
function TInfoXINSCOMPBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..8] of string = ('COMPANYCODE','DRAFTACCOUNT','TRACKINGCODE','NAME','ADDRESS','CITYSTATE'
,'ZIP','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 8) and (flist[x] <> s) do inc(x);
if x <= 8 then result := x else result := 0;
end;
function TInfoXINSCOMPBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftSmallInt;
end;
end;
function TInfoXINSCOMPBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCompanyCode;
2 : result := @Data.PDraftAccount;
3 : result := @Data.PTrackingCode;
4 : result := @Data.PName;
5 : result := @Data.PAddress;
6 : result := @Data.PCityState;
7 : result := @Data.PZip;
8 : result := @Data.PModCount;
end;
end;
end.
|
unit bsConsultationManager;
{------------------------------------------------------------------------------}
{ Автор: М. Морозов. }
{ Начат: 10.05.2006 г. }
{ Назначение: Менеджер консультаций. }
{------------------------------------------------------------------------------}
// $Id: bsConsultationManager.pas,v 1.5 2011/05/19 12:16:55 lulin Exp $
// $Log: bsConsultationManager.pas,v $
// Revision 1.5 2011/05/19 12:16:55 lulin
// {RequestLink:266409354}.
//
// Revision 1.4 2010/04/20 14:34:01 oman
// - new: {RequestLink:185205022}
//
// Revision 1.3 2009/12/11 14:22:36 lulin
// {RequestLink:172984520}.
//
// Revision 1.2 2009/12/11 14:14:52 lulin
// {RequestLink:172984520}.
//
// Revision 1.1 2009/09/14 11:28:47 lulin
// - выводим пути и для незавершённых модулей.
//
// Revision 1.12 2009/08/17 11:10:54 lulin
// {RequestLink:129240934}. №47.
//
// Revision 1.11 2009/08/14 14:57:46 lulin
// {RequestLink:129240934}. №42.
//
// Revision 1.10 2009/01/21 19:17:42 lulin
// - <K>: 135602528.
//
// Revision 1.9 2008/12/25 12:19:30 lulin
// - <K>: 121153186.
//
// Revision 1.8 2008/12/24 18:23:35 lulin
// - <K>: 121153186.
//
// Revision 1.7 2008/08/21 06:31:30 oman
// - fix: Перепроверяем наличие связи по нотификации (К-109511093)
//
// Revision 1.6 2008/02/07 19:14:21 lulin
// - избавляемся от излишне универсальных методов базовых списков.
//
// Revision 1.5 2006/10/03 13:29:32 mmorozov
// - new: сообщаем пользовалю об отключенном доступе к консультациям (CQ: OIT500022637);
//
// Revision 1.4 2006/09/29 07:19:22 mmorozov
// - change: переменная менеджера консультаций переместилась в модуль bsConsultationManager;
//
// Revision 1.3 2006/08/01 09:29:27 mmorozov
// - new: обработка нотификации о отправке консультаций (CQ: OIT500021819);
//
// Revision 1.2 2006/07/28 14:24:08 mmorozov
// - new: обработка открытия запросов из папки "Исходящие запросы";
// - new: обработка нотификации при отправке консультаций (не прошла валидацию, нет связи с сервером);
//
// Revision 1.1 2006/05/12 07:43:40 mmorozov
// - new: менеджер консультаций;
//
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Interfaces,
l3Base,
l3LongintList,
l3NotifyPtrList,
eeInterfaces,
vcmBase,
bsInterfaces
;
{$IfEnd}
{$If not defined(Admin) AND not defined(Monitorings)}
type
_l3Notifier_Parent_ = TvcmBase;
{$Include l3Notifier.imp.pas}
TbsConsultationManager = class(_l3Notifier_, IbsConsultationManager)
{* Менеджер консультаций. }
private
// internal fields
f_Unread: Integer;
private
// internal methods
procedure UpdateUnread;
{-}
private
// IbsConsultationManager
function pm_GetHasUnread: Boolean;
{* - наличие не прочитанных консультаций. }
// public methods
procedure UnreadChanged;
{* - изменилось количество не прочтенных. }
procedure NoConnection;
{* - нет доступа к серверу консультаций. }
procedure NoSubscription;
{* - у пользователя нет доступа к сервису консультаций. }
procedure InternetConnected;
{-}
procedure InternetDisConnected;
{-}
public
// public methods
constructor Create{(anOwner: TObject = nil)};
//override;
{-}
class function Make: IbsConsultationManager;
{-}
function As_Il3ChangeNotifier: Il3ChangeNotifier;
end;
{$IfEnd}
{$If not defined(Admin) AND not defined(Monitorings)}
var
g_ConsultationManager: IbsConsultationManager = nil;
{* - получается по первому требованию в модуле nsManagers. }
{$IfEnd}
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
SysUtils,
DataAdapter,
bsTypes,
bsUtils
;
{$IfEnd}
{$If not defined(Admin) AND not defined(Monitorings)}
{$Include l3Notifier.imp.pas}
{ TbsConsultationManager }
constructor TbsConsultationManager.Create{(anOwner: TObject)};
// override;
{-}
begin
inherited;
f_Unread := -1;
end;
class function TbsConsultationManager.Make: IbsConsultationManager;
{-}
var
l_Class: TbsConsultationManager;
begin
l_Class := Create;
try
Result := l_Class;
finally
FreeAndNil(l_Class);
end;
end;
function TbsConsultationManager.As_Il3ChangeNotifier: Il3ChangeNotifier;
begin
Result := Self;
end;
function TbsConsultationManager.pm_GetHasUnread: Boolean;
{* - наличие не прочитанных консультаций. }
begin
if f_Unread = -1 then
UpdateUnread;
Result := f_Unread > 0;
end;
procedure TbsConsultationManager.NoSubscription;
{* - у пользователя нет доступа к сервису консультаций. }
begin
CallNotify(Ord(nConsultation), Ord(coNoSubscription));
end;
procedure TbsConsultationManager.NoConnection;
{* - нет доступа к серверу консультаций. }
begin
CallNotify(Ord(nConsultation), Ord(coNoConnection));
end;
procedure TbsConsultationManager.UnreadChanged;
begin
UpdateUnread;
CallNotify(Ord(nConsultation), Ord(coUnreadChanged));
end;
procedure TbsConsultationManager.UpdateUnread;
{-}
begin
f_Unread := DefDataAdapter.ConsultationManager.UpdateNotReadedConsultations;
end;
procedure TbsConsultationManager.InternetConnected;
begin
CallNotify(Ord(nConsultation), Ord(coInternetConnected));
end;
procedure TbsConsultationManager.InternetDisConnected;
begin
CallNotify(Ord(nConsultation), Ord(coInternetDisconnected));
end;
{$IfEnd}
{$If not defined(Admin) AND not defined(Monitorings)}
initialization
finalization
g_ConsultationManager := nil;
{$IfEnd}
end.
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
/// \mainpage Chakra Hosting Debugging API Reference
///
/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can
/// also be hosted independently by other applications. This reference describes the APIs available
/// to applications to debug JavaScript.
/// \file
/// \brief The Chakra hosting debugging API.
///
/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll.
{$IFNDEF _CHAKRADEBUG_H_}
{$DEFINE _CHAKRADEBUG_H_}
type
/// <summary>
/// Debug events reported from ChakraCore engine.
/// </summary>
JsDiagDebugEvent =
(
/// <summary>
/// Indicates a new script being compiled, this includes script, eval, new function.
/// </summary>
JsDiagDebugEventSourceCompile = 0,
/// <summary>
/// Indicates compile error for a script.
/// </summary>
JsDiagDebugEventCompileError = 1,
/// <summary>
/// Indicates a break due to a breakpoint.
/// </summary>
JsDiagDebugEventBreakpoint = 2,
/// <summary>
/// Indicates a break after completion of step action.
/// </summary>
JsDiagDebugEventStepComplete = 3,
/// <summary>
/// Indicates a break due to debugger statement.
/// </summary>
JsDiagDebugEventDebuggerStatement = 4,
/// <summary>
/// Indicates a break due to async break.
/// </summary>
JsDiagDebugEventAsyncBreak = 5,
/// <summary>
/// Indicates a break due to a runtime script exception.
/// </summary>
JsDiagDebugEventRuntimeException = 6
);
/// <summary>
/// Break on Exception attributes.
/// </summary>
JsDiagBreakOnExceptionAttributes =
(
/// <summary>
/// Don't break on any exception.
/// </summary>
JsDiagBreakOnExceptionAttributeNone = $00,
/// <summary>
/// Break on uncaught exception.
/// </summary>
JsDiagBreakOnExceptionAttributeUncaught = $01,
/// <summary>
/// Break on first chance exception.
/// </summary>
JsDiagBreakOnExceptionAttributeFirstChance = $02
);
/// <summary>
/// Stepping types.
/// </summary>
JsDiagStepType =
(
/// <summary>
/// Perform a step operation to next statement.
/// </summary>
JsDiagStepTypeStepIn = 0,
/// <summary>
/// Perform a step out from the current function.
/// </summary>
JsDiagStepTypeStepOut = 1,
/// <summary>
/// Perform a single step over after a debug break if the next statement is a function call, else behaves as a stepin.
/// </summary>
JsDiagStepTypeStepOver = 2,
/// <summary>
/// Perform a single step back to the previous statement (only applicable in TTD mode).
/// </summary>
JsDiagStepTypeStepBack = 3,
/// <summary>
/// Perform a reverse continue operation (only applicable in TTD mode).
/// </summary>
JsDiagStepTypeReverseContinue = 4,
/// <summary>
/// Perform a forward continue operation. Clears any existing step value.
/// </summary>
JsDiagStepTypeContinue = 5
);
type
/// <summary>
/// User implemented callback routine for debug events.
/// </summary>
/// <remarks>
/// Use <c>JsDiagStartDebugging</c> to register the callback.
/// </remarks>
/// <param name="debugEvent">The type of JsDiagDebugEvent event.</param>
/// <param name="eventData">Additional data related to the debug event.</param>
/// <param name="callbackState">The state passed to <c>JsDiagStartDebugging</c>.</param>
JsDiagDebugEventCallback = procedure(debugEvent: JsDiagDebugEvent; eventData: JsValueRef; callbackState: Pointer); stdcall;
/// <summary>
/// Starts debugging in the given runtime.
/// </summary>
/// <param name="runtimeHandle">Runtime to put into debug mode.</param>
/// <param name="debugEventCallback">Registers a callback to be called on every JsDiagDebugEvent.</param>
/// <param name="callbackState">User provided state that will be passed back to the callback.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The runtime should be active on the current thread and should not be in debug state.
/// </remarks>
function JsDiagStartDebugging(runtimeHandle: JsRuntimeHandle; debugEventCallback: JsDiagDebugEventCallback; callbackState: Pointer): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagStartDebugging' {$ENDIF};
/// <summary>
/// Stops debugging in the given runtime.
/// </summary>
/// <param name="runtimeHandle">Runtime to stop debugging.</param>
/// <param name="callbackState">User provided state that was passed in JsDiagStartDebugging.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The runtime should be active on the current thread and in debug state.
/// </remarks>
function JsDiagStopDebugging(runtimeHandle: JsRuntimeHandle; var callbackState: Pointer): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagStopDebugging' {$ENDIF};
/// <summary>
/// Request the runtime to break on next JavaScript statement.
/// </summary>
/// <param name="runtimeHandle">Runtime to request break.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The runtime should be in debug state. This API can be called from another runtime.
/// </remarks>
function JsDiagRequestAsyncBreak(runtimeHandle: JsRuntimeHandle): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagRequestAsyncBreak' {$ENDIF};
/// <summary>
/// List all breakpoints in the current runtime.
/// </summary>
/// <param name="breakpoints">Array of breakpoints.</param>
/// <remarks>
/// <para>
/// [{
/// "breakpointId" : 1,
/// "scriptId" : 1,
/// "line" : 0,
/// "column" : 62
/// }]
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagGetBreakpoints(var breakpoints: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetBreakpoints' {$ENDIF};
/// <summary>
/// Sets breakpoint in the specified script at give location.
/// </summary>
/// <param name="scriptId">Id of script from JsDiagGetScripts or JsDiagGetSource to put breakpoint.</param>
/// <param name="lineNumber">0 based line number to put breakpoint.</param>
/// <param name="columnNumber">0 based column number to put breakpoint.</param>
/// <param name="breakpoint">Breakpoint object with id, line and column if success.</param>
/// <remarks>
/// <para>
/// {
/// "breakpointId" : 1,
/// "line" : 2,
/// "column" : 4
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagSetBreakpoint(scriptId: cardinal; lineNumber: cardinal; columnNumber: cardinal; var breakpoint: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagSetBreakpoint' {$ENDIF};
/// <summary>
/// Remove a breakpoint.
/// </summary>
/// <param name="breakpointId">Breakpoint id returned from JsDiagSetBreakpoint.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagRemoveBreakpoint(breakpointId: cardinal): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagRemoveBreakpoint' {$ENDIF};
/// <summary>
/// Sets break on exception handling.
/// </summary>
/// <param name="runtimeHandle">Runtime to set break on exception attributes.</param>
/// <param name="exceptionAttributes">Mask of JsDiagBreakOnExceptionAttributes to set.</param>
/// <remarks>
/// <para>
/// If this API is not called the default value is set to JsDiagBreakOnExceptionAttributeUncaught in the runtime.
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The runtime should be in debug state. This API can be called from another runtime.
/// </remarks>
function JsDiagSetBreakOnException(runtimeHandle: JsRuntimeHandle; exceptionAttributes: JsDiagBreakOnExceptionAttributes): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagSetBreakOnException' {$ENDIF};
/// <summary>
/// Gets break on exception setting.
/// </summary>
/// <param name="runtimeHandle">Runtime from which to get break on exception attributes, should be in debug mode.</param>
/// <param name="exceptionAttributes">Mask of JsDiagBreakOnExceptionAttributes.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The runtime should be in debug state. This API can be called from another runtime.
/// </remarks>
function JsDiagGetBreakOnException(runtimeHandle: JsRuntimeHandle; var exceptionAttributes: JsDiagBreakOnExceptionAttributes): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetBreakOnException' {$ENDIF};
/// <summary>
/// Sets the step type in the runtime after a debug break.
/// </summary>
/// <remarks>
/// Requires to be at a debug break.
/// </remarks>
/// <param name="resumeType">Type of JsDiagStepType.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagSetStepType(stepType: JsDiagStepType): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagSetStepType' {$ENDIF};
/// <summary>
/// Gets list of scripts.
/// </summary>
/// <param name="scriptsArray">Array of script objects.</param>
/// <remarks>
/// <para>
/// [{
/// "scriptId" : 2,
/// "fileName" : "c:\\Test\\Test.js",
/// "lineCount" : 4,
/// "sourceLength" : 111
/// }, {
/// "scriptId" : 3,
/// "parentScriptId" : 2,
/// "scriptType" : "eval code",
/// "lineCount" : 1,
/// "sourceLength" : 12
/// }]
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagGetScripts(var scriptsArray: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetScripts' {$ENDIF};
/// <summary>
/// Gets source for a specific script identified by scriptId from JsDiagGetScripts.
/// </summary>
/// <param name="scriptId">Id of the script.</param>
/// <param name="source">Source object.</param>
/// <remarks>
/// <para>
/// {
/// "scriptId" : 1,
/// "fileName" : "c:\\Test\\Test.js",
/// "lineCount" : 12,
/// "sourceLength" : 15154,
/// "source" : "var x = 1;"
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagGetSource(scriptId: cardinal; var source: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetSource' {$ENDIF};
/// <summary>
/// Gets the source information for a function object.
/// </summary>
/// <param name="function">JavaScript function.</param>
/// <param name="functionPosition">Function position - scriptId, start line, start column, line number of first statement, column number of first statement.</param>
/// <remarks>
/// <para>
/// {
/// "scriptId" : 1,
/// "fileName" : "c:\\Test\\Test.js",
/// "line" : 1,
/// "column" : 2,
/// "firstStatementLine" : 6,
/// "firstStatementColumn" : 0
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// This API can be called when runtime is at a break or running.
/// </remarks>
function JsDiagGetFunctionPosition(func: JsValueRef; var functionPosition: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetFunctionPosition' {$ENDIF};
/// <summary>
/// Gets the stack trace information.
/// </summary>
/// <param name="stackTrace">Stack trace information.</param>
/// <remarks>
/// <para>
/// [{
/// "index" : 0,
/// "scriptId" : 2,
/// "line" : 3,
/// "column" : 0,
/// "sourceLength" : 9,
/// "sourceText" : "var x = 1",
/// "functionHandle" : 1
/// }]
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagGetStackTrace(var stackTrace: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetStackTrace' {$ENDIF};
/// <summary>
/// Gets the list of properties corresponding to the frame.
/// </summary>
/// <param name="stackFrameIndex">Index of stack frame from JsDiagGetStackTrace.</param>
/// <param name="properties">Object of properties array (properties, scopes and globals).</param>
/// <remarks>
/// <para>
/// propertyAttributes is a bit mask of
/// NONE = 0x1,
/// HAVE_CHILDRENS = 0x2,
/// READ_ONLY_VALUE = 0x4,
/// IN_TDZ = 0x8,
/// </para>
/// <para>
/// {
/// "thisObject": {
/// "name": "this",
/// "type" : "object",
/// "className" : "Object",
/// "display" : "{...}",
/// "propertyAttributes" : 1,
/// "handle" : 306
/// },
/// "exception" : {
/// "name" : "{exception}",
/// "type" : "object",
/// "display" : "'a' is undefined",
/// "className" : "Error",
/// "propertyAttributes" : 1,
/// "handle" : 307
/// }
/// "arguments" : {
/// "name" : "arguments",
/// "type" : "object",
/// "display" : "{...}",
/// "className" : "Object",
/// "propertyAttributes" : 1,
/// "handle" : 190
/// },
/// "returnValue" : {
/// "name" : "[Return value]",
/// "type" : "undefined",
/// "propertyAttributes" : 0,
/// "handle" : 192
/// },
/// "functionCallsReturn" : [{
/// "name" : "[foo1 returned]",
/// "type" : "number",
/// "value" : 1,
/// "propertyAttributes" : 2,
/// "handle" : 191
/// }
/// ],
/// "locals" : [],
/// "scopes" : [{
/// "index" : 0,
/// "handle" : 193
/// }
/// ],
/// "globals" : {
/// "handle" : 194
/// }
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagGetStackProperties(stackFrameIndex: cardinal; var properties: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetStackProperties' {$ENDIF};
/// <summary>
/// Gets the list of children of a handle.
/// </summary>
/// <param name="objectHandle">Handle of object.</param>
/// <param name="fromCount">0-based from count of properties, usually 0.</param>
/// <param name="totalCount">Number of properties to return.</param>
/// <param name="propertiesObject">Array of properties.</param>
/// <remarks>Handle should be from objects returned from call to JsDiagGetStackProperties.</remarks>
/// <remarks>For scenarios where object have large number of properties totalCount can be used to control how many properties are given.</remarks>
/// <remarks>
/// <para>
/// {
/// "totalPropertiesOfObject": 10,
/// "properties" : [{
/// "name" : "__proto__",
/// "type" : "object",
/// "display" : "{...}",
/// "className" : "Object",
/// "propertyAttributes" : 1,
/// "handle" : 156
/// }
/// ],
/// "debuggerOnlyProperties" : [{
/// "name" : "[Map]",
/// "type" : "string",
/// "value" : "size = 0",
/// "propertyAttributes" : 2,
/// "handle" : 157
/// }
/// ]
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagGetProperties(objectHandle: cardinal; fromCount: cardinal; totalCount: cardinal; var propertiesObject: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetProperties' {$ENDIF};
/// <summary>
/// Gets the object corresponding to handle.
/// </summary>
/// <param name="objectHandle">Handle of object.</param>
/// <param name="handleObject">Object corresponding to the handle.</param>
/// <remarks>
/// <para>
/// {
/// "scriptId" : 24,
/// "line" : 1,
/// "column" : 63,
/// "name" : "foo",
/// "type" : "function",
/// "handle" : 2
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagGetObjectFromHandle(objectHandle: cardinal; var handleObject: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagGetObjectFromHandle' {$ENDIF};
/// <summary>
/// Evaluates an expression on given frame.
/// </summary>
/// <param name="expression">
/// Javascript String or ArrayBuffer (incl. ExternalArrayBuffer).
/// </param>
/// <param name="stackFrameIndex">Index of stack frame on which to evaluate the expression.</param>
/// <param name="parseAttributes">
/// Defines how `expression` (JsValueRef) should be parsed.
/// - `JsParseScriptAttributeNone` when `expression` is a Utf8 encoded ArrayBuffer and/or a Javascript String (encoding independent)
/// - `JsParseScriptAttributeArrayBufferIsUtf16Encoded` when `expression` is Utf16 Encoded ArrayBuffer
/// - `JsParseScriptAttributeLibraryCode` has no use for this function and has similar effect with `JsParseScriptAttributeNone`
/// </param>
/// <param name="forceSetValueProp">Forces the result to contain the raw value of the expression result.</param>
/// <param name="evalResult">Result of evaluation.</param>
/// <remarks>
/// <para>
/// evalResult when evaluating 'this' and return is JsNoError
/// {
/// "name" : "this",
/// "type" : "object",
/// "className" : "Object",
/// "display" : "{...}",
/// "propertyAttributes" : 1,
/// "handle" : 18
/// }
///
/// evalResult when evaluating a script which throws JavaScript error and return is JsErrorScriptException
/// {
/// "name" : "a.b.c",
/// "type" : "object",
/// "className" : "Error",
/// "display" : "'a' is undefined",
/// "propertyAttributes" : 1,
/// "handle" : 18
/// }
/// </para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, evalResult will contain the result
/// The code <c>JsErrorScriptException</c> if evaluate generated a JavaScript exception, evalResult will contain the error details
/// Other error code for invalid parameters or API was not called at break
/// </returns>
/// <remarks>
/// The current runtime should be in debug state. This API can only be called when runtime is at a break.
/// </remarks>
function JsDiagEvaluate(expression: JsValueRef; stackFrameIndex: cardinal; parseAttributes: JsParseScriptAttributes; forceSetValueProp: boolean; var evalResult: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsDiagEvaluate' {$ENDIF};
type
/// //////////////////
/// <summary>
/// TimeTravel move options as bit flag enum.
/// </summary>
JsTTDMoveMode =
(
/// <summary>
/// Indicates no special actions needed for move.
/// </summary>
JsTTDMoveNone = $0,
/// <summary>
/// Indicates that we want to move to the first event.
/// </summary>
JsTTDMoveFirstEvent = $1,
/// <summary>
/// Indicates that we want to move to the last event.
/// </summary>
JsTTDMoveLastEvent = $2,
/// <summary>
/// Indicates that we want to move to the kth event -- top 32 bits are event count.
/// </summary>
JsTTDMoveKthEvent = $4,
/// <summary>
/// Indicates if we are doing the scan for a continue operation
/// </summary>
JsTTDMoveScanIntervalForContinue = $10,
/// <summary>
/// Indicates if we are doing the scan for a continue operation and are in the time-segment where the active breakpoint was
/// </summary>
JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment = $20,
/// <summary>
/// Indicates if we want to set break on entry or just run and let something else trigger breakpoints.
/// </summary>
JsTTDMoveBreakOnEntry = $100
);
type
/// <summary>
/// A handle for URI's that TTD information is written to/read from.
/// </summary>
JsTTDStreamHandle = Pointer;
/// <summary>
/// TTD API -- may change in future versions:
/// Construct a JsTTDStreamHandle that will be used to read/write the event log portion of the TTD data based on the uri
/// provided by JsTTDInitializeUriCallback.
/// </summary>
/// <remarks>
/// <para>Exactly one of read or write will be set to true.</para>
/// </remarks>
/// <param name="uriLength">The length of the uri array that the host passed in for storing log info.</param>
/// <param name="uri">The URI that the host passed in for storing log info.</param>
/// <param name="asciiNameLength">The length of the ascii name array that the host passed in for storing log info.</param>
/// <param name="asciiResourceName">An optional ascii string giving a unique name to the resource that the JsTTDStreamHandle will be created for.</param>
/// <param name="read">If the handle should be opened for reading.</param>
/// <param name="write">If the handle should be opened for writing.</param>
/// <returns>A JsTTDStreamHandle opened in read/write mode as specified.</returns>
TTDOpenResourceStreamCallback = function(uriLength: NativeUInt; uri: PAnsiChar; asciiNameLength: NativeUInt; asciiResourceName: PAnsiChar; read: boolean; write: boolean): JsTTDStreamHandle; stdcall;
/// <summary>
/// TTD API -- may change in future versions:
/// A callback for reading data from a handle.
/// </summary>
/// <param name="handle">The JsTTDStreamHandle to read the data from.</param>
/// <param name="buff">The buffer to place the data into.</param>
/// <param name="size">The max number of bytes that should be read.</param>
/// <param name="readCount">The actual number of bytes read and placed in the buffer.</param>
/// <returns>true if the read was successful false otherwise.</returns>
JsTTDReadBytesFromStreamCallback = function(handle: JsTTDStreamHandle; buff: PByte; size: NativeUInt; var readCount: NativeUInt): boolean; stdcall;
/// <summary>
/// TTD API -- may change in future versions:
/// A callback for writing data to a handle.
/// </summary>
/// <param name="handle">The JsTTDStreamHandle to write the data to.</param>
/// <param name="buff">The buffer to copy the data from.</param>
/// <param name="size">The max number of bytes that should be written.</param>
/// <param name="readCount">The actual number of bytes written to the HANDLE.</param>
/// <returns>true if the write was successful false otherwise.</returns>
JsTTDWriteBytesToStreamCallback = function(handle: JsTTDStreamHandle; const buff: PByte; size: NativeUInt; var writtenCount: NativeUInt): boolean; stdcall;
/// <summary>
/// TTD API -- may change in future versions:
/// Flush and close the stream represented by the HANDLE as needed.
/// </summary>
/// <remarks>
/// <para>Exactly one of read or write will be set to true.</para>
/// </remarks>
/// <param name="handle">The JsTTDStreamHandle to close.</param>
/// <param name="read">If the handle was opened for reading.</param>
/// <param name="write">If the handle was opened for writing.</param>
JsTTDFlushAndCloseStreamCallback = procedure(handle: JsTTDStreamHandle; read: boolean; write: boolean); stdcall;
/// <summary>
/// TTD API -- may change in future versions:
/// Creates a new runtime in Record Mode.
/// </summary>
/// <param name="attributes">The attributes of the runtime to be created.</param>
/// <param name="snapInterval">The interval to wait between snapshots (measured in millis).</param>
/// <param name="snapHistoryLength">The amount of history to maintain before discarding -- measured in number of snapshots and controls how far back in time a trace can be reversed.</param>
/// <param name="openResourceStream">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>
/// <param name="writeBytesToStream">The <c>JsTTDWriteBytesToStreamCallback</c> function for writing bytes to a JsTTDStreamHandle.</param>
/// <param name="flushAndCloseStream">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>
/// <param name="threadService">The thread service for the runtime. Can be null.</param>
/// <param name="runtime">The runtime created.</param>
/// <remarks>
/// <para>See <c>JsCreateRuntime</c> for additional information.</para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsTTDCreateRecordRuntime(attributes: JsRuntimeAttributes; snapInterval: NativeUInt; snapHistoryLength: NativeUInt; openResourceStream: TTDOpenResourceStreamCallback; writeBytesToStream: JsTTDWriteBytesToStreamCallback; flushAndCloseStream: JsTTDFlushAndCloseStreamCallback; threadService: JsThreadServiceCallback; var runtime: JsRuntimeHandle): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDCreateRecordRuntime' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Creates a new runtime in Debug Mode.
/// </summary>
/// <param name="attributes">The attributes of the runtime to be created.</param>
/// <param name="infoUri">The uri where the recorded Time-Travel data should be loaded from.</param>
/// <param name="enableDebugging">A flag to enable additional debugging operation support during replay.</param>
/// <param name="openResourceStream">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>
/// <param name="readBytesFromStream">The <c>JsTTDReadBytesFromStreamCallback</c> function for reading bytes from a JsTTDStreamHandle.</param>
/// <param name="flushAndCloseStream">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>
/// <param name="threadService">The thread service for the runtime. Can be null.</param>
/// <param name="runtime">The runtime created.</param>
/// <remarks>
/// <para>See <c>JsCreateRuntime</c> for additional information.</para>
/// </remarks>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsTTDCreateReplayRuntime(attributes: JsRuntimeAttributes; infoUri: PAnsiChar; infoUriCount: NativeUInt; enableDebugging: boolean; openResourceStream: TTDOpenResourceStreamCallback; readBytesFromStream: JsTTDReadBytesFromStreamCallback; flushAndCloseStream: JsTTDFlushAndCloseStreamCallback; threadService: JsThreadServiceCallback; var runtime: JsRuntimeHandle): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDCreateReplayRuntime' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Creates a script context that takes the TTD mode from the log or explicitly is not in TTD mode (regular takes mode from currently active script).
/// </summary>
/// <param name="runtime">The runtime the script context is being created in.</param>
/// <param name="useRuntimeTTDMode">Set to true to use runtime TTD mode false to explicitly be non-TTD context.</param>
/// <param name="newContext">The created script context.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsTTDCreateContext(runtimeHandle: JsRuntimeHandle; useRuntimeTTDMode: boolean; var newContext: JsContextRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDCreateContext' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the time-travel system that a context has been identified as dead by the gc (and is being de-allocated).
/// </summary>
/// <param name="context">The script context that is now dead.</param>
/// <returns>
/// The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
/// </returns>
function JsTTDNotifyContextDestroy(context: JsContextRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDNotifyContextDestroy' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Start Time-Travel record or replay at next turn of event loop.
/// </summary>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDStart(): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDStart' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Stop Time-Travel record or replay.
/// </summary>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDStop(): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDStop' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Pause Time-Travel recording before executing code on behalf of debugger or other diagnostic/telemetry.
/// </summary>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDPauseTimeTravelBeforeRuntimeOperation(): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDPauseTimeTravelBeforeRuntimeOperation' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// ReStart Time-Travel recording after executing code on behalf of debugger or other diagnostic/telemetry.
/// </summary>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDReStartTimeTravelAfterRuntimeOperation(): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDReStartTimeTravelAfterRuntimeOperation' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the Js runtime we are at a safe yield point in the event loop (i.e. no locals on the stack and we can process as desired).
/// </summary>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDNotifyYield(): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDNotifyYield' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the TTD runtime that we are doing a weak add on a reference (we may use this in external API calls and the release will happen in a GC callback).
/// </summary>
/// <param name="value">The value we are adding the ref to.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDNotifyLongLivedReferenceAdd(value: JsValueRef): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDNotifyLongLivedReferenceAdd' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the Js runtime the host is aborting the process and what the status code is.
/// </summary>
/// <param name="statusCode">The exit status code.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDHostExit(statusCode: integer): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDHostExit' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the event log that the contents of one buffer have been copied to a second buffer.
/// </summary>
/// <param name="dst">The buffer that was written into.</param>
/// <param name="dstIndex">The first index modified.</param>
/// <param name="src">The buffer that was copied from.</param>
/// <param name="srcIndex">The first index copied.</param>
/// <param name="count">The number of bytes copied.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDRawBufferCopySyncIndirect(dst: JsValueRef; dstIndex: NativeUInt; src: JsValueRef; srcIndex: NativeUInt; count: NativeUInt): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDRawBufferCopySyncIndirect' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the event log that the contents of a naked byte* buffer passed to the host have been modified synchronously.
/// </summary>
/// <param name="buffer">The buffer that was modified.</param>
/// <param name="index">The first index modified.</param>
/// <param name="count">The number of bytes written.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDRawBufferModifySyncIndirect(buffer: JsValueRef; index: NativeUInt; count: NativeUInt): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDRawBufferModifySyncIndirect' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Get info for notifying the TTD system that a raw buffer it shares with the host has been modified.
/// </summary>
/// <param name="instance">The array buffer we want to monitor for contents modification.</param>
/// <param name="initialModPos">The first position in the buffer that may be modified.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDRawBufferAsyncModificationRegister(instance: JsValueRef; initialModPos: PByte): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDRawBufferAsyncModificationRegister' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Notify the event log that the contents of a naked byte* buffer passed to the host have been modified asynchronously.
/// </summary>
/// <param name="finalModPos">One past the last modified position in the buffer.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDRawBufferAsyncModifyComplete(finalModPos: PByte): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDRawBufferAsyncModifyComplete' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// A check for unimplemented TTD actions in the host.
/// This API is a TEMPORARY API while we complete the implementation of TTD support in the Node host and will be deleted once that is complete.
/// </summary>
/// <param name="msg">The message to print if we should be catching this as a TTD operation.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDCheckAndAssertIfTTDRunning(const msg: PAnsiChar): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDCheckAndAssertIfTTDRunning' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Before calling JsTTDMoveToTopLevelEvent (which inflates a snapshot and replays) check to see if we want to reset the script context.
/// We reset the script context if the move will require inflating from a different snapshot that the last one.
/// </summary>
/// <param name="runtimeHandle">The runtime handle that the script is executing in.</param>
/// <param name="moveMode">Flags controlling the way the move it performed and how other parameters are interpreted.</param>
/// <param name="kthEvent">When <c>moveMode == JsTTDMoveKthEvent</c> indicates which event, otherwise this parameter is ignored.</param>
/// <param name="targetEventTime">The event time we want to move to or -1 if not relevant.</param>
/// <param name="targetStartSnapTime">Out parameter with the event time of the snapshot that we should inflate from.</param>
/// <param name="targetEndSnapTime">Optional Out parameter with the snapshot time following the event.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDGetSnapTimeTopLevelEventMove(runtimeHandle: JsRuntimeHandle; moveMode: JsTTDMoveMode; kthEvent: cardinal; var targetEventTime: int64; var targetStartSnapTime: int64; var targetEndSnapTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDGetSnapTimeTopLevelEventMove' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Get the snapshot interval that bounds the target event time.
/// </summary>
/// <param name="runtimeHandle">The runtime handle that the script is executing in.</param>
/// <param name="targetEventTime">The event time we want to get the interval for.</param>
/// <param name="startSnapTime">The snapshot time that comes before the desired event.</param>
/// <param name="endSnapTime">The snapshot time that comes after the desired event (-1 if the leg ends before a snapshot appears).</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDGetSnapShotBoundInterval(runtimeHandle: JsRuntimeHandle; targetEventTime: int64; var startSnapTime: int64; var endSnapTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDGetSnapShotBoundInterval' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Get the snapshot interval that precedes the one given by currentSnapStartTime (or -1 if there is no such interval).
/// </summary>
/// <param name="runtimeHandle">The runtime handle that the script is executing in.</param>
/// <param name="currentSnapStartTime">The current snapshot interval start time.</param>
/// <param name="previousSnapTime">The resulting previous snapshot interval start time or -1 if no such time.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDGetPreviousSnapshotInterval(runtimeHandle: JsRuntimeHandle; currentSnapStartTime: int64; var previousSnapTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDGetPreviousSnapshotInterval' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// During debug operations some additional information is populated during replay. This runs the code between the given
/// snapshots to populate this information which may be needed by the debugger to determine time-travel jump targets.
/// </summary>
/// <param name="runtimeHandle">The runtime handle that the script is executing in.</param>
/// <param name = "startSnapTime">The snapshot time that we will start executing from.< / param>
/// <param name = "endSnapTime">The snapshot time that we will stop at (or -1 if we want to run to the end).< / param>
/// <param name="moveMode">Additional flags for controling how the move is done.</param>
/// <param name="newTargetEventTime">The updated target event time set according to the moveMode (-1 if not found).</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDPreExecuteSnapShotInterval(runtimeHandle: JsRuntimeHandle; startSnapTime: int64; endSnapTime: int64; moveMode: JsTTDMoveMode; var newTargetEventTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDPreExecuteSnapShotInterval' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Move to the given top-level call event time (assuming JsTTDPrepContextsForTopLevelEventMove) was called previously to reset any script contexts.
/// This also computes the ready-to-run snapshot if needed.
/// </summary>
/// <param name="runtimeHandle">The runtime handle that the script is executing in.</param>
/// <param name="moveMode">Additional flags for controling how the move is done.</param>
/// <param name="snapshotTime">The event time that we will start executing from to move to the given target time.</param>
/// <param name="eventTime">The event that we want to move to.</param>
/// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>
function JsTTDMoveToTopLevelEvent(runtimeHandle: JsRuntimeHandle; moveMode: JsTTDMoveMode; snapshotTime: int64; eventTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDMoveToTopLevelEvent' {$ENDIF};
/// <summary>
/// TTD API -- may change in future versions:
/// Execute from the current point in the log to the end returning the error code.
/// </summary>
/// <param name="moveMode">Additional flags for controling how the move is done.</param>
/// <param name="rootEventTime">The event time that we should move to next or notification (-1) that replay has ended.</param>
/// <returns>
/// If the debugger requested an abort the code is JsNoError -- rootEventTime is the target event time we need to move to and re - execute from.
/// If we aborted at the end of the replay log the code is JsNoError -- rootEventTime is -1.
/// If there was an unhandled script exception the code is JsErrorCategoryScript.
/// </returns>
function JsTTDReplayExecution(var moveMode: JsTTDMoveMode; var rootEventTime: int64): JsErrorCode;
stdcall; external CHAKRA_LIB {$IFDEF MACOS} name '_JsTTDReplayExecution' {$ENDIF};
{$ENDIF} // _CHAKRADEBUG_H_
|
unit QRXLSXFilt;
////////////////////////////////////////////////////////////////////////////
// Unit : QRXLSXFilt
//
// TQRXMLSSAbstractExportFilter -> TQRXMLSSDocumentFilter
//
// The XMLSS Export document for XL spreadsheet -
//
// (c) 2010 QBS Software
//
// 22/08/2012 changed FItems to dynamic array
// 04/08/2016 fixed shapes to be as standard preview
////////////////////////////////////////////////////////////////////////////
{$include QRDefs.inc}
interface
uses windows, classes, controls, stdctrls, sysutils, graphics, buttons,
forms, extctrls, dialogs, printers, db, ComCtrls,
QRPrntr, Quickrpt, QR6Const, qrctrls, grids{$ifndef DXE}, system.UITypes{$endif};
const
CRLF = chr($0D) + chr($0A);
// ascii
ORD0 = ord('0');
ORDA = ord('A');
type
XLXSTextItem = record
row, col : integer;
X,Y : extended;
text, fontname : string;
exportAs : TExporttype;
fontbold, fontitalic, fontstrike : boolean;
fontsize : integer;
fontcolor : TColor;
controlName : string;
end;
TQRXMLSSAbstractExportFilter = class(TQRExportFilter)
private
FStream : TStream;
FLineCount,
FColCount : integer;
FPageProcessed : boolean;
dlist : TStringlist;
protected
function GetText(X, Y : extended; var Font : TFont) : string;
function GetFilterName : string; override;
function GetDescription : string; override;
function GetExtension : string; override;
procedure WriteToStream(const AText : string);
procedure WriteLnToStream(const AText : string);
procedure CreateStream(Filename : string); virtual;
procedure CloseStream; virtual;
procedure ProcessPage; virtual;
procedure StorePage; virtual;
property Stream : TStream read FStream write FStream;
property PageProcessed : boolean read FPageProcessed write FPageProcessed;
property LineCount : integer read FLineCount write FLineCount;
property ColCount : integer read FColCount write FColCount;
public
constructor Create( filename : string );override;
procedure Start(PaperWidth, PaperHeight : integer; Font : TFont); override;
procedure Finish; override;
procedure EndPage; override;
procedure NewPage; override;
//procedure TextOut(X, Y : extended; Text : string; exportAs : TExportType; xlColumn : integer);virtual;
end;
TQRXMLSSDocumentFilter = class(TQRXMLSSAbstractExportFilter)
private
FFreeStream : boolean;
// doc filter properties
FLastRecordNum : longint;
FPagenumber : longint;
//FDocType : string;
//FCreator : string;
FTitle : string;
//FAuthor,
FLastAuthor,
FCreated,
FLastSaved,
//FCompany,
//FWorkSheetname,
FXLStyleURL : string;
FConcatenating : boolean;
FXLEncoding: string;
FItems : array of XLXSTextItem;
FSortList : TStringlist;
FStylenames : TStringlist;
FFontTags : TStringlist;
FItemcount : integer;
//FOpenHeight : integer;
//FOpenWidth : integer;
FPageYOffset : extended;
FMaxYValue : extended;
rowno, colno, maxcols, fixline1, styleinsert : integer;
procedure SetCreator( value : string);
function getCreator: string;
function getAuthor: string;
procedure SetAuthor( value : string);
procedure SetCompany( value : string);
function getCompany: string;
procedure SetWorkSheetName( value : string);
function getWorkSheetName: string;
procedure SetOpenWidth( value : integer);
function getOpenWidth: integer;
function getOpenHeight: integer;
procedure SetOpenHeight( value : integer);
protected
function GetFilterName : string; override;
function GetDescription : string; override;
function GetExtension : string; override;
function GetStreaming : boolean; override;
procedure CreateStream(Filename : string); override;
procedure CloseStream; override;
procedure ProcessItems;
public
constructor Create( filename : string );override;
destructor Destroy; override;
procedure TextOutRec( ExportInfo : TExportInfoRec); override;
procedure NewDocument( doclist : TStringlist; PaperWidth, PaperHeight : double;
Papername, orient : string);
//procedure TextOut(X, Y : extended; Text : string; exportAs : TExportType; xlColumn : integer);override;
procedure LoadProlog;
procedure ProcessPage; override;
procedure Start(PaperWidth, PaperHeight : integer; Font : TFont); override;
procedure EndConcat;
procedure Finish; override;
procedure NewPage; override;
procedure EndPage; override;
procedure SetDocumentProperties( author, title, company : string );
property Stream;
property FreeStream : boolean read FFreeStream write FFreeStream;
property Title : string read FTitle write FTitle;
property LastAuthor : string read FLastAuthor write FLastAuthor;
property Created : string read FCreated write FCreated;
property LastSaved : string read FLastSaved write FLastSaved;
property XLEncoding: string read FXLEncoding write FXLEncoding;
property XLStyleURL : string read FXLStyleURL write FXLStyleURL;
property Concatenating : boolean read FConcatenating write FConcatenating;
property OpenWidth : integer read getOpenWidth write setOpenWidth;
property OpenHeight : integer read getOpenHeight write setOpenHeight;
property Creator : string read getCreator write setCreator;
property Author : string read getAuthor write setAuthor;
property Company : string read getCompany write setCompany;
property WorkSheetname : string read getWorkSheetname write setWorkSheetname;
end;
TQRXMLSSFilter = class(TComponent)
private
procedure SetCreator( value : string);
function getCreator: string;
function getAuthor: string;
procedure SetAuthor( value : string);
procedure SetCompany( value : string);
function getCompany: string;
procedure SetWorkSheetName( value : string);
function getWorkSheetName: string;
procedure SetOpenWidth( value : integer);
function getOpenWidth: integer;
function getOpenHeight: integer;
procedure SetOpenHeight( value : integer);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
property OpenWidth : integer read getOpenWidth write setOpenWidth;
property OpenHeight : integer read getOpenHeight write setOpenHeight;
property Creator : string read getCreator write setCreator;
property Author : string read getAuthor write setAuthor;
property Company : string read getCompany write setCompany;
property WorkSheetname : string read getWorkSheetname write setWorkSheetname;
end;
function EntityReplace( var ctext : string ) : string;
function ColTrans( ct : TColor ) : string;
implementation
uses grimgctrl;
var
xmlCreator, xmlAuthor, xmlCompany, xmlWorkSheetname : string;
xmlOpenWidth, xmlOpenHeight : integer;
//-------------------------------------------
function TQRXMLSSDocumentFilter.getCreator: string;
begin
result := xmlCreator;
end;
procedure TQRXMLSSDocumentFilter.SetCreator( value : string);
begin
xmlCreator := value;
end;
function TQRXMLSSDocumentFilter.getAuthor: string;
begin
result := xmlAuthor;
end;
procedure TQRXMLSSDocumentFilter.SetAuthor( value : string);
begin
xmlCreator := value;
end;
procedure TQRXMLSSDocumentFilter.SetCompany( value : string);
begin
xmlCompany := value;
end;
function TQRXMLSSDocumentFilter.getCompany: string;
begin
result := xmlCompany;
end;
procedure TQRXMLSSDocumentFilter.SetWorkSheetName( value : string);
begin
xmlWorkSheetName := value;
end;
function TQRXMLSSDocumentFilter.getWorkSheetName: string;
begin
result := xmlWorkSheetName;
end;
procedure TQRXMLSSDocumentFilter.SetOpenWidth( value : integer);
begin
xmlOpenWidth := value;
end;
function TQRXMLSSDocumentFilter.getOpenWidth: integer;
begin
result := xmlOpenWidth;
end;
procedure TQRXMLSSDocumentFilter.SetOpenHeight( value : integer);
begin
xmlOpenHeight := value;
end;
function TQRXMLSSDocumentFilter.getOpenHeight: integer;
begin
result := xmlOpenHeight;
end;
//---------------------------------------------
constructor TQRXMLSSFilter.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
QRExportFilterLibrary.AddFilter(TQRXMLSSDocumentFilter);
end;
destructor TQRXMLSSFilter.Destroy;
begin
QRExportFilterLibrary.RemoveFilter(TQRXMLSSDocumentFilter);
inherited Destroy;
end;
//-------------------------------------------
function TQRXMLSSFilter.getCreator: string;
begin
result := xmlCreator;
end;
procedure TQRXMLSSFilter.SetCreator( value : string);
begin
xmlCreator := value;
end;
function TQRXMLSSFilter.getAuthor: string;
begin
result := xmlAuthor;
end;
procedure TQRXMLSSFilter.SetAuthor( value : string);
begin
xmlCreator := value;
end;
procedure TQRXMLSSFilter.SetCompany( value : string);
begin
xmlCompany := value;
end;
function TQRXMLSSFilter.getCompany: string;
begin
result := xmlCompany;
end;
procedure TQRXMLSSFilter.SetWorkSheetName( value : string);
begin
xmlWorkSheetName := value;
end;
function TQRXMLSSFilter.getWorkSheetName: string;
begin
result := xmlWorkSheetName;
end;
procedure TQRXMLSSFilter.SetOpenWidth( value : integer);
begin
xmlOpenWidth := value;
end;
function TQRXMLSSFilter.getOpenWidth: integer;
begin
result := xmlOpenWidth;
end;
procedure TQRXMLSSFilter.SetOpenHeight( value : integer);
begin
xmlOpenHeight := value;
end;
function TQRXMLSSFilter.getOpenHeight: integer;
begin
result := xmlOpenHeight;
end;
//---------------------------------------------
{TQRXMLSSAbstractExportFilter}
constructor TQRXMLSSAbstractExportFilter.Create( filename : string);
begin
inherited Create(filename);
end;
function TQRXMLSSAbstractExportFilter.GetFilterName : string;
begin
result := 'QRAbstract'; // Do not translate
end;
function TQRXMLSSAbstractExportFilter.GetDescription : string;
begin
Result := '';
end;
function TQRXMLSSAbstractExportFilter.GetExtension : string;
begin
Result := '';
end;
procedure TQRXMLSSAbstractExportFilter.Start(PaperWidth, PaperHeight : integer; Font : TFont);
begin
CreateStream(Filename);
Active := true;
end;
procedure TQRXMLSSAbstractExportFilter.CreateStream(Filename : string);
begin
FStream := TFileStream.Create(Filename, fmCreate);
end;
procedure TQRXMLSSAbstractExportFilter.CloseStream;
begin
FStream.Free;
end;
procedure TQRXMLSSAbstractExportFilter.WriteToStream(const AText : string);
begin
if length(AText)>0 then
Stream.Write(AText[1], length(AText));
end;
procedure TQRXMLSSAbstractExportFilter.WriteLnToStream(const AText : string);
begin
WriteToStream(AText + #13 + #10);
end;
procedure TQRXMLSSAbstractExportFilter.Finish;
begin
CloseStream;
inherited Finish;
end;
procedure TQRXMLSSAbstractExportFilter.NewPage;
begin
FPageProcessed := False;
inherited NewPage;
end;
procedure TQRXMLSSAbstractExportFilter.EndPage;
begin
//EndPage;??
ProcessPage;
inherited EndPage;
end;
procedure TQRXMLSSAbstractExportFilter.ProcessPage;
begin
FPageProcessed := True;
end;
procedure TQRXMLSSAbstractExportFilter.StorePage;
begin
end;
function TQRXMLSSAbstractExportFilter.GetText(X, Y : extended; var Font : TFont) : string;
begin
end;
{TQRXMLSSDocumentFilter}
function TQRXMLSSDocumentFilter.GetFilterName : string;
begin
Result := SqrQRXDocument;
end;
function TQRXMLSSDocumentFilter.GetDescription : string;
begin
Result := SqrExcelX;
end;
function TQRXMLSSDocumentFilter.GetExtension : string;
begin
Result := 'xml'; // Do not translate
end;
function TQRXMLSSDocumentFilter.GetStreaming : boolean;
begin
Result := false;// stream multipage report mode
end;
procedure TQRXMLSSDocumentFilter.CreateStream(Filename : string);
begin
if Filename = '' then
begin
FStream := TMemoryStream.Create;
FreeStream := false;
end else
begin
FreeStream := true;
inherited CreateStream(Filename);
end;
end;
procedure TQRXMLSSDocumentFilter.CloseStream;
begin
// the stream is not freed if it's a memory stream
if FreeStream then
inherited CloseStream;
end;
constructor TQRXMLSSDocumentFilter.Create( filename : string );
begin
inherited Create( filename);
FItemcount := 0;
FSortList := TStringlist.Create;
FSortlist.Sorted := true;
FSortlist.Duplicates := dupAccept;
FStylenames := TStringlist.Create;
FFontTags := TStringlist.Create;
xmlWorkSheetname := 'Sheet 1';
FMaxYValue := 0.0;
xmlOpenWidth := 1000;
xmlOpenHeight := 600;
FLastRecordNum := 0;
FPagenumber := 1;
xmlCreator := 'QRXLSXDocumentFilter';
FCreated := datetostr( date );
FLastsaved := FCreated;
FXLEncoding := 'UTF-8';// west europe latin, 1250 is east europe.
end;
destructor TQRXMLSSDocumentFilter.Destroy;
begin
FSortList.Free;
FStylenames.Free;
FFonttags.Free;
inherited Destroy;
end;
procedure TQRXMLSSDocumentFilter.ProcessPage;
begin
FPageProcessed := True;
StorePage;
end;
procedure TQRXMLSSDocumentFilter.SetDocumentProperties( author, title, company : string );
begin
xmlAuthor := author;
FTitle := title;
xmlCompany := company;
end;
procedure TQRXMLSSDocumentFilter.LoadProlog;
var
astr, bstr : string;
begin
dlist.add('<?xml version="1.0" encoding="UTF-8"?>');
astr := '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" ';
bstr := 'xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel">';
dlist.add(astr+bstr);
dlist.add('<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">');
dlist.add('<Author xmlns="urn:schemas-microsoft-com:office:office">'+Author+'</Author>');
dlist.add('<Company xmlns="urn:schemas-microsoft-com:office:office">'+Company+'</Company>');
dlist.add('<Version xmlns="urn:schemas-microsoft-com:office:office">10.4219</Version>');
dlist.add('</DocumentProperties>');
dlist.add('<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">');
dlist.add('<DownloadComponents xmlns="urn:schemas-microsoft-com:office:office" />');
dlist.add('<LocationOfComponents xmlns="urn:schemas-microsoft-com:office:office" HRef="file:///\\phlfsnt01\DOWNLOAD\OfficeXPSrc\" />');
dlist.add('</OfficeDocumentSettings>');
dlist.add('<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">');
dlist.add('<WindowHeight xmlns="urn:schemas-microsoft-com:office:excel">'+inttostr(Openheight*10)+'</WindowHeight>');
dlist.add('<WindowWidth xmlns="urn:schemas-microsoft-com:office:excel">'+inttostr(Openwidth*10)+'</WindowWidth>');
dlist.add('<WindowTopX xmlns="urn:schemas-microsoft-com:office:excel">0</WindowTopX>');
dlist.add('<WindowTopY xmlns="urn:schemas-microsoft-com:office:excel">60</WindowTopY>');
dlist.add('<ProtectStructure xmlns="urn:schemas-microsoft-com:office:excel">False</ProtectStructure>');
dlist.add('<ProtectWindows xmlns="urn:schemas-microsoft-com:office:excel">False</ProtectWindows>');
dlist.add('</ExcelWorkbook>');
dlist.add('<Styles>');
dlist.add('<Style ss:ID="Default" ss:Name="Normal">');
dlist.add('<Alignment ss:Vertical="Bottom" />');
dlist.add('<Borders />');
dlist.add('<Font />');
dlist.add('<Interior />');
dlist.add('<NumberFormat />');
dlist.add('<Protection />');
dlist.add('</Style>');
styleinsert := dlist.count-1;
dlist.add('</Styles>');
dlist.add('<Worksheet ss:Name="'+WorkSheetName+'">');
dlist.add('<Table ss:ExpandedColumnCount="%cols%" ss:ExpandedRowCount="%rows%" x:FullColumns="1" x:FullRows="1">');
fixline1 := dlist.Count-1;
end;
// places a blank document in the stringlist
procedure TQRXMLSSDocumentFilter.NewDocument( doclist : TStringlist; PaperWidth, PaperHeight : double;
Papername, orient : string);
begin
//Title*, DocType*, Creator*, Author*, Date*, Copyright*, Orientation*
LoadProlog;
end;
// Overridden Start
procedure TQRXMLSSDocumentFilter.Start(PaperWidth, PaperHeight : integer; Font : TFont);
//var
// k : integer;
begin
inherited; // creates a stream
// output the prolog
dlist := TStringlist.create;
LoadProlog;
end;
function GetY( pstr : string ) : integer;
var
tstr : string;
p, ec : integer;
begin
p := pos(':', pstr);
tstr := copy( pstr,1,p-1);
val( tstr, p, ec);
result := p;
end;
// CAUTION : these routines are sensitive to the layout of FSortlist.
function GetItem( pstr : string ) : integer;
var
tstr : string;
p, ec : integer;
begin
//p := pos(':', pstr);
tstr := copy( pstr,13,5);
val( tstr, p, ec);
result := p;
end;
procedure TQRXMLSSDocumentFilter.ProcessItems;
var
currY, currItem, k, p : integer;
currText, typestr : string;
currExpType : TExportType;
reqCol : integer;
begin
//FSortList.SaveToFile('sortlist.txt'); // debugging
if FSortList.count = 0 then exit;
rowno := 1;
colno := 0;
k := 0;
maxcols := 0;
currY := getY( FSortList[0]);
dlist.add(' <Row>');
while k < FSortlist.count do
begin
currItem := GetItem( FSortList[k]);
currText := FItems[currItem].text;
currExpType := FItems[currItem].exportAs;
reqCol := FItems[currItem].col;
if reqCol > colno then
for p := 1 to (reqCol-colno-1) do
begin
dlist.add(' <Cell><Data ss:Type="String"> </Data></Cell>');
inc(colno);
end;
typestr := 'String';
if currExpType = exptNumeric then typestr := 'Number';
dlist.add(' <Cell ss:StyleID="'+FItems[currItem].controlName+'" ><Data ss:Type="'+typestr+'">'+currText+'</Data></Cell>');
inc(colno);
if colno > maxcols then maxcols := colno;
inc(k);
if k = FSortlist.Count then break;
if currY <> getY( FSortList[k]) then
begin
currY := getY( FSortList[k]);
dlist.add(' </Row>');
dlist.add(' <Row>');
inc(rowno);
colno := 0;
end;
end;
dlist.add(' </Row>');
end;
// overridden Finish
procedure TQRXMLSSDocumentFilter.Finish;
var
tstr : string;
k : integer;
begin
if fconcatenating then exit;
ProcessItems;
dlist.add('</Table>');
dlist.add('<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">');
dlist.add('<Print xmlns="urn:schemas-microsoft-com:office:excel">');
dlist.add('<ValidPrinterInfo xmlns="urn:schemas-microsoft-com:office:excel" />');
dlist.add('<HorizontalResolution xmlns="urn:schemas-microsoft-com:office:excel">1200</HorizontalResolution>');
dlist.add('<VerticalResolution xmlns="urn:schemas-microsoft-com:office:excel">1200</VerticalResolution>');
dlist.add('</Print>');
dlist.add('<ProtectObjects xmlns="urn:schemas-microsoft-com:office:excel">False</ProtectObjects>');
dlist.add('<ProtectScenarios xmlns="urn:schemas-microsoft-com:office:excel">False</ProtectScenarios>');
dlist.add('</WorksheetOptions>');
dlist.add('</Worksheet>');
dlist.add('</Workbook>');
// fix the table params
tstr := dlist[fixline1];
tstr := stringreplace( tstr, '%cols%', inttostr(maxcols), [rfReplaceall]);
tstr := stringreplace( tstr, '%rows%', inttostr(rowno), [rfReplaceall]);
dlist[fixline1] := tstr;
// insert Styles
for k := FFonttags.Count-1 downto 0 do
dlist.Insert(styleinsert+1, FFonttags[k]);
dlist.SaveToStream(FStream, TEncoding.UTF8);
dlist.Free;
inherited;
end;
procedure TQRXMLSSDocumentFilter.EndConcat;
begin
fconcatenating := false;
Finish;
end;
procedure TQRXMLSSDocumentFilter.TextOutRec( ExportInfo : TExportInfoRec);
var
//I : integer;
nItem : XLXSTextItem;
sortstr, fontstr, colorstr : string;
begin
nItem.col := ExportInfo.Column;
nItem.X := ExportInfo.Xpos;
nItem.Y := ExportInfo.Ypos + FPageYOffset;
if nItem.Y > FMaxYValue then FMaxYValue := nItem.Y;
nItem.text := EntityReplace(ExportInfo.Text);
nItem.exportAs := ExportInfo.exportAs;
// style stuff
nItem.fontname := ExportInfo.Font.Name;
nItem.fontsize := ExportInfo.Font.Size;
nItem.fontbold := fsBold in ExportInfo.Font.Style;
nItem.fontitalic := fsItalic in ExportInfo.Font.Style;
nItem.fontstrike := fsStrikeout in ExportInfo.Font.Style;
nItem.fontcolor := ExportInfo.Font.Color;
if nItem.fontcolor<0 then nItem.fontcolor := 0;
nItem.controlName := ExportInfo.controlName;
if trim(nItem.controlName)='' then
nItem.controlName := 'noname';
if FStylenames.IndexOf(Nitem.controlName) = -1 then
begin
colorstr := colTrans(Nitem.fontcolor);
fontstr := '<ss:Font ss:FontName="'+nItem.fontname+'" ss:Size="'
+ inttostr(nItem.fontsize) + '" ss:Color="'+colorstr+'" ';
if nItem.fontbold then fontstr := fontstr + 'ss:Bold="1" ';
if nItem.fontitalic then fontstr := fontstr + 'ss:Italic="1" ';
fontstr := fontstr + '/>';
FStylenames.Add(nItem.controlName);
FFontTags.Add('<Style ss:ID="'+nItem.controlName+'" >');
FFontTags.Add(fontstr);
FFontTags.Add('</Style>');
end;
setlength(FItems,FItemcount+1);
FItems[FItemcount] := nItem;
sortstr := format( '%5d:%5d:%5d',[trunc(nItem.Y), nItem.col, FItemcount]);
sortstr := stringreplace( sortstr, ' ','0',[rfReplaceall]);
sortstr := sortstr+':'+nItem.text;
FSortList.Add(sortstr);
inc(FItemcount);
end;
procedure TQRXMLSSDocumentFilter.EndPage;
begin
//do nothing;
end;
procedure TQRXMLSSDocumentFilter.NewPage;
begin
inc(FPagenumber);
FPageYoffset := FMaxYvalue;
end;
function EntityReplace( var ctext : string ) : string;
begin
ctext := stringreplace( ctext, '&', '&', [rfReplaceAll] ); // must be first
ctext := stringreplace( ctext, '<', '<', [rfReplaceAll] );
ctext := stringreplace( ctext, '>', '>', [rfReplaceAll] );
ctext := stringreplace( ctext, '''', ''', [rfReplaceAll] );
ctext := stringreplace( ctext, '"', '"', [rfReplaceAll] );
result := ctext;
end;
function ColTrans( ct : TColor ) : string;
var
tempstr : string;
begin
if ct < 0 then
begin
ct := ct and $FFFFFF;
end;
tempstr := format ( '%6.6x', [longint(ct)]);
result := '#' + copy( tempstr, 5, 2 ) +copy( tempstr, 3, 2 ) +copy( tempstr, 1, 2 ) ;
end;
{#ifdef STUFF}
// turns a byte into 2 hex digits
{CH procedure Hexit( var c1 : char; var c2 : char; b : byte );
var
b1, b2 : byte;
begin
b1 := b shr 4;
b2 := b and $0F;
if b1 < 10 then
c1 := chr( b1 + ORD0 )
else
c1 := chr( (b1-10) + ORDA );
if b2 < 10 then
c2 := chr( b2 + ORD0 )
else
c2 := chr( (b2-10) + ORDA );
end; }
// strip off file extension
{CH function basename( fname : string ) : string;
var
p : integer;
ps,fs : string;
begin
basename := fname;
ps:=sysutils.ExtractFilePath(fname);
fs:=sysutils.ExtractFileName(fname);
p := pos( '.', fs );
if p = 0 then exit;
basename := ps + copy( fs, 1, p - 1 );
end; }
{#endif}
end.
|
unit UGeCondicaoPagto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UGrPadraoCadastro, ImgList, IBCustomDataSet, IBUpdateSQL, DB,
Mask, DBCtrls, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, ComCtrls,
ToolWin, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus,
cxButtons, DBClient, Provider, dxSkinsCore, dxSkinBlueprint,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinHighContrast,
dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White,
dxSkinSevenClassic, dxSkinSharpPlus, dxSkinTheAsphaltWorld, dxSkinVS2010,
dxSkinWhiteprint, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver;
type
TfrmGeCondicaoPagto = class(TfrmGrPadraoCadastro)
lblNome: TLabel;
dbNome: TDBEdit;
IbDtstTabelaCOND_COD: TSmallintField;
IbDtstTabelaCOND_DESCRICAO: TIBStringField;
IbDtstTabelaCOND_PRAZO: TSmallintField;
IbDtstTabelaCOND_PRAZO_01: TSmallintField;
IbDtstTabelaCOND_PRAZO_02: TSmallintField;
IbDtstTabelaCOND_PRAZO_03: TSmallintField;
IbDtstTabelaCOND_PRAZO_04: TSmallintField;
IbDtstTabelaCOND_PRAZO_05: TSmallintField;
IbDtstTabelaCOND_PRAZO_06: TSmallintField;
IbDtstTabelaCOND_PRAZO_07: TSmallintField;
IbDtstTabelaCOND_PRAZO_08: TSmallintField;
IbDtstTabelaCOND_PRAZO_09: TSmallintField;
IbDtstTabelaCOND_PRAZO_10: TSmallintField;
IbDtstTabelaCOND_PRAZO_11: TSmallintField;
IbDtstTabelaCOND_PRAZO_12: TSmallintField;
IbDtstTabelaCOND_DESCRICAO_FULL: TIBStringField;
dbPrazo: TDBCheckBox;
lblPrazo01: TLabel;
dbPrazo01: TDBEdit;
lblPrazo02: TLabel;
dbPrazo02: TDBEdit;
lblPrazo03: TLabel;
dbPrazo03: TDBEdit;
dbPrazo04: TDBEdit;
lblPrazo04: TLabel;
lblPrazo05: TLabel;
dbPrazo05: TDBEdit;
dbPrazo06: TDBEdit;
lblPrazo06: TLabel;
dbPrazo07: TDBEdit;
lblPrazo07: TLabel;
dbPrazo08: TDBEdit;
lblPrazo08: TLabel;
lblPrazo09: TLabel;
dbPrazo09: TDBEdit;
dbPrazo10: TDBEdit;
lblPrazo10: TLabel;
dbPrazo11: TDBEdit;
lblPrazo11: TLabel;
dbPrazo12: TDBEdit;
lblPrazo12: TLabel;
dbCondicaoPagtoPDV: TDBCheckBox;
IbDtstTabelaCOND_PDV: TSmallintField;
IbDtstTabelaCOND_QTDE_PARCELAS: TSmallintField;
IbDtstTabelaAPrazo: TStringField;
qryFormaPagtoLista: TIBDataSet;
dspFormaPagtoLista: TDataSetProvider;
cdsFormaPagtoLista: TClientDataSet;
dtsFormaPagtoLista: TDataSource;
cdsFormaPagtoListaSELECIONAR: TIntegerField;
cdsFormaPagtoListaCODIGO: TSmallintField;
dbgFormaPagto: TDBGrid;
cdsFormaPagtoListaDESCRICAO: TWideStringField;
cdsFormaPagtoListaUSAR_PDV: TWideStringField;
lblRegistroDesativado: TLabel;
dbAtiva: TDBCheckBox;
IbDtstTabelaATIVA: TSmallintField;
procedure FormCreate(Sender: TObject);
procedure DtSrcTabelaDataChange(Sender: TObject; Field: TField);
procedure IbDtstTabelaNewRecord(DataSet: TDataSet);
procedure IbDtstTabelaBeforePost(DataSet: TDataSet);
procedure IbDtstTabelaCalcFields(DataSet: TDataSet);
procedure dbgFormaPagtoDblClick(Sender: TObject);
procedure dbgFormaPagtoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure IbDtstTabelaAfterScroll(DataSet: TDataSet);
procedure btbtnCancelarClick(Sender: TObject);
procedure btbtnSalvarClick(Sender: TObject);
procedure DtSrcTabelaStateChange(Sender: TObject);
procedure cdsFormaPagtoListaSELECIONARGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
private
{ Private declarations }
procedure CarregarFormaPagto;
public
{ Public declarations }
procedure GravarRelacaoFormaCondicao;
end;
(*
Tabelas:
- TBCONDICAOPAGTO
- TBFORMPAGTO
- TBFORMPAGTO_CONDICAO
Views:
Procedures:
*)
var
frmGeCondicaoPagto: TfrmGeCondicaoPagto;
procedure MostrarTabelaCondicoesPagto(const AOwner : TComponent);
function SelecionarCondicaoPagto(const AOwner : TComponent; var Codigo : Integer; var Nome : String) : Boolean; overload;
function SelecionarCondicaoPagto(const AOwner : TComponent; var Codigo : Integer; var Nome : String; var Prazos : IntegerArray) : Boolean; overload;
implementation
uses
UDMBusiness, UConstantesDGE;
{$R *.dfm}
procedure MostrarTabelaCondicoesPagto(const AOwner : TComponent);
var
frm : TfrmGeCondicaoPagto;
begin
frm := TfrmGeCondicaoPagto.Create(AOwner);
try
frm.ShowModal;
finally
frm.Destroy;
end;
end;
function SelecionarCondicaoPagto(const AOwner : TComponent; var Codigo : Integer; var Nome : String) : Boolean;
var
frm : TfrmGeCondicaoPagto;
begin
frm := TfrmGeCondicaoPagto.Create(AOwner);
try
Result := frm.SelecionarRegistro(Codigo, Nome);
finally
frm.Destroy;
end;
end;
function SelecionarCondicaoPagto(const AOwner : TComponent; var Codigo : Integer; var Nome : String; var Prazos : IntegerArray) : Boolean;
var
frm : TfrmGeCondicaoPagto;
I : Integer;
begin
frm := TfrmGeCondicaoPagto.Create(AOwner);
try
Result := frm.SelecionarRegistro(Codigo, Nome);
if ( Result ) then
begin
for I := COND_PARCELA_MIN to COND_PARCELA_MAX do
if ( not frm.IbDtstTabela.FieldByName('COND_PRAZO_' + FormatFloat('00', I)).IsNull ) then
begin
//SetLength(Prazos, Length(Prazos) + I);;
Prazos[I] := frm.IbDtstTabela.FieldByName('COND_PRAZO_' + FormatFloat('00', I)).AsInteger;
end;
end;
finally
frm.Destroy;
end;
end;
procedure TfrmGeCondicaoPagto.FormCreate(Sender: TObject);
var
I ,
X : SmallInt;
begin
inherited;
RotinaID := ROTINA_CAD_CONDICAO_PAGTO_ID;
ControlFirstEdit := dbNome;
DisplayFormatCodigo := '000';
NomeTabela := 'TBCONDICAOPAGTO';
CampoCodigo := 'Cond_cod';
CampoDescricao := 'Cond_descricao';
CampoCadastroAtivo := 'ATIVA';
if (gSistema.Codigo = SISTEMA_PDV) then
WhereAdditional := '(c.Cond_pdv = 1)';
UpdateGenerator;
btbtnIncluir.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]);
btbtnAlterar.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]);
btbtnExcluir.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]);
btbtnCancelar.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]);
btbtnSalvar.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]);
dbgFormaPagto.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_PDV, SISTEMA_GESTAO_OPME]);
dbCondicaoPagtoPDV.Visible := (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_PDV]);
if not dbCondicaoPagtoPDV.Visible then
GrpBxDadosNominais.Height := 153;
for I := -1 to 1 do
begin
X := StrToInt(FormatDateTime('YYYY', Date)) + I;
GerarCompetencias( X );
end;
end;
procedure TfrmGeCondicaoPagto.DtSrcTabelaDataChange(Sender: TObject;
Field: TField);
begin
inherited;
if ( Field = IbDtstTabela.FieldByName('COND_PRAZO') ) then
begin
dbPrazo01.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo02.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo03.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo04.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo05.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo06.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo07.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo08.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo09.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo10.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo11.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
dbPrazo12.ReadOnly := (IbDtstTabelaCOND_PRAZO.AsInteger = 0);
end;
end;
procedure TfrmGeCondicaoPagto.IbDtstTabelaNewRecord(DataSet: TDataSet);
begin
inherited;
IbDtstTabelaCOND_PRAZO.AsInteger := 0;
IbDtstTabelaCOND_PDV.AsInteger := 0;
IbDtstTabelaATIVA.AsInteger := FLAG_SIM;
IbDtstTabelaCOND_QTDE_PARCELAS.AsInteger := 0;
IbDtstTabelaCOND_PRAZO_01.Clear;
IbDtstTabelaCOND_PRAZO_02.Clear;
IbDtstTabelaCOND_PRAZO_03.Clear;
IbDtstTabelaCOND_PRAZO_04.Clear;
IbDtstTabelaCOND_PRAZO_05.Clear;
IbDtstTabelaCOND_PRAZO_06.Clear;
IbDtstTabelaCOND_PRAZO_07.Clear;
IbDtstTabelaCOND_PRAZO_08.Clear;
IbDtstTabelaCOND_PRAZO_09.Clear;
IbDtstTabelaCOND_PRAZO_10.Clear;
IbDtstTabelaCOND_PRAZO_11.Clear;
IbDtstTabelaCOND_PRAZO_12.Clear;
end;
procedure TfrmGeCondicaoPagto.IbDtstTabelaBeforePost(DataSet: TDataSet);
var
I ,
iQtde : Integer;
sCmp ,
Str : String;
begin
inherited;
(*
IMR - 22/10/2014 :
Inserção da variável QTDE para que esta defina o número de parcelas da condição de pagamento a prazo a partir dos prazos de vencimentos.
*)
iQtde := 0;
// limpar campos de prazos vazios
for I := COND_PARCELA_MIN to COND_PARCELA_MAX do
begin
sCmp := 'COND_PRAZO_' + FormatFloat('00', I);
if IbDtstTabela.Fields.FindField(sCmp) <> nil then
if Trim(IbDtstTabela.FieldByName(sCmp).AsString) = EmptyStr then
IbDtstTabela.FieldByName(sCmp).Clear;
end;
if ( IbDtstTabelaCOND_PRAZO.AsInteger = 0 ) then
Str := Trim(IbDtstTabelaCOND_DESCRICAO.AsString)
else
begin
Str := Trim(IbDtstTabelaCOND_DESCRICAO.AsString) + ' [';
if ( not IbDtstTabelaCOND_PRAZO_01.IsNull ) then
begin
Str := Str + IbDtstTabelaCOND_PRAZO_01.AsString;
iQtde := 1;
end;
if ( not IbDtstTabelaCOND_PRAZO_02.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_02.AsString;
iQtde := 2;
end;
if ( not IbDtstTabelaCOND_PRAZO_03.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_03.AsString;
iQtde := 3;
end;
if ( not IbDtstTabelaCOND_PRAZO_04.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_04.AsString;
iQtde := 4;
end;
if ( not IbDtstTabelaCOND_PRAZO_05.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_05.AsString;
iQtde := 5;
end;
if ( not IbDtstTabelaCOND_PRAZO_06.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_06.AsString;
iQtde := 6;
end;
if ( not IbDtstTabelaCOND_PRAZO_07.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_07.AsString;
iQtde := 7;
end;
if ( not IbDtstTabelaCOND_PRAZO_08.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_08.AsString;
iQtde := 8;
end;
if ( not IbDtstTabelaCOND_PRAZO_09.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_09.AsString;
iQtde := 9;
end;
if ( not IbDtstTabelaCOND_PRAZO_10.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_10.AsString;
iQtde := 10;
end;
if ( not IbDtstTabelaCOND_PRAZO_11.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_11.AsString;
iQtde := 11;
end;
if ( not IbDtstTabelaCOND_PRAZO_12.IsNull ) then
begin
Str := Str + ', ' + IbDtstTabelaCOND_PRAZO_12.AsString;
iQtde := 12;
end;
Str := Str + ']';
end;
IbDtstTabelaCOND_QTDE_PARCELAS.AsInteger := iQtde;
IbDtstTabelaCOND_DESCRICAO_FULL.AsString := Str;
end;
procedure TfrmGeCondicaoPagto.IbDtstTabelaCalcFields(DataSet: TDataSet);
begin
IbDtstTabelaAPrazo.AsString := IfThen(IbDtstTabelaCOND_PRAZO.AsInteger = 1, 'X', '.');
end;
procedure TfrmGeCondicaoPagto.CarregarFormaPagto;
begin
with cdsFormaPagtoLista, Params do
begin
Close;
ParamByName('condicao_pagto').AsInteger := IbDtstTabelaCOND_COD.AsInteger;
Open;
end;
end;
procedure TfrmGeCondicaoPagto.GravarRelacaoFormaCondicao;
var
sSQL : String;
const
SQL_INSERT = 'Insert Into TBFORMPAGTO_CONDICAO (FORMA_PAGTO, CONDICAO_PAGTO, SELECIONAR) values (%s, %s, 1)';
SQL_DELETE = 'Delete from TBFORMPAGTO_CONDICAO where FORMA_PAGTO = %s and CONDICAO_PAGTO = %s';
begin
(*
IMR - 11/03/2015 :
Rotina que permite a gravação de várias formas de pagamento para a mesma condição de pagamento.
*)
cdsFormaPagtoLista.First;
while not cdsFormaPagtoLista.Eof do
begin
if cdsFormaPagtoListaSELECIONAR.AsInteger = 1 then
sSQL := SQL_INSERT
else
sSQL := SQL_DELETE;
with DMBusiness, fdQryBusca do
begin
SQL.Clear;
SQL.Add( Format(SQL_DELETE, [cdsFormaPagtoListaCODIGO.AsString, IbDtstTabelaCOND_COD.AsString]) );
ExecSQL;
SQL.Clear;
SQL.Add( Format(sSQL, [cdsFormaPagtoListaCODIGO.AsString, IbDtstTabelaCOND_COD.AsString]) );
ExecSQL;
CommitTransaction;
end;
cdsFormaPagtoLista.Next;
end;
cdsFormaPagtoLista.First;
end;
procedure TfrmGeCondicaoPagto.dbgFormaPagtoDblClick(Sender: TObject);
begin
if dtsFormaPagtoLista.AutoEdit then
if ( not cdsFormaPagtoLista.IsEmpty ) then
begin
cdsFormaPagtoLista.Edit;
if ( cdsFormaPagtoListaSELECIONAR.AsInteger = 0 ) then
cdsFormaPagtoListaSELECIONAR.AsInteger := 1
else
cdsFormaPagtoListaSELECIONAR.AsInteger := 0;
cdsFormaPagtoLista.Post;
end;
end;
procedure TfrmGeCondicaoPagto.dbgFormaPagtoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if ( Key = VK_SPACE ) then
dbgFormaPagtoDblClick(Sender);
end;
procedure TfrmGeCondicaoPagto.IbDtstTabelaAfterScroll(DataSet: TDataSet);
begin
inherited;
CarregarFormaPagto;
end;
procedure TfrmGeCondicaoPagto.btbtnCancelarClick(Sender: TObject);
begin
inherited;
if ( not OcorreuErro ) then
CarregarFormaPagto;
end;
procedure TfrmGeCondicaoPagto.btbtnSalvarClick(Sender: TObject);
begin
(*
IMR - 11/03/2015 :
Rotina que permite a gravação de várias formas de pagamentos para a mesma condição de pagamento.
*)
IbDtstTabela.AfterScroll := nil;
inherited;
IbDtstTabela.AfterScroll := IbDtstTabelaAfterScroll;
if ( not OcorreuErro ) then
GravarRelacaoFormaCondicao;
end;
procedure TfrmGeCondicaoPagto.DtSrcTabelaStateChange(Sender: TObject);
begin
inherited;
dtsFormaPagtoLista.AutoEdit := (IbDtstTabela.State in [dsEdit, dsInsert]);
end;
procedure TfrmGeCondicaoPagto.cdsFormaPagtoListaSELECIONARGetText(
Sender: TField; var Text: String; DisplayText: Boolean);
begin
if not Sender.IsNull then
Case Sender.AsInteger of
0 : Text := '.';
1 : Text := 'X';
end;
end;
initialization
FormFunction.RegisterForm('frmGeCondicaoPagto', TfrmGeCondicaoPagto);
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
BVisage: TButton;
BNoir: TButton;
BEchec: TButton;
BRouge: TButton;
BQuatre: TButton;
BAlterne: TButton;
Image: TImage;
procedure BAlterneClick(Sender: TObject);
procedure BEchecClick(Sender: TObject);
procedure BNoirClick(Sender: TObject);
procedure BQuatreClick(Sender: TObject);
procedure BRougeClick(Sender: TObject);
procedure BVisageClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.BNoirClick(Sender: TObject);
begin
Image.Canvas.Brush.color := clblack;
Image.Canvas.Rectangle (0,0,300,300);
end;
procedure TForm1.BAlterneClick(Sender: TObject);
var
cpt : integer;
begin
Cpt:=0;
While (Cpt<300) do
begin
Image.Canvas.Pen.color:=clRed;
Image.Canvas.Line (Cpt,0,Cpt,300);
Image.Canvas.Pen.color:=clYellow;
Image.Canvas.Line (Cpt+1,0,Cpt+1,300);
Image.Canvas.Pen.color:=clGreen;
Image.Canvas.Line (Cpt+2,0,Cpt+2,300);
Image.Canvas.Pen.color:=clBlue;
Image.Canvas.Line (Cpt+3,0,Cpt+3,300);
Cpt:=Cpt+4;
end;
end;
procedure TForm1.BEchecClick(Sender: TObject);
var
i, j : integer;
begin
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
if (i = j) OR (i = j + 2) OR (i = j - 2) OR (i = j + 4) OR (i = j - 4) OR (i = j + 6) OR (i = j - 6) then
begin
Image.Canvas.Brush.color := clblack;
Image.Canvas.Rectangle (i*37,j*37,(i+1)*37,(j+1)*37)
end
else
begin
Image.Canvas.Brush.color := clwhite;
Image.Canvas.Rectangle (i*37,j*37,(i+1)*37,(j+1)*37);
end;
end;
end;
end;
procedure TForm1.BQuatreClick(Sender: TObject);
begin
Image.Canvas.Brush.color := clblue;
Image.Canvas.Rectangle(0,0,150,150);
Image.Canvas.Brush.color := clgreen;
Image.Canvas.Rectangle(300,300,150,150);
Image.Canvas.Brush.color := clyellow;
Image.Canvas.Rectangle(300,0,150,150);
Image.Canvas.Brush.color := clpurple;
Image.Canvas.rectangle(0,300,150,150);
end;
procedure TForm1.BRougeClick(Sender: TObject);
begin
Image.Canvas.Brush.color := clred;
Image.Canvas.Rectangle(0,0,300,300);
end;
procedure TForm1.BVisageClick(Sender: TObject);
begin
Image.canvas.Brush.color := clyellow;
Image.canvas.Rectangle(0,0,300,300);
Image.canvas.Brush.color := clblue;
Image.canvas.Ellipse(50,50,150,150);
Image.canvas.Ellipse(150,50,250,150);
Image.canvas.Brush.color := clwhite;
Image.canvas.Rectangle(50,200,250,250);
end;
end.
|
unit save_txt_dialog;
interface
uses Messages, Windows, SysUtils, Classes, Controls, StdCtrls, Graphics,
ExtCtrls, Buttons, Dialogs;
type
TOpenPictureDialog = class(TSaveDialog)
private
SkipDescr, WordWrap,Indent,Hyph,IgnoreStrongC,IgnoreItalicC:TCheckBox;
WidthEdit,IndentEdit:TEdit;
EncodingsList,BRTypeList:TComboBox;
FChecksPanel: TPanel;
TextWidth,IndentWidth,CodePage,BrType:Integer;
function GetSkipDescr:boolean;
function GetTextWidth:integer;
function GetIndent:integer;
function GetHyphenate:boolean;
function GetCodePage:Integer;
function GetBr:string;
function GetItalicIgnore:boolean;
function GetStrongIgnore:boolean;
protected
procedure DoClose; override;
procedure DoShow; override;
Procedure OnWWClick(sender: TObject);
Procedure OnWWKey(Sender: TObject; var Key: Char);
Procedure OnIndentClick(sender: TObject);
Procedure OnIndentKey(Sender: TObject; var Key: Char);
Procedure TextWidthChange(sender: TObject);
Procedure IndentWidthChange(sender: TObject);
Procedure OnDialogShow(sender: TObject);
Procedure OnCodePageChange(sender: TObject);
Procedure OnBrTypeChange(sender: TObject);
public
property DoSkipDescr:boolean read GetSkipDescr;
property TextFixedWidth:integer read GetTextWidth;
property ParaIndent:integer read GetIndent;
property Hyphenate:boolean read GetHyphenate;
property OutCodePage:Integer read GetCodePage;
property ItalicIgnore:boolean read GetItalicIgnore;
property StrongIgnore:boolean read GetStrongIgnore;
property LnBr:string read GetBr;
constructor Create(AOwner: TComponent); override;
function Execute: Boolean; override;
function ProducePanel(Parent:TComponent):TPanel;
end;
const
EncCount=40;
BrCount=3;
CP_UTF16=3;
Type
TEncCollection=Array[1..EncCount] of record
CP:Integer;
Name:String;
end;
TBrTypes=Array[1..BrCount] of record
Chars:string;
Name:String;
end;
const
RegistryKey='Software\Grib Soft\FB to TXT\1.0';
BRTypes:TBrTypes=(
(Chars:#13#10; Name: 'Windows line breaks (CR,LF)'),
(Chars:#10; Name: 'UNIX line breaks (LF)'),
(Chars:#13; Name: 'Macintosh line breaks (CR)')
);
SupportedEncodings:TEncCollection=(
(CP: 1250; Name: 'Windows 3.1 Eastern European'),
(CP: 1251; Name: 'Windows 3.1 Cyrillic'),
(CP: 1252; Name: 'Windows 3.1 US (ANSI)'),
(CP: 1253; Name: 'Windows 3.1 Greek'),
(CP: 1254; Name: 'Windows 3.1 Turkish'),
(CP: 1255; Name: 'Hebrew'),
(CP: 1256; Name: 'Arabic'),
(CP: 1257; Name: 'Baltic'),
(CP: 437; Name: 'MS-DOS United States'),
(CP: 708; Name: 'Arabic (ASMO 708)'),
(CP: 709; Name: 'Arabic (ASMO 449+, BCON V4)'),
(CP: 710; Name: 'Arabic (Transparent Arabic)'),
(CP: 720; Name: 'Arabic (Transparent ASMO)'),
(CP: 737; Name: 'Greek (formerly 437G)'),
(CP: 775; Name: 'Baltic'),
(CP: 850; Name: 'MS-DOS Multilingual (Latin I)'),
(CP: 852; Name: 'MS-DOS Slavic (Latin II)'),
(CP: 855; Name: 'IBM Cyrillic'),
(CP: 857; Name: 'IBM Turkish'),
(CP: 860; Name: 'MS-DOS Portuguese'),
(CP: 861; Name: 'MS-DOS Icelandic'),
(CP: 862; Name: 'Hebrew'),
(CP: 863; Name: 'MS-DOS Canadian-French'),
(CP: 864; Name: 'Arabic'),
(CP: 865; Name: 'MS-DOS Nordic'),
(CP: 866; Name: 'MS-DOS Russian (USSR)'),
(CP: 869; Name: 'IBM Modern Greek'),
(CP: 874; Name: 'Thai'),
(CP: 932; Name: 'Japan'),
(CP: 936; Name: 'Chinese (PRC, Singapore)'),
(CP: 949; Name: 'Korean'),
(CP: 950; Name: 'Chinese (Taiwan, Hong Kong)'),
(CP: 874; Name: 'Thai'),
(CP: 10000; Name: 'Macintosh Roman'),
(CP: 10001; Name: 'Macintosh Japanese'),
(CP: 10006; Name: 'Macintosh Greek I'),
(CP: 10007; Name: 'Macintosh Cyrillic'),
(CP: 10029; Name: 'Macintosh Latin 2'),
(CP: 10079; Name: 'Macintosh Icelandic'),
(CP: 10081; Name: 'Macintosh Turkish')
);
implementation
uses Consts, Math, Forms, CommDlg, Dlgs,Registry;
{$R MyExtdlg.res}
function TOpenPictureDialog.GetSkipDescr;
Begin
result:= SkipDescr.checked;
end;
function TOpenPictureDialog.GetItalicIgnore:boolean;
Begin
result:= IgnoreItalicC.checked;
end;
function TOpenPictureDialog.GetStrongIgnore:boolean;
Begin
result:= IgnoreStrongC.checked;
end;
Function TOpenPictureDialog.GetTextWidth:integer;
Begin
if WordWrap.Checked then
result:=TextWidth
else
Result:=-1;
end;
Function TOpenPictureDialog.GetIndent:integer;
Begin
if Indent.Checked then
result:=IndentWidth
else
Result:=-1;
end;
Function TOpenPictureDialog.GetHyphenate:boolean;
Begin
result:=Hyph.Checked and WordWrap.Checked;
end;
Function TOpenPictureDialog.GetCodePage:Integer;
Begin
result:=CodePage;
end;
Function TOpenPictureDialog.GetBr:string;
Begin
result:=BRTypes[BrType+1].Chars;
end;
Procedure TOpenPictureDialog.OnBrTypeChange;
Begin
BrType:=BRTypeList.ItemIndex;
end;
Procedure TOpenPictureDialog.OnCodePageChange;
Begin
CodePage:=Integer(EncodingsList.Items.Objects[EncodingsList.ItemIndex]);
end;
procedure TOpenPictureDialog.OnWWClick;
Begin
WidthEdit.Enabled:=WordWrap.Checked;
Hyph.Enabled:=WordWrap.Checked;
end;
Procedure TOpenPictureDialog.TextWidthChange(sender: TObject);
Begin
try
TextWidth:=StrToInt(WidthEdit.Text);
except
TextWidth:=80;
WidthEdit.Text:=IntToStr(TextWidth);
end;
end;
Procedure TOpenPictureDialog.IndentWidthChange(sender: TObject);
Begin
try
IndentWidth:=StrToInt(IndentEdit.text);
except
IndentWidth:=3;
IndentEdit.Text:=IntToStr(IndentWidth);
end;
end;
procedure TOpenPictureDialog.OnWWKey;
Begin
OnWWClick(Nil);
end;
Procedure TOpenPictureDialog.OnIndentClick(sender: TObject);
Begin
IndentEdit.Enabled:=Indent.Checked;
end;
Procedure TOpenPictureDialog.OnIndentKey(Sender: TObject; var Key: Char);
Begin
OnIndentClick(Nil);
end;
Function TOpenPictureDialog.ProducePanel(Parent:TComponent):TPanel;
Var
FChecksPanel:TPanel;
Begin
FChecksPanel:=TPanel.Create(Parent);
Result:=FChecksPanel;
with FChecksPanel do
Begin
Name := 'PicturePanel';
Caption := '';
SetBounds(10, 150, 200, 200);
BevelOuter := bvNone;
BorderWidth := 6;
TabOrder := 1;
SkipDescr:=TCheckBox.Create(Self);
With SkipDescr do Begin
Name := 'SkipDescr';
Caption := 'Skip description';
Left:=0;
Top:=3;
TabOrder := 1;
Width:=200;
Parent:=FChecksPanel;
end;
WordWrap:=TCheckBox.Create(Self);
With WordWrap do Begin
Name := 'WordWrap';
Caption := 'Fixed-width';
Left:=130;
Top:=3;
TabOrder := 2;
Width:=95;
Parent:=FChecksPanel;
end;
WordWrap.OnClick:=OnWWClick;
WordWrap.OnKeyPress:=OnWWKey;
WidthEdit:=TEdit.Create(Self);
with WidthEdit do Begin
Name := 'WrapEdit';
Left:=225;
Top:=0;
Width:=20;
Height:=10;
Text:='80';
Parent:=FChecksPanel;
TabOrder:=3;
end;
WidthEdit.OnChange:=TextWidthChange;
Hyph:=TCheckBox.Create(Self);
With Hyph do Begin
Name := 'Hyphenate';
Caption := 'Hyphenate';
Left:=270;
Top:=3;
TabOrder:= 6;
Width:=90;
Parent:=FChecksPanel;
end;
Indent:=TCheckBox.Create(Self);
With Indent do Begin
Name := 'Indent';
Caption := 'Paragraph indent';
Left:=375;
Top:=3;
TabOrder:= 4;
Width:=130;
Parent:=FChecksPanel;
end;
Indent.OnClick:=OnIndentClick;
Indent.OnKeyPress:=OnIndentKey;
IndentEdit:=TEdit.Create(Self);
with IndentEdit do Begin
Name := 'IndentEdit';
Left:=505;
Top:=0;
Width:=20;
Height:=10;
Text:='4';
Parent:=FChecksPanel;
TabOrder:=5;
end;
IndentEdit.OnChange:=IndentWidthChange;
EncodingsList:=TComboBox.Create(Self);
With EncodingsList do Begin
Name := 'EncBox';
Top:=28;
Left:=0;
Width:=246;
TabOrder:=7;
Style:=csDropDownList;
Parent:=FChecksPanel;
end;
BRTypeList:=TComboBox.Create(Self);
With BRTypeList do Begin
Name := 'LineBrBox';
Top:=28;
Left:=270;
Width:=256;
TabOrder:=8;
Style:=csDropDownList;
Parent:=FChecksPanel;
end;
IgnoreStrongC:=TCheckBox.Create(Self);
With IgnoreStrongC do Begin
Name := 'IgnoreStrongC';
Caption := 'No strong to UPPERCASE';
Left:=0;
Top:=61;
TabOrder:= 9;
Width:=200;
Parent:=FChecksPanel;
end;
IgnoreItalicC:=TCheckBox.Create(Self);
With IgnoreItalicC do Begin
Name := 'IgnoreItalicC';
Caption := 'No emphasis to _emphasis_';
Left:=270;
Top:=61;
TabOrder:= 9;
Width:=200;
Parent:=FChecksPanel;
end;
end;
end;
constructor TOpenPictureDialog.Create(AOwner: TComponent);
Var
Reg:TRegistry;
begin
inherited Create(AOwner);
Options:=[ofOverwritePrompt,ofEnableSizing];
FChecksPanel:=ProducePanel(Self);
Reg:=TRegistry.Create(KEY_READ);
Try
Try
if Reg.OpenKeyReadOnly(RegistryKey) then
Begin
WordWrap.Checked:=Reg.ReadBool('Word wrap');
SkipDescr.Checked:=Reg.ReadBool('Skip description');
Indent.Checked:=Reg.ReadBool('Do indent para');
Hyph.Checked:=Reg.ReadBool('Hyphenate');
WidthEdit.Text:=IntToStr(Reg.ReadInteger('Text width'));
IndentEdit.Text:=IntToStr(Reg.ReadInteger('Indent width'));
CodePage:=Reg.ReadInteger('File codepage');
BrType:=Reg.ReadInteger('Line breaks type');
IgnoreStrongC.Checked:=Reg.ReadBool('Ignore strong');
IgnoreItalicC.Checked:=Reg.ReadBool('Ignore emphasis');
end;
Finally
Reg.Free;
end;
Except
end;
OnWWClick(Nil);
OnIndentClick(Nil);
TextWidthChange(Nil);
IndentWidthChange(Nil);
Filter:='Text files (*.txt)|*.txt|All files (*.*)|*.*';
Title:='FB2 to txt v0.17b by GribUser';
OnShow:=OnDialogShow;
DefaultExt:='txt';
end;
procedure TOpenPictureDialog.OnDialogShow;
Var
I:Integer;
VerInfo:TOSVersionInfo;
Begin
EncodingsList.AddItem('ANSI system default codepage',Pointer(CP_ACP));
EncodingsList.AddItem('OEM system default codepage',Pointer(CP_OEMCP));
EncodingsList.AddItem('MAC system default codepage',Pointer(CP_MACCP));
VerInfo.dwOSVersionInfoSize:=SizeOf(VerInfo);
GetVersionEx(VerInfo);
if VerInfo.dwPlatformId=VER_PLATFORM_WIN32_NT then
EncodingsList.AddItem('UTF-8',Pointer(CP_UTF8));// For WinNT only
EncodingsList.AddItem('UTF-16',Pointer(CP_UTF16));
For I:=1 to EncCount do
EncodingsList.AddItem(IntToStr(SupportedEncodings[i].CP)+' - '+SupportedEncodings[i].Name,
Pointer(SupportedEncodings[i].CP));
EncodingsList.ItemIndex:=EncodingsList.Items.IndexOfObject(Pointer(CodePage));
EncodingsList.OnChange:=OnCodePageChange;
For I:=1 to BrCount do
BRTypeList.AddItem(BRTypes[I].Name,Nil);
BRTypeList.ItemIndex:=BrType;
BRTypeList.OnChange:=OnBrTypeChange;
end;
procedure TOpenPictureDialog.DoShow;
var
PreviewRect, StaticRect: TRect;
begin
GetClientRect(Handle, PreviewRect);
StaticRect := GetStaticRect;
{ Move preview area to right of static area }
PreviewRect.Top:= StaticRect.Top + (StaticRect.Bottom - StaticRect.Top);
Inc(PreviewRect.Left, 10);
FChecksPanel.BoundsRect := PreviewRect;
FChecksPanel.ParentWindow := Handle;
inherited DoShow;
end;
procedure TOpenPictureDialog.DoClose;
begin
inherited DoClose;
{ Hide any hint windows left behind }
Application.HideHint;
end;
function TOpenPictureDialog.Execute;
Var
Reg:TRegistry;
begin
Template := 'DLGTEMPLATE2';
Options:=[ofOverwritePrompt,ofEnableSizing];
Result := inherited Execute;
if Result then
Begin
Reg:=TRegistry.Create(KEY_ALL_ACCESS);
Try
if Reg.OpenKey(RegistryKey,True) then
Begin
Reg.WriteBool('Word wrap',WordWrap.Checked);
Reg.WriteBool('Skip description',SkipDescr.Checked);
Reg.WriteBool('Do indent para',Indent.Checked);
Reg.WriteBool('Hyphenate',Hyph.Checked);
Reg.WriteInteger('Text width',TextWidth);
Reg.WriteInteger('Indent width',IndentWidth);
Reg.WriteInteger('File codepage',CodePage);
Reg.WriteInteger('Line breaks type',BrType);
Reg.WriteBool('Ignore strong',IgnoreStrongC.Checked);
Reg.WriteBool('Ignore emphasis',IgnoreItalicC.Checked);
end;
Finally
Reg.Free;
end;
end;
end;
end.
|
unit cCadRecibo;
interface
uses System.Classes, Vcl.Controls, cCadLancamento,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TRecibo = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_recibo: Integer;
F_cod_cheque: Integer;
F_descricao: string;
F_valor: Double;
F_data_recibo: TDateTime;
F_data_lancamento: TDateTime;
F_cargo: string;
F_cod_congregacao: Integer;
F_cod_operacao:Integer;
F_endereco: string;
F_bairro: string;
F_cidade:string;
F_uf:string;
F_cpf:string;
oLancamento: TLancamento;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_congregacao: Integer read F_cod_congregacao
write F_cod_congregacao;
property cod_operacao: Integer read F_cod_operacao
write F_cod_operacao;
property cod_recibo: Integer read F_cod_recibo write F_cod_recibo;
property cod_cheque: Integer read F_cod_cheque write F_cod_cheque;
property descricao: string read F_descricao write F_descricao;
property valor: Double read F_valor write F_valor;
property cargo: string read F_cargo write F_cargo;
property endereco: string read F_endereco write F_endereco;
property bairro: string read F_bairro write F_bairro;
property cidade: string read F_cidade write F_cidade;
property uf: string read F_uf write F_uf;
property cpf: string read F_cpf write F_cpf;
property data_recibo: TDateTime read F_data_recibo write F_data_recibo;
property data_lancamento: TDateTime read F_data_lancamento write F_data_lancamento;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TRecibo.Create;
begin
ConexaoDB := aConexao;
oLancamento := TLancamento.Create(ConexaoDB);
end;
destructor TRecibo.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TRecibo.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_recibo) + #13 + 'Descrição: ' + F_descricao, mtConfirmation,
[mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add
('DELETE FROM tb_recibo WHERE cod_recibo=:cod_recibo');
Qry.ParamByName('cod_recibo').AsInteger := F_cod_recibo;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result := false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TRecibo.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_recibo '+
' SET descricao=:descricao, data_recibo=:data_recibo, valor=:valor, endereco=:endereco, '+
' bairro=:bairro, cidade=:cidade, uf=:uf, cpf=:cpf, cod_operacao=:cod_operacao, '+
' data_lancamento=:data_lancamento, cod_congregacao=:cod_congregacao WHERE cod_recibo=:cod_recibo ');
Qry.ParamByName('cod_congregacao').AsInteger := F_cod_congregacao;
Qry.ParamByName('cod_operacao').AsInteger := F_cod_operacao;
Qry.ParamByName('cod_recibo').AsInteger := F_cod_recibo;
Qry.ParamByName('endereco').AsString := F_endereco;
Qry.ParamByName('descricao').AsString := F_descricao;
Qry.ParamByName('valor').AsFloat := F_valor;
Qry.ParamByName('data_recibo').AsDate := F_data_recibo;
Qry.ParamByName('data_lancamento').AsDate := F_data_lancamento;
Qry.ParamByName('bairro').AsString := F_bairro;
Qry.ParamByName('cidade').AsString := F_cidade;
Qry.ParamByName('uf').AsString := F_uf;
Qry.ParamByName('cpf').AsString := F_cpf;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TRecibo.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_recibo '+
' (descricao, data_recibo, valor, endereco, bairro, cidade, uf, cpf, cod_operacao, data_lancamento, cod_congregacao) '+
' VALUES(:descricao,:data_recibo,:valor,:endereco,:bairro,:cidade,:uf,:cpf,:cod_operacao, '+
' :data_lancamento,:cod_congregacao)');
Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao;
Qry.ParamByName('cpf').AsString := Self.F_cpf;
Qry.ParamByName('cod_operacao').AsInteger := Self.F_cod_operacao;
Qry.ParamByName('descricao').AsString := Self.F_descricao;
Qry.ParamByName('valor').AsFloat := Self.F_valor;
Qry.ParamByName('data_recibo').AsDate := Self.F_data_recibo;
Qry.ParamByName('data_lancamento').AsDate := Self.F_data_lancamento;
Qry.ParamByName('endereco').AsString := Self.F_endereco;
Qry.ParamByName('cidade').AsString := Self.F_cidade;
Qry.ParamByName('uf').AsString := Self.F_uf;
Qry.ParamByName('bairro').AsString := Self.F_bairro;
Qry.ParamByName('cod_operacao').AsInteger := Self.F_cod_operacao;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
//ENVIAR DADOS PARA O CADASTRO DE LANÇAMENTO
oLancamento.cod_entrada := 0;
oLancamento.cod_congregacao := Self.F_cod_congregacao;
oLancamento.nro_documento := Self.F_cod_operacao;
oLancamento.descricao := 'DOAÇÃO ASSISTÊNCIAL';
oLancamento.valor := Self.F_valor;
oLancamento.dta_movimento := Self.F_data_recibo;
oLancamento.tipo := 'SAIDA';
oLancamento.usuario_inclusao := '';
oLancamento.Inserir;
except
ConexaoDB.Rollback;
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TRecibo.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add
('SELECT cod_recibo, descricao, data_recibo, valor, endereco, bairro, cidade, '
+ ' uf, cpf, cod_operacao, data_lancamento,cod_congregacao ' +
' FROM tb_recibo WHERE cod_recibo=:cod_recibo ');
Qry.ParamByName('cod_recibo').AsInteger := id;
try
Qry.Open;
Self.F_cod_congregacao := Qry.FieldByName('cod_congregacao').AsInteger;
Self.F_cod_recibo := Qry.FieldByName('cod_recibo').AsInteger;
Self.F_cod_operacao := Qry.FieldByName('cod_operacao').AsInteger;
Self.F_cpf := Qry.FieldByName('cpf').AsString;
Self.F_descricao := Qry.FieldByName('descricao').AsString;
Self.F_valor := Qry.FieldByName('valor').AsFloat;
Self.F_data_recibo := Qry.FieldByName('data_recibo').AsDateTime;
Self.F_data_lancamento := Qry.FieldByName('data_lancamento').AsDateTime;
Self.F_endereco := Qry.FieldByName('endereco').AsString;
Self.F_bairro := Qry.FieldByName('bairro').AsString;
Self.F_cidade := Qry.FieldByName('cidade').AsString;
Self.F_uf := Qry.FieldByName('uf').AsString;
Self.F_cpf := Qry.FieldByName('cpf').AsString;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
// AKTools akFileUtils unit.
// Модуль, содержащий функции по работе с файлами.
//=============================================================================
unit akFileUtils;
interface
uses Classes, SysUtils, Windows;
type
//----------------------------------------------------------------------------
// Получает список всех вложенных файлов в директории Dir с маской Mask
TCustomTreeFileList = class(TObject)
private
FDir: string;
FMask: string;
fStopIt: boolean;
procedure FindRecurse(Folder: string; Mask: string);
procedure FindFiles(Folder: string; Mask: string);
protected
// Перекройте этот метод, для получения информации о найденных файлах.
procedure _Process(FileName: string); virtual;
// Если вернуть "false", то процесс поиска прекратится:
function _Process2(FileName: string): Boolean; virtual;
procedure Process(FileName: string);
public
constructor Create(dir: string; mask: string);
destructor Destroy; override;
procedure ProcessFind;
end;
// Ищет по каталогам N-ный (с нуля) файл, соответсвующий маске:
function FindFile(stfolder: string; Mask: string): string;
// Возвращает число файлов с указанной маской в указанном каталоге и всех
// его подкаталогах.
function GetFilesCount(dir, mask: string): Integer;
// Возвращает имя файла без расширения
function GetFileNameWOExt(fn: string): string;
// Добавляет "\" к имени директории, если это нужно
function GetDirectory(St: string): string;
// Возвращает путь к Program Files
function GetProgramFilesDir: string;
// Удаляет от имени FName путь CurFolder
function TrimPathToRelative(CurFolder, FName: string): string;
// Удаляет букву диска от имени файла
function GetRelativeDirectory(St: string): string;
// Возвращает полный путь к файлу по его относительному пути
function CompletePath(fn, CurDir: string): string;
// Удаляет из строки d1 все двойные "\" и "/", т.е. из
// строки "c:\\\\/tools\\txt" функция сделает "c:\tools\txt"
function RepairPathName(d1: string): string;
// Возвращает имя более низко расположенного каталога
function GetPrevFolder(path: string): string;
// Возвращает путь к файлу, преобразованный в unix-Формат (т.е. слэши направлены
// в другую сторону: "/")
function FileNameToUnix(path: string): string;
// Сравнивает два пути, игнорируя регистр букв и
// лишние "\", "/".
function CompareDirectoryes(d1, d2: string): Boolean;
// Создает файл, если таковой не существует
procedure CreateFileIfNotExists(fn: string);
// Копирует файл таким образом, что он во время копирования имеет атрибут
// Hidden, и только после копирования становится нормальынм.
procedure CopyFileHidden(src, targ: string);
// Получить имя временного файла (без расширения) (Dmitry Kudinov)
function CreateTempFileName: string;
// Возвращает уникальное имя файла с маской Mask для директории Dir.
// В маске должен присутствовать символ "#", заменяемый в процессе трансляции
// уникальным числовым идентификатором.
function MakeUniqueFileName(Dir: string; Mask: string = 'Untitled-#'): string;
// возвращает true - если fn похоже на имя файла. Если же строка начинается с
// ftp:// или http://, то пишется это урл и вернется false.
function IsFileName(fn: string): Boolean;
// возвраещет урл с отрезанными параметрами (если они есть):
// т.е. от http://www.aklabs.com/mycool.php?test=34&ar=34 останется только
// http://www.aklabs.com/mycool.php
function RemoveUrlParameters(url: string): string;
// Пишет строку в файл на диске:
procedure SaveStrToFile(fn, str: string);
// Возвращает системный путь:
// Folder - это CSIDL
function GetSystemPath(Folder: Integer): string;
// Возвращает каталог Application Data:
function GetAppDataFolder(AppName: string): string;
function GetMyDocFolder: string;
// Перемещает фолдер в другое место, показывая диалог копирования.
function MoveDir(const FromDir, ToDir: string): Boolean;
// Проверяет открыт ли файл уже на запись
function IsFileLocked(fn: string): boolean;
implementation
uses ShellApi, ShlObj, ActiveX;
resourcestring
exWrongMask = 'MakeUniqueFileName: Wrong mask "%s"';
// ================== GETFilesCount ===============================
type
TFileCountTreeFileList = class(TCustomTreeFileList)
private
fFileCount: Integer;
procedure _Process(FileName: string); override;
public
constructor Create(dir: string; mask: string);
end;
function GetFilesCount(dir, mask: string): Integer;
begin
with TFileCountTreeFileList.Create(dir, mask) do
try
ProcessFind;
Result := fFileCount;
finally
Free;
end;
end;
// ================== GETFilesCount ===============================
function RemoveUrlParameters(url: string): string;
var ps, ln: Integer;
begin
ps := Pos('?', url);
if ps > 0 then
ln := ps - 1
else
ln := maxint;
Result := Copy(url, 1, ln);
end;
function IsFileName(fn: string): Boolean;
begin
Result := (lowercase(Copy(Trim(fn), 1, 7)) <> 'mailto:') and
(pos('://', fn) = 0) and (fn <> '');
end;
function FileNameToUnix(path: string): string;
var i: Integer;
begin
Result := path;
for i := 1 to Length(Result) do
if Result[i] = '\' then Result[i] := '/';
end;
// Возвращает имя более низко расположенного каталога
function GetPrevFolder(path: string): string;
var
npath: string;
begin
npath := RepairPathName(path);
if Copy(npath, length(npath), 1) = '\' then
npath := Copy(npath, 1, length(npath) - 1);
Result := ExtractFilePath(npath);
end;
function GetProgramFilesDirByKeyStr(KeyStr: string): string;
var
dwKeySize: DWORD;
Key: HKEY;
dwType: DWORD;
begin
if RegOpenKeyEx(HKEY_LOCAL_MACHINE, PChar(KeyStr), 0, KEY_READ, Key) = ERROR_SUCCESS then
try
RegQueryValueEx(Key, 'ProgramFilesDir', nil, @dwType, nil, @dwKeySize);
if (dwType in [REG_SZ, REG_EXPAND_SZ]) and (dwKeySize > 0) then
begin
SetLength(Result, dwKeySize);
RegQueryValueEx(Key, 'ProgramFilesDir', nil, @dwType, PByte(PChar(Result)), @dwKeySize);
end
else
begin
RegQueryValueEx(Key, 'ProgramFilesPath', nil, @dwType, nil, @dwKeySize);
if (dwType in [REG_SZ, REG_EXPAND_SZ]) and (dwKeySize > 0) then
begin
SetLength(Result, dwKeySize);
RegQueryValueEx(Key, 'ProgramFilesPath', nil, @dwType, PByte(PChar(Result)), @dwKeySize);
end;
end;
finally
RegCloseKey(Key);
end;
end;
function GetProgramFilesDir: string;
const
DefaultProgramFilesDir = '%SystemDrive%\Program Files';
var
FolderName: string;
dwStrSize: DWORD;
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
FolderName := GetProgramFilesDirByKeyStr('Software\Microsoft\Windows NT\CurrentVersion');
if Length(FolderName) = 0 then
FolderName := GetProgramFilesDirByKeyStr('Software\Microsoft\Windows\CurrentVersion');
if Length(FolderName) = 0 then
FolderName := DefaultProgramFilesDir;
dwStrSize := ExpandEnvironmentStrings(PChar(FolderName), nil, 0);
SetLength(Result, dwStrSize);
ExpandEnvironmentStrings(PChar(FolderName), PChar(Result), dwStrSize);
Result := Trim(Result);
end;
function GetFileNameWOExt(fn: string): string;
begin
Result := Trim(Copy(fn, 1, Length(fn) - Length(ExtractFileExt(fn))));
end;
function GetDirectory(St: string): string;
begin
Result := St;
if Length(st) > 0 then
if not (st[Length(st)] in ['\', '/', ':']) then
Result := Trim(Result) + '\';
end;
function TrimPathToRelative(CurFolder, FName: string): string;
var cfr, fnr: string;
begin
cfr := GetDirectory(RepairPathName(CurFolder));
fnr := RepairPathName(FName);
if AnsiCompareText(Copy(fnr, 1, Length(cfr)), cfr) = 0 then
Result := Copy(fnr, Length(cfr) + 1, maxint)
else
Result := ExtractFileName(FName);
end;
function GetRelativeDirectory(St: string): string;
var ps: Integer;
begin
ps := Pos(':', St);
if ps = 0 then
Result := St
else
Result := Copy(st, ps + 1, Length(st) - ps);
end;
function CompletePath(fn, CurDir: string): string;
var LastDir: string;
begin
{ St := Copy(ExtractFileDrive(CurDir), 1, 1);
if Length(St) <> 1 then
raise EConvertError.Create('CompletePath failed'); }
GetDir(0, LastDir);
ChDir(CurDir);
Result := ExpandFileName(fn);
ChDir(LastDir);
end;
function RepairPathName(d1: string): string;
var i, p: Integer;
prevCh: Char;
begin
Result := d1; p := 0; prevCh := #0;
for i := 1 to Length(d1) do
begin
inc(p);
Result[p] := d1[i];
if d1[i] = '/' then Result[p] := '\';
if (d1[i] in ['\', '/']) and (i > 2) then
if (PrevCh in ['\', '/']) then
dec(p);
PrevCh := d1[i];
end;
SetLength(Result, p);
end;
function CompareDirectoryes(d1, d2: string): Boolean;
begin
Result := AnsiCompareText(GetDirectory(RepairPathName(d1)),
GetDirectory(RepairPathName(d2))) = 0;
end;
procedure CreateFileIfNotExists(fn: string);
begin
if not FileExists(fn) then
with TFileStream.Create(fn, fmCreate or fmShareDenyNone) do
Free;
end;
//******************************************************************************
//==============================================================================
// TCustomTreeFileList
//==============================================================================
//******************************************************************************
constructor TCustomTreeFileList.Create(dir, mask: string);
begin
FDir := GetDirectory(dir);
FMask := mask;
end;
destructor TCustomTreeFileList.Destroy;
begin
inherited;
end;
procedure TCustomTreeFileList.FindFiles(Folder, Mask: string);
var di: TSearchRec;
Res: Integer;
begin
Res := FindFirst(Folder + Mask, faAnyFile, di);
while Res = 0 do
begin
if not ((di.Attr and faDirectory) = faDirectory) then begin
Process(GetDirectory(Folder) + di.Name);
if fStopIt then break;
end;
Res := FindNext(di);
end;
sysUtils.FindClose(di);
end;
procedure TCustomTreeFileList.FindRecurse(Folder, Mask: string);
var di: TSearchRec;
Res: Integer;
Fldr: string;
begin
Res := FindFirst(Folder + '*.*', faAnyFile, di);
while Res = 0 do
begin
if (di.Name <> '.') and (di.Name <> '..') and ((di.Attr and faDirectory) = faDirectory) then
begin
Fldr := GetDirectory(Folder + di.Name);
FindFiles(Fldr, Mask);
if fStopIt then break;
FindRecurse(Fldr, Mask);
end;
Res := FindNext(di);
end;
SysUtils.FindClose(di);
end;
procedure TCustomTreeFileList.Process(FileName: string);
begin
_Process(FileName);
if not _Process2(FileName) then
fStopIt := true;
end;
procedure TCustomTreeFileList.ProcessFind;
begin
fStopIt := false;
FindFiles(FDir, FMask);
FindRecurse(FDir, FMask);
end;
function CreateTempFileName: string;
var
a: integer;
Hour, Min, Sec, MSec: word;
begin
DecodeTime(Time, Hour, Min, Sec, MSec);
a := MSec + Sec * 100 + Min * 10000 + Hour * 1000000;
Result := IntToHex(a, 8);
end;
function MakeUniqueFileName(Dir: string; Mask: string = 'Untitled-#'): string;
var i: Integer;
dr, fn: string;
begin
if Pos('#', Mask) = -1 then
raise Exception.CreateFmt(exWrongMask, [Mask]);
dr := GetDirectory(Dir);
for i := 1 to MaxInt do
begin
fn := StringReplace(Mask, '#', IntToStr(i), []);
if not FileExists(dr + fn) then
begin
Result := fn;
Break;
end;
end;
end;
{ TFileCountTreeFileList }
procedure TFileCountTreeFileList._Process(FileName: string);
begin
inc(fFileCount);
end;
constructor TFileCountTreeFileList.Create(dir, mask: string);
begin
inherited Create(dir, mask);
fFileCount := 0;
end;
function GetSystemPath(Folder: Integer): string;
var
PIDL: PItemIDList;
Path: LPSTR;
AMalloc: IMalloc;
begin
Path := StrAlloc(MAX_PATH);
SHGetSpecialFolderLocation(0, Folder, PIDL);
if SHGetPathFromIDList(PIDL, Path) then
Result := Path
else
Result := '';
SHGetMalloc(AMalloc);
AMalloc.Free(PIDL);
StrDispose(Path);
end;
function GetAppDataFolder(AppName: string): string;
begin
Result := GetSystemPath(CSIDL_APPDATA);
if Result = '' then
Result := GetDirectory(ExtractFilePath(ParamStr(0))) + 'AppData\'
else
Result := GetDirectory(Result) + AppName;
end;
function GetMyDocFolder: string;
begin
Result := GetSystemPath(CSIDL_PERSONAL);
Result := GetDirectory(Result);
end;
function MoveDir(const FromDir, ToDir: string): Boolean;
var
SH: SHFILEOPSTRUCT;
begin
FillChar(SH, SizeOf(SH), 0);
with SH do
begin
Wnd := 0;
wFunc := FO_MOVE;
pFrom := PChar(GetDirectory(FromDir) + '*' + #0);
pTo := PChar(ToDir + #0);
fFlags := FOF_NOCONFIRMMKDIR;
{or FOF_NOCONFIRMATION}
{or FOF_NOCONFIRMMKDIR}
{or FOF_RENAMEONCOLLISION}
{or FOF_SILENT};
end;
Result := SHFileOperation(SH) = 0;
if Result then
RemoveDirectory(PChar(FromDir));
end;
// ===============FindFile============================
type
TFileFindTreeFileList = class(TCustomTreeFileList)
private
fFileNum: Integer;
fFileNme: string;
fCurFile: Integer;
function _Process2(FileName: string): Boolean; override;
public
property FileNme: string read fFileNme write fFileNme;
property FileNum: Integer read fFileNum write fFileNum;
constructor Create(dir: string; mask: string);
end;
function FindFile(stfolder: string; Mask: string): string;
begin
Result := '';
with TFileFindTreeFileList.Create(stfolder, mask) do
try
ProcessFind;
Result := FileNme;
finally
Free;
end;
end;
{ TFileFindTreeFileList }
function TFileFindTreeFileList._Process2(FileName: string): Boolean;
begin
Result := True;
if FileNum = fCurFile then begin
FileNme := FileName;
Result := false;
end;
inc(fCurFile);
end;
constructor TFileFindTreeFileList.Create(dir, mask: string);
begin
inherited;
FileNum := 0;
FileNme := '';
fCurFile := 0;
end;
procedure TCustomTreeFileList._Process(FileName: string);
begin
{}
end;
function TCustomTreeFileList._Process2(FileName: string): Boolean;
begin
Result := true;
end;
procedure CopyFileHidden(src, targ: string);
var fhand: THandle;
buf: string;
attr: Integer;
rdsize: DWORD;
res: Boolean;
begin
with TFileStream.Create(src, fmOpenRead) do
try
SetLength(buf, Size);
ReadBuffer(buf[1], Length(buf));
finally
Free;
end;
attr := FileGetAttr(src);
fhand := CreateFile(PChar(targ), GENERIC_WRITE, 0, nil,
CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, 0);
if fhand = INVALID_HANDLE_VALUE then
raise EInOutError.CreateFmt('Unable to create file %s', [targ])
else begin
try
res := WriteFile(fhand, buf[1], Length(buf), rdsize, nil);
if (not res) or (Length(buf) <> Integer(rdsize)) then
raise EInOutError.CreateFmt('File write error (%s).', [targ]);
finally
CloseHandle(fhand);
end;
end;
if FileSetAttr(PChar(targ), attr) <> 0 then
raise Exception.CreateFmt('Unable to change file attribute (%s)', [targ]);
end;
function IsFileLocked(fn: string): boolean;
var hnd: THandle;
err: Integer;
begin
Result := False;
hnd := CreateFile(PChar(fn), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if hnd = INVALID_HANDLE_VALUE then begin
err := GetLastError;
Result := err <> 0;
end else
CloseHandle(hnd);
end;
procedure SaveStrToFile(fn, str: string);
var f: TFileStream;
begin
f := TFileStream.CreatE(fn, fmCreate);
try
f.WriteBuffer(str[1], Length(str));
finally
f.Free;
end;
end;
end.
|
unit vcmRepOperationsCollection;
{* Коллекция операций. }
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmRepOperationsCollection - }
{ Начат: 19.11.2003 13:44 }
{ $Id: vcmRepOperationsCollection.pas,v 1.4 2015/09/24 14:29:20 kostitsin Exp $ }
// $Log: vcmRepOperationsCollection.pas,v $
// Revision 1.4 2015/09/24 14:29:20 kostitsin
// {requestlink: 605157327 }
//
// Revision 1.3 2012/08/07 14:37:42 lulin
// {RequestLink:358352265}
//
// Revision 1.2 2003/11/19 15:18:41 law
// - bug fix: неправильно вычислялся _GroupID.
// - new behavior: дерегестрируем описатели операций из MenuManager'а.
//
// Revision 1.1 2003/11/19 11:38:25 law
// - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано.
//
{$I vcmDefine.inc }
interface
uses
Classes,
vcmBaseOperationsCollection
;
type
TvcmRepOperationsCollection = class(TvcmBaseOperationsCollection)
{* Коллекция операций. }
public
// public methods
class function GetItemClass: TCollectionItemClass;
override;
{-}
procedure RemoveHolder(anOpHolder : TObject);
overload;
{-}
end;//TvcmRepOperationsCollection
implementation
uses
vcmRepOperationsCollectionItem,
vcmOperationsCollectionItem
;
// start class TvcmRepOperationsCollection
class function TvcmRepOperationsCollection.GetItemClass: TCollectionItemClass;
//override;
{-}
begin
Result := TvcmRepOperationsCollectionItem;
end;
procedure TvcmRepOperationsCollection.RemoveHolder(anOpHolder : TObject);
//overload;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(Count) do
begin
Assert(anOpHolder is TvcmOperationsCollectionItem);
TvcmRepOperationsCollectionItem(Items[l_Index]).RemoveHolder(anOpHolder as TvcmOperationsCollectionItem);
end;
end;
end.
|
unit PlayerGif;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
SpeedBmp, PlayerAnim, CodingGif;
type
TGifPlayer =
class( TAnimPlayer )
private
fGifDecoder : TGifDecoder;
fTickCounter : integer;
protected
procedure ResetPalette; override;
procedure InitPlayer; override;
procedure DonePlayer; override;
procedure SetPaintFlags( Value : TPaintFlags ); override;
procedure SetStartingFrame( aStartingFrame : integer ); override;
procedure SetEndingFrame( aEndingFrame : integer ); override;
function GetStartingFrame : integer; override;
function GetEndingFrame : integer; override;
function GetKeyframed : boolean; override;
function GetAnimFrame : integer; override;
function GetAnimFrameCount : integer; override;
public
property GifDecoder : TGifDecoder read fGifDecoder;
constructor Create( AOwner : TComponent ); override;
procedure TimerTick; override;
procedure LoadFromStream( aStream : TStream ); override;
procedure SeekFrame( Index : integer ); override;
procedure Next; override;
function Empty : boolean; override;
class function TimerResolution : integer; override;
published
property OnFramePlayed;
property OnFinished;
property OnFrameCountPlayed;
property OnFatalException;
property AutoSize;
property Paused;
property Center;
property Stretch;
property Loop;
property Filename;
property StartingFrame;
property EndingFrame;
property ShareTimer;
property PaintFlags;
published
property Align;
property Visible;
property Enabled;
property ParentShowHint;
property ShowHint;
property PopupMenu;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property DragMode;
property DragCursor;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnStartDrag;
end;
// VCL Registration
procedure Register;
implementation
uses
WinUtils, GDI, ColorSpaces, Dibs, FlicPlayback,
MemUtils, NumUtils, ViewUtils;
{$R *.DCR}
// TGifPlayer
procedure TGifPlayer.TimerTick;
begin
inc( fTickCounter, fTimerInterval );
if fTickCounter >= fGifDecoder.FrameDelay[AnimFrame]
then
begin
fTickCounter := 0;
inherited;
end;
end;
constructor TGifPlayer.Create( AOwner : TComponent );
begin
inherited;
PlayFrom := pfAuto;
end;
function TGifPlayer.Empty : boolean;
begin
Result := ( GifDecoder = nil );
end;
const
LoadInMemoryThreshold = 512 * 1024;
procedure TGifPlayer.InitPlayer;
var
i, newInterval : integer;
begin
inherited;
with fAnimRect do
begin
Left := 0;
Top := 0;
Right := GifDecoder.Width;
Bottom := GifDecoder.Height;
end;
GifDecoder.OnFinished := Finished;
newInterval := GifDecoder.FrameDelay[1];
for i := 2 to GifDecoder.FrameCount do
NewInterval := mcd( NewInterval, GifDecoder.FrameDelay[i] );
if newInterval > 0
then TimerInterval := newInterval;
fAnimBuffer := TSpeedBitmap.CreateSized( AnimWidth, -AnimHeight, 8 );
with AnimBuffer do
begin
GifDecoder.AttachToDib( 0, 0, DibHeader, ScanLines );
ChangePaletteEntries( 0, GifDecoder.fDibHeader.biClrUsed, DibColors( GifDecoder.fDibHeader )^ );
if pfIgnorePalette in PaintFlags
then IgnorePalette := true;
if pfUseIdentityPalette in PaintFlags
then ForcePaletteIdentity( true, true );
end;
Changed;
Next;
end;
procedure TGifPlayer.DonePlayer;
begin
inherited;
FreeObject( fGifDecoder );
end;
class function TGifPlayer.TimerResolution : integer;
begin
Result := 15;
end;
procedure TGifPlayer.SetPaintFlags( Value : TPaintFlags );
var
FullUpdate : boolean;
begin
inherited;
FullUpdate := pfFullUpdate in Value;
if FullUpdate <> (pfFullUpdate in PaintFlags)
then
begin
if FullUpdate
then Include( fPaintFlags, pfFullUpdate )
else Exclude( fPaintFlags, pfFullUpdate );
end;
end;
procedure TGifPlayer.LoadFromStream( aStream : TStream );
begin
DonePlayer;
fGifDecoder := TGifDecoder.Create;
try
GifDecoder.LoadFromStream( aStream );
InitPlayer;
except
DonePlayer;
end;
end;
procedure TGifPlayer.Next;
begin
try
with GifDecoder do
begin
ProcessFrame;
inherited;
NextFrame;
end;
except
DonePlayer;
FatalException;
end;
end;
procedure TGifPlayer.SetStartingFrame( aStartingFrame : integer );
begin
if Assigned( GifDecoder )
then GifDecoder.StartingFrame := aStartingFrame;
inherited;
end;
procedure TGifPlayer.SetEndingFrame( aEndingFrame : integer );
begin
if Assigned( GifDecoder )
then GifDecoder.EndingFrame := aEndingFrame;
inherited;
end;
procedure TGifPlayer.SeekFrame( Index : integer );
begin
if Assigned( GifDecoder )
then GifDecoder.SeekFrame( Index );
inherited;
end;
function TGifPlayer.GetAnimFrame : integer;
begin
if Assigned( GifDecoder )
then Result := GifDecoder.CurrentFrameIndx
else Result := 0;
end;
function TGifPlayer.GetAnimFrameCount : integer;
begin
if Assigned( GifDecoder )
then Result := GifDecoder.FrameCount
else Result := 0;
end;
function TGifPlayer.GetKeyframed : boolean;
begin
Result := false;
end;
function TGifPlayer.GetStartingFrame : integer;
begin
if Assigned( GifDecoder )
then Result := GifDecoder.StartingFrame
else Result := 1;
end;
function TGifPlayer.GetEndingFrame : integer;
begin
if Assigned( GifDecoder )
then Result := GifDecoder.EndingFrame
else Result := -1;
end;
procedure TGifPlayer.ResetPalette;
var
bakCurrentFrame : integer;
begin
bakCurrentFrame := AnimFrame;
SeekFrame( 1 ); // Make sure we replay the palette chunk
SeekFrame( bakCurrentFrame );
end;
// Registration
procedure Register;
begin
RegisterComponents( 'Merchise', [TGifPlayer] );
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-10-22
描述: 运行信息摘要
*******************************************************************************}
unit UFrameSummary;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, StdCtrls, ExtCtrls;
type
TfFrameSummary = class(TfFrameBase)
GroupBox1: TGroupBox;
Timer1: TTimer;
BtnRefresh: TButton;
EditSrvTcp: TLabeledEdit;
EditSrvHttp: TLabeledEdit;
GroupBox3: TGroupBox;
EditNumTCPTotal: TLabeledEdit;
EditNumHttpTotal: TLabeledEdit;
EditNumTotal: TLabeledEdit;
EditNumConn: TLabeledEdit;
EditRegister: TLabeledEdit;
EditLogin: TLabeledEdit;
EditNumSHeart: TLabeledEdit;
EditNumDB: TLabeledEdit;
EditNumQuery: TLabeledEdit;
EditExecute: TLabeledEdit;
EditUpdates: TLabeledEdit;
EditNumTCPActive: TLabeledEdit;
EditNumHttpActive: TLabeledEdit;
EditNumTCPMax: TLabeledEdit;
EditNumHttpMax: TLabeledEdit;
EditNumActionError: TLabeledEdit;
EditRemote: TLabeledEdit;
procedure Timer1Timer(Sender: TObject);
procedure BtnRefreshClick(Sender: TObject);
private
{ Private declarations }
FCounterA: Integer;
//计数变量
procedure LoadROModuleStatus;
//载入状态
public
{ Public declarations }
procedure OnCreateFrame; override;
class function FrameID: integer; override;
end;
implementation
{$R *.dfm}
uses
UMgrControl, USysConst, UMgrDBConn, UROModule, ULibFun;
class function TfFrameSummary.FrameID: integer;
begin
Result := cFI_FrameSummary;
end;
procedure TfFrameSummary.OnCreateFrame;
begin
FVerCentered := True;
end;
//Desc: 刷新参数
procedure TfFrameSummary.BtnRefreshClick(Sender: TObject);
begin
BtnRefresh.Enabled := False;
try
LoadROModuleStatus;
finally
BtnRefresh.Enabled := True;
end;
end;
procedure TfFrameSummary.Timer1Timer(Sender: TObject);
begin
Inc(FCounterA);
if FCounterA >= 2 then
begin
FCounterA := 0;
LoadROModuleStatus;
end;
end;
//Desc: 远程模块运行状态
procedure TfFrameSummary.LoadROModuleStatus;
begin
with ROModule.LockModuleStatus^ do
try
if FSrvTCP then
EditSrvTcp.Text := Format('工作中 端口: %d', [gROModuleParam.FPortTCP])
else EditSrvTcp.Text := '已关闭';
if FSrvHttp then
EditSrvHttp.Text := Format('工作中 端口: %d', [gROModuleParam.FPortHttp])
else EditSrvHttp.Text := '已关闭';
EditRemote.Text := gROModuleParam.FRemoteURL;
//remote service
EditNumTCPTotal.Text := Format('%d 次', [FNumTCPTotal]);
EditNumTCPActive.Text := Format('%d 个', [FNumTCPActive]);
EditNumTCPMax.Text := Format('%d 个', [FNumTCPMax]);
EditNumHttpTotal.Text := Format('%d 次', [FNumHttpTotal]);
EditNumHttpActive.Text := Format('%d 个', [FNumHttpActive]);
EditNumHttpMax.Text := Format('%d 个', [FNumHttpMax]);
EditNumTotal.Text := Format('%d 次', [FNumConn+FNumDB]);
EditNumDB.Text := Format('%d 次', [FNumDB]);
EditNumConn.Text := Format('%d 次', [FNumConn]);
EditNumSHeart.Text := Format('%d 次', [FNumSweetHeart]);
EditLogin.Text := Format('%d 次', [FNumSignIn]);
EditRegister.Text := Format('%d 次', [FNumRegister]);
EditNumQuery.Text := Format('%d 次', [FNumSQLQuery]);
EditExecute.Text := Format('%d 次', [FNumSQLExecute]);
EditUpdates.Text := Format('%d 次', [FNumSQLUpdates]);
EditNumActionError.Text := Format('%d 次', [FNumActionError]);
finally
ROModule.ReleaseStatusLock;
end;
end;
initialization
gControlManager.RegCtrl(TfFrameSummary, TfFrameSummary.FrameID);
end.
|
{ Subroutine SST_R_SYN_DECLARE
*
* Process DECLARE syntax, which declares the existance of a symbol.
}
module sst_r_syn_declare;
define sst_r_syn_declare;
%include 'sst_r_syn.ins.pas';
procedure sst_r_syn_declare; {process DECLARE syntax}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {tag from syntax tree}
syname: string_var32_t; {name of syntax symbol being declared}
prname: string_var32_t; {name of procedure to run syntax}
token: string_var16_t; {scratch string for number conversion}
flags: sst_symflag_t; {flags for SST subroutine name symbol}
data_p: symbol_data_p_t; {pointer to user data in hash table entry}
func_p: sst_symbol_p_t; {pnt to syntax parsing function being defined}
sym_p: sst_symbol_p_t; {scratch pointer to a SST symbol}
arg_p: sst_proc_arg_p_t; {pointer to info about subroutine argument}
dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t;
label
opt_tag, done_opt_tags, trerr;
begin
syname.max := sizeof(syname.str); {init local var strings}
prname.max := sizeof(prname.str);
token.max := sizeof(token.str);
if not syn_trav_next_down (syn_p^) {down into DECLARE syntax}
then goto trerr;
tag := syn_trav_next_tag (syn_p^); {get symbol name tag}
if tag <> 1 then begin
syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'syerr_declare', nil, 0);
end;
syn_trav_tag_string (syn_p^, syname); {get the symbol name}
{
* Init to defaults before processing options.
}
prname.len := 0; {subroutine name not explicitly set}
flags := []; {syntax subroutine will be local to this file}
{
* Back here to get each optional tag.
}
opt_tag:
tag := syn_trav_next_tag (syn_p^); {get tag for next option, if any}
case tag of
1: begin {tag is for subroutine name}
syn_trav_tag_string (syn_p^, prname); {get the subroutine name}
flags := flags + [sst_symflag_global_k]; {subroutine will be globally visible}
end;
2: begin {tag is EXTERNAL option}
flags := flags + [sst_symflag_extern_k]; {subroutine not defined here}
end;
syn_tag_end_k: begin {done processing all the optional tags}
if prname.len = 0 then begin {need to make subroutine name ?}
string_copy (prefix, prname); {init subroutine name with prefix}
prname.len := min(prname.len, prname.max - 6); {leave room for suffix}
string_appendn (prname, '_sy', 3);
string_f_int_max_base ( {make subroutine sequence number string}
token, {output string}
seq_subr, {input number}
10, {base}
3, {field width}
[string_fi_leadz_k, string_fi_unsig_k], {write leading zeros, no sign}
stat);
if sys_error(stat) then begin
sys_msg_parm_vstr (msg_parm[1], syname);
syn_error_bomb (syn_p^, stat,
'sst_syn_read', 'seq_subr_err', msg_parm, 1);
end;
string_append (prname, token); {make full subroutine name}
seq_subr := seq_subr + 1; {update sequence number for next time}
string_downcase (prname); {default subroutine names are lower case}
end;
goto done_opt_tags; {all done processing tags}
end;
otherwise
syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'syerr_declare', nil, 0);
sys_bomb;
end; {end of optional tag type cases}
goto opt_tag; {back for next optional tag}
done_opt_tags: {done processing optional tags}
if not syn_trav_up (syn_p^)
then goto trerr;
string_upcase (syname); {SYN file symbols are case-insensitive}
{
* All done reading the input stream for this SYMBOL command. The SYN file
* symbol name is in SYNAME, and the subroutine name is in PRNAME.
*
* Create the new SYN symbol.
}
sst_r_syn_sym_add (syname, data_p); {add name to table, bomb if already there}
{
* Create the SST procedure. FUNC_P will be left pointing to the procedure
* descriptor.
}
sst_symbol_new_name ( {add function name to SST symbol table}
prname, func_p, stat);
syn_error_bomb (syn_p^, stat, '', '', nil, 0);
data_p^.sym_p := func_p; {point SYN symbol to the SST symbol}
sst_scope_new; {create private scope for new function}
sst_scope_p^.symbol_p := func_p; {set pointer to top symbol for this scope}
{
* Create the SYN dummy argument. ARG_P will be left pointing to the
* argument descriptor.
}
sst_symbol_new_name ( {create symbol for arg inside routine}
string_v('syn'(0)), sym_p, stat);
syn_error_bomb (syn_p^, stat, '', '', nil, 0);
sst_mem_alloc_scope (sizeof(arg_p^), arg_p); {alloc memory for subr arg descriptor}
sym_p^.symtype := sst_symtype_var_k; {symbol is a variable}
sym_p^.flags := [sst_symflag_def_k]; {symbol is defined}
sym_p^.var_dtype_p := sym_syn_t_p^.dtype_dtype_p; {variable's data type}
sym_p^.var_val_p := nil; {no initial value}
sym_p^.var_arg_p := arg_p; {to arg descriptor when dummy arg}
sym_p^.var_proc_p := addr(func_p^.proc); {procedure this is dummy arg of}
sym_p^.var_com_p := nil; {not in a common block}
sym_p^.var_next_p := nil; {no next var in common block}
arg_p^.next_p := nil; {init to no following argument in list}
arg_p^.sym_p := sym_p; {point to symbol for the function argument}
arg_p^.name_p := nil; {arg name when arg in routine template}
arg_p^.exp_p := nil; {expression when routine is called}
arg_p^.dtype_p := sym_p^.var_dtype_p; {data type of the argument}
arg_p^.pass := sst_pass_ref_k; {argument is passed by reference}
arg_p^.rwflag_int := {access permission inside the routine}
[sst_rwflag_read_k, sst_rwflag_write_k];
arg_p^.rwflag_ext := {access permission of routine in called code}
[sst_rwflag_read_k, sst_rwflag_write_k];
arg_p^.univ := false; {not allowed to match any data type}
{
* Create the data type descriptor for this routine. DT_P will be left
* pointing to the data type descriptor.
}
sst_dtype_new (dt_p); {create PROC data type descriptor}
dt_p^.symbol_p := func_p; {point to symbol representing this data type}
dt_p^.dtype := sst_dtype_proc_k; {this dtype is a procedure}
dt_p^.bits_min := 0; {fill in benign data size and alignment values}
dt_p^.align_nat := 1;
dt_p^.align := 1;
dt_p^.size_used := 0;
dt_p^.size_align := 0;
dt_p^.proc_p := addr(func_p^.proc); {set pointer to procedure descriptor}
{
* Fill in the procedure descriptor for the syntax parsing function that will
* be associated with the SYN symbol being declared. FUNC_P is pointing to
* the procedure descriptor to fill in.
}
func_p^.proc_scope_p := sst_scope_p; {save pointer to routine's scope}
func_p^.symtype := sst_symtype_proc_k; {symbol is a routine}
func_p^.flags := flags; {init EXTERN, etc, as known now}
func_p^.proc.sym_p := func_p; {point routine descriptor to name symbol}
func_p^.proc.dtype_func_p := sst_dtype_bool_p; {function value data type}
func_p^.proc.n_args := 1; {number of arguments the routine takes}
func_p^.proc.flags := []; {init separate flags}
func_p^.proc.first_arg_p := arg_p; {point to first argument in list}
func_p^.proc_scope_p := sst_scope_p; {scope inside the routine}
func_p^.proc_dtype_p := dt_p; {routine's "data type"}
func_p^.proc_funcvar_p := nil; {init to no var that is func ret value yet}
sst_scope_old; {pop back from subroutine's scope}
return;
{
* The syntax tree is not as expected. We assume this is due to a syntax
* error.
}
trerr:
sys_message ('sst_syn_read', 'syerr_declare');
syn_parse_err_show (syn_p^);
sys_bomb;
end;
|
unit Debug;
interface
uses
SysUtils;
//{$define _NODEBUG}
const
Debugging = {$ifndef _NODEBUG} true {$else} false {$endif};
Logging = Debugging and true;
{$ifndef _NODEBUG}
const
BreakOnError = false;
SaveToLogFile = true;
LogTime = true;
type
EDebug =
class(Exception)
destructor Destroy; override;
end;
{$else}
type
EDebug = class(Exception);
{$endif}
procedure Assert(cond : boolean; const msg : string);
procedure DebugError(const msg : string);
procedure LogThis(const msg : string);
procedure BrowseObject(obj : TObject);
procedure UnbrowseObject(obj : TObject);
procedure WriteDebugStr(which : string); // protected
procedure DebugBreakPoint;
implementation
{$ifndef _NODEBUG}
uses
Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, StrUtils, ComCtrls;
type
TLogForm =
class(TForm)
public
constructor CreateNew(aOwner : TComponent);
destructor Destroy; override;
public
procedure WriteStrs(const msgs : array of string);
procedure WriteStr(const msg : string);
protected
procedure Resize; override;
procedure SaveToFile;
private
Messages : TRichEdit;
procedure MessagesDblClick(Sender: TObject);
procedure MessagesKeyDown(Sender : TObject; var Key : word; Shift : TShiftState);
procedure OnLogDestroy(Sender : TObject);
end;
type
TBrowser =
class
public
constructor CreateNew(aOwner : TComponent);
destructor Destroy; override;
public
procedure Browse(obj : TObject);
procedure Unbrowse(obj : TObject);
private
//Objects : TList;
//procedure FreeList;
end;
var
LogForm : TLogForm = nil;
Browser : TBrowser = nil;
// TLogForm
constructor TLogForm.CreateNew(aOwner : TComponent);
begin
inherited;
OnDestroy := OnLogDestroy;
Width := Screen.Width;
Height := Screen.Height div 5;
Messages := TRichEdit.Create(Self);
with Messages do
begin
Align := alClient;
OnDblClick := MessagesDblClick;
OnKeyDown := MessagesKeyDown;
ScrollBars := ssBoth;
WordWrap := false;
PlainText := true;
Parent := Self;
Lines.Add('*** ' + UpperCase(ParamStr(0)) + ' LOG FILE. ' + DateTimeToStr(Now) + ' ***'^M^J);
end;
end;
destructor TLogForm.Destroy;
begin
if LogForm = Self
then LogForm := nil;
inherited;
end;
procedure TLogForm.WriteStrs(const msgs : array of string);
var
i : integer;
s : string;
begin
s := msgs[low(msgs)];
for i := succ(low(msgs)) to high(msgs) do
s := s + msgs[i];
WriteStr(s);
end;
procedure TLogForm.WriteStr(const msg : string);
begin
Messages.Lines.Add(msg);
end;
procedure TLogForm.Resize;
const
ButtonsAreaHeight = 70;
begin
inherited;
Messages.Height := Height - ButtonsAreaHeight;
end;
procedure TLogForm.SaveToFile;
begin
if SaveToLogFile
then Messages.Lines.SaveToFile(ChangeFileExt(ParamStr(0), '.LOG'));
end;
procedure TLogForm.MessagesDblClick(Sender: TObject);
begin
Messages.Clear;
end;
procedure TLogForm.MessagesKeyDown(Sender : TObject; var Key : word; Shift : TShiftState);
begin
case Key of
ord('S') :
if ssCtrl in Shift
then SaveToFile;
end;
end;
procedure TLogForm.OnLogDestroy(Sender : TObject);
begin
SaveToFile;
end;
// TBrowser
constructor TBrowser.CreateNew(aOwner : TComponent);
begin
inherited;
end;
destructor TBrowser.Destroy;
begin
if Browser = Self
then Browser := nil;
inherited;
end;
procedure TBrowser.Browse(obj : TObject);
begin
end;
procedure TBrowser.Unbrowse(obj : TObject);
begin
end;
(*
procedure TBrowser.FreeList;
begin
end;
*)
// Misc
procedure WriteDebugStr(which : string);
begin
OutputDebugString(pchar(which));
if IsConsole
then writeln(which)
else
begin
if LogForm = nil
then LogForm := TLogForm.CreateNew(Application);
if not LogForm.Showing
then LogForm.Show;
LogForm.WriteStr(which);
end;
end;
procedure DebugBreakPoint;
begin
DebugBreak;
end;
procedure LocalLog(const logo, msg : string);
var
s : string;
begin
if LogTime
then s := FormatDateTime('hh:nn:ss <', Time)
else s := '';
s := s + logo + '> ' + msg;
WriteDebugStr(s);
end;
procedure Assert(cond : boolean; const msg : string);
begin
if not cond
then
begin
LocalLog('A', msg);
if BreakOnError
then DebugBreak;
end;
end;
procedure DebugError(const msg : string);
begin
LocalLog('E', msg);
if BreakOnError
then DebugBreak;
end;
procedure LogThis(const msg : string);
begin
LocalLog('L', msg);
end;
procedure BrowseObject(obj : TObject);
begin
end;
procedure UnbrowseObject(obj : TObject);
begin
end;
// EDebug
destructor EDebug.Destroy;
begin
LocalLog('X', 'Destroying: ' + Message);
inherited;
end;
{$else}
procedure WriteDebugStr(which : string);
begin
end;
procedure DebugBreakPoint;
begin
end;
procedure DebugError(const msg : string);
begin
end;
procedure LocalLog(const logo, msg : string);
begin
end;
procedure Assert(cond : boolean; const msg : string);
begin
end;
procedure LogThis(const msg : string);
begin
end;
procedure BrowseObject(obj : TObject);
begin
end;
procedure UnbrowseObject(obj : TObject);
begin
end;
{$endif}
end.
|
unit ZMOprZip;
// ZMZipOpr.pas - Zip operation
(* ***************************************************************************
TZipMaster VCL originally by Chris Vleghert, Eric W. Engler.
Present Maintainers and Authors Roger Aelbrecht and Russell Peters.
Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler
Copyright (C) 1992-2008 Eric W. Engler
Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht
Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht
The MIT License (MIT)
Copyright (c) 2014, 2015 delphizip
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.
contact: problems AT delphizip DOT org
updates: http://www.delphizip.org
*************************************************************************** *)
// modified 2015-05-21
interface
{$Include '.\ZipVers.inc'}
{$ALIGN ON}
{$BOOLEVAL OFF} // important: must be off!
{$LONGSTRINGS ON}
{$EXTENDEDSYNTAX ON}
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
{$TYPEDADDRESS ON}
{$WRITEABLECONST OFF}
uses
{$IFDEF VERDXE2up} // Delphi XE2 or newer
System.Classes, WinApi.Windows,
{$ELSE}
Classes, Windows,
{$ENDIF}
ZMHandler;
// {$DEFINE ZDEBUG}
{$DEFINE _DEBUG_CAUGHT}
type
TZMOpZips = class(TZMOperationRoot)
public
function Changes: TZMOperRes; override;
// function Execute(TheBody: TZMHandler): Integer; override;
// function Name: string; override;
function Needs: TZMOperRes; override;
end;
type
TZMOpZip = class(TZMOpZips)
public
// function Changes: TZMOperRes; override;
function Execute(TheBody: TZMHandler): Integer; override;
function Name: string; override;
end;
implementation
uses
{$IFDEF VERDXE2up} // Delphi XE2 or newer
System.SysUtils, VCL.Controls, VCL.Graphics, VCL.Dialogs, System.Contnrs,
{$ELSE}
SysUtils, Controls, Graphics, Dialogs,
{$ENDIF}
Forms, ZipMstr, ZMBody, ZMBaseOpr, ZMXcpt, ZMFileOpr, ZMLister,
ZMMsg, ZMUtils, ZMDrv, ZMStructs, ZMUTF8, ZMReader, ZMWinFuncsU,
ZMWinFuncsA, ZMFileIO, ZMWriter, ZMCore, ZMCommand, ZMMaker, ZMEntryMaker,
ZMCollector, ZMDirectory, ZMHuntMisc, ZMNameUtils, ZMDiags,
ZMEntryWriter, ZMHunter, ZMCentral;
const
__UNIT__ = 49;
const _U_ = (__UNIT__ shl ZERR_LINE_SHIFTS);
type
TZMZipOpr = class(TZMFileOpr)
private
FCollector: TZMCollector;
WritingNewZip: Boolean;
function CheckDestination: Integer;
procedure FinishAddOperations(var Error: Integer);
procedure HailSuccesses(DfltZip: TZMWriter);
function IsDestWritable(const Fname: string; AllowEmpty: Boolean): Boolean;
procedure RemoveCompletedFiles;
procedure ResetArchive(const XName: string);
procedure ResetArchiveBits(DfltZip: TZMWriter);
function WriteTheZip: Integer;
protected
procedure CreateInterimZip; override;
function FinalizeInterimZip(OrigZip: TZMReader): Integer; override;
procedure PrepareInterimZip; override;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
// TODO: CanAppend
// function CanAppend(const OrigZip: TZMReader): boolean;
function ZipFiles: Integer;
end;
const
EventChangedIt = 16;
{ TZMOpZips }
function TZMOpZips.Changes: TZMOperRes;
begin
Result := [ZorFSpecArgs, ZorZip];
end;
function TZMOpZips.Needs: TZMOperRes;
begin
Result := [ZorFSpecArgs];
end;
function TZMOpZip.Execute(TheBody: TZMHandler): Integer;
var
FOper: TZMZipOpr;
begin
FOper := TZMZipOpr.Create(TheBody as TZMLister);
AnOperation := FOper;
Result := FOper.ZipFiles;
end;
function TZMOpZip.Name: string;
begin
Result := 'Add';
end;
procedure TZMZipOpr.AfterConstruction;
begin
inherited;
FCollector := TZMCollector.Create(Lister);
end;
procedure TZMZipOpr.BeforeDestruction;
begin
FCollector.Free;
inherited;
end;
function TZMZipOpr.CheckDestination: Integer;
var
Curz: TZMReader;
DestPath: string;
MultiDisk: Boolean;
begin
Curz := Current;
if Curz.ArchiveName = '' then
Curz.ArchiveName := ZipFileName;
Curz.WorkDrive.HasMedia(False);
MultiDisk := ZwoDiskSpan in WriteOptions;
// drive must exist and be changeable
Result := Curz.RefuseWriteSplit; //TODO: is still needed?
if Result = 0 then
begin
// make certain destination can exist
{ We must allow a zipfile to be specified that doesn't already exist,
so don't check here for existance. }
if (Curz.WorkDrive.DriveIsFixed or not MultiDisk) then
begin
DestPath := ExtractFilePath(ZipFileName);
if ZwoForceDest in WriteOptions then
_Z_ForceDirectory(DestPath);
if not _Z_DirExists(DestPath) then
begin
Result := Body.PrepareErrMsg(ZE_NoDestDir, [DestPath], _U_ + 190);
exit;
end;
end;
end;
if (Result = 0) and not IsDestWritable(ZipFileName, MultiDisk) then
Result := Body.PrepareErrMsg(ZE_NotChangeable, [ZipFileName], _U_ + 197);
end;
procedure TZMZipOpr.CreateInterimZip;
var
DidIt: Boolean;
begin
InterimZip := TZMMaker.Create(Lister);
if WritingNewZip then
DidIt := InterimZip.File_Create(Lister.ZipFileName)
else
DidIt := true;// InterimZip.File_CreateTemp(PRE_INTER, '');
if not DidIt then
raise EZipMaster.CreateMsg(Body, ZE_NoOutFile, _U_ + 210);
end;
function TZMZipOpr.FinalizeInterimZip(OrigZip: TZMReader): Integer;
var
Entry: TZMEntryWriter;
FailedToAppend: Boolean;
LastKept: Integer;
Offset: Int64;
Part: Integer;
I: Integer;
OrigEntry: TZMCentralItem;
begin
if WritingNewZip then
begin
Result := InterimZip.Commit(ZwoZipTime in WriteOptions);
InterimZip.File_Close;
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, _U_ + 223);
end
else
begin
FailedToAppend := True;
// if TZMCopier(InterimZip).CanModifySourceZip(Part, Offset, OrigZip) then
if TZMCopier(InterimZip).CanAppendToSourceZip(OrigZip, LastKept) then
begin
FailedToAppend := False;
// what ?
Body.DiagStr(ZInform, 'Should be able to append after ' + IntToStr(LastKept), _U_+231);
if LastKept = (OrigZip.Count - 1) then
begin
Part := OrigZip.CentralDiskNo;
Offset := OrigZip.CentralOffset;
end
else
begin
Part := OrigZip[LastKept + 1].StartOnDisk;
Offset := OrigZip[LastKept + 1].RelOffLocalHdr;
end;
Body.DiagStr(ZInform, 'Should be able to append: ' + IntToStr(Part) + ', ' + IntToStr(Offset), _U_+242);
// copy details of kept entries
for I := 0 to LastKept do
begin
OrigEntry := OrigZip[I];
Entry := InterimZip[I];
// check same name
if not SameStr(OrigEntry.FileName, Entry.FileName) then
begin
Body.DiagStr(ZInform, 'Could not append: ' + OrigEntry.FileName + ' <> ' + Entry.FileName, _U_+242);
FailedToAppend := True;
Break;
end;
// Entry.Free;
Entry := TZMEntryKeeper.Create(InterimZip);
TZMMaker(InterimZip).Items[I] := Entry;
Entry.AssignFrom(OrigEntry);
end;
if not FailedToAppend then
begin
OrigZip.File_Close;
//TODO: seek correct disk
if not InterimZip.File_Open(OrigZip.RealFileName, fmOpenReadWrite or fmShareExclusive) then
raise EZipMaster.CreateMsg(Body, ZE_NoOutFile, _U_ + 247);
if InterimZip.Seek(Offset, soBeginning) <> Offset then
raise EZipMaster.CreateMsg(Body, ZE_SeekError, _U_ + 247);
InterimZip.IsTemp := False;
raise EZipMaster.CreateMsg(Body, -1, _U_ + 277);
end;
end ;
if FailedToAppend then
begin
if not InterimZip.File_CreateTemp(PRE_INTER, '') then
raise EZipMaster.CreateMsg(Body, ZE_NoOutFile, _U_ + 253);
Result := inherited FinalizeInterimZip(OrigZip);
end;
{ if OrigZip = nil then
OrigZip := Lister.Current;
OrigZip.File_Reopen(FmOpenRead or FmShareDenyWrite);
Result := InterimZip.Commit(ZwoZipTime in WriteOptions);
OrigZip.File_Close;
InterimZip.File_Close;
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, _U_ + 380);
PrepareZip(OrigZip);
// Recreate like orig
Result := Recreate(InterimZip, OrigZip);
if Result < 0 then
raise EZipMaster.CreateMsg(Body, Result, _U_ + 385); }
end;
end;
procedure TZMZipOpr.FinishAddOperations(var Error: Integer);
begin
// Write proposed zip
if Error > 0 then
Error := WriteTheZip
else
if Error = 0 then
Error := ZMError(ZE_NothingToDo, _U_ + 258);
IncludeSpecs.Clear;
if Error >= 0 then
HailSuccesses(InterimZip);
if (Error > 0) and (AddResetArchive in Body.AddOptions) then
ResetArchiveBits(InterimZip);
if (Error > 0) and (AddMove in Body.AddOptions) then
RemoveCompletedFiles;
// Update the Zip Directory by calling List method
// for spanned exe avoid swapping to last disk
if SuccessCnt >= 0 then
Reload := ZlrReload // force reload
else
Reload := ZlrClear;
end;
procedure TZMZipOpr.HailSuccesses(DfltZip: TZMWriter);
var
I: Integer;
Rec: TZMEntryWriter;
begin
if DfltZip <> nil then
begin
for I := 0 to DfltZip.Count - 1 do
begin
Rec := DfltZip[I];
if Rec.Status[ZsbHail] then
IncludeSpecs.Add(Rec.Title);
end;
end;
end;
function TZMZipOpr.IsDestWritable(const Fname: string; AllowEmpty: Boolean):
Boolean;
var
HFile: Integer;
Sr: _Z_TSearchRec;
Wd: TZMWorkDrive;
Xname: string;
begin
Result := False;
Wd := TZMWorkDrive.Create(Body);
try
Xname := ExpandUNCFileName(Fname);
// test if destination can be written
Wd.DriveStr := Xname;
if not Wd.HasMedia(False) then
begin
Result := AllowEmpty and (Wd.DriveType = DRIVE_REMOVABLE);
// assume can put in writeable disk
Exit;
end;
if {$IFNDEF UNICODE}IsWinXP or {$ENDIF}(Wd.DriveType <> DRIVE_CDROM) then
begin
if _Z_FindFirst(Xname, FaAnyFile, Sr) = 0 then
begin
Result := (Sr.Attr and FaReadOnly) = 0;
_Z_FindClose(Sr);
if Result then
begin
// exists and is not read-only - test locked
HFile := _Z_FileOpen(Xname, FmOpenWrite);
Result := HFile > -1;
if Result then
{$IFDEF VERDXE2up}System.{$ENDIF}SysUtils.FileClose(HFile);
end;
Exit;
end;
// file did not exist - try to create it
HFile := _Z_FileCreate(Xname);
if HFile > -1 then
begin
Result := True;
{$IFDEF VERDXE2up}System.{$ENDIF}SysUtils.FileClose(HFile);
File_Delete(Xname);
end;
end;
finally
Wd.Free;
end;
end;
procedure TZMZipOpr.PrepareInterimZip;
begin
inherited;
if WritingNewZip then
InterimZip.ZipComment := Lister.ZipComment;
end;
procedure TZMZipOpr.RemoveCompletedFiles;
var
FullPath: string;
I: Integer;
SortedCatch: TZMCaughtItemList;
begin
SortedCatch := TZMCaughtItemList.Create;
try
SortedCatch.Capacity := FCollector.Count;
for I := 0 to FCollector.Count - 1 do
SortedCatch.Add(FCollector[I]);
SortedCatch.Sort(AlphaSort);
//{$IFDEF _DEBUG_CAUGHT}SortedCatch.DumpList('e:\tmp\Sortedfilelist.txt');{$ENDIF}
for I := SortedCatch.Count - 1 downto 0 do
begin
FullPath := SortedCatch[I].FullPath;
if SortedCatch[I].IsFolder then
begin
DiagStr(ZT_RemovingFolder, FullPath, _U_ + 365);
end
else
begin
DiagStr(ZT_Removing, FullPath, _U_ + 369);
//TODO: check read-only?
// if FileExists(FullPath) and not DeleteFile(FullPath) then
// Body.Trace('Failed to remove: ' + FullPath, {_LINE_}575, __UNIT__);
end;
end;
finally
SortedCatch.Free;
end;
end;
function AlphaSort1(Item1, Item2: pointer): integer;
var
L1: Integer;
L2: Integer;
S1: string;
S2: string;
T1: string;
T2: string;
begin
S1 := TZMCaughtItem(Item1).Name;
if TZMCaughtItem(Item1).IsFolder then
begin
T1 := S1;
L1 := -1;
end
else
begin
L1 := LastPos(S1, '\');
if L1 > 1 then
T1 := Copy(S1, 1, L1)
else
T1 := '\';
end;
S2 := TZMCaughtItem(Item2).Name;
if TZMCaughtItem(Item2).IsFolder then
begin
T2 := S2;
L2 := -1;
end
else
begin
L2 := LastPos(S2, '\');
if L2 > 1 then
T2 := Copy(S2, 1, L2)
else
T2 := '\';
end;
Result := CompareText(T1, T2);
if Result = 0 then
begin
if L1 < 0 then
T1 := ''
else
T1 := Copy(S1, L1+1, MAXINT);
if L2 < 0 then
T2 := ''
else
T2 := Copy(S2, L2+1, MAXINT);
Result := CompareText(T1, T2);
end;
end;
// TODO: CanAppend
//// ZsbError = $40; // processing error
//// ZsbDiscard = $80; // discard entry
//// ZsbUpdate = $100; // mark for updating
//// ZsbKeep = $800; // keep entry
//// ZsbToAdd = $1000; // new entry to be processed
//// ZsbUpdating = $4000; // updating existing entry
//
//function TZMZipOpr.CanAppend(const OrigZip: TZMReader): boolean;
//const
//ChangedStatus = ZsbError + ZsbDiscard + ZsbUpdate + ZsbToAdd + ZsbUpdating;
//var
//Changed: Integer;
//I: Integer;
//begin
//Result := OrigZip.Count > 0;
//// test if any Kept entries after modified entries
//Changed := -1;
//for I := 0 to OrigZip.Count - 1 do
//begin
// if OrigZip[I] = nil then
// Continue;
// if (OrigZip[I].StatusBits and ChangedStatus) <> 0 then
// begin
// if Changed < 0 then
// Changed := I;
// end
// else
// if Changed >= 0 then
// begin
// Result := False;
// Break;
// end;
//end;
//end;
procedure TZMZipOpr.ResetArchive(const XName: string);
begin
if (XName <> '') and (XName[1] <> '<') then
begin
if not SetFileAttributes(PChar(XName), GetFileAttributes(PChar(XName)) and
(not FILE_ATTRIBUTE_ARCHIVE)) then
begin
DiagStr(DFSys+ ZI_ArchiveBitCouldNotBeSetFor, XName, _U_ + 476);
//TODO: add to fails ?
end;
end;
end;
procedure TZMZipOpr.ResetArchiveBits(DfltZip: TZMWriter);
var
I: Integer;
Rec: TZMEntryWriter;
begin
Body.Progress.NewXtraItem('*resetting archive bits', SuccessCnt);
for I := 0 to DfltZip.Count - 1 do
begin
Rec := DfltZip[I];
if Rec.Status[ZsbHail] then
begin
ResetArchive(Rec.XName);
Body.Progress.AdvanceXtra(1);
end;
end;
Body.Progress.Clear;
end;
function TZMZipOpr.WriteTheZip: Integer;
var
DfltZip: TZMMaker;
ZipExists: Boolean;
begin
ZipExists := Lister.Count > 0;
WritingNewZip := (PathType(Lister.ZipFileName) <> ZptUNC) and not ZipExists;
PrepareInterimZip; // make zip to write to
DfltZip := InterimZip as TZMMaker;
{$IFDEF _DEBUG_CAUGHT}FCollector.DumpList('e:\tmp\WriteTheZip.txt');{$ENDIF}
if WritingNewZip then
Result := DfltZip.BuildNew(FCollector, False)
else
begin
if ZipExists and (Lister.Count > 0) then
Result := DfltZip.Merge(FCollector, Lister.Current)
else
Result := DfltZip.BuildNew(FCollector, ZipExists);
end;
if (Result > 0) and (FCollector.FoundStreams.Count > 0) then
Result := DfltZip.BuildStreams(FCollector.FoundStreams);
if Result >= 0 then
Result := FinalizeInterimZip(Lister.Current); // write results
if Result >= 0 then
SuccessCnt := TZMMaker(DfltZip).Successes;
end;
function TZMZipOpr.ZipFiles: Integer;
var
Hunter: TZMHunter;
begin
// Diag(ZT_StartupZipFiles, _U_ + 996);
if Lister.ZipFileName = '' then // make sure we have a zip filename
raise EZipMaster.CreateMsg(Body, ZE_NoZipSpecified, _U_ + 536);
if (IncludeSpecs.Count = 0) then
IncludeSpecs.Add(WILD_ALL); // do add all
Result := CheckDestination;
if Result < 0 then
Exit;
ShowProgress := ZspFull;
Hunter := TZMHunter.Create(Body);
try
// Hunter.KeepingEmpty := ZwoKeepEmpty in WriteOptions;
Result := Hunter.Hunt(FCollector);
finally
Hunter.Free;
end;
if Result < 0 then
DiagErr(ZT_HuntingFilesReturned, Result, _U_ + 554)
// DiagErr(ZT_CollectingFilesReturned, Result, _U_ + 1014)
else
DiagFmt(ZT_HuntingFilesCaughtFiles, [FCollector.Count], _U_ + 557);
// DiagFmt(ZT_CollectingFilesFoundFiles, [FCollector.Count], _U_ + 1017);
{$IFDEF _DEBUG_CAUGHT}FCollector.DumpList('e:\tmp\CaughtFiles.txt');{$ENDIF}
// Write proposed zip
FinishAddOperations(Result);
// Diag(ZT_FinishedAdd, _U_ + 1022);
end;
{There are still a few things missing in the various stages
C. 'unsafe' adds. (modifying the original zip).
}
end.
|
unit Com_Exception;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, Com_Sync, Winapi.ShlObj;
type
(* More actions could be added here as required. *)
ActionListType = ( NoLog, Display_SysMessg, Display_UserMessg, FreeException );
ActionList = set of ActionListType;
ENetworkDown = class( Exception );
EAccountPaymentAlreadyMade = class( Exception );
EDeleteTradedSKU = class( Exception );
EBDEConvertException = class( Exception );
(* Routine Handles the displaying and logging of all exceptions *)
Procedure HandleException
( E : Exception; const UserMessage : String; Actions : ActionList ); overload;
Procedure HandleException
( const UserMessage : String; Actions : ActionList ); overload;
Procedure HandleException
( const UserMessage : String ); overload;
Procedure HandleExceptionMsg
( const UserMessage : String; Actions : ActionList ); overload;
Procedure HandleExceptionMsg
( const UserMessage : String ); overload;
Procedure DebugLog( const UserMessage : String); overload;
Procedure DebugLog( const UserMessage : String; const Args : array of const); overload;
function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string;
type
TExceptionHandler = class
private
FFilename : String;
FModuleName : String;
FLock : TSyncObj;
FLastExcept : String;
FLastUserMsg : String;
FLastTime : TDateTime;
FTimes : Integer;
protected
public
constructor Create(AFileName : String = '');
destructor Destroy; override;
procedure HandleException( E : Exception; const UserMessage : String; Actions : ActionList ); overload;
procedure HandleException( const UserMessage : String; Actions : ActionList ); overload;
procedure HandleException( const UserMessage : String ); overload;
procedure HandleExceptionMsg( const UserMessage : String; Actions : ActionList ); overload;
procedure HandleExceptionMsg( const UserMessage : String ); overload;
property FileName : String read FFileName;
property ModuleName : String read FModuleName;
end;
TGlobalExceptionHandler = class(TExceptionHandler)
private
FDebugFileName : String;
public
constructor Create;
procedure DebugLog( const UserMessage : String; const Args : array of const); overload;
procedure DebugLog( const UserMessage : String ); overload;
end;
var
GlobalExceptionHandler : TGlobalExceptionHandler;
const
C_Max_Log_Size = 2048 * 1024;
procedure CreateGlobalExceptionHandler;
implementation
uses
FileCtrl, Com_Streams;
{ TExceptionHandler }
function GetDatabaseDirectory: String;
begin
Result := GetSpecialFolderPath(CSIDL_APPDATA, False);
//CSIDL_LOCAL_APPDATA go to C:\Users\stevenw.QTECH<user name>\AppData\Local
//CSIDL_APPDATA go to C:\Users\stevenw.QTECH<user name>\AppData\Roaming
//CSIDL_MYDOCUMENTS go to C:\Users\stevenw.QTECH<user name>\Documents
//CSIDL_COMMON_DOCUMENTS go to C:\Users\Public\Documents
//CSIDL_COMMON_APPDATA go to C:\ProgramData have permission issue
if Result[Length(Result)] <> '\' then
Result := Result + '\';
Result := Result + ChangeFileExt(ExtractFileName(Application.ExeName), '')+ '\';
if not SysUtils.DirectoryExists(Result) then
CreateDir(Result);
end;
constructor TExceptionHandler.Create(AFileName : String);
var
i : Integer;
function FileLength(const FileName : String) : Int64;
var
F : TSearchRec;
begin
if FindFirst(FileName,faArchive or faReadOnly,F) = 0 then
begin
Int64Rec(Result).Hi := F.FindData.nFileSizeHigh;
Int64Rec(Result).Lo := F.FindData.nFileSizeLow;
FindClose(F);
end
else
Result := -1;
end;
begin
if AFileName = '' then
AFileName := 'Except.Log';
FFileName := GetDatabaseDirectory + 'Log\';
if not SysUtils.DirectoryExists(FFileName) then
CreateDir(FFileName);
FFileName := FFileName + AFileName;
if FileLength(FFileName) > C_Max_Log_Size then
RenameFile(FFileName,ChangeFileExt(FFileName,'.' + FormatDateTime('yyyymmdd',Now) + ExtractFileExt(FFileName)));
AFileName := FFileName;
for i := 1 to Length(AFileName) do
if CharInSet(AFileName[i],[':','\','/']) then
AFileName[i] := '.';
FLock := TRealMutexSync.Create(AFileName,True);
FModuleName := Uppercase(ChangeFileExt(ExtractFileName(ParamStr(0)),''));
end;
destructor TExceptionHandler.Destroy;
begin
try
FreeAndNil(FLock);
except
end;
end;
procedure TExceptionHandler.HandleException( E : Exception; const UserMessage : String; Actions : ActionList );
var
DupStr : String;
LogFile : TTextStream;
begin
try
DupStr := '';
(* Log Error to a text file *)
if not ( nolog in Actions ) then
try
FLastTime := Now;
FLastExcept := E.Message;
FLastUserMsg:= UserMessage;
FTimes := 0;
LogFile := nil;
if FLock.Acquire(1500) then
try
LogFile := TTextStream.Append(FFileName);
if DupStr <> '' then
LogFile.WriteLn(DupStr);
DupStr := FormatDateTime('dd/mm/yy hh:nn:ss',Now) + '-';
DupStr := DupStr + FModuleName + ',';
DupStr := DupStr + E.Message + '.' + UserMessage;
LogFile.WriteLn(DupStr);
finally
FreeAndNil(LogFile);
FLock.Release;
end;
except
end;
except
end;
if FreeException in Actions then
try
E.Free;
except
end;
end;
procedure TExceptionHandler.HandleException(const UserMessage: String; Actions: ActionList);
begin
if ExceptObject <> nil then
HandleException(Exception(ExceptObject),UserMessage,Actions);
end;
procedure TExceptionHandler.HandleException(const UserMessage: String);
begin
if ExceptObject <> nil then
HandleException(Exception(ExceptObject),UserMessage,[]);
end;
procedure TExceptionHandler.HandleExceptionMsg(const UserMessage: String; Actions: ActionList);
var
E : Exception;
begin
E := Exception.Create(UserMessage);
try
HandleException(E,'',Actions);
finally
E.Free;
end;
end;
procedure TExceptionHandler.HandleExceptionMsg(const UserMessage: String);
begin
HandleExceptionMsg(UserMessage,[]);
end;
{ TGlobalExceptionHandler }
constructor TGlobalExceptionHandler.Create;
begin
inherited Create;
FDebugFileName := ExtractFilePath(FileName) + 'Debug.Log';
end;
procedure TGlobalExceptionHandler.DebugLog(const UserMessage: String;
const Args: array of const);
begin
Debuglog(Format(UserMessage,Args));
end;
procedure TGlobalExceptionHandler.DebugLog(const UserMessage: String);
var
LogFile : TTextStream;
begin
LogFile := TTextStream.Append(FDebugFileName);
try
LogFile.WriteLn(FormatDateTime('dd/mm/yy hh:nn:ss',Now) + ': ' + ModuleName + ': ' + UserMessage);
FreeAndNil(LogFile);
except
FreeAndNil(LogFile);
end;
end;
{ Procuedures}
procedure CreateGlobalExceptionHandler;
begin
if not Assigned(GlobalExceptionHandler) then
GlobalExceptionHandler := TGlobalExceptionHandler.Create;
end;
Procedure HandleException
( const UserMessage : String; Actions : ActionList );
begin
if ExceptObject <> nil then
HandleException(Exception(ExceptObject), UserMessage, Actions);
end;
Procedure HandleException
( const UserMessage : String );
begin
if ExceptObject <> nil then
HandleException(Exception(ExceptObject), UserMessage, []);
end;
Procedure HandleExceptionMsg
( const UserMessage : String; Actions : ActionList );
var
E : Exception;
begin
E := Exception.Create(UserMessage);
try
HandleException(E,'',Actions);
finally
E.Free;
end;
end;
Procedure HandleExceptionMsg
( const UserMessage : String );
begin
HandleExceptionMsg(UserMessage,[]);
end;
Procedure HandleException
( E : Exception; const UserMessage : String; Actions : ActionList );
begin
CreateGlobalExceptionHandler;
GlobalExceptionHandler.HandleException(E,UserMessage,Actions);
end;
Procedure DebugLog( const UserMessage : String; const Args : array of const);
begin
DebugLog(Format(UserMessage,Args));
end;
Procedure DebugLog( const UserMessage : String);
begin
CreateGlobalExceptionHandler;
GlobalExceptionHandler.DebugLog(UserMessage);
end;
function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string;
{ Gets path of special system folders
Call this routine as follows:
GetSpecialFolderPath (CSIDL_PERSONAL, false)
returns folder as result
CSIDL_DESKTOP = $0000; <desktop>
CSIDL_INTERNET = $0001; Internet Explorer (icon on desktop)
CSIDL_PROGRAMS = $0002; Start Menu\Programs
CSIDL_CONTROLS = $0003; My Computer\Control Panel
CSIDL_PRINTERS = $0004; My Computer\Printers
CSIDL_PERSONAL = $0005; My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above
CSIDL_FAVORITES = $0006; <user name>\Favorites
CSIDL_STARTUP = $0007; Start Menu\Programs\Startup
CSIDL_RECENT = $0008; <user name>\Recent
CSIDL_SENDTO = $0009; <user name>\SendTo
CSIDL_BITBUCKET = $000a; <desktop>\Recycle Bin
CSIDL_STARTMENU = $000b; <user name>\Start Menu
CSIDL_MYDOCUMENTS = $000c; logical "My Documents" desktop icon
CSIDL_MYMUSIC = $000d; "My Music" folder
CSIDL_MYVIDEO = $000e; "My Video" folder
CSIDL_DESKTOPDIRECTORY = $0010; <user name>\Desktop
CSIDL_DRIVES = $0011; My Computer
CSIDL_NETWORK = $0012; Network Neighborhood (My Network Places)
CSIDL_NETHOOD = $0013; <user name>\nethood
CSIDL_FONTS = $0014; windows\fonts
CSIDL_TEMPLATES = $0015;
CSIDL_COMMON_STARTMENU = $0016; All Users\Start Menu
CSIDL_COMMON_PROGRAMS = $0017; All Users\Start Menu\Programs
CSIDL_COMMON_STARTUP = $0018; All Users\Startup
CSIDL_COMMON_DESKTOPDIRECTORY = $0019; All Users\Desktop
CSIDL_APPDATA = $001a; <user name>\Application Data
CSIDL_PRINTHOOD = $001b; <user name>\PrintHood
CSIDL_LOCAL_APPDATA = $001c; <user name>\Local Settings\Application Data (non roaming)
CSIDL_ALTSTARTUP = $001d; non localized startup
CSIDL_COMMON_ALTSTARTUP = $001e; non localized common startup
CSIDL_COMMON_FAVORITES = $001f; CSIDL_INTERNET_CACHE = $0020;
CSIDL_COOKIES = $0021;
CSIDL_HISTORY = $0022;
CSIDL_COMMON_APPDATA = $0023; All Users\Application Data
CSIDL_WINDOWS = $0024; GetWindowsDirectory()
CSIDL_SYSTEM = $0025; GetSystemDirectory()
CSIDL_PROGRAM_FILES = $0026; C:\Program Files
CSIDL_MYPICTURES = $0027; C:\Program Files\My Pictures
CSIDL_PROFILE = $0028; USERPROFILE
CSIDL_SYSTEMX86 = $0029; x86 system directory on RISC
CSIDL_PROGRAM_FILESX86 = $002a; x86 C:\Program Files on RISC
CSIDL_PROGRAM_FILES_COMMON = $002b; C:\Program Files\Common
CSIDL_PROGRAM_FILES_COMMONX86 = $002c; x86 C:\Program Files\Common on RISC
CSIDL_COMMON_TEMPLATES = $002d; All Users\Templates
CSIDL_COMMON_DOCUMENTS = $002e; All Users\Documents
CSIDL_COMMON_ADMINTOOLS = $002f; All Users\Start Menu\Programs\Administrative Tools
CSIDL_ADMINTOOLS = $0030; <user name>\Start Menu\Programs\Administrative Tools
CSIDL_CONNECTIONS = $0031; Network and Dial-up Connections
CSIDL_COMMON_MUSIC = $0035; All Users\My Music
CSIDL_COMMON_PICTURES = $0036; All Users\My Pictures
CSIDL_COMMON_VIDEO = $0037; All Users\My Video
CSIDL_RESOURCES = $0038; Resource Directory
CSIDL_RESOURCES_LOCALIZED = $0039; Localized Resource Directory
CSIDL_COMMON_OEM_LINKS = $003a; Links to All Users OEM specific apps
CSIDL_CDBURN_AREA = $003b; USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
CSIDL_COMPUTERSNEARME = $003d; Computers Near Me (computered from Workgroup membership)
CSIDL_PROFILES = $003e;
}
var
FilePath: array [0..255] of char;
begin
SHGetSpecialFolderPath(0, @FilePath[0], FOLDER, CanCreate);
Result := FilePath;
end;
initialization
finalization
FreeAndNil(GlobalExceptionHandler);
end.
|
unit Unit1Utils;
interface
type
TPublicUtil = class
class function GetNumberWithRound(Min, Max: Integer): Integer;
end;
implementation
{ TPublicUtil }
{*------------------------------------------------------------------------------
在指定范围获取一个随机数
@param Min 范围起始值
@param Max 范围的结束值
@return 返回的随机数
-------------------------------------------------------------------------------}
class function TPublicUtil.GetNumberWithRound(Min, Max: Integer): Integer;
begin
//初始化随机种子
Randomize;
Result := Random(Max) mod (Max - Min + 1) + Min;
end;
end.
|
unit Extract;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
TFileExtractor class
$jrsoftware: issrc/Projects/Extract.pas,v 1.30 2010/03/13 18:51:37 jr Exp $
}
interface
uses
Windows, SysUtils, Int64Em, FileClass, Compress, Struct, ArcFour;
type
TExtractorProgressProc = procedure(Bytes: Cardinal);
TFileExtractor = class
private
FDecompressor: array[Boolean] of TCustomDecompressor;
FSourceF: TFile;
FOpenedSlice, FChunkFirstSlice, FChunkLastSlice: Integer;
FChunkStartOffset: Longint;
FChunkBytesLeft, FChunkDecompressedBytesRead: Integer64;
FNeedReset: Boolean;
FChunkCompressed, FChunkEncrypted: Boolean;
FCryptContext: TArcFourContext;
FCryptKey: String;
FEntered: Integer;
procedure DecompressBytes(var Buffer; Count: Cardinal);
class function FindSliceFilename(const ASlice: Integer): String;
procedure OpenSlice(const ASlice: Integer);
function ReadProc(var Buf; Count: Longint): Longint;
public
constructor Create(ADecompressorClass: TCustomDecompressorClass);
destructor Destroy; override;
procedure DecompressFile(const FL: TSetupFileLocationEntry; const DestF: TFile;
const ProgressProc: TExtractorProgressProc; const VerifyChecksum: Boolean);
procedure SeekTo(const FL: TSetupFileLocationEntry;
const ProgressProc: TExtractorProgressProc);
property CryptKey: String write FCryptKey;
end;
function FileExtractor: TFileExtractor;
procedure FreeFileExtractor;
implementation
uses
PathFunc, CmnFunc2, Main, Msgs, MsgIDs, InstFunc, CompressZlib, bzlib,
LZMADecomp, SHA1, Logging, NewDisk;
var
FFileExtractor: TFileExtractor;
function FileExtractor: TFileExtractor;
const
DecompClasses: array[TSetupCompressMethod] of TCustomDecompressorClass =
(TStoredDecompressor, TZDecompressor, TBZDecompressor, TLZMA1Decompressor,
TLZMA2Decompressor);
begin
if FFileExtractor = nil then
FFileExtractor := TFileExtractor.Create(DecompClasses[SetupHeader.CompressMethod]);
Result := FFileExtractor;
end;
procedure FreeFileExtractor;
begin
FreeAndNil(FFileExtractor);
end;
procedure SourceIsCorrupted(const AReason: String);
begin
Log('Source file corrupted: ' + AddPeriod(AReason));
raise Exception.Create(SetupMessages[msgSourceIsCorrupted]);
end;
{ TFileExtractor }
constructor TFileExtractor.Create(ADecompressorClass: TCustomDecompressorClass);
begin
inherited Create;
FOpenedSlice := -1;
FChunkFirstSlice := -1;
{ Create one 'decompressor' for use with uncompressed chunks, and another
for use with compressed chunks }
FDecompressor[False] := TStoredDecompressor.Create(ReadProc);
FDecompressor[True] := ADecompressorClass.Create(ReadProc);
end;
destructor TFileExtractor.Destroy;
begin
FSourceF.Free;
FDecompressor[True].Free;
FDecompressor[False].Free;
inherited;
end;
var
LastSourceDir: String;
class function TFileExtractor.FindSliceFilename(const ASlice: Integer): String;
var
Major, Minor: Integer;
Prefix, F1, F2, Path: String;
begin
Prefix := PathChangeExt(PathExtractName(SetupLdrOriginalFilename), '');
Major := ASlice div SetupHeader.SlicesPerDisk + 1;
Minor := ASlice mod SetupHeader.SlicesPerDisk;
if SetupHeader.SlicesPerDisk = 1 then
F1 := Format('%s-%d.bin', [Prefix, Major])
else
F1 := Format('%s-%d%s.bin', [Prefix, Major, Chr(Ord('a') + Minor)]);
F2 := Format('..\DISK%d\', [Major]) + F1;
if LastSourceDir <> '' then begin
Result := AddBackslash(LastSourceDir) + F1;
if NewFileExists(Result) then Exit;
end;
Result := AddBackslash(SourceDir) + F1;
if NewFileExists(Result) then Exit;
if LastSourceDir <> '' then begin
Result := PathExpand(AddBackslash(LastSourceDir) + F2);
if NewFileExists(Result) then Exit;
end;
Result := PathExpand(AddBackslash(SourceDir) + F2);
if NewFileExists(Result) then Exit;
Path := SourceDir;
LogFmt('Asking user for new disk containing "%s".', [F1]);
if SelectDisk(Major, F1, Path) then begin
LastSourceDir := Path;
Result := AddBackslash(Path) + F1;
end
else
Abort;
end;
procedure TFileExtractor.OpenSlice(const ASlice: Integer);
var
Filename: String;
TestDiskSliceID: TDiskSliceID;
DiskSliceHeader: TDiskSliceHeader;
begin
if FOpenedSlice = ASlice then
Exit;
FOpenedSlice := -1;
FreeAndNil(FSourceF);
if SetupLdrOffset1 = 0 then
Filename := FindSliceFilename(ASlice)
else
Filename := SetupLdrOriginalFilename;
FSourceF := TFile.Create(Filename, fdOpenExisting, faRead, fsRead);
if SetupLdrOffset1 = 0 then begin
if FSourceF.Read(TestDiskSliceID, SizeOf(TestDiskSliceID)) <> SizeOf(TestDiskSliceID) then
SourceIsCorrupted('Invalid slice header (1)');
if TestDiskSliceID <> DiskSliceID then
SourceIsCorrupted('Invalid slice header (2)');
if FSourceF.Read(DiskSliceHeader, SizeOf(DiskSliceHeader)) <> SizeOf(DiskSliceHeader) then
SourceIsCorrupted('Invalid slice header (3)');
if FSourceF.Size.Lo <> DiskSliceHeader.TotalSize then
SourceIsCorrupted('Invalid slice header (4)');
end;
FOpenedSlice := ASlice;
end;
procedure TFileExtractor.DecompressBytes(var Buffer; Count: Cardinal);
begin
try
FDecompressor[FChunkCompressed].DecompressInto(Buffer, Count);
except
{ If DecompressInto raises an exception, force a decompressor reset &
re-seek the next time SeekTo is called by setting FNeedReset to True.
We don't want to get stuck in an endless loop with the decompressor
in e.g. a data error state. Also, we have no way of knowing if
DecompressInto successfully decompressed some of the requested bytes
before the exception was raised. }
FNeedReset := True;
raise;
end;
Inc64(FChunkDecompressedBytesRead, Count);
end;
procedure TFileExtractor.SeekTo(const FL: TSetupFileLocationEntry;
const ProgressProc: TExtractorProgressProc);
procedure InitDecryption;
var
Salt: TSetupSalt;
Context: TSHA1Context;
Hash: TSHA1Digest;
begin
{ Read the salt }
if FSourceF.Read(Salt, SizeOf(Salt)) <> SizeOf(Salt) then
SourceIsCorrupted('Failed to read salt');
{ Initialize the key, which is the SHA-1 hash of the salt plus FCryptKey }
SHA1Init(Context);
SHA1Update(Context, Salt, SizeOf(Salt));
SHA1Update(Context, Pointer(FCryptKey)^, Length(FCryptKey)*SizeOf(FCryptKey[1]));
Hash := SHA1Final(Context);
ArcFourInit(FCryptContext, Hash, SizeOf(Hash));
{ The compiler discards the first 1000 bytes for extra security,
so we must as well }
ArcFourDiscard(FCryptContext, 1000);
end;
procedure Discard(Count: Integer64);
var
Buf: array[0..65535] of Byte;
BufSize: Cardinal;
begin
try
while True do begin
BufSize := SizeOf(Buf);
if (Count.Hi = 0) and (Count.Lo < BufSize) then
BufSize := Count.Lo;
if BufSize = 0 then
Break;
DecompressBytes(Buf, BufSize);
Dec64(Count, BufSize);
if Assigned(ProgressProc) then
ProgressProc(0);
end;
except
on E: ECompressDataError do
SourceIsCorrupted(E.Message);
end;
end;
var
TestCompID: TCompID;
Diff: Integer64;
begin
if FEntered <> 0 then
InternalError('Cannot call file extractor recursively');
Inc(FEntered);
try
if (foChunkEncrypted in FL.Flags) and (FCryptKey = '') then
InternalError('Cannot read an encrypted file before the key has been set');
{ Is the file in a different chunk than the current one?
Or, is the file in a part of the current chunk that we've already passed?
Or, did a previous decompression operation fail, necessitating a reset? }
if (FChunkFirstSlice <> FL.FirstSlice) or
(FChunkStartOffset <> FL.StartOffset) or
(Compare64(FL.ChunkSuboffset, FChunkDecompressedBytesRead) < 0) or
FNeedReset then begin
FChunkFirstSlice := -1;
FDecompressor[foChunkCompressed in FL.Flags].Reset;
FNeedReset := False;
OpenSlice(FL.FirstSlice);
FSourceF.Seek(SetupLdrOffset1 + FL.StartOffset);
if FSourceF.Read(TestCompID, SizeOf(TestCompID)) <> SizeOf(TestCompID) then
SourceIsCorrupted('Failed to read CompID');
if Longint(TestCompID) <> Longint(ZLIBID) then
SourceIsCorrupted('Invalid CompID');
if foChunkEncrypted in FL.Flags then
InitDecryption;
FChunkFirstSlice := FL.FirstSlice;
FChunkLastSlice := FL.LastSlice;
FChunkStartOffset := FL.StartOffset;
FChunkBytesLeft := FL.ChunkCompressedSize;
FChunkDecompressedBytesRead.Hi := 0;
FChunkDecompressedBytesRead.Lo := 0;
FChunkCompressed := foChunkCompressed in FL.Flags;
FChunkEncrypted := foChunkEncrypted in FL.Flags;
end;
{ Need to seek forward in the chunk? }
if Compare64(FL.ChunkSuboffset, FChunkDecompressedBytesRead) > 0 then begin
Diff := FL.ChunkSuboffset;
Dec6464(Diff, FChunkDecompressedBytesRead);
Discard(Diff);
end;
finally
Dec(FEntered);
end;
end;
function TFileExtractor.ReadProc(var Buf; Count: Longint): Longint;
var
Buffer: Pointer;
Left, Res: Cardinal;
begin
Buffer := @Buf;
Left := Count;
if (FChunkBytesLeft.Hi = 0) and (FChunkBytesLeft.Lo < Left) then
Left := FChunkBytesLeft.Lo;
Result := Left;
while Left <> 0 do begin
Res := FSourceF.Read(Buffer^, Left);
Dec64(FChunkBytesLeft, Res);
{ Decrypt the data after reading from the file }
if FChunkEncrypted then
ArcFourCrypt(FCryptContext, Buffer^, Buffer^, Res);
if Left = Res then
Break
else begin
Dec(Left, Res);
Inc(Longint(Buffer), Res);
{ Go to next disk }
if FOpenedSlice >= FChunkLastSlice then
{ Already on the last slice, so the file must be corrupted... }
SourceIsCorrupted('Already on last slice');
OpenSlice(FOpenedSlice + 1);
end;
end;
end;
procedure TFileExtractor.DecompressFile(const FL: TSetupFileLocationEntry;
const DestF: TFile; const ProgressProc: TExtractorProgressProc;
const VerifyChecksum: Boolean);
var
BytesLeft: Integer64;
Context: TSHA1Context;
AddrOffset: LongWord;
BufSize: Cardinal;
Buf: array[0..65535] of Byte;
{ ^ *must* be the same buffer size used by the compiler (TCompressionHandler),
otherwise the TransformCallInstructions call will break }
begin
if FEntered <> 0 then
InternalError('Cannot call file extractor recursively');
Inc(FEntered);
try
BytesLeft := FL.OriginalSize;
{ To avoid file system fragmentation, preallocate all of the bytes in the
destination file }
DestF.Seek64(BytesLeft);
DestF.Truncate;
DestF.Seek(0);
SHA1Init(Context);
try
AddrOffset := 0;
while True do begin
BufSize := SizeOf(Buf);
if (BytesLeft.Hi = 0) and (BytesLeft.Lo < BufSize) then
BufSize := BytesLeft.Lo;
if BufSize = 0 then
Break;
DecompressBytes(Buf, BufSize);
if foCallInstructionOptimized in FL.Flags then begin
TransformCallInstructions(Buf, BufSize, False, AddrOffset);
Inc(AddrOffset, BufSize); { may wrap, but OK }
end;
Dec64(BytesLeft, BufSize);
SHA1Update(Context, Buf, BufSize);
DestF.WriteBuffer(Buf, BufSize);
if Assigned(ProgressProc) then
ProgressProc(BufSize);
end;
except
on E: ECompressDataError do
SourceIsCorrupted(E.Message);
end;
if VerifyChecksum and not SHA1DigestsEqual(SHA1Final(Context), FL.SHA1Sum) then
SourceIsCorrupted('SHA-1 hash mismatch');
finally
Dec(FEntered);
end;
end;
end.
|
unit UDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUIBaseControl,
FMX.TMSNativeUIView, iOSApi.CoreGraphics, iOSApi.UIKit, iOSApi.QuartzCore;
type
TForm1034 = class(TForm)
TMSFMXNativeUIView1: TTMSFMXNativeUIView;
procedure TMSFMXNativeUIView1DrawRect(Sender: TObject; ARect: TRectF);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1034: TForm1034;
implementation
uses
Math;
{$R *.fmx}
procedure TForm1034.FormCreate(Sender: TObject);
begin
TMSFMXNativeUIView1.View.setContentMode(UIViewContentModeRedraw);
end;
procedure TForm1034.TMSFMXNativeUIView1DrawRect(Sender: TObject; ARect: TRectF);
var
context: CGContextRef;
w, h: Double;
tr: CGAffineTransform;
begin
context := UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 150, 150);
CGContextAddLineToPoint(context, 100, 200);
CGContextAddLineToPoint(context, 50, 150);
CGContextAddLineToPoint(context, 100, 100);
CGContextSetFillColorWithColor(context, TUIColor.Wrap(TUIColor.OCClass.redColor).CGColor);
CGContextFillPath(context);
CGContextSetLineWidth(context, 4.0);
CGContextSetStrokeColorWithColor(context, TUIColor.Wrap(TUIColor.OCClass.greenColor).CGColor);
CGContextMoveToPoint(context, 200, 100);
CGContextAddArcToPoint(context, 200,200, 300,200, 100);
CGContextStrokePath(context);
h := ARect.Height;
CGContextTranslateCTM(context, 0, h);
CGContextScaleCTM(context, 1, -1);
CGContextSelectFont(context,
UTF8ToString(TUIFont.Wrap(TUIFont.OCClass.boldSystemFontOfSize(h/10)).fontName.UTF8String),
h/10,
kCGEncodingMacRoman);
CGContextSetCharacterSpacing(context, 10);
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
CGContextSetRGBFillColor(context, 0, 1, 0, 0.5);
CGContextSetRGBStrokeColor(context, 0, 0, 1, 1);
tr := CGAffineTransformMakeRotation(DegToRad(25));
CGContextSetTextMatrix(context, tr);
CGContextShowTextAtPoint(context, 30, 30, 'Quartz 2D', 9);
end;
end.
|
Unit debugui;
{$mode objfpc}{$H+}
Interface
Uses
classes, sysutils, fileutil, forms, controls, graphics, dialogs, StdCtrls;
Type
{ TfrmDebug }
TfrmDebug = Class(tform)
MemoLog: tmemo;
Procedure formshow(sender: tobject);
Private
{ private declarations }
Public
{ public declarations }
procedure AddLog(const msg : string);
End;
Var
frmDebug: TfrmDebug;
Implementation
{$R *.lfm}
{ TfrmDebug }
procedure TfrmDebug.AddLog(const msg : string);
begin
MemoLog.Lines.Add(formatdatetime('hh:mm:ss',Now,[]) + ': ' + msg);
End;
Procedure tfrmdebug.formshow(sender: tobject);
Begin
Top := 0;
Left := 0;
end;
End.
|
unit App;
{ Based on 021_morphing.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App,
Sample.Geometry;
type
TMorphingApp = class(TApplication)
private const
POINT_COUNT = 4096;
private
FProgram: TGLProgram;
FVBOs: array [0..3] of TGLBuffer;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
FUniStatus: TGLUniform;
FStatus: Single;
private
function MakeShape1: TGLBuffer;
function MakeShape2: TGLBuffer;
function MakeRadiance(const AAttrName: RawByteString): TGLBuffer;
public
procedure Initialize; override;
procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
procedure Resize(const AWidth, AHeight: Integer); override;
end;
implementation
uses
{$INCLUDE 'OpenGL.inc'}
System.UITypes,
Sample.Math,
Sample.Platform;
{ TMorphingApp }
procedure TMorphingApp.Initialize;
var
VertexShader, FragmentShader: TGLShader;
Uniform: TGLUniform;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'uniform vec3 Color1, Color2;'#10+
'uniform float Status, ScreenScale;'#10+
'attribute vec4 Position1, Position2;'#10+
'attribute float Radiance1, Radiance2;'#10+
'varying vec3 vertColor;'#10+
'void main(void)'#10+
'{'#10+
' gl_Position = '#10+
' ProjectionMatrix * '#10+
' CameraMatrix * '#10+
' ModelMatrix * '#10+
' mix(Position1, Position2, Status);'#10+
' gl_PointSize = (2.0 + 3.0 * mix('#10+
' Radiance1, '#10+
' Radiance2, '#10+
' Status)) * ScreenScale;'#10+
' vertColor = mix('#10+
' (0.2 + Radiance1) * Color1,'#10+
' (0.2 + Radiance2) * Color2,'#10+
' Status);'#10+
'}');
VertexShader.Compile;
FragmentShader.New(TGLShaderType.Fragment,
'precision mediump float;'#10+
'varying vec3 vertColor;'#10+
'void main(void)'#10+
'{'#10+
' gl_FragColor = vec4(vertColor, 1.0);'#10+
'}');
FragmentShader.Compile;
FProgram.New(VertexShader, FragmentShader);
FProgram.Link;
VertexShader.Delete;
FragmentShader.Delete;
FProgram.Use;
FVBOs[0] := MakeShape1;
FVBOs[1] := MakeShape2;
FVBOs[2] := MakeRadiance('Radiance1');
FVBOs[3] := MakeRadiance('Radiance2');
{ Uniforms }
Uniform.Init(FProgram, 'Color1');
Uniform.SetValue(1.0, 0.5, 0.4);
Uniform.Init(FProgram, 'Color2');
Uniform.SetValue(1.0, 0.8, 0.7);
{ The gl_PointSize vertex shader output does not take screen scale into
account. So we scale it ourselves. }
Uniform.Init(FProgram, 'ScreenScale');
Uniform.SetValue(TPlatform.ScreenScale);
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
FUniStatus.Init(FProgram, 'Status');
gl.ClearColor(0.2, 0.2, 0.2, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
gl.Enable(TGLCapability.Blend);
end;
procedure TMorphingApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
function TMorphingApp.MakeRadiance(const AAttrName: RawByteString): TGLBuffer;
var
Data: TArray<Single>;
I: Integer;
Attr: TGLVertexAttrib;
begin
SetLength(Data, POINT_COUNT);
for I := 0 to POINT_COUNT- 1 do
Data[I] := Random(101) * 0.01;
Result.New(TGLBufferType.Vertex);
Result.Bind;
Result.Data(Data);
Attr.Init(FProgram, AAttrName);
Attr.SetConfig<Single>;
Attr.Enable;
end;
function TMorphingApp.MakeShape1: TGLBuffer;
var
Data: TArray<TVector3>;
I: Integer;
Phi, Rho, SPhi, CPhi, SRho, CRho: Single;
Attr: TGLVertexAttrib;
begin
SetLength(Data, POINT_COUNT);
for I := 0 to POINT_COUNT - 1 do
begin
Phi := 2 * Pi * (Random(1001) * 0.001);
Rho := 0.5 * Pi * ((Random(1001) * 0.002) - 1.0);
FastSinCos(Phi, SPhi, CPhi);
FastSinCos(Rho, SRho, CRho);
Data[I].Init(CPhi * CRho, SRho, SPhi * CRho);
end;
Result.New(TGLBufferType.Vertex);
Result.Bind;
Result.Data(Data);
Attr.Init(FProgram, 'Position1');
Attr.SetConfig<TVector3>;
Attr.Enable;
end;
function TMorphingApp.MakeShape2: TGLBuffer;
var
Data: TArray<TVector3>;
I: Integer;
Phi, Rho, SPhi, CPhi, SRho, CRho: Single;
Attr: TGLVertexAttrib;
begin
SetLength(Data, POINT_COUNT);
for I := 0 to POINT_COUNT - 1 do
begin
Phi := 2 * Pi * (Random(1001) * 0.001);
Rho := 2 * Pi * (Random(1001) * 0.001);
FastSinCos(Phi, SPhi, CPhi);
FastSinCos(Rho, SRho, CRho);
Data[I].Init(
CPhi * (0.5 + (0.5 * (1.0 + CRho))),
SRho * 0.5,
SPhi * (0.5 + (0.5 * (1.0 + CRho))));
end;
Result.New(TGLBufferType.Vertex);
Result.Bind;
Result.Data(Data);
Attr.Init(FProgram, 'Position2');
Attr.SetConfig<TVector3>;
Attr.Enable;
end;
procedure TMorphingApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
CameraMatrix, ModelMatrix: TMatrix4;
begin
if ((Trunc(ATotalTimeSec) and 3) = 0) then
FStatus := FStatus + ADeltaTimeSec
else if (FStatus <> Trunc(FStatus)) then
begin
if (Frac(FStatus) < 0.5) then
FStatus := Trunc(FStatus)
else
FStatus := 1 + Trunc(FStatus);
end;
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
{ Use the program }
FProgram.Use;
FUniStatus.SetValue(0.5 - (0.5 * FastCos(Pi * FStatus)));
{ Set the matrix for camera orbiting the origin }
OrbitCameraMatrix(TVector3.Zero, 5.5, ATotalTimeSec * Pi / 9.5,
Radians(45 + FastSin(Pi * ATotalTimeSec / 7.5) * 40), CameraMatrix);
FUniCameraMatrix.SetValue(CameraMatrix);
{ Render }
ModelMatrix.InitRotationX(FStatus * Pi * 0.5);
FUniModelMatrix.SetValue(ModelMatrix);
gl.DrawArrays(TGLPrimitiveType.Points, POINT_COUNT);
end;
procedure TMorphingApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(48), AWidth / AHeight, 1, 20);
FProgram.Use;
FUniProjectionMatrix.SetValue(ProjectionMatrix);
end;
procedure TMorphingApp.Shutdown;
var
I: Integer;
begin
{ Release resources }
for I := 0 to Length(FVBOs) - 1 do
FVBOs[I].Delete;
FProgram.Delete;
end;
end.
|
{
Free Component miniLog Version 2.0
Copyright (©) 2010, by Sergiy Tkach (Apromix), bees@meta.ua
}
unit uLog;
interface
type
TmLog = class
private
FAppName : string;
FAppPath : string;
LogFile: Text;
protected
function ExtractFilePath(const FileName: string): string;
function ExtractFileName(const FileName: string): string;
function Trim(const S: string): string;
function LineStr(S: String; N: Integer): String;
public
constructor Create(AAppName: String = '');
destructor Destroy; override;
procedure Log(LogMessage : string; AddDateTime: Boolean = False); overload;
procedure Log(LogMessage, LogStrValue: string; AddDateTime: Boolean = False); overload;
procedure Log(LogMessage: string; LogIntValue : Integer; AddDateTime: Boolean = False); overload;
procedure LogDiv;
published
property ApplicationName : string read FAppName;
property ApplicationPath : string read FAppPath;
end;
var
Log: TmLog;
implementation
uses SysUtils;
const
DefaultLogFileEx = '.log'; // Расширение лога
DefaultLogFileName = ''; // Название лога, если оставить пустым, то будет именем приложения
LogDv = '-->'; // Разделитель в сообщениях лога
MsgDivLength = 80; // Длина разделителя между сообщениями
MsgDivStr = '-'; // Разделитель между сообщениями (звено)
var
DivMessage: String = '';
DTMsg : String = '';
const
WinS = '\';
Empty = '';
Space = ' ';
constructor TmLog.Create(AAppName: String = '');
begin
inherited Create;
DivMessage := LineStr(MsgDivStr, MsgDivLength);
if (Trim(AAppName) = Empty) then FAppName := ExtractFileName( ParamStr(0) ) else FAppName := Trim(AAppName) + LineStr(Space, 4);
FAppPath := ExtractFilePath( ParamStr(0) );
Assign(LogFile, FAppPath + Copy(FAppName, 0, Length(FAppName) - 4) + DefaultLogFileEx);
Rewrite(LogFile);
Log('File: ' + FAppName);
Log('Path: ' + FAppPath);
LogDiv;
Log('Opening Log at ' + LogDv + Space + DateToStr(Date) + Space + TimeToStr(Time));
end;
destructor TmLog.Destroy;
begin
Log('Closing Log at ' + LogDv + Space + DateToStr(Date) + Space + TimeToStr(Time));
Close(LogFile);
inherited Destroy;
end;
function TmLog.ExtractFileName(const FileName: string): string;
var
N: Integer;
I: Integer;
begin
N := Length(FileName);
Result := Empty;
if (N = 0) then Exit;
for I := N downto 1 do
begin
if (FileName[i] = WinS) then Exit;
Result := FileName[I] + Result;
end;
end;
function TmLog.ExtractFilePath(const FileName: string): string;
var
N: Integer;
I: Integer;
begin
N := Length(FileName);
Result := Empty;
if (N = 0) then Exit;
for I := N downto 1 do
begin
if (FileName[I] = WinS) then
begin
Result := Copy(FileName, 1, I);
Exit;
end;
end;
end;
function TmLog.LineStr(S: String; N: Integer): String;
var
I: Integer;
R: String;
begin
R := Empty;
for I := 1 to N do
R := R + Trim(S);
Result := R;
end;
function TmLog.Trim(const S: string): string;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= Space) do Inc(I);
if (I > L) then Result := Empty else
begin
while S[L] <= Space do Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
procedure TmLog.Log(LogMessage : string; AddDateTime: Boolean = False);
begin
DTMsg := Empty;
if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space;
WriteLn(LogFile, Trim(DTMsg + LogMessage));
end;
procedure TmLog.Log(LogMessage, LogStrValue: string; AddDateTime: Boolean = False);
begin
DTMsg := Empty;
if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space;
WriteLn(LogFile, Trim(DTMsg + LogMessage) + Space + LogDv + Space + Trim(LogStrValue));
end;
procedure TmLog.Log(LogMessage: string; LogIntValue: Integer; AddDateTime: Boolean = False);
var
V: String;
begin
DTMsg := Empty;
if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space;
Str(LogIntValue, V);
WriteLn(LogFile, Trim(DTMsg + LogMessage) + Space + LogDv + Space + V);
end;
procedure TmLog.LogDiv;
begin
WriteLn(LogFile, Trim(DivMessage));
end;
initialization
begin
Log := TmLog.Create(DefaultLogFileName);
with Log do
begin
LogDiv;
Log('Initialization', 'Starting Application');
LogDiv;
end;
end;
finalization
begin
with Log do
begin
LogDiv;
Log('Finalization', 'Terminating Application');
LogDiv;
Free;
end;
Log := nil;
end;
end.
|
{************************************************************************}
{ TExeInfo component }
{ for Delphi & C++Builder }
{ }
{ written by TMS Software }
{ copyright © 2004 - 2013 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{ }
{ The source code is given as is. The author is not responsible }
{ for any possible damage done due to the use of this code. }
{ The component can be freely used in any application. The complete }
{ source code remains property of the author and may not be distributed, }
{ published, given or sold in any form as such. No parts of the source }
{ code can be included in any other component or application without }
{ written authorization of the author. }
{************************************************************************}
unit ExeInfo;
interface
{$I TMSDEFS.INC}
uses
Windows, Messages, SysUtils, Classes, Forms, Graphics, Controls, Dialogs,
TypInfo;
const
MAJ_VER = 1; // Major version nr.
MIN_VER = 3; // Minor version nr.
REL_VER = 0; // Release nr.
BLD_VER = 0; // Build nr.
// version history
// 1.2.0.0 : Added support for Windows 2003, Windows Vista
// 1.2.0.1 : Fixed : issue with memory allocation for Delphi 2009
// 1.2.1.0 : New : method GetVersionInfoOfApp() method added
// 1.2.2.0 : New : support for Windows 7
// : New : exposes version number as integer
// 1.2.3.0 : Improved : FileCreation returns file age when version info resource doesn't include info
// 1.2.3.1 : Improved : Changed FileAge() call to avoid deprecated parameter list in newer Delphi versions
// 1.2.4.0 : New : Support for Windows 8 version detection
// 1.3.0.0 : New : Build, Release, Major, Minor version as separate functions exposed
type
{$IFDEF DELPHIXE2_LVL}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TExeInfo = class(TComponent)
private
{ Private declarations }
FCompanyName : String;
FFileDescription : String;
FFileVersion : String;
FInternalName : String;
FLegalCopyright : String;
FLegalTradeMark : String;
FOriginalFileName : String;
FProductName : String;
FProductVersion : String;
FComments : String;
FComputerName : String;
FOsName : String;
FWindowsDir : String;
FSystemDir : String;
FTempDir : String;
FFileFlags : integer;
FFileOS : integer;
FFileType : integer;
FFileCreation : TDateTime;
function GetVersion: string;
procedure SetVersion(const Value: string);
function GetFileVersionInt: integer;
protected
{ Protected declarations }
function GetVersionNr: Integer; virtual;
procedure GetVersionInfo; virtual;
function GetComputerName : String; virtual;
procedure SetComputerName(Name : String); virtual;
function GetWinDir : String;
function GetSysDir : String;
function GetTempDir : String;
function GetVersionPart(idx: integer): integer;
public
{ Public declarations }
procedure GetVersionInfoOfApp(const AAppName:String);
constructor Create(AOwner: TComponent); override;
property FileFlags : integer read FFileFlags;
property FileOS : integer read FFileOS;
property FileType : integer read FFileType;
property FileCreation : TDateTime read FFileCreation;
function GetOperatingSystem : string; virtual;
function MajorVersion: integer;
function MinorVersion: integer;
function ReleaseNumber: integer;
function BuildNumber: integer;
property FileVersionInt: integer read GetFileVersionInt;
published
{ Published declarations }
property CompanyName : string read FCompanyName write FCompanyName stored false;
property FileDescription : string read FFileDescription write FFileDescription stored false;
property FileVersion : string read FFileVersion write FFileVersion stored false;
property InternalName : string read FInternalName write FInternalName stored false;
property LegalCopyright : string read FLegalCopyright write FLegalCopyright stored false;
property LegalTradeMark : string read FLegalTradeMark write FLegalTradeMark stored false;
property OriginalFileName : string read FOriginalFileName write FOriginalFileName stored false;
property ProductName : string read FProductName write FProductName stored false;
property ProductVersion : string read FProductVersion write FProductVersion stored false;
property Comments : string read FComments write FComments stored false;
property ComputerName : string read GetComputerName write SetComputerName stored false;
property OSName : string read GetOperatingSystem write FOSName stored false;
property WindowsDir : string read GetWinDir write FWindowsDir stored false;
property SystemDir : string read GetSysDir write FSystemDir stored false;
property TempDir : string read GetTempDir write FTempDir stored false;
property Version : string read GetVersion write SetVersion;
end;
implementation
uses
StrUtils;
function TExeInfo.BuildNumber: integer;
begin
Result := GetVersionPart(3);
end;
constructor TExeInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCompanyName := 'Updated at run-time';
FFileDescription := 'Updated at run-time';
FFileVersion := 'Updated at run-time';
FInternalName := 'Updated at run-time';
FLegalCopyright := 'Updated at run-time';
FLegalTradeMark := 'Updated at run-time';
FOriginalFileName := 'Updated at run-time';
FProductName := 'Updated at run-time';
FProductVersion := 'Updated at run-time';
FComments := 'Updated at run-time';
FComputerName := '';
if not (csDesigning in ComponentState) then
Begin
GetVersionInfo;
FComputerName := GetComputerName;
End;
end;
procedure TExeInfo.GetVersionInfoOfApp(const AAppName: string);
type
PTransBuffer = ^TTransBuffer;
TTransBuffer = array[1..4] of smallint;
var
iAppSize, iLenOfValue : DWord;
pcBuf,pcValue : PChar;
VerSize : DWord;
pTrans : PTransBuffer;
TransStr : string;
sAppName : String;
fvip : pointer;
ft : TFileTime;
st : TSystemTime;
begin
sAppName := AAppName;
// get version information values
iAppSize:= GetFileVersionInfoSize(PChar(sAppName),// pointer to filename string
iAppSize); // pointer to variable to receive zero
// if GetFileVersionInfoSize is successful
if iAppSize > 0 then
begin
pcBuf := AllocMem(iAppSize);
GetFileVersionInfo(PChar(sAppName), // pointer to filename string
0, // ignored
iAppSize, // size of buffer
pcBuf); // pointer to buffer to receive file-version info.
VerQueryValue(pcBuf, '\', fvip, iLenOfValue);
FFileFlags := TVSFixedFileInfo(fvip^).dwFileFlags and TVSFixedFileInfo (fvip^).dwFileFlagsMask;
FFileOS := TVSFixedFileInfo(fvip^).dwFileOS;
FFileType := TVSFixedFileInfo(fvip^).dwFileType;
ft.dwLowDateTime := TVSFixedFileInfo(fvip^).dwFileDateLS;
ft.dwHighDateTime := TVSFixedFileInfo(fvip^).dwFileDateMS;
if (ft.dwLowDateTime <> 0) or (ft.dwHighDateTime <> 0) then
begin
FileTimeToSystemTime(ft,st);
FFileCreation := SystemTimeToDateTime(st);
end
else
begin
{$IFDEF DELPHI_UNICODE}
FileAge(Application.ExeName, FFileCreation);
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
FFileCreation := FileDateToDateTime(FileAge(Application.ExeName));
{$ENDIF}
end;
VerQueryValue(pcBuf, PChar('\VarFileInfo\Translation'),
pointer(ptrans), verSize);
TransStr:= IntToHex(ptrans^[1], 4) + IntToHex(ptrans^[2], 4);
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'CompanyName'), Pointer(pcValue),iLenOfValue) then
FCompanyName := pcValue
Else FCompanyName := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'FileDescription'), Pointer(pcValue),iLenOfValue) then
FFileDescription := pcValue
Else FFileDescription := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'FileVersion'), Pointer(pcValue),iLenOfValue) then
FFileVersion := pcValue
Else FFileVersion := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'InternalName'), Pointer(pcValue),iLenOfValue) then
FInternalName := pcValue
Else FInternalName := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'LegalCopyright'), Pointer(pcValue),iLenOfValue) then
FLegalCopyright := pcValue
Else FLegalCopyright := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'LegalTradeMarks'), Pointer(pcValue),iLenOfValue) then
FLegalTradeMark := pcValue
Else FLegalTradeMark := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'OriginalFileName'), Pointer(pcValue),iLenOfValue) then
FOriginalFileName := pcValue
Else FOriginalFileName := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'ProductName'), Pointer(pcValue),iLenOfValue) then
FProductName := pcValue
Else FProductName := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'ProductVersion'), Pointer(pcValue),iLenOfValue) then
FProductVersion := pcValue
Else FProductVersion := '';
if VerQueryValue(pcBuf,PChar('StringFileInfo\' + TransStr + '\' +
'Comments'), Pointer(pcValue),iLenOfValue) then
FComments := pcValue
Else FComments := '';
FreeMem(pcBuf,iAppSize);
end;
end;
procedure TExeInfo.GetVersionInfo;
begin
GetVersionInfoOfApp(Application.ExeName);
end;
function TExeInfo.GetComputerName : String;
var
pcComputer : PChar;
dwCSize : DWORD;
begin
dwCSize := MAX_COMPUTERNAME_LENGTH + 1;
{$IFDEF DELPHI_UNICODE}
GetMem( pcComputer, dwCSize * 2); // allocate memory for the string
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
GetMem( pcComputer, dwCSize ); // allocate memory for the string
{$ENDIF}
try
if Windows.GetComputerName( pcComputer, dwCSize ) then
GetComputerName := StrPas(pcComputer);
finally
FreeMem( pcComputer ); // now free the memory allocated for the string
end;
end;
function TExeInfo.GetFileVersionInt: integer;
var
sl: TStringList;
verstr: string;
i: integer;
begin
Result := -1;
if FileVersion = '' then
Exit;
verstr := StringReplace(FileVersion,'.','.',[rfReplaceAll]);
sl := TStringList.Create;
try
sl.CommaText := verstr;
verstr := '';
for i := 0 to sl.Count - 1 do
begin
while (length(sl[i]) < 2) do
sl[i] := '0' + sl[i];
sl[i] := copy(sl[i],1,2);
verstr := verstr + sl[i];
end;
finally
sl.Free;
end;
Result := StrToInt(verstr);
end;
procedure TExeInfo.SetComputerName(Name : String);
var
pcComputer : PChar;
dwCSize : DWORD;
begin
dwCSize := MAX_COMPUTERNAME_LENGTH + 1;
{$IFDEF DELPHI_UNICODE}
GetMem( pcComputer, dwCSize * 2); // allocate memory for the string
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
GetMem( pcComputer, dwCSize ); // allocate memory for the string
{$ENDIF}
pcComputer := StrpCopy(pcComputer,Name);
try
Windows.SetComputerName( pcComputer )
finally
FreeMem( pcComputer ); // now free the memory allocated for the string
end;
end;
function TExeInfo.GetOperatingSystem : string;
const
SM_SERVERR2 = 89;
VER_NT_WORKSTATION = $0000001;
type
TOSVersionInfoEx = record
dwOSVersionInfoSize:DWORD;
dwMajorVersion:DWORD;
dwMinorVersion:DWORD;
dwBuildNumber:DWORD;
dwPlatformId:DWORD;
szCSDVersion: array[0..127] of Char;
wServicePackMajor:WORD;
wServicePackMinor:WORD;
wSuiteMask:WORD;
wProductType:BYTE;
wReserved:BYTE;
End;
var
osVerInfo: TOSVersionInfoEx;
majorVer, minorVer: Integer;
begin
Result := 'Unknown';
{ set operating system type flag }
osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
if GetVersionEx(Windows.POSVersionInfo(@osVerInfo)^) then
begin
majorVer := osVerInfo.dwMajorVersion;
minorVer := osVerInfo.dwMinorVersion;
case osVerInfo.dwPlatformId of
VER_PLATFORM_WIN32_NT: { Windows NT/2000 }
begin
if majorVer <= 4 then
Result := 'Windows NT'
else if (majorVer = 5) and (minorVer = 0) then
Result := 'Windows 2000'
else if (majorVer = 5) and (minorVer = 1) then
Result := 'Windows XP'
else if (majorVer = 5) and (minorVer = 2) then
Result := 'Windows 2003'
else if (majorVer = 6) and (minorVer = 0) then
begin
Result := 'Windows Vista';
if osVerInfo.wProductType = VER_NT_WORKSTATION then
Result := 'Windows Vista'
else
Result := 'Windows Server 2008';
end
else if (majorVer = 6) and (minorVer = 1) then
begin
if osVerInfo.wProductType = VER_NT_WORKSTATION then
Result := 'Windows 7'
else
Result := 'Windows Server 2008R2';
end
else if (majorVer = 6) and (minorVer = 2) then
begin
if osVerInfo.wProductType = VER_NT_WORKSTATION then
Result := 'Windows 8'
else
Result := 'Windows Server 2012'
end
else
Result := 'Unknown';
end;
VER_PLATFORM_WIN32_WINDOWS: { Windows 9x/ME }
begin
if (majorVer = 4) and (minorVer = 0) then
Result := 'Windows 95'
else if (majorVer = 4) and (minorVer = 10) then
begin
if osVerInfo.szCSDVersion[1] = 'A' then
Result := 'Windows 98 SE'
else
Result := 'Windows 98';
end
else if (majorVer = 4) and (minorVer = 90) then
Result := 'Windows ME'
else
Result := 'Unknown';
end;
else
Result := 'Unknown';
end;
end
else
Result := 'Unknown';
end;
function TExeInfo.GetWinDir : String;
//Returns the windows directory
var
pcWindowsDirectory : PChar;
dwWDSize : DWORD;
begin
dwWDSize := MAX_PATH + 1;
{$IFDEF DELPHI_UNICODE}
GetMem( pcWindowsDirectory, dwWDSize * 2); // allocate memory for the string
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
GetMem( pcWindowsDirectory, dwWDSize ); // allocate memory for the string
{$ENDIF}
try
if Windows.GetWindowsDirectory( pcWindowsDirectory, dwWDSize ) <> 0 then
Result := StrPas(pcWindowsDirectory) + '\';
finally
FreeMem( pcWindowsDirectory ); // now free the memory allocated for the string
end;
end;
function TExeInfo.MajorVersion: integer;
begin
Result := GetVersionPart(0);
end;
function TExeInfo.MinorVersion: integer;
begin
Result := GetVersionPart(1);
end;
function TExeInfo.ReleaseNumber: integer;
begin
Result := GetVersionPart(2);
end;
function TExeInfo.GetSysDir : String;
//Returns system directory
var
pcSystemDirectory : PChar;
dwSDSize : DWORD;
begin
dwSDSize := MAX_PATH + 1;
{$IFDEF DELPHI_UNICODE}
GetMem( pcSystemDirectory, dwSDSize * 2); // allocate memory for the string
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
GetMem( pcSystemDirectory, dwSDSize ); // allocate memory for the string
{$ENDIF}
try
if Windows.GetSystemDirectory( pcSystemDirectory, dwSDSize ) <> 0 then
Result := StrPas(pcSystemDirectory) + '\';
finally
FreeMem( pcSystemDirectory ); // now free the memory allocated for the string
end;
end;
function TExeInfo.GetTempDir : String;
//Returns temp directory
var
pcTempDirectory : PChar;
dwSDSize : DWORD;
begin
dwSDSize := MAX_PATH + 1;
{$IFDEF DELPHI_UNICODE}
GetMem( pcTempDirectory, dwSDSize * 2); // allocate memory for the string
{$ENDIF}
{$IFNDEF DELPHI_UNICODE}
GetMem( pcTempDirectory, dwSDSize ); // allocate memory for the string
{$ENDIF}
try
if Windows.GetTempPath( dwSDSize, pcTempDirectory ) <> 0 then
Result := pcTempDirectory;
finally
FreeMem( pcTempDirectory ); // now free the memory allocated for the string
end;
end;
function TExeInfo.GetVersion: string;
var
vn: Integer;
begin
vn := GetVersionNr;
Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;
function TExeInfo.GetVersionNr: Integer;
begin
Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;
function TExeInfo.GetVersionPart(idx: integer): integer;
var
sl: TStringList;
verstr: string;
begin
Result := -1;
if FileVersion = '' then
Exit;
verstr := StringReplace(FileVersion,'.',',',[rfReplaceAll]);
sl := TStringList.Create;
try
sl.CommaText := verstr;
if idx < sl.Count then
Result := StrToInt(sl.Strings[idx]);
finally
sl.Free;
end;
end;
procedure TExeInfo.SetVersion(const Value: string);
begin
end;
end.
|
unit uImportaNFe;
interface
uses
Classes, ACBrNFe, ZConnection, ZDataset, pcnNFeRTXT, pcnConversao, funcoes, Controls;
type
TTipoArquivo = (taTXT, taXML);
TCliente = record
Codigo: integer;
Filial: Integer;
Nome: string[60];
CNPJ: string[20];
IE: string[20];
Logradouro: string[60];
Numero: string[20];
Complemento: string[60];
Bairro: string[60];
CodMunicipio: string[7];
Municipio: string[60];
UF: string[2];
CEP: string[9];
Fone: string[10];
Finalidade: Byte;
end;
TProduto = record
Codigo: string[60];
NCM: string[8];
EAN: string[14];
Nome: string[100];
Unidade: string[5];
ST_Pis: string[2];
AliqPis: Currency;
ST_Cofins: string[2];
AliqCofins: Currency;
end;
TImportaNFe = class
private
NFe: TACBrNFe;
Cliente: TCliente;
Produto: TProduto;
bErro: Boolean;
FIDNota: Integer;
FTipoOperacao: string[1];
FSerie: Integer;
FNota: Integer;
FEmissao: TDateTime;
FDatabase: TZConnection;
FArquivo: string;
FEmpresa: Integer;
FEmpresaLogin: Integer;
FEditaNF: Boolean;
FTipoArquivo: TTipoArquivo;
FFinalidade: Byte;
FCalcularIBPT: Boolean;
procedure RemoverUTF8(const AArquivo: string);
function CarregaNFe: Boolean;
function CNPJCPF(const AValue: string): string;
function VeCliente(const ACNPJ: string): Boolean;
function VeProduto(const AProduto: string; AItem: Integer): Boolean;
function VeEmpresa(ACnpj: string): Integer;
function VeNotaAltera(ASerie, ANota: string): Integer;
function VeNotaExiste(AEmpresa, ASerie, ANota: string): Boolean;
procedure AtualizarCadastro;
procedure AtualizarCadProdutos(AItem: Integer);
procedure GravaNotasFiscais;
procedure GravaNotasFiscaisItens;
procedure GravaDuplicatas(ADuplicata: string; AVencimento: TDateTime; AValor: Currency);
procedure AtualizaTotais;
function StatusNFe: Char;
procedure VeCancelamento;
public
constructor Create;
destructor Destroy; override;
property Database: TZConnection read FDatabase write FDatabase;
property Arquivo: string read FArquivo write FArquivo;
property Empresa: Integer read FEmpresa write FEmpresa;
property EditaNF: Boolean read FEditaNF write FEditaNF;
property TipoArquivo: TTipoArquivo read FTipoArquivo write FTipoArquivo;
function ImportaNFe(var AEmissao: TDate): Boolean;
end;
implementation
uses
SysUtils, pcnNFe, DB, udmPrincipal;
{ TImportaNFe }
constructor TImportaNFe.Create;
begin
inherited Create;
NFe := TACBrNFe.Create(nil);
bErro := False;
end;
destructor TImportaNFe.Destroy;
begin
NFe.Free;
inherited Destroy;
end;
procedure TImportaNFe.AtualizarCadastro;
var
Query: TZReadOnlyQuery;
Cliente, Filial: Integer;
Cnpj: string;
begin
with Query, NFe.NotasFiscais.Items[0].NFe do
begin
Query := TZReadOnlyQuery.Create(nil);
try
Query.Connection := FDatabase;
Cnpj := copy(CNPJCPF(Dest.CNPJCPF), 1, 10);
Close;
SQL.Clear;
SQL.Add('select codigo, max(filial)+1 filial from clientes_fornecedores where left(cnpj,10)="' + Cnpj + '"');
Open;
if (FieldByName('codigo').IsNull) and (FieldByName('filial').IsNull) then
begin
Cliente := Sequenciador('clientes');
Filial := 1;
end
else
begin
Cliente := FieldByName('codigo').Value;
Filial := FieldByName('filial').Value;
end;
Close;
sql.clear;
sql.Add('insert into clientes_fornecedores');
sql.Add(' (codigo,filial,tipo_cadastro,tipo_pessoa,nome,fantasia,cnpj,ie,logradouro,numero,');
sql.Add(' complemento,bairro,cep,codigo_cidade,cidade,uf,nome_pais,codigo_pais,telefone1,');
sql.Add(' user_inclusao,data_inclusao)');
sql.Add('values');
sql.Add(' (:codigo,:filial,"A",:tipo_pessoa,:nome,:fantasia,:cnpj,:ie,:logradouro,:numero,');
sql.Add(' :complemento,:bairro,:cep,:codigo_cidade,:cidade,:uf,:nome_pais,:codigo_pais,:telefone1,');
sql.Add(' "IMPORTADO",current_date)');
ParamByName('codigo').Value := Cliente;
ParamByName('filial').Value := Filial;
if Length(Dest.CNPJCPF) > 11 then
ParamByName('tipo_pessoa').Value := 'J'
else
ParamByName('tipo_pessoa').Value := 'F';
ParamByName('nome').Value := AnsiUpperCase(Dest.xNome);
ParamByName('fantasia').Value := Copy(AnsiUpperCase(Dest.xNome), 1, 43) + ' - ' + FormatFloat('000', Filial);
ParamByName('cnpj').Value := CNPJCPF(Dest.CNPJCPF);
ParamByName('ie').Value := Dest.IE;
ParamByName('logradouro').Value := AnsiUpperCase(Dest.EnderDest.xLgr);
ParamByName('numero').Value := AnsiUpperCase(Dest.EnderDest.nro);
ParamByName('complemento').Value := AnsiUpperCase(Dest.EnderDest.xCpl);
ParamByName('bairro').Value := AnsiUpperCase(Dest.EnderDest.xBairro);
ParamByName('cep').Value := FormataCep(IntToStr(Dest.EnderDest.CEP));
ParamByName('codigo_cidade').Value := IntToStr(Dest.EnderDest.cMun);
ParamByName('cidade').Value := AnsiUpperCase(Dest.EnderDest.xMun);
ParamByName('uf').Value := AnsiUpperCase(Dest.EnderDest.UF);
ParamByName('nome_pais').Value := AnsiUpperCase(Dest.EnderDest.xPais);
ParamByName('codigo_pais').Value := IntToStr(Dest.EnderDest.cPais);
if Copy(Dest.EnderDest.fone, 1, 1) = '0' then
ParamByName('telefone1').Value := Copy(Dest.EnderDest.fone, 2, Length(Dest.EnderDest.fone))
else
ParamByName('telefone1').Value := Dest.EnderDest.fone;
ExecSQL;
finally
FreeAndNil(Query);
end;
end;
end;
function TImportaNFe.CarregaNFe: Boolean;
var
NFeRTXT: TNFeRTXT;
bTxt: Boolean;
begin
NFe.NotasFiscais.Clear;
NFe.NotasFiscais.Add;
NFeRTXT := TNFeRTXT.Create(NFe.NotasFiscais.Items[0].NFe);
try
RemoverUTF8(FArquivo);
NFeRTXT.CarregarArquivo(FArquivo);
if NFeRTXT.LerTxt then
Result := True
else
begin
NFe.NotasFiscais.Clear;
try
NFe.NotasFiscais.LoadFromFile(FArquivo);
except
Result := False;
end;
Result := True;
end;
finally
NFeRTXT.Free
end;
end;
procedure TImportaNFe.RemoverUTF8(const AArquivo: string);
var
Arquivo: TStringList;
Linha: string;
begin
Arquivo := TStringList.Create;
try
Arquivo.LoadFromFile(AArquivo);
if Arquivo.Count = 0 then
Exit;
Linha := Trim(Arquivo[0]);
if copy(Linha, 1, 3) = '' then
begin
Arquivo[0] := Trim(Copy(Linha, 4, Length(Linha) - 3));
Arquivo.SaveToFile(AArquivo);
end;
finally
Arquivo.Free;
end;
end;
function TImportaNFe.CNPJCPF(const AValue: string): string;
begin
if Length(AValue) > 11 then
Result := FormataCnpj(AValue)
else
Result := FormataCpf(AValue);
end;
procedure TImportaNFe.GravaNotasFiscais;
var
Query: TZReadOnlyQuery;
sObservacoes: string;
i: Integer;
begin
sObservacoes := '';
bErro := False;
try
if CarregaNFe then
if VeCliente(NFe.NotasFiscais.Items[0].NFe.Dest.CNPJCPF) then
with Query, NFe.NotasFiscais.Items[0].NFe do
begin
FEmpresaLogin := VeEmpresa(Emit.CNPJCPF);
if not (FEmpresaLogin <> 0) then
begin
bErro := True;
Exit;
end;
Query := TZReadOnlyQuery.Create(nil);
try
Connection := FDatabase;
FIDNota := VeNotaAltera(IntToStr(Ide.serie), IntToStr(Ide.nNF));
if FIDNota > 0 then
begin
Close;
SQL.Clear;
SQL.Add('delete from notas_fiscais where id=' + IntToStr(FIDNota));
ExecSQL;
Close;
SQL.Clear;
SQL.Add('delete from notas_fiscais_eletronicas where id=' + IntToStr(FIDNota));
ExecSQL;
Close;
SQL.Clear;
SQL.Add('delete from notas_fiscais_itens where id_nota=' + IntToStr(FIDNota));
ExecSQL;
Close;
SQL.Clear;
SQL.Add('delete from duplicatas where tipo="NF" and documento=' + IntToStr(FIDNota));
ExecSQL;
end
else if VeNotaExiste(IntToStr(FEmpresaLogin), IntToStr(Ide.serie), IntToStr(Ide.nNF)) then
begin
bErro := True;
Exit;
end
else
FIDNota := Sequenciador('notas_fiscais', FEmpresa);
Close;
sql.clear;
sql.add('insert into notas_fiscais(');
sql.add(' id, tipo_operacao, empresa_codigo, serie, nota, modelo, cfop, cfop_dv, ');
sql.add(' nat_operacao, emissao, saida, vencimento, quantidade_volumes, especie_volumes, marca_volumes, ');
sql.add(' peso_liquido, peso_bruto, tipo_frete, fatura, tipo_pagamento, valor_produtos, ');
sql.add(' valor_nota, base_icms, valor_icms, base_st_retido, valor_st_retido, frete, seguro, outras_despesas, ');
sql.add(' desconto, cliente_codigo, cliente_filial, cliente_nome, cliente_cnpj, cliente_ie, end_logradouro, ');
sql.add(' end_numero, end_complemento, end_bairro, end_codigo_cidade, end_cidade, end_uf, end_nome_pais, ');
sql.add(' end_codigo_pais, end_cep, telefone, transp_placa, transp_placa_uf, transp_nome, transp_cnpj,ipi,pis,cofins, ');
sql.add(' transp_ie, transp_logradouro, transp_numero, transp_cidade, transp_uf, observacoes, observacoes1, emitido, finalidade)');
sql.add('values(');
sql.add(' :id, :tipo_operacao, :empresa_codigo, :serie, :nota, :modelo, :cfop, :cfop_dv, ');
sql.add(' :nat_operacao, :emissao, :saida, :vencimento, :quantidade_volumes, :especie_volumes, :marca_volumes, ');
sql.add(' :peso_liquido, :peso_bruto, :tipo_frete, :fatura, :tipo_pagamento, :valor_produtos, ');
sql.add(' :valor_nota, :base_icms, :valor_icms, :base_substituicao, :valor_substituicao, :frete, :seguro, :outras_despesas, ');
sql.add(' :desconto, :cliente_codigo, :cliente_filial, :cliente_nome, :cliente_cnpj, :cliente_ie, :end_logradouro, ');
sql.add(' :end_numero, :end_complemento, :end_bairro, :end_codigo_cidade, :end_cidade, :end_uf, :end_nome_pais, ');
sql.add(' :end_codigo_pais, :end_cep, :telefone, :transp_placa, :transp_placa_uf, :transp_nome, :transp_cnpj,:ipi,:pis,:cofins, ');
sql.add(' :transp_ie, :transp_logradouro, :transp_numero, :transp_cidade, :transp_uf, :observacoes, :observacoes1, :emitido, :finalidade)');
ParamByName('id').Value := FIDNota;
case Ide.tpNF of
tnEntrada: FTipoOperacao := 'E';
tnSaida: FTipoOperacao := 'S';
end;
FSerie := Ide.serie;
FNota := Ide.nNF;
FEmissao := Ide.dEmi;
ParamByName('tipo_operacao').Value := FTipoOperacao;
ParamByName('empresa_codigo').Value := FEmpresaLogin;
ParamByName('serie').Value := FSerie;
ParamByName('nota').Value := FNota;
ParamByName('modelo').Value := ide.modelo;
ParamByName('cfop').Value := Det.Items[0].Prod.CFOP;
ParamByName('cfop_dv').Value := 1;
ParamByName('nat_operacao').Value := AnsiUpperCase(Ide.natOp);
ParamByName('emissao').Value := FEmissao;
ParamByName('saida').Value := Ide.dSaiEnt;
if Cobr.Dup.Count > 0 then
begin
ParamByName('tipo_pagamento').Value := 'D';
try
ParamByName('vencimento').AsDateTime := Cobr.Dup.Items[0].dVenc;
for i := 0 to Cobr.Dup.Count - 1 do
GravaDuplicatas(Cobr.Dup.Items[i].nDup, Cobr.Dup.Items[i].dVenc, Cobr.Dup.Items[i].vDup);
except
end;
end
else
begin
case Ide.indPag of
ipVista:
begin
ParamByName('tipo_pagamento').Value := 'V';
ParamByName('vencimento').Value := ParamByName('emissao').Value;
end;
ipPrazo:
begin
ParamByName('tipo_pagamento').Value := 'C';
end;
ipOutras:
begin
ParamByName('tipo_pagamento').Value := 'O';
end;
end;
end;
if Transp.Vol.Count > 0 then
begin
ParamByName('quantidade_volumes').Value := Transp.Vol.Items[0].qVol;
ParamByName('especie_volumes').Value := AnsiUpperCase(Transp.Vol.Items[0].esp);
ParamByName('marca_volumes').Value := AnsiUpperCase(Transp.Vol.Items[0].marca);
ParamByName('peso_liquido').AsFloat := Transp.Vol.Items[0].pesoL;
ParamByName('peso_bruto').AsFloat := Transp.Vol.Items[0].pesoB;
end
else
begin
ParamByName('quantidade_volumes').Value := 0;
ParamByName('especie_volumes').Clear;
ParamByName('marca_volumes').Clear;
ParamByName('peso_liquido').Clear;
ParamByName('peso_bruto').Clear;
end;
case Transp.modFrete of
mfContaEmitente: ParamByName('tipo_frete').Value := 'E';
mfContaDestinatario: ParamByName('tipo_frete').Value := 'D';
mfContaTerceiros: ParamByName('tipo_frete').Value := 'T';
mfSemFrete: ParamByName('tipo_frete').Value := 'S';
end;
ParamByName('fatura').Clear;
ParamByName('valor_produtos').AsFloat := Total.ICMSTot.vProd;
ParamByName('valor_nota').AsFloat := Total.ICMSTot.vNF;
ParamByName('base_icms').AsFloat := Total.ICMSTot.vBC;
ParamByName('valor_icms').AsFloat := Total.ICMSTot.vICMS;
ParamByName('base_substituicao').AsFloat := Total.ICMSTot.vBCST;
ParamByName('valor_substituicao').AsFloat := Total.ICMSTot.vST;
ParamByName('frete').AsFloat := Total.ICMSTot.vFrete;
ParamByName('seguro').AsFloat := Total.ICMSTot.vSeg;
ParamByName('outras_despesas').AsFloat := Total.ICMSTot.vOutro;
ParamByName('desconto').AsFloat := Total.ICMSTot.vDesc;
ParamByName('ipi').AsFloat := Total.ICMSTot.vIPI;
ParamByName('pis').AsFloat := Total.ICMSTot.vPIS;
ParamByName('cofins').AsFloat := Total.ICMSTot.vCOFINS;
ParamByName('cliente_codigo').Value := Cliente.Codigo;
ParamByName('cliente_filial').Value := Cliente.Filial;
ParamByName('cliente_nome').Value := Cliente.Nome;
ParamByName('cliente_cnpj').Value := Cliente.CNPJ;
ParamByName('cliente_ie').Value := Cliente.IE;
ParamByName('end_logradouro').Value := Cliente.Logradouro;
ParamByName('end_numero').Value := Cliente.Numero;
ParamByName('end_complemento').Value := Cliente.Complemento;
ParamByName('end_bairro').Value := Cliente.Bairro;
ParamByName('end_codigo_cidade').Value := Cliente.CodMunicipio;
ParamByName('end_cidade').Value := Cliente.Municipio;
ParamByName('end_uf').Value := Cliente.UF;
ParamByName('end_nome_pais').Value := Dest.EnderDest.xPais;
ParamByName('end_codigo_pais').Value := Dest.EnderDest.cPais;
ParamByName('end_cep').Value := Cliente.CEP;
ParamByName('telefone').Value := Cliente.Fone;
ParamByName('transp_placa').Value := AnsiUpperCase(Transp.veicTransp.placa);
ParamByName('transp_placa_uf').Value := AnsiUpperCase(Transp.veicTransp.UF);
ParamByName('transp_nome').Value := AnsiUpperCase(Transp.Transporta.xNome);
ParamByName('transp_cnpj').Value := Transp.Transporta.CNPJCPF;
ParamByName('transp_ie').Value := Transp.Transporta.IE;
ParamByName('transp_logradouro').Value := AnsiUpperCase(Transp.Transporta.xEnder);
ParamByName('transp_numero').Clear;
ParamByName('transp_cidade').Value := AnsiUpperCase(Transp.Transporta.xMun);
ParamByName('transp_uf').Value := AnsiUpperCase(Transp.Transporta.UF);
sObservacoes := AnsiUpperCase(InfAdic.infCpl);
ParamByName('observacoes').AsString := sObservacoes;
ParamByName('observacoes1').Value := AnsiUpperCase(InfAdic.infAdFisco);
if dmPrincipal.CodigoUsuario = 9999 then
ParamByName('emitido').AsInteger := 1
else
ParamByName('emitido').AsInteger := 0;
ParamByName('finalidade').AsInteger := Cliente.Finalidade;
FFinalidade := Cliente.Finalidade;
if (Length(Cliente.CNPJ) < 18) and (Cliente.Finalidade = 1) then
begin
ParamByName('finalidade').AsInteger := 2;
FFinalidade := 2;
end;
ExecSQL;
finally
FreeAndNil(Query);
end;
end;
except
bErro := True;
end;
end;
function TImportaNFe.VeCliente(const ACNPJ: string): Boolean;
function Ve: Boolean;
var
Query: TZReadOnlyQuery;
begin
Result := True;
Query := TZReadOnlyQuery.Create(nil);
try
with Query, Cliente do
begin
if (Length(Trim(ACNPJ)) = 0) or (NFe.NotasFiscais.Items[0].NFe.Dest.EnderDest.cMun = 9999999) then
begin
with NFe.NotasFiscais.Items[0].NFe do
begin
Codigo := 99999;
Filial := 999;
Nome := AnsiUpperCase(Dest.xNome);
CNPJ := '';
IE := '';
Logradouro := AnsiUpperCase(Dest.EnderDest.xLgr);
Numero := AnsiUpperCase(Dest.EnderDest.nro);
Complemento := AnsiUpperCase(Dest.EnderDest.xCpl);
Bairro := AnsiUpperCase(Dest.EnderDest.xBairro);
CodMunicipio := '9999999';
Municipio := 'EXTERIOR';
UF := 'EX';
CEP := FormataCep(IntToStr(Dest.EnderDest.CEP));
if Copy(Dest.EnderDest.fone, 1, 1) = '0' then
Fone := Copy(Dest.EnderDest.fone, 2, Length(Dest.EnderDest.fone))
else
Fone := Dest.EnderDest.fone;
end;
end
else
begin
Connection := FDatabase;
Close;
SQL.clear;
SQL.Add('select * from clientes_fornecedores');
SQL.Add('where replace(replace(replace(cnpj,".",""),"/",""),"-","")=' + ACNPJ);
Open;
if not IsEmpty then
begin
Codigo := FieldByName('codigo').Value;
Filial := FieldByName('filial').Value;
Nome := AnsiUpperCase(FieldByName('nome').AsString);
CNPJ := FieldByName('cnpj').AsString;
IE := FieldByName('ie').AsString;
Logradouro := AnsiUpperCase(FieldByName('logradouro').AsString);
Numero := AnsiUpperCase(FieldByName('numero').AsString);
Complemento := AnsiUpperCase(FieldByName('complemento').AsString);
Bairro := AnsiUpperCase(FieldByName('bairro').AsString);
CodMunicipio := FieldByName('codigo_cidade').AsString;
Municipio := AnsiUpperCase(FieldByName('cidade').AsString);
UF := AnsiUpperCase(FieldByName('uf').AsString);
CEP := FieldByName('cep').AsString;
Fone := FieldByName('telefone1').AsString;
Finalidade := StrToIntDef(FieldByName('finalidade').AsString, 1);
end
else
Result := False;
end;
end;
finally
FreeAndNil(Query);
end;
end;
begin
Result := False;
if not Ve then
begin
try
AtualizarCadastro;
Result := Ve;
except
Result := False;
end;
end
else
Result := True;
end;
procedure TImportaNFe.GravaNotasFiscaisItens;
var
Query: TZReadOnlyQuery;
pIcms, reducao, vBase, vIcms, vBaseST, vST, vBaseSTRetido, vSTRetido: Currency;
pIcmsST, ReducaoST, pMVA: Currency;
BasePisCofins: Currency;
i: Integer;
modIcms, modIcmsST: string;
begin
with Query, NFe.NotasFiscais.Items[0].NFe do
begin
Query := TZReadOnlyQuery.Create(nil);
try
Connection := FDatabase;
for I := 0 to Det.Count - 1 do
begin
if VeProduto(Det.Items[I].Prod.cProd, I) then
with Det.Items[I], Produto do
begin
Close;
sql.clear;
sql.add('insert into notas_fiscais_itens(');
sql.add(' id,id_nota,tipo_operacao,empresa_codigo,serie,nota,emissao,cliente_codigo,cliente_filial,');
sql.add(' cfop_item,cfop_dv_item,num_item,produto_codigo,produto_ncm,produto_ean,produto_nome,');
sql.add(' produto_inf_adcional,cst,unidade,quantidade,valor_unitario,valor_total,desconto_item,');
sql.add(' icms_item,reducao_item,base_icms_item,valor_icms_item,user_inclusao,data_inclusao,');
sql.add(' base_st_item,valor_st_item,base_st_retido_item,valor_st_retido_item,ipi_item,valor_ipi_item,');
sql.Add(' cst_ipi,base_ipi_item,mod_icms,mod_icms_st,mva_st,icms_retido_item,reducao_st_retido_item,');
sql.Add(' frete_item,seguro_item,despesa_item,base_pis_cofins_item,cst_pis,pis_item,valor_pis_item,');
SQL.add(' cst_cofins,cofins_item,valor_cofins_item,calcula_icms,calcula_ipi,calcula_icms_st,calcula_pis,');
SQL.Add(' calcula_cofins,tributos_item)');
sql.add('values(');
sql.add(' :id,:id_nota,:tipo_operacao,:empresa_codigo,:serie,:nota,:emissao,:cliente_codigo,:cliente_filial,');
sql.add(' :cfop_item,:cfop_dv_item,:num_item,:produto_codigo,:produto_ncm,:produto_ean,:produto_nome,');
sql.add(' :produto_inf_adcional,:cst,:unidade,:quantidade,:valor_unitario,:valor_total,:desconto_item,');
sql.add(' :icms_item,:reducao_item,:base_icms_item,:valor_icms_item,:user_inclusao,:data_inclusao,');
sql.add(' :base_st_item,:valor_st_item,:base_st_retido_item,:valor_st_retido_item,:ipi_item,:valor_ipi_item,');
sql.Add(' :cst_ipi,:base_ipi_item,:mod_icms,:mod_icms_st,:mva_st,:icms_retido_item,:reducao_st_retido_item,');
sql.Add(' :frete_item,:seguro_item,:despesa_item,:base_pis_cofins_item,:cst_pis,:pis_item,:valor_pis_item,');
SQL.add(' :cst_cofins,:cofins_item,:valor_cofins_item,"N","N","N","N","N",:tributos_item)');
ParamByName('id').Value := Sequenciador('notas_fiscais_itens', FEmpresa);
ParamByName('id_nota').Value := FIDNota;
ParamByName('tipo_operacao').Value := FTipoOperacao;
ParamByName('empresa_codigo').Value := FEmpresaLogin;
ParamByName('serie').Value := FSerie;
ParamByName('nota').Value := FNota;
ParamByName('emissao').Value := FEmissao;
ParamByName('cliente_codigo').Value := Cliente.Codigo;
ParamByName('cliente_filial').Value := Cliente.Filial;
ParamByName('cfop_item').Value := Prod.CFOP;
ParamByName('cfop_dv_item').Value := 1;
ParamByName('num_item').Value := Prod.nItem;
ParamByName('produto_codigo').Value := AnsiUpperCase(Codigo);
ParamByName('produto_ncm').Value := NCM;
ParamByName('produto_ean').Value := EAN;
ParamByName('produto_nome').Value := AnsiUpperCase(Nome);
ParamByName('produto_inf_adcional').Value := AnsiUpperCase(infAdProd);
if dmPrincipal.simples_nacional then
ParamByName('cst').Value := OrigToStr(Imposto.ICMS.orig) + CSOSNIcmsToStr(Imposto.ICMS.CSOSN)
else
ParamByName('cst').Value := OrigToStr(Imposto.ICMS.orig) + CSTICMSToStr(Imposto.ICMS.CST);
ParamByName('unidade').Value := AnsiUpperCase(Unidade);
ParamByName('quantidade').AsFloat := Prod.qCom;
ParamByName('valor_unitario').AsFloat := Prod.vUnCom;
ParamByName('valor_total').AsFloat := Prod.vProd;
ParamByName('desconto_item').AsFloat := Prod.vDesc;
ParamByName('user_inclusao').Value := dmPrincipal.usuario;
ParamByName('data_inclusao').Value := Date;
ParamByName('frete_item').AsFloat := Prod.vFrete;
ParamByName('seguro_item').AsFloat := Prod.vSeg;
ParamByName('despesa_item').AsFloat := Prod.vOutro;
if not StringEmBranco(CSTPISToStr(Imposto.PIS.CST)) then
begin
ParamByName('cst_pis').AsString := CSTPISToStr(Imposto.PIS.CST);
ParamByName('pis_item').AsFloat := Imposto.PIS.pPIS;
end
else
begin
ParamByName('cst_pis').AsString := ST_Pis;
ParamByName('pis_item').AsFloat := AliqPis;
end;
if not StringEmBranco(CSTCOFINSToStr(Imposto.COFINS.CST)) then
begin
ParamByName('cst_cofins').AsString := CSTCOFINSToStr(Imposto.COFINS.CST);
ParamByName('cofins_item').AsFloat := Imposto.COFINS.pCOFINS;
end
else
begin
ParamByName('cst_cofins').AsString := ST_Cofins;
ParamByName('cofins_item').AsFloat := AliqCofins;
end;
if (ParamByName('cst_pis').AsString = '01') or (ParamByName('cst_pis').AsString = '02') then
begin
BasePisCofins := Imposto.PIS.vBC;
if BasePisCofins = 0 then
BasePisCofins := Imposto.COFINS.vBC;
if BasePisCofins = 0 then
BasePisCofins := prod.vProd - Prod.vDesc + Prod.vFrete + Prod.vSeg + Prod.vOutro;
ParamByName('base_pis_cofins_item').AsFloat := BasePisCofins;
if Imposto.PIS.vPIS = 0 then
ParamByName('valor_pis_item').AsFloat := BasePisCofins * ParamByName('pis_item').AsFloat / 100
else
ParamByName('valor_pis_item').AsFloat := Imposto.PIS.vPIS;
end
else
begin
ParamByName('base_pis_cofins_item').AsFloat := 0;
ParamByName('valor_pis_item').AsFloat := 0;
end;
if (ParamByName('cst_cofins').AsString = '01') or (ParamByName('cst_cofins').AsString = '02') then
begin
if Imposto.COFINS.vCOFINS = 0 then
ParamByName('valor_cofins_item').AsFloat := BasePisCofins * ParamByName('cofins_item').AsFloat / 100
else
ParamByName('valor_cofins_item').AsFloat := Imposto.COFINS.vCOFINS;
end
else
ParamByName('valor_cofins_item').AsFloat := 0;
pIcms := 0;
reducao := 0;
vBase := 0;
vIcms := 0;
vBaseST := 0;
vST := 0;
vBaseSTRetido := 0;
vSTRetido := 0;
modIcms := '';
modIcmsST := '';
pIcmsST := 0;
ReducaoST := 0;
pMVA := 0;
with Imposto do
begin
if ICMS.CST = cst00 then //Tributado integralmente
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
modIcms := modBCToStr(ICMS.modBC);
end
else if ICMS.CST = cst10 then //Tributado e com cobrança do ICMS por ST
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
modIcms := modBCToStr(ICMS.modBC);
vBaseSTRetido := ICMS.vBCST;
vSTRetido := ICMS.vICMSST;
modIcmsST := modBCSTToStr(ICMS.modBCST);
pIcmsST := ICMS.pICMSST;
ReducaoST := ICMS.pRedBCST;
pMVA := ICMS.pMVAST;
end
else if ICMS.CST = cst20 then //Com redução da base de calculo
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
modIcms := modBCToStr(ICMS.modBC);
if (ICMS.pRedBC > 0) and (ICMS.vBC > 0) then
reducao := ICMS.pRedBC;
end
else if ICMS.CST = cst30 then //Isenta ou não tributada com cobrança do ICMS por ST
begin
vBaseSTRetido := ICMS.vBCST;
vSTRetido := ICMS.vICMSST;
pIcmsST := ICMS.pICMSST;
ReducaoST := ICMS.pRedBCST;
pMVA := ICMS.pMVAST;
modIcmsST := modBCSTToStr(ICMS.modBCST);
end
else if ICMS.CST = cst51 then //Diferimento
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
if (ICMS.pRedBC > 0) and (ICMS.vBC > 0) then
reducao := ICMS.pRedBC;
modIcms := modBCToStr(ICMS.modBC);
end
else if ICMS.CST = cst60 then //ICMS cobrado anteriormente por ST
begin
vBaseST := ICMS.vBCST;
vST := ICMS.vICMSST;
end
else if ICMS.CST = cst70 then //Com redução da base de calculo e cobrança por ST
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
if (ICMS.pRedBC > 0) and (ICMS.vBC > 0) then
reducao := ICMS.pRedBC;
vBaseSTRetido := ICMS.vBCST;
vSTRetido := ICMS.vICMSST;
modIcms := modBCToStr(ICMS.modBC);
modIcmsST := modBCSTToStr(ICMS.modBCST);
pMVA := ICMS.pMVAST;
ReducaoST := ICMS.pRedBCST;
pIcmsST := ICMS.pICMSST;
end
else if ICMS.CST = cst90 then //Outras
begin
pIcms := ICMS.pICMS;
vBase := ICMS.vBC;
vIcms := ICMS.vICMS;
if (ICMS.pRedBC > 0) and (ICMS.vBC > 0) then
reducao := ICMS.pRedBC;
vBaseSTRetido := ICMS.vBCST;
vSTRetido := ICMS.vICMSST;
modIcms := modBCToStr(ICMS.modBC);
modIcmsST := modBCSTToStr(ICMS.modBCST);
pMVA := ICMS.pMVAST;
ReducaoST := ICMS.pRedBCST;
pIcmsST := ICMS.pICMSST;
end;
if (IPI.vBC > 0) then
begin
with IPI do
begin
if Length(CSTIPIToStr(CST)) > 0 then
ParamByName('cst_ipi').AsString := CSTIPIToStr(CST)
else
ParamByName('cst_ipi').Clear;
ParamByName('base_ipi_item').AsFloat := vBC;
ParamByName('ipi_item').AsFloat := pIPI;
ParamByName('valor_ipi_item').AsFloat := vIPI;
end;
end
else
begin
ParamByName('cst_ipi').Clear;
ParamByName('base_ipi_item').AsFloat := 0;
ParamByName('ipi_item').AsFloat := 0;
ParamByName('valor_ipi_item').AsFloat := 0;
end;
end;
ParamByName('icms_item').AsFloat := pIcms;
ParamByName('reducao_item').AsFloat := reducao;
ParamByName('base_icms_item').AsFloat := vBase;
ParamByName('valor_icms_item').AsFloat := vIcms;
ParamByName('base_st_item').AsFloat := vBaseST;
ParamByName('valor_st_item').AsFloat := vST;
ParamByName('base_st_retido_item').AsFloat := vBaseSTRetido;
ParamByName('valor_st_retido_item').AsFloat := vSTRetido;
ParamByName('mva_st').AsFloat := pMVA;
ParamByName('icms_retido_item').AsFloat := pIcmsST;
ParamByName('reducao_st_retido_item').AsFloat := ReducaoST;
ParamByName('mod_icms').AsString := modIcms;
ParamByName('mod_icms_st').AsString := modIcmsST;
//Lei 12.741/2012 { *** Finalidade 2 <-> Consumidor Final *** }
if (FFinalidade = 2) or (FCalcularIBPT) then
begin
if StrToIntDef(Copy(ParamByName('cst').AsString, 1, 1), 0) in [0, 3, 4, 5] then //Produto Nacional
ParamByName('tributos_item').AsFloat := ParamByName('valor_total').AsFloat * IndiceIBPT(ParamByName('produto_ncm').AsString) / 100
else
ParamByName('tributos_item').AsFloat := ParamByName('valor_total').AsFloat * IndiceIBPT(ParamByName('produto_ncm').AsString, 'I') / 100;
end;
ExecSQL;
end;
end;
finally
FreeAndNil(Query);
end;
end;
end;
function TImportaNFe.VeNotaAltera(ASerie, ANota: string): Integer;
var
Query: TZReadOnlyQuery;
begin
Query := TZReadOnlyQuery.Create(nil);
try
with Query do
begin
Connection := FDatabase;
Close;
SQL.clear;
SQL.Add('select n.id idt');
SQL.Add('from');
SQL.Add(' notas_fiscais n left join notas_fiscais_eletronicas ne on n.id=ne.id');
SQL.Add('where');
SQL.Add(' (ne.operacao="X" or isnull(ne.id)) and isnull(n.cancelado) and n.nota=' + ANota);
SQL.Add(' and n.serie=' + ASerie);
SQL.Add(' and n.empresa_codigo=:pEmpresa');
ParamByName('pEmpresa').AsInteger := FEmpresa;
Open;
if IsEmpty then
Result := 0
else
Result := FieldByName('idt').AsInteger;
end;
finally
FreeAndNil(Query);
end;
end;
function TImportaNFe.VeNotaExiste(Aempresa, ASerie, ANota: string): Boolean;
var
Query: TZReadOnlyQuery;
begin
Query := TZReadOnlyQuery.Create(nil);
try
with Query do
begin
Connection := FDatabase;
Close;
SQL.clear;
SQL.Add('select n.id idt');
SQL.Add('from');
SQL.Add(' notas_fiscais n join notas_fiscais_eletronicas ne on n.id=ne.id');
SQL.Add('where');
SQL.Add(' ne.operacao<>"X" and n.nota=' + ANota);
SQL.Add(' and n.tipo_pt="P" and n.serie=' + ASerie);
SQL.Add(' and n.empresa_codigo=' + AEmpresa);
Open;
Result := not IsEmpty;
end;
finally
FreeAndNil(Query);
end;
end;
function TImportaNFe.ImportaNFe(var AEmissao: TDate): Boolean;
begin
AEmissao := 0;
try
GravaNotasFiscais;
if not bErro then
begin
GravaNotasFiscaisItens;
if FEditaNF then
grava_notas_eletronica(FIDNota, FEmpresaLogin, FSerie, FNota, FEmissao, 'X')
else
grava_notas_eletronica(FIDNota, FEmpresaLogin, FSerie, FNota, FEmissao, 'A');
if FTipoArquivo = taXML then
begin
if StatusNFe = 'K' then
VeCancelamento;
if CriaTabelaXmlProprio(FormatDateTime('yyyymm', FEmissao)) then
grava_xml_proprio(FIDNota, FEmpresaLogin,
FormatDateTime('yyyymm', FEmissao),
NFe.NotasFiscais.Items[0].NFe.procNFe.chNFe,
NFe.NotasFiscais.Items[0].NFe.procNFe.nProt,
NFe.NotasFiscais.Items[0].XML);
end;
if FTipoArquivo = taTXT then
AtualizaTotais; //Para corrigir erros do HCI
Result := True;
AEmissao := FEmissao;
end
else
Result := False;
except
Result := False;
end;
end;
function TImportaNFe.VeEmpresa(ACnpj: string): Integer;
var
query: TZReadOnlyQuery;
begin
Result := 0;
try
query := TZReadOnlyQuery.Create(nil);
with query do
begin
Connection := FDatabase;
close;
sql.clear;
sql.add('select codigo,calcular_ibpt from empresas');
SQL.add('where replace(replace(replace(cnpj,".",""),"/",""),"-","")=:pCnpj');
ParamByName('pCnpj').AsString := ACnpj;
Open;
if not IsEmpty then
begin
Result := query['codigo'];
FCalcularIBPT := query['calcular_ibpt'] = 'S';
end;
end;
finally
FreeAndNil(query);
end;
end;
procedure TImportaNFe.AtualizarCadProdutos(AItem: Integer);
var
Query: TZReadOnlyQuery;
begin
with Query, NFe.NotasFiscais.Items[0].NFe.Det.Items[AItem] do
begin
Query := TZReadOnlyQuery.Create(nil);
try
Query.Connection := FDatabase;
Close;
sql.clear;
sql.Add('insert into produtos');
sql.Add(' (codigo,codigo_ncm,codigo_ean,nome,unidade,tipo,origem,user_inclusao,data_inclusao)');
sql.Add('values');
sql.Add(' (:codigo,:codigo_ncm,:codigo_ean,:nome,:unidade,"P",:origem,"IMPORTADO",current_date)');
ParamByName('codigo').AsString := AnsiUpperCase(Prod.cProd);
ParamByName('codigo_ncm').AsString := Prod.NCM;
ParamByName('codigo_ean').AsString := Prod.cEAN;
ParamByName('nome').AsString := AnsiUpperCase(Prod.xProd);
ParamByName('unidade').Value := AnsiUpperCase(Prod.uCom);
ParamByName('origem').Value := OrigToStr(Imposto.ICMS.orig);
ExecSQL;
finally
FreeAndNil(Query);
end;
end;
end;
function TImportaNFe.VeProduto(const AProduto: string; AItem: Integer): Boolean;
function Ve: Boolean;
var
Query: TZReadOnlyQuery;
begin
Result := True;
Query := TZReadOnlyQuery.Create(nil);
try
with Query, Produto do
begin
Connection := FDatabase;
Close;
SQL.clear;
SQL.Add('select * from produtos');
SQL.Add('where codigo=:pProduto');
ParamByName('pProduto').AsString := AProduto;
Open;
if not IsEmpty then
begin
Codigo := FieldByName('codigo').AsString;
NCM := FieldByName('codigo_ncm').AsString;
EAN := FieldByName('codigo_ean').AsString;
Nome := AnsiUpperCase(FieldByName('nome').AsString);
Unidade := AnsiUpperCase(FieldByName('unidade').AsString);
if FTipoOperacao = 'S' then
begin
ST_Pis := FieldByName('st_pis_saida').AsString;
AliqPis := FieldByName('aliq_pis').AsCurrency;
ST_Cofins := FieldByName('st_cofins_saida').AsString;
AliqCofins := FieldByName('aliq_cofins').AsCurrency;
end
else
begin
ST_Pis := FieldByName('st_pis_entrada').AsString;
AliqPis := FieldByName('aliq_pis').AsCurrency;
ST_Cofins := FieldByName('st_cofins_entrada').AsString;
AliqCofins := FieldByName('aliq_cofins').AsCurrency;
end;
end
else
Result := False;
end;
finally
FreeAndNil(Query);
end;
end;
begin
Result := False;
if not Ve then
begin
try
AtualizarCadProdutos(AItem);
Result := Ve;
except
Result := False;
end;
end
else
Result := True;
end;
procedure TImportaNFe.AtualizaTotais; //Para corrigir problema do HCI
var
Query: TZReadOnlyQuery;
begin
Query := TZReadOnlyQuery.Create(nil);
try
with Query do
begin
Connection := FDatabase;
Close;
SQL.Clear;
SQL.Add('update notas_fiscais_itens set');
SQL.Add(' base_icms_item=if(base_icms_item>0,(valor_total+frete_item-desconto_item)*(1 - (reducao_item / 100)),0),');
SQL.Add(' valor_icms_item=base_icms_item*icms_item/100');
SQL.Add('where id_nota=:pID');
ParamByName('pID').AsInteger := FIDNota;
ExecSQL;
Close;
SQL.Clear;
SQL.Add('update notas_fiscais set');
SQL.Add(' base_icms=(select round(sum(base_icms_item),2) from notas_fiscais_itens where id_nota=:pID),');
SQL.Add(' valor_icms=(select round(sum(valor_icms_item),2) from notas_fiscais_itens where id_nota=:pID),');
SQL.Add(' valor_produtos=(select round(sum(valor_total),2) from notas_fiscais_itens where id_nota=:pID),');
SQL.Add(' total_tributos=(select round(sum(tributos_item),2) from notas_fiscais_itens where id_nota=:pID),');
SQL.Add(' desconto=(select round(sum(desconto_item),2) from notas_fiscais_itens where id_nota=:pID)');
SQL.Add('where id=:pID');
ParamByName('pID').AsInteger := FIDNota;
ExecSQL;
end;
finally
FreeAndNil(Query);
end;
end;
procedure TImportaNFe.GravaDuplicatas(ADuplicata: string; AVencimento: TDateTime; AValor: Currency);
var
Query: TZReadOnlyQuery;
begin
Query := TZReadOnlyQuery.Create(nil);
try
with Query do
begin
Connection := FDatabase;
Close;
SQL.Clear;
SQL.Add('insert into duplicatas(');
SQL.Add(' documento,tipo,duplicata,vencimento,valor)');
SQL.Add('values(');
SQL.Add(' :documento,"NF",:duplicata,:vencimento,:valor)');
ParamByName('documento').AsInteger := FIDNota;
ParamByName('duplicata').AsString := ADuplicata;
ParamByName('vencimento').AsDate := AVencimento;
ParamByName('valor').AsCurrency := AValor;
ExecSQL;
end;
finally
FreeAndNil(Query);
end;
end;
function TImportaNFe.StatusNFe: Char;
var
Query: TZReadOnlyQuery;
NF: TNFe;
begin
Result := 'A';
Query := TZReadOnlyQuery.Create(nil);
Query.Connection := FDatabase;
try
with Query do
begin
Close;
SQL.Clear;
SQL.Add('update notas_fiscais_eletronicas set');
SQL.Add(' operacao=:operacao,');
SQL.Add(' scan="N",');
SQL.Add(' email="S",');
SQL.Add(' producao=:producao,');
SQL.Add(' forma="N",');
SQL.Add(' status=:status,');
SQL.Add(' status_descricao=:status_descricao,');
SQL.Add(' chave=:chave,');
SQL.Add(' protocolo=:protocolo,');
SQL.Add(' cancelamento=:cancelamento,');
SQL.Add(' digest=:digest,');
SQL.Add(' justificativa=:justificativa,');
SQL.Add(' xml="J",');
SQL.Add(' versao=:versao,');
SQL.Add(' ambiente=:ambiente,');
SQL.Add(' data_recibo=:data_recibo');
SQL.Add('where id=:pID');
NF := NFe.NotasFiscais.Items[0].NFe;
if NF.procNFe.cStat in [100, 150] then
begin
Result := 'J';
ParamByName('operacao').AsString := 'J';
end
else if NF.procNFe.cStat in [101, 151, 155] then
begin
Result := 'K';
ParamByName('operacao').AsString := 'K';
end
else
ParamByName('operacao').AsString := 'X';
if NF.procNFe.tpAmb = taProducao then
ParamByName('producao').AsString := 'S'
else
ParamByName('producao').AsString := 'N';
ParamByName('status').AsInteger := NF.procNFe.cStat;
ParamByName('status_descricao').AsString := NF.procNFe.xMotivo;
ParamByName('chave').AsString := NF.procNFe.chNFe;
ParamByName('protocolo').AsString := NF.procNFe.nProt;
ParamByName('cancelamento').Clear;
ParamByName('digest').AsString := NF.procNFe.digVal;
ParamByName('justificativa').Clear;
ParamByName('versao').AsString := NF.procNFe.verAplic;
ParamByName('ambiente').AsString := TpAmbToStr(NF.procNFe.tpAmb);
ParamByName('data_recibo').AsDateTime := NF.procNFe.dhRecbto;
ParamByName('pID').AsInteger := FIDNota;
ExecSQL;
end;
finally
Query.Close;
FreeAndNil(Query);
end;
end;
procedure TImportaNFe.VeCancelamento;
var
Query: TZReadOnlyQuery;
begin
Query := TZReadOnlyQuery.Create(nil);
try
Query.Connection := FDatabase;
Query.SQL.Text := 'update notas_fiscais set cancelado=:pCancelado where id=:pID';
Query.ParamByName('pID').AsInteger := FIDNota;
Query.ParamByName('pCancelado').AsDate := NFe.NotasFiscais.Items[0].NFe.procNFe.dhRecbto;
Query.ExecSQL;
finally
FreeAndNil(Query);
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2015-2018 Kike Pérez
Unit : Quick.Network
Description : Network related functions
Author : Kike Pérez
Version : 1.4
Created : 11/07/2017
Modified : 07/04/2018
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Network;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
Math,
IdDNSResolver;
type
TDNSResolve = class
private
fHost : string;
fPort : Integer;
function ResolveDNS(const aDNS : string; aRegType: TQueryRecordTypes): string;
public
constructor Create(const aNameServer : string = '8.8.8.8'; aServerPort : Integer = 53);
function ResolveA(const aDNS : string): string;
function ResolveAAAA(const aDNS : string): string;
function ResolveCNAME(const aDNS : string): string;
function ResolveNS(const aDNS : string): string;
function ResolveTXT(const aDNS : string): string;
end;
function IntToIPv4(IPv4: LongWord): string;
function IPv4ToInt(const IPv4: string) : LongWord;
function IPv4ToIntReverse(const IPv4: string) : LongWord;
procedure CIDRToRange(CIDR : string; out MinIP,MaxIP : string); overload;
procedure CIDRToRange(CIDR : string; out MinIP,MaxIP : LongWord); overload;
procedure GetIPRange(const cIP, cMask : string; out LowIP, HighIP : string);
implementation
function IntToIPv4(IPv4: LongWord): string;
var
Retvar : string;
iSeg,iShift,
i, iMask : LongWord;
begin
Retvar := '';
iShift := 24;
iMask := $FF000000;
for i := 1 to 4 do
begin
iSeg := (IPv4 and iMask) shr iShift;
Retvar := Retvar + IntToStr(iSeg);
if i < 4 then Retvar := Retvar + '.';
iMask := iMask shr 8;
dec(iShift,8);
end;
Result := Retvar;
end;
function IPv4ToInt(const IPv4: string) : LongWord;
var
S : TStrings;
begin
S := TStringList.Create;
try
S.Delimiter := '.';
S.DelimitedText := IPv4;
if S.Count <> 4 then raise Exception.Create('Invalid IP4 Address string');
Result := (StrToInt(S[0]) shl 24) + (StrToInt(S[1]) shl 16) + (StrToInt(S[2]) shl 8) + StrToInt(S[3]);
finally
S.Free;
end;
end;
function IPv4ToIntReverse(const IPv4: string) : LongWord;
var
S : TStrings;
begin
S := TStringList.Create;
try
S.Delimiter := '.';
S.DelimitedText := IPv4;
if S.Count <> 4 then raise Exception.Create('Invalid IP4 Address string');
Result := (StrToInt(S[3]) shl 24) + (StrToInt(S[2]) shl 16) + (StrToInt(S[1]) shl 8) + StrToInt(S[0]);
finally
S.Free;
end;
end;
procedure CIDRToRange(CIDR : string; out MinIP,MaxIP : string);
var
Mask : Integer;
begin
Mask := StrToInt(Copy(CIDR,Pos('/',CIDR)+1,CIDR.Length));
CIDR := Copy(CIDR,0,Pos('/',CIDR)-1);
MinIP := IntToIPv4((IPv4ToInt(CIDR)) and ((-1 shl (32 - Mask))));
MaxIP := IntToIPv4((IPv4ToInt(MinIP)) + Round(Power(2,(32 - Mask))) - 1);
end;
procedure CIDRToRange(CIDR : string; out MinIP,MaxIP : LongWord);
var
Mask : Integer;
aux : string;
begin
Mask := StrToInt(Copy(CIDR,Pos('/',CIDR)+1,CIDR.Length));
CIDR := Copy(CIDR,0,Pos('/',CIDR)-1);
aux := IntToIPv4((IPv4ToInt(CIDR)) and ((-1 shl (32 - Mask))));
MinIP := IPv4ToInt(aux);
aux := IntToIPv4((IPv4ToInt(aux)) + Round(Power(2,(32 - Mask))) - 1);
MaxIP := IPv4ToInt(aux);
end;
procedure GetIPRange(const cIP, cMask : string; out LowIP, HighIP : string);
begin
try
LowIP := IntToIPv4((IPv4ToInt(cIP) and (IPv4ToInt(cMask)) + 1));
HighIP := IntToIPv4(IPv4ToInt(cIP) or not(IPv4ToInt(cMask))-1);
except
on E : Exception do raise Exception.Create(Format('GetIPRange error: %s',[e.Message]));
end;
end;
{ TDNSResolve }
constructor TDNSResolve.Create(const aNameServer : string = '8.8.8.8'; aServerPort : Integer = 53);
begin
fHost := aNameServer;
fPort := aServerPort;
end;
function TDNSResolve.ResolveDNS(const aDNS : string; aRegType: TQueryRecordTypes): string;
var
dnsresolver : TIdDNSResolver;
begin
Result := '';
dnsresolver := TIdDNSResolver.Create(nil);
try
dnsresolver.Host := fHost;
dnsresolver.Port := fPort;
dnsresolver.QueryResult.Clear;
dnsresolver.QueryType := [aRegType];
dnsresolver.Resolve(aDNS);
if dnsresolver.QueryResult.Count > 0 then
begin
if dnsresolver.QueryResult[0].RecType = aRegType then
begin
case aRegType of
qtNS : Result := TNSRecord(dnsresolver.QueryResult.Items[0]).HostName;
qtA : Result := TARecord(dnsresolver.QueryResult.Items[0]).IPAddress;
qtAAAA : Result := TAAAARecord(dnsresolver.QueryResult.Items[0]).Address;
qtNAME : Result := TCNRecord(dnsresolver.QueryResult.Items[0]).HostName;
qtTXT : Result := TTextRecord(dnsresolver.QueryResult.Items[0]).Text.Text;
else raise Exception.Create('Not implemented yet!');
end;
end;
end;
finally
dnsresolver.Free;
end;
end;
function TDNSResolve.ResolveNS(const aDNS : string): string;
begin
Result := ResolveDNS(aDNS,qtNS);
end;
function TDNSResolve.ResolveA(const aDNS : string): string;
begin
Result := ResolveDNS(aDNS,qtA);
end;
function TDNSResolve.ResolveAAAA(const aDNS : string): string;
begin
Result := ResolveDNS(aDNS,qtAAAA);
end;
function TDNSResolve.ResolveCNAME(const aDNS : string): string;
begin
Result := ResolveDNS(aDNS,qtName);
end;
function TDNSResolve.ResolveTXT(const aDNS : string): string;
begin
Result := ResolveDNS(aDNS,qtTXT);
end;
end.
|
unit nsUnderControlRoot;
////////////////////////////////////////////////////////////////////////////////
// Библиотека : Проект Немезис;
// Назначение : Корень списка документов на контроле;
// Версия : $Id: nsUnderControlRoot.pas,v 1.5 2013/06/03 11:51:37 kostitsin Exp $
////////////////////////////////////////////////////////////////////////////////
interface
uses
afwInterfaces,
l3TreeInterfaces,
l3Tree_TLB,
l3Interfaces,
l3LongintList,
BaseTreeSupportUnit,
nsNodes,
nsTypes,
FoldersDomainInterfaces
;
type
TnsUnderControlRoot = class(TnsCacheableNode,
InsUnderControlRoot)
private
// fields
f_SortType : TnsUCSortType;
protected
// methods
function pm_GetSortType: TnsUCSortType;
procedure pm_SetSortType(aValue: TnsUCSortType);
function DoCompareChild(const aChildrenNode1, aChildrenNode2 : Il3Node) : Integer;
override;
{* - сравнивает aChildrenNode1 и aChildrenNode2 (обычно Text), возвращает
<0 если aChildrenNode1 < aChildrenNode2
0 если aChildrenNode1 = aChildrenNode2
>0 если aChildrenNode1 > aChildrenNode2
используется при сортировке ветки дерева. }
public
// methods
class function Make: Il3Node;
reintroduce;
{-}
end;//TnsUnderControlRoot
implementation
uses
SysUtils,
l3String,
l3Types,
l3MinMax,
l3Nodes,
l3Base,
vcmBase,
UnderControlUnit,
DataAdapter,
nsUtils,
nsUnderControlNode,
StdRes
;
// Start class TnsUnderControlRoot
class function TnsUnderControlRoot.Make : Il3Node;
var
l_Node : TnsUnderControlRoot;
begin
l_Node := Create(nil, -1, -1);
try
result := l_Node;
finally
FreeAndNil(l_Node);
end;
end;
function TnsUnderControlRoot.pm_GetSortType: TnsUCSortType;
begin
Result := f_SortType;
end;
procedure TnsUnderControlRoot.pm_SetSortType(aValue: TnsUCSortType);
begin
f_SortType := aValue;
SortChilds;
end;
function TnsUnderControlRoot.DoCompareChild(const aChildrenNode1,
aChildrenNode2 : Il3Node): Integer;
//override;
var
l_Controllable1,
l_Controllable2: IControllable;
begin
case f_SortType of
ucstAlphabet :
Result := l3Compare(aChildrenNode1.Text, aChildrenNode2.Text, l3_siCaseUnsensitive);
ucstChanging :
begin
Result := 0;
// сравниваем элементы по типу изменений
if Supports(aChildrenNode1, IControllable, l_Controllable1) and
Supports(aChildrenNode2, IControllable, l_Controllable2) then
try
Result := ULongComp(LongInt(l_Controllable2.GetControlStatus), LongInt(l_Controllable1.GetControlStatus));
finally
l_Controllable1 := nil;
l_Controllable2 := nil;
end;
// если элементы равны, то сортировка по алфавиту
if Result = 0 then
Result := l3Compare(aChildrenNode1.Text, aChildrenNode2.Text, l3_siCaseUnsensitive);
end;
else
Result := 0;
end;
end;
end.
|
unit xNumInWords;
interface
uses
xLngDefs;
//used for money-related purposes mainly
function NumInWords(number: Int64; gender: Tgender; padezh: Tpadezh = padezhIE): String;
function TimeInWords(Value: TDateTime; AFormat: String): String;
// mainly internal functions, but who knows
function weekDayName(ALangID, day: Integer; short: Boolean; padezh: Tpadezh = padezhIE): String;
function monthName(ALangID, month: Integer; short: Boolean; padezh: Tpadezh = padezhIE): String;
function yearInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
function monthInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
function dayInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
function hourInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
function minuteInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
function secondInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
xNumInWords_RUS,
xNumInWords_UKR,
xNumInWords_ENG,
xNumInWords_ESP,
DateUtils, sysUtils, strUtils;
//==============================================================================================
function NumInWords(number: Int64; gender: TGender; padezh: Tpadezh = padezhIE): String;
begin
case RepLangID of
lidRUS: Result := numInWords_RUS(number, gender, padezh);
lidUKR: Result := numInWords_UKR(number, gender, padezh);
lidENG: Result := numInWords_ENG(number);
lidESP: Result := numInWords_ESP(number) + ' ';
else Result := 'no NumInWords for lang: ' + intToStr(langID);
end;
end;
//==============================================================================================
function weekDayName(ALangID, day: Integer; short: Boolean; padezh: Tpadezh = padezhIE): String;
const
ruroots: array[1..7] of String = ('понедельник', 'вторник', 'сред', 'четверг', 'пятниц', 'суббот', 'воскресен');
//1 Имен ед.ч, 2 Имен мн.ч, 3 Родит ед.ч, 4 Родит мн.ч, 5 Дат ед.ч, 6 Дат мн.ч,
//7 Винит ед.ч, 8 Винит мн.ч, 9 Твор ед.ч, 10 Твор мн.ч, 11 Предл ед.ч, 12 Предл мн.ч,
rusuff: array[1..7, TPadezh] of String = (
//1 2 3 4 5 6 7 8 9 10 11 12
('', 'и', '', 'и', 'у', 'ам', '', 'и', 'ом', 'ами', 'е', 'ах'), //понедельник
('', 'и', '', 'и', 'у', 'ам', '', 'и', 'ом', 'ами', 'е', 'ах'), //вторник',
('а', 'ы', 'у', 'ы', 'е', 'ам', 'у', 'ы', 'ой', 'ами', 'е', 'ах'), //сред',
('', 'и', '', 'и', 'у', 'ам', '', 'и', 'ом', 'ами', 'е', 'ах'), //четверг',
('а', 'ы', 'у', 'ы', 'е', 'ам', 'у', 'ы', 'ей', 'ами', 'е', 'ах'), //пятниц',
('а', 'ы', 'у', 'ы', 'е', 'ам', 'у', 'ы', 'ой', 'ами', 'е', 'ах'), //суббот',
('ье', 'ья', 'ье', 'ья', 'ью', 'ьям', 'ье', 'ья', 'ьем', 'ьями', 'ье', 'ьях') //воскресен'
);
rushort: array[1..7] of String = ('пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс');
en: array[1..7] of String = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
enshort: array[1..7] of String = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
begin
case ALangID of
lidUKR, // sorry ;)
lidRUS:
if short
then Result := rushort[day]
else Result := ruroots[day] + rusuff[day, padezh];
lidENG:
if short
then Result := enshort[day]
else Result := en[day];
//lidESP:
end; // case ALangID of
end;
//==============================================================================================
function monthName(ALangID, month: Integer; short: Boolean; padezh: Tpadezh = padezhIE): String;
const
ruroots: array[1..12] of String = ('январ', 'феврал', 'март', 'апрел', 'ма', 'июн', 'июл', 'август', 'сентябр', 'октябр', 'ноябр', 'декабр');
//1 Имен ед.ч, 2 Имен мн.ч, 3 Родит ед.ч, 4 Родит мн.ч, 5 Дат ед.ч, 6 Дат мн.ч,
//7 Винит ед.ч, 8 Винит мн.ч, 9 Твор ед.ч, 10 Твор мн.ч, 11 Предл ед.ч, 12 Предл мн.ч,
rusuff: array[1..12, TPadezh] of String = (
//1 2 3 4 5 6 7 8 9 10 11 12
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях'), // январ
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях'), // феврал
('ь', 'ы', '', 'ов', 'у', 'ам', '', 'ы', 'ом', 'ами', 'е', 'ах'), // март
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ем', 'ями', 'е', 'ях'), // апрел
('й', 'и', 'й', 'ев', 'ю', 'ям', 'й', 'и', 'ем', 'ями', 'е', 'ях'), // ма
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ем', 'ями', 'е', 'ях'), // июн
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ем', 'ями', 'е', 'ях'), // июл
('', 'ы', '', 'ов', 'у', 'ам', '', 'ы', 'ом', 'ами', 'е', 'ах'), // август
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях'), // сентябр
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях'), // октябр
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях'), // ноябр
('ь', 'и', 'ь', 'ей', 'ю', 'ям', 'ь', 'и', 'ём', 'ями', 'е', 'ях') // декабр
);
rushort: array[1..12] of String = ('янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');
en: array[1..12] of String = ('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december');
enshort: array[1..12] of String = ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
begin
case ALangID of
lidUKR, // sorry ;)
lidRUS:
if short
then Result := rushort[month]
else Result := ruroots[month] + rusuff[month, padezh];
lidENG:
if short
then Result := enshort[month]
else Result := en[month];
//lidESP:
end; // case ALangID of
end;
//==============================================================================================
//==============================================================================================
//==============================================================================================
const
// for word forms tables lookup
wantYear = 1;
wantMonth = 2;
wantDay = 3;
wantHour = 4;
wantMinute = 5;
wantSecond = 6;
want_Max = 6; // max value
enforms: array[1..want_Max] of String = ('year', 'month', 'day', 'hour', 'minute', 'second');
//1 Имен ед.ч, 2 Имен мн.ч, 3 Родит ед.ч, 4 Родит мн.ч, 5 Дат ед.ч, 6 Дат мн.ч,
//7 Винит ед.ч, 8 Винит мн.ч, 9 Твор ед.ч, 10 Твор мн.ч, 11 Предл ед.ч, 12 Предл мн.ч,
// имен мн.ч. (2) содержит формы окончаний на 0,5..9,11..19, винит мн.ч. (8) содержит формы для окончаний на 2..4.
ruforms: array[1..want_Max, TPadezh] of String = (
//1 2 3 4 5 6 7 8 9 10 11 12
('год', 'лет', 'год', 'лет', 'году', 'годам', 'год', 'года', 'годом', 'годами', 'годе', 'годах'),
('месяц', 'месяцев', 'месяц', 'месяца', 'месяцу', 'месяцам', 'месяц', 'месяца', 'месяцом', 'месяцами', 'месяце', 'месяцах'),
('день', 'дней', 'день', 'дней', 'дню', 'дням', 'день', 'дня', 'днём', 'днями', 'дне', 'днях'),
('час', 'часов', 'час', 'часов', 'часу', 'часам', 'час', 'часа', 'часом', 'часами', 'часе', 'часах'),
('минута', 'минут', 'минуту', 'минут', 'минуте', 'минутам', 'минуту', 'минуты', 'минутой', 'минутами', 'минуте', 'минутах'),
('секунда', 'секунд', 'секунду', 'секунд', 'секунде', 'секундам', 'секунду', 'секунды', 'секундой', 'секундами', 'секунде', 'секундах')
);
//==============================================================================================
// internal one.
function someInWords(ALangID: Integer; Value: Int64; wantWhat: Integer; padezh: Tpadezh): String;
var
n: Integer;
begin
if ALangID = lidENG then begin
Result := enforms[wantWhat] + ifThen(Value <> 1, 's', '');
Exit;
end; // EN
Value := abs(Value);
n := Value mod 100; // checking fo 11..19 first
if (n < 11) or (n > 19) then n := Value mod 10; // getting just last digit
if ALangID = lidRUS then begin
if padezh = padezhVM then padezh := padezhIM; // винительный мн переходит в именительный мн
// формы множ числа имеют нечётные индексы.
if odd(integer(padezh)) and (n = 1) then dec(padezh); // при окончании на 1 множ число переходит в единств
case padezh of
padezhIM:
if n in [2..4]
then Result := ruforms[wantWhat, padezhVM] // объяснение вверху таблицы
else Result := ruforms[wantWhat, padezhIM]
else
Result := ruforms[wantWhat, padezh]
end; // case padezh
end// RU
// украинский пока лениво и непонятно, как делать. в сущности оно может и не отличаться от русского по словообразованию
else if ALangID = lidUKR then begin
if padezh = padezhVM then padezh := padezhIM; // винительный мн переходит в именительный мн
// формы множ числа имеют нечётные индексы.
if odd(integer(padezh)) and (n = 1) then dec(padezh); // при окончании на 1 множ число переходит в единств
case padezh of
padezhIM:
if n in [2..4]
then Result := ruforms[wantWhat, padezhVM] // объяснение вверху таблицы
else Result := ruforms[wantWhat, padezhIM]
else
Result := ruforms[wantWhat, padezh]
end; // case padezh
end;// UKR
end;
//==============================================================================================
function yearInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantYear, padezh);
end;
//==============================================================================================
function monthInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantMonth, padezh);
end;
//==============================================================================================
function dayInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantDay, padezh);
end;
//==============================================================================================
function hourInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantHour, padezh);
end;
//==============================================================================================
function minuteInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantMinute, padezh);
end;
//==============================================================================================
function secondInWords(ALangID, Value: Int64; padezh: Tpadezh = padezhIE): String;
begin
Result := someInWords(ALangID, Value, wantSecond, padezh);
end;
//==============================================================================================
{
format is equivalent of some of stftime() functions:
%A is replaced by national representation of the full weekday name.
%a is replaced by national representation of the abbreviated weekday name.
%B is replaced by national representation of the full month name.
%b is replaced by national representation of the abbreviated month name.
%C is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%D is equivalent to ``%m/%d/%y''.
%d is replaced by the day of the month as a decimal number (01-31).
%e is replaced by the day of month as a decimal number (1-31); single digits are preceded by a blank.
%F is equivalent to ``%Y-%m-%d''.
%H is replaced by the hour (24-hour clock) as a decimal number (00-23).
%h the same as %b.
%I is replaced by the hour (12-hour clock) as a decimal number (01-12).
%j is replaced by the day of the year as a decimal number (001-366).
%k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
%l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
%M is replaced by the minute as a decimal number (00-59).
%m is replaced by the month as a decimal number (01-12).
%n is replaced by a newline.
%p is replaced by national representation of either "ante meridiem" or "post meridiem" as appropriate.
%R is equivalent to ``%H:%M''.
%r is equivalent to ``%I:%M:%S %p''.
%S is replaced by the second as a decimal number (00-60).
%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
%T is equivalent to ``%H:%M:%S''.
%t is replaced by a tab.
%U is replaced by the week number of the year (00-53).
%u is replaced by the weekday as a decimal number (1-7).
%v is equivalent to ``%e-%b-%Y''.
%W = %U
%w = %u
%Y is replaced by the year with century as a decimal number.
%y is replaced by the year without century as a decimal number (00-99).
%Z is replaced by the time zone name.
%% is replaced by `%'.
}
function TimeInWords(Value: TDateTime; AFormat: String): String;
var
i, fmtlen: Integer;
year,month,day,hour,minute,second,msec: Word;
percent: Boolean;
decl: Tpadezh;
// for recursive uses
function parse(code: char): String;
begin
case code of
'A': begin //is replaced by national representation of the full weekday name.
Result := weekDayName(ReplangID, DayOfTheWeek(Value), False);
end;
'a': begin // is replaced by national representation of the abbreviated weekday name.
Result := weekDayName(ReplangID, DayOfTheWeek(Value), true);
end;
'B': begin // is replaced by national representation of the full month name.
Result := monthName(ReplangID, month, False);
end;
'b','h': begin // is replaced by national representation of the abbreviated month name.
Result := monthName(ReplangID, month, True);
end;
'C': begin // is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
Result := format('%02d', [year - 1900]);
end;
'D': begin // is equivalent to ``%m/%d/%y''.
Result := parse('m') + '/' + parse('d') + '/' + parse('y');
end;
'd': begin // is replaced by the day of the month as a decimal number (01-31).
Result := format('%02d', [day]);
end;
'e': begin // is replaced by the day of month as a decimal number (1-31); single digits are preceded by a blank.
Result := format('%2d', [day]);
end;
'F': begin // is equivalent to ``%Y-%m-%d''.
Result := parse('Y') + '-' + parse('m') + '-' + parse('d');
end;
'H': begin // is replaced by the hour (24-hour clock) as a decimal number (00-23).
Result := format('%02d', [hour]);
end;
'I': begin // is replaced by the hour (12-hour clock) as a decimal number (01-12).
Result := format('%02d', [hour mod 12]);
end;
'j': begin // is replaced by the day of the year as a decimal number (001-366).
Result := format('%03d', [dayOfTheYear(Value)]);
end;
'k': begin // is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
Result := format('%2d', [hour]);
end;
'l': begin // is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
Result := format('%2d', [hour mod 12]);
end;
'M': begin // is replaced by the minute as a decimal number (00-59).
Result := format('%02d', [minute]);
end;
'm': begin // is replaced by the month as a decimal number (01-12).
Result := format('%02d', [month]);
end;
'n': begin // is replaced by a newline.
Result := #13#10;
end;
'p': begin // is replaced by national representation of either "ante meridiem" or "post meridiem" as appropriate.
case RepLangID of
//lidRUS: Result := ifThen(hour > 12, 'после', 'до') + ' полудня';
//lidUKR: Result := ifThen(hour > 12, 'пiсля', 'до') + ' пiвдня';
lidENG: Result := ifThen(hour > 12, 'post', 'ante') + ' meridiem';
//lidESP: Result := ifThen(hour > 12, '', '') + '';
end;
end;
'R': begin // is equivalent to ``%H:%M''.
Result := parse('H') + ':' + parse('M');
end;
'r': begin // is equivalent to ``%I:%M:%S %p''.
Result := parse('I') + ':' + parse('M') + ':' + parse('S') + ' ' + parse('p');
end;
'S': begin // is replaced by the second as a decimal number (00-60).
Result := format('%02d', [second]);
end;
{'s': begin // is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
Result := format('%d', []);
end;
}
'T': begin // is equivalent to ``%H:%M:%S''.
Result := parse('H') + ':' + parse('M') + ':' + parse('S');
end;
't': begin // is replaced by a tab.
Result := #9;
end;
'U', 'W': begin // is replaced by the week number of the year (00-53).
Result := format('%02d', [WeekOfTheYear(Value)]);
end;
'u', 'w': begin // is replaced by the weekday as a decimal number (1-7).
Result := format('%d', [DayOfTheWeek(Value)]);
end;
'v': begin // is equivalent to ``%e-%b-%Y''.
Result := parse('e') + '-' + parse('b') + '-' + parse('Y');
end;
'Y': begin // is replaced by the year with century as a decimal number.
Result := format('%d', [year]);
end;
'y': begin // is replaced by the year without century as a decimal number (00-99).
Result := format('%02d', [year - 1900]);
end;
{'Z': begin // is replaced by the time zone name.
Result := format('%d', []);
end;
}
'_': begin // less than N ...
//if year > 0 then Result := IntToStr(year) + ' ' + yearInWords(
end;
end; // case code
end;
begin
Result := '';
percent := False;
i := 1;
fmtlen := length(aformat);
decodeDate(Value, year, month, day);
decodeTime(Value, hour, minute, second, msec);
while i <= fmtlen do begin
if aformat[i] = '%' then begin
if percent then begin
Result := Result + '%';
percent := False;
end
else percent := True;
inc(i);
Continue;
end;
if not percent then begin
Result := Result + aformat[i];
inc(i);
Continue;
end;
Result := Result + parse(Aformat[i]);
inc(i);
end; //while i <= fmtlen do begin
end;
{
unused items:
%c is replaced by national representation of time and date.
%E* %O*
POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od
%Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to
provide alternate representations.
Additionly %OB implemented to represent alternative months names
(used standalone, without day mentioned).
%O* the same as %E*.
%G is replaced by a year as a decimal number with century. This year
is the one that contains the greater part of the week (Monday as
the first day of the week).
%g is replaced by the same year as in ``%G'', but as a decimal number without century (00-99).
%V is replaced by the week number of the year (Monday as the first day
of the week) as a decimal number (01-53). If the week containing
January 1 has four or more days in the new year, then it is week 1;
otherwise it is the last week of the previous year, and the next
week is week 1.
%X is replaced by national representation of the time.
%x is replaced by national representation of the date.
%z is replaced by the time zone offset from UTC; a leading plus sign
stands for east of UTC, a minus sign for west of UTC, hours and
minutes follow with two digits each and no delimiter between them
(common form for RFC 822 date headers).
%+ is replaced by national representation of the date and time (the
format is similar to that produced by date(1)).
}
end.
|
unit Rule_Boll2;
interface
uses
BaseRule,
Rule_MA,
Rule_STD;
type
TRule_Boll_Price = class(TBaseRule)
protected
fMA: TRule_MA;
fStd: TRule_Std;
fParamN: Word;
function GetBoll(AIndex: integer): double;
function GetLB(AIndex: integer): double;
function GetUB(AIndex: integer): double;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
public
constructor Create(ADataType: TRuleDataType = dtDouble); override;
destructor Destroy; override;
procedure Execute; override;
property Boll[AIndex: integer]: double read GetBoll;
property UB[AIndex: integer]: double read GetUB;
property LB[AIndex: integer]: double read GetLB;
property ParamN: Word read GetParamN write SetParamN;
property MA: TRule_MA read fMA;
property Std: TRule_Std read fStd;
end;
implementation
{ TRule_Boll }
(*//
BOLL:MA(CLOSE,N);
UB:BOLL+2*STD(CLOSE,N);
LB:BOLL-2*STD(CLOSE,N);
======================================================
输出BOLL:收盘价的N日简单移动平均
输出UB:BOLL+2*收盘价的N日估算标准差
输出LB:BOLL-2*收盘价的N日估算标准差
//*)
constructor TRule_Boll_Price.Create(ADataType: TRuleDataType = dtDouble);
begin
inherited;
fParamN := 20;
fMA := TRule_MA.Create(dtDouble);
fMA.ParamN := fParamN;
fStd := TRule_Std.Create(dtDouble);
fStd.ParamN := fParamN;
end;
destructor TRule_Boll_Price.Destroy;
begin
inherited;
end;
procedure TRule_Boll_Price.Execute;
begin
fMA.OnGetDataLength := Self.OnGetDataLength;
fMA.OnGetDataF := Self.OnGetDataF;
fMA.Execute;
fStd.OnGetDataLength := Self.OnGetDataLength;
fStd.OnGetDataF := Self.OnGetDataF;
fStd.Execute;
end;
function TRule_Boll_Price.GetParamN: Word;
begin
Result := fParamN;
end;
procedure TRule_Boll_Price.SetParamN(const Value: Word);
begin
if Value > 0 then
begin
fParamN := Value;
fMA.ParamN := fParamN;
fStd.ParamN := fParamN;
end;
end;
function TRule_Boll_Price.GetBoll(AIndex: integer): double;
begin
Result := fMA.ValueF[AIndex];
end;
function TRule_Boll_Price.GetLB(AIndex: integer): double;
begin
Result := Boll[AIndex] - 2 * fStd.ValueF[AIndex];
end;
function TRule_Boll_Price.GetUB(AIndex: integer): double;
begin
Result := Boll[AIndex] + 2 * fStd.ValueF[AIndex];
end;
end.
|
unit OperationEditUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FormEditAbsUnit, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, dxBarDBNav, dxBar, cxClasses,
ImgList, ActnList, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxPC, ExtCtrls, cxContainer,
cxTextEdit, cxDBEdit, cxLabel, cxMaskEdit, cxButtonEdit, cxDropDownEdit,
cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxMemo,
cxCalc, Menus, StdCtrls, cxButtons;
type
TOperationEdit = class(TFormEditAbs)
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
cxExpense: TcxDBButtonEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
cxLabel5: TcxLabel;
cxComment: TcxDBMemo;
cxPeriod: TcxDBButtonEdit;
cxOperationKind: TcxDBButtonEdit;
cxSum: TcxDBCalcEdit;
tvMainRatioValue: TcxGridDBColumn;
tvMainPerson: TcxGridDBColumn;
tvMainSumValue: TcxGridDBColumn;
acCalcRatio: TAction;
cxCalcTotal: TcxButton;
acCalcSum: TAction;
dxBarButton7: TdxBarButton;
dxBarButton8: TdxBarButton;
procedure cxPeriodPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxExpensePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxOperationKindPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxCalcTotalClick(Sender: TObject);
procedure acCalcRatioExecute(Sender: TObject);
procedure acCalcSumExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
OperationEdit: TOperationEdit;
implementation
{$R *.dfm}
uses
DataModuleUnit
,PeriodUnit
,PeriodEditUnit
,ExpenseUnit
,ExpenseEditUnit
,OperationKindUnit
,OperationKindEditUnit
;
procedure TOperationEdit.cxPeriodPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
F: TForm;
begin
F := TPeriod.Execute(PeriodEdit, 'modal');
F.ShowModal;
if F.Tag = mrOk then
begin
dmPublic.tOperation.Edit;
dmPublic.tOperationPeriodId.Value := dmPublic.tPeriodPeriodId.Value;
end;
end;
procedure TOperationEdit.cxExpensePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
F: TForm;
begin
F := TExpense.Execute(ExpenseEdit, 'modal');
F.ShowModal;
if F.Tag = mrOk then
begin
dmPublic.tOperation.Edit;
dmPublic.tOperationExpenseId.Value := dmPublic.tExpenseExpenseId.Value;
end;
end;
procedure TOperationEdit.cxOperationKindPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
F: TForm;
begin
F := TOperationKind.Execute(OperationKindEdit, 'modal');
F.ShowModal;
if F.Tag = mrOk then
begin
dmPublic.tOperation.Edit;
dmPublic.tOperationOperationKindId.Value := dmPublic.tOperationKindOperationKindId.Value;
end;
end;
procedure TOperationEdit.cxCalcTotalClick(Sender: TObject);
var
s: real;
begin
s := 0;
dmPublic.tRatio.First;
while not dmPublic.tRatio.Eof do
begin
try
s := s + dmPublic.tRatioSumValue.Value;
except
end;
dmPublic.tRatio.Next;
end;
dmPublic.tOperation.Edit;
dmPublic.tOperationOperationSum.Value := s;
end;
procedure TOperationEdit.acCalcRatioExecute(Sender: TObject);
var
s: real;
begin
s := dmPublic.tOperationOperationSum.Value;
if s <> 0 then
begin
dmPublic.tRatio.First;
while not dmPublic.tRatio.Eof do
begin
dmPublic.tRatio.Edit;
dmPublic.tRatioRatioValue.Value := dmPublic.tRatioSumValue.Value / dmPublic.tOperationOperationSum.Value;
dmPublic.tRatio.Post;
dmPublic.tRatio.Next;
end;
end;
end;
procedure TOperationEdit.acCalcSumExecute(Sender: TObject);
var
s: real;
n: real;
begin
s := dmPublic.tOperationOperationSum.Value;
n := 0;
dmPublic.tRatio.First;
while not dmPublic.tRatio.Eof do
begin
n := n + dmPublic.tRatioRatioValue.Value;
dmPublic.tRatio.Next;
end;
dmPublic.tRatio.First;
while not dmPublic.tRatio.Eof do
begin
dmPublic.tRatio.Edit;
if n = 0 then
dmPublic.tRatioSumValue.Value := 0
else
dmPublic.tRatioSumValue.Value := dmPublic.tOperationOperationSum.Value * dmPublic.tRatioRatioValue.Value / n;
dmPublic.tRatio.Post;
dmPublic.tRatio.Next;
end;
end;
end.
|
unit NodeMaterialForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OkCancel_frame, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls,
DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery,
PrjConst, System.UITypes, FIBDatabase, pFIBDatabase;
type
TNodeMaterialForm = class(TForm)
OkCancelFrame1: TOkCancelFrame;
CnErrors: TCnErrorProvider;
dsMaterials: TpFIBDataSet;
srcMaterials: TDataSource;
trRead: TpFIBTransaction;
trWrite: TpFIBTransaction;
lblAttribute: TLabel;
dbluMat: TDBLookupComboboxEh;
ednCount: TDBNumberEditEh;
lbl1: TLabel;
memNotice: TDBMemoEh;
Label1: TLabel;
edtSN: TDBEditEh;
procedure OkCancelFrame1bbOkClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
function SaveInDb(const NODE_ID: Integer): Boolean;
public
end;
function AddMaterial(const NODE_ID: Integer): Boolean;
implementation
uses DM, NodesForma, RegularExpressions, pFIBQuery;
{$R *.dfm}
function AddMaterial(const NODE_ID: Integer): Boolean;
begin
with TNodeMaterialForm.Create(Application) do
try
dsMaterials.ParamByName('NODE_ID').AsInteger := NODE_ID;
dsMaterials.Open;
if ShowModal = mrOk then
begin
result := SaveInDb(NODE_ID);
end
else
begin
result := false;
end;
dsMaterials.Close;
finally
free
end;
end;
procedure TNodeMaterialForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
OkCancelFrame1bbOkClick(Sender);
end;
procedure TNodeMaterialForm.OkCancelFrame1bbOkClick(Sender: TObject);
var
errors: Boolean;
begin
errors := false;
if dbluMat.Text.IsEmpty then
begin
CnErrors.SetError(dbluMat, rsInputIncorrect, iaMiddleLeft, bsNeverBlink);
errors := true;
end
else
CnErrors.Dispose(dbluMat);
if edtSN.Text.IsEmpty then
begin
CnErrors.SetError(edtSN, rsInputIncorrect, iaMiddleLeft, bsNeverBlink);
errors := true;
end
else
CnErrors.Dispose(edtSN);
if not errors then
ModalResult := mrOk
else
ModalResult := mrNone;
end;
function TNodeMaterialForm.SaveInDb(const NODE_ID: Integer): Boolean;
var
fq: TpFIBQuery;
begin
result := false;
fq := TpFIBQuery.Create(Self);
try
fq.Database := dmMain.dbTV;
fq.Transaction := trWrite;
fq.sql.Text := 'insert into Inventory (Owner, Owner_Type, M_Id, Serial, ownership, Quant, Notice)';
fq.sql.add('values (:Owner, :Owner_Type, :M_Id, :Serial, :ownership, :Quant, :Notice)');
fq.ParamByName('Owner').AsInteger := NODE_ID;
fq.ParamByName('Owner_Type').AsInteger := 2; // 2=Узел
fq.ParamByName('ownership').AsInteger := 0;
fq.ParamByName('M_Id').AsInteger := dbluMat.KeyValue;
fq.ParamByName('Serial').AsString := edtSN.Text;
fq.ParamByName('Notice').AsString := memNotice.Lines.Text;
if not ednCount.Text.IsEmpty then
fq.ParamByName('Quant').AsDouble := ednCount.Value;
fq.Transaction.StartTransaction;
fq.ExecQuery;
fq.Transaction.Commit;
fq.Close;
result := true;
finally
fq.free;
end;
end;
end.
|
{$MODE OBJFPC}
program NETSRV;
const
InputFile = 'netsrv.inp';
OutputFile = 'netsrv.out';
maxN = 150000;
maxQ = Round(1E5);
maxlgN = 18;
type
TAdj = record
vertex: Integer;
link: Integer;
end;
TInterval = record
x1, x2, y: Integer;
weight: Integer;
close: Boolean;
link: Integer;
end;
TTreeNode = record
sum: Integer;
max: Integer;
end;
var
fi, fo: TextFile;
n, lgN: Integer;
adj: array [-maxN + 1 .. maxN - 1] of TAdj;
head: array [1 .. maxN] of Integer;
parent: array [0 .. maxlgN, 1 .. maxN] of Integer;
depth: array [1 .. maxN] of Integer;
first, last: array [1 .. maxN] of Integer;
it: array [1 .. 4 * maxQ] of TInterval;
tree: array [1 .. 4 * maxN] of TTreeNode;
leaf: array [1 .. maxN] of Integer;
nit: Integer;
q: Integer;
res: Integer;
procedure Enter;
var
i: Integer;
x, y: Integer;
begin
ReadLn(fi, n);
lgN := Trunc(ln(n) / ln(2)) + 1;
FillChar(head[1], SizeOf(head[1]) * n, 0);
for i := 1 to n - 1 do
begin
ReadLn(fi, x, y);
with adj[i] do
begin
vertex := y; link := head[x]; head[x] := i;
end;
with adj[-i] do
begin
vertex := x; link := head[y]; head[y] := -i;
end;
end;
end;
procedure DFS;
var
time: Integer;
procedure Visit(u: Integer; dv: Integer);
var
i: Integer;
begin
Inc(time); first[u] := time;
depth[u] := dv;
i := head[u];
while i <> 0 do
with adj[i] do
begin
if parent[0, vertex] = -1 then
begin
parent[0, vertex] := u; Visit(vertex, dv + 1);
end;
i := link;
end;
last[u] := time;
end;
begin
FillChar(parent[0, 1], SizeOf(parent[0, 1]) * n, $FF); // -1
parent[0, 1] := 0;
time := 0;
Visit(1, 0);
end;
procedure InitFarJumpPtrs;
var
level, u, v: Integer;
begin
for level := 1 to lgN do
for u := 1 to n do
begin
v := parent[level - 1, u];
if v = 0 then
parent[level, u] := 0
else
parent[level, u] := parent[level - 1, v];
end;
end;
function Jump(u: Integer; k: Integer): Integer;
var
i: Integer;
begin
for i := 0 to lgN do
begin
if Odd(k) then
u := parent[i, u];
k := k div 2;
if k = 0 then
Break;
end;
Result := u;
end;
procedure ReadQueries;
var
i, s, t, weight: Integer;
procedure AddRect(_x1, _x2, _y1, _y2: Integer; _weight: Integer);
begin
Inc(nit);
with it[nit] do
begin
x1 := _x1;
x2 := _x2;
y := _y1;
close := False;
weight := _weight;
end;
it[nit + 1] := it[nit];
it[nit + 1].y := _y2;
it[nit + 1].close := True;
Inc(nit);
end;
procedure AddRects(s, t, w: Integer);
var
a, b, c, d, e, f: Integer;
i, j, temp, u: Integer;
begin
if first[s] > first[t] then
begin
temp := s; s := t; t := temp;
end;
a := first[s]; b := last[s];
c := first[t]; d := last[t];
if b < c then
begin
AddRect(a, b, c, d, w);
Exit;
end;
u := Jump(t, depth[t] - depth[s] - 1);
e := first[u]; f := last[u];
if 1 <= e - 1 then
AddRect(1, e - 1, c, d, w);
if f + 1 <= n then
AddRect(c, d, f + 1, n, w);
end;
begin
ReadLn(fi, q);
nit := 0;
for i := 1 to q do
begin
ReadLn(fi, s, t, weight);
AddRects(s, t, weight);
end;
FillChar(head[1], n * SizeOf(head[1]), 0);
for i := 1 to nit do
with it[i] do
if close then
begin
link := head[y]; head[y] := i;
end;
for i := 1 to nit do
with it[i] do
if not close then
begin
link := head[y]; head[y] := i;
end;
end;
procedure Build(x, Low, High: Integer);
var
middle: Integer;
begin
tree[x].sum := 0; tree[x].max := 0;
if Low = High then
leaf[low] := x
else
begin
middle := (Low + High) shr 1;
Build(x * 2, low, middle);
Build(x * 2 + 1, middle + 1, High);
end;
end;
function GetMax(a, b: Integer): Integer;
begin
if a > b then Result := a else Result := b;
end;
procedure Increment(pos: Integer; delta: Integer);
var
x: Integer;
begin
if pos > n then
Exit;
x := leaf[pos];
Inc(tree[x].sum, delta);
Inc(tree[x].max, delta);
repeat
x := x shr 1;
if x = 0 then
Break;
Inc(tree[x].sum, delta);
tree[x].max := GetMax(tree[2 * x].max, tree[2 * x].sum + tree[2 * x + 1].max);
until False;
end;
procedure ProcessInterval(const it: TInterval);
begin
if not it.close then
begin
Increment(it.x1, it.weight);
Increment(it.x2 + 1, -it.weight);
end
else
begin
Increment(it.x1, -it.weight);
Increment(it.x2 + 1, it.weight);
end;
if res < tree[1].max then
res := tree[1].max;
end;
function Solve: Integer;
var
y, i: Integer;
begin
Enter;
DFS;
InitFarJumpPtrs;
ReadQueries;
Build(1, 1, n);
res := 0;
for y := 1 to n do
begin
i := head[y];
while i <> 0 do
begin
ProcessInterval(it[i]);
i := it[i].link;
end;
end;
Result := res;
end;
procedure SolveAll;
var
itest, ntest: Integer;
begin
ReadLn(fi, ntest);
for itest := 1 to ntest do
WriteLn(fo, Solve);
end;
begin
AssignFile(fi, InputFile); Reset(fi);
AssignFile(fo, OutputFile); Rewrite(fo);
try
SolveAll;
finally
CloseFile(fi); CloseFile(fo);
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.Objects, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP;
type
TForm1 = class(TForm)
IdHTTP: TIdHTTP;
btnGetJPEG: TButton;
imgCameraImage: TImage;
procedure btnGetJPEGClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.btnGetJPEGClick(Sender: TObject);
var
ResponseContent: TMemoryStream;
begin
// Create response stream
ResponseContent := TMemoryStream.Create;
try
// Request single JPEG from camera
IdHTTP.Request.BasicAuthentication := TRUE;
IdHTTP.Request.Username := 'root';
IdHTTP.Request.Password := 'pass';
IdHTTP.Get('http://10.1.39.2/axis-cgi/jpg/image.cgi', ResponseContent);
// Load image to bitmap
ResponseContent.Position := 0;
imgCameraImage.Bitmap.LoadFromStream(ResponseContent);
finally
ResponseContent.Free;
end;
end;
end.
|
unit gm_engine;
interface
uses
zglHeader, Scenes;
// MOUSE
const
M_BLEFT = 0;
M_BMIDDLE = 1;
M_BRIGHT = 2;
M_WUP = 0;
M_WDOWN = 1;
const
// KEYBOARD
K_SYSRQ = $B7;
K_PAUSE = $C5;
K_ESCAPE = $01;
K_ENTER = $1C;
K_KP_ENTER = $9C;
K_UP = $C8;
K_DOWN = $D0;
K_LEFT = $CB;
K_RIGHT = $CD;
K_BACKSPACE = $0E;
K_SPACE = $39;
K_TAB = $0F;
K_TILDE = $29;
K_INSERT = $D2;
K_DELETE = $D3;
K_HOME = $C7;
K_END = $CF;
K_PAGEUP = $C9;
K_PAGEDOWN = $D1;
K_CTRL = $FF - $01;
K_CTRL_L = $1D;
K_CTRL_R = $9D;
K_ALT = $FF - $02;
K_ALT_L = $38;
K_ALT_R = $B8;
K_SHIFT = $FF - $03;
K_SHIFT_L = $2A;
K_SHIFT_R = $36;
K_SUPER = $FF - $04;
K_SUPER_L = $DB;
K_SUPER_R = $DC;
K_APP_MENU = $DD;
K_CAPSLOCK = $3A;
K_NUMLOCK = $45;
K_SCROLL = $46;
K_BRACKET_L = $1A; // [ {
K_BRACKET_R = $1B; // ] }
K_BACKSLASH = $2B; // \
K_SLASH = $35; // /
K_COMMA = $33; // ,
K_DECIMAL = $34; // .
K_SEMICOLON = $27; // : ;
K_APOSTROPHE = $28; // ' "
K_0 = $0B;
K_1 = $02;
K_2 = $03;
K_3 = $04;
K_4 = $05;
K_5 = $06;
K_6 = $07;
K_7 = $08;
K_8 = $09;
K_9 = $0A;
K_MINUS = $0C;
K_EQUALS = $0D;
K_A = $1E;
K_B = $30;
K_C = $2E;
K_D = $20;
K_E = $12;
K_F = $21;
K_G = $22;
K_H = $23;
K_I = $17;
K_J = $24;
K_K = $25;
K_L = $26;
K_M = $32;
K_N = $31;
K_O = $18;
K_P = $19;
K_Q = $10;
K_R = $13;
K_S = $1F;
K_T = $14;
K_U = $16;
K_V = $2F;
K_W = $11;
K_X = $2D;
K_Y = $15;
K_Z = $2C;
K_KP_0 = $52;
K_KP_1 = $4F;
K_KP_2 = $50;
K_KP_3 = $51;
K_KP_4 = $4B;
K_KP_5 = $4C;
K_KP_6 = $4D;
K_KP_7 = $47;
K_KP_8 = $48;
K_KP_9 = $49;
K_KP_SUB = $4A;
K_KP_ADD = $4E;
K_KP_MUL = $37;
K_KP_DIV = $B5;
K_KP_DECIMAL = $53;
K_F1 = $3B;
K_F2 = $3C;
K_F3 = $3D;
K_F4 = $3E;
K_F5 = $3F;
K_F6 = $40;
K_F7 = $41;
K_F8 = $42;
K_F9 = $43;
K_F10 = $44;
K_F11 = $57;
K_F12 = $58;
KA_DOWN = 0;
KA_UP = 1;
const
K_INV = K_I;
K_CHAR = K_C;
K_SKILL = K_A;
const
FOM_CREATE = $01; // Create
FOM_OPENR = $02; // Read
PR2D_FILL = $010000;
PR2D_SMOOTH = $020000;
const
TEXT_HALIGN_LEFT = $000001;
TEXT_HALIGN_CENTER = $000002;
TEXT_HALIGN_RIGHT = $000004;
TEXT_HALIGN_JUSTIFY = $000008;
TEXT_VALIGN_TOP = $000010;
TEXT_VALIGN_CENTER = $000020;
TEXT_VALIGN_BOTTOM = $000040;
TEXT_CLIP_RECT = $000080;
TEXT_FX_VCA = $000100;
TEXT_FX_LENGTH = $000200;
// FX
const
FX_BLEND_NORMAL = $00;
FX_BLEND_ADD = $01;
FX_BLEND_MULT = $02;
FX_BLEND_BLACK = $03;
FX_BLEND_WHITE = $04;
FX_BLEND_MASK = $05;
FX_COLOR_MIX = $00;
FX_COLOR_SET = $01;
FX_BLEND = $100000;
FX_COLOR = $200000;
// FX 2D
const
FX2D_FLIPX = $000001;
FX2D_FLIPY = $000002;
FX2D_VCA = $000004;
FX2D_VCHANGE = $000008;
FX2D_SCALE = $000010;
FX2D_RPIVOT = $000020;
type
TPoint = record
X, Y : Integer;
end;
type
TRect = record
Left, Top, Width, Height: Integer;
end;
type
TCamera2D = zglTCamera2D;
TPCamera2D = zglPCamera2D;
type
TFont = zglPFont;
TFile = zglTFile;
TTexture = zglPTexture;
const
SlotSize = 34;
var
ScreenWidth : Integer = 800;// + 500;
ScreenHeight : Integer = 600;// + 0;// + 300;
FullScr : Boolean = False;
VSync : Boolean = False;
ChBIFlag : Boolean = False;
Cam : TCamera2D;
MPrev : TPoint;
NMTime : Integer;
NewGame : Boolean = False;
ShowMinimap : Boolean = True;
SpellPoints : Integer = 0;
SellSpellN : Integer = -1;
BtnDwn : Integer;
WalkPause : Integer;
MapSide : Integer = 50;
procedure SetCam;
function Rect(X, Y, Width, Height: Integer): TRect;
function PointInRect(P: TPoint; X, Y, Width, Height: Integer): Boolean;
function MouseInRect(X, Y, Width, Height: Integer): Boolean;
function StrToPAChar(const Value: string): PAnsiChar;
//function A2U8(const S: string; const cp: integer = 1251): UTF8String;
function Angle(x1, y1, x2, y2 : Single): Single;
function Sin(Angle : Integer): Single;
function Cos(Angle : Integer): Single;
function GetFileExt(const FileName: string): UTF8String;
function GetDirectory(const FileName: string): UTF8String;
function GetFileName(const FileName: string): UTF8String;
function IntToStr(Value: Integer): UTF8String;
procedure SetFrameSize(var Texture: zglPTexture; FrameWidth, FrameHeight: Word);
function LoadTexture(const FileName: string; TransparentColor: LongWord = TEX_NO_COLORKEY; Flags: LongWord = TEX_DEFAULT_2D): TTexture;
function LoadFont(const FileName: string): TFont;
function GetDist(A, B: TPoint): Single;
function MouseDown(Button: Byte): Boolean;
function MouseUp(Button: Byte): Boolean;
function MouseClick(Button: Byte): Boolean;
function MouseDblClick(Button: Byte): Boolean;
function MouseWheel(Axis: Byte): Boolean;
function SetScreenOptions(Width, Height, Refresh: Word; FullScreen, VSync: Boolean): Boolean;
function KeyDown(KeyCode: Byte): Boolean;
function KeyPress(KeyCode: Byte): Boolean;
procedure ClearStates;
procedure ClearKeyState;
procedure ClearMouseState;
procedure TextOut(Font: TFont; X, Y : Single; const Text: string; Flags: LongWord = 0); overload;
procedure TextOut(Font: TFont; X, Y, Scale, Step: Single; const Text: string; Alpha: Byte = 255; Color: LongWord = $FFFFFF; Flags: LongWord = 0); overload;
function TextWidth(Font: TFont; const Text: string; Step: Single = 0.0): Single;
procedure InitCamera2D(out Camera: TCamera2D);
procedure SetCamera2D(Camera: TPCamera2D);
function FileGetSize(FileHandle: TFile): LongWord;
function FileWrite(FileHandle: TFile; const Buffer; Bytes: LongWord): LongWord;
function FileOpen(out FileHandle: TFile; const FileName: UTF8String; Mode: Byte): Boolean;
function FileRead(FileHandle: TFile; var Buffer; Bytes: LongWord): LongWord;
procedure FileClose(var FileHandle: TFile);
function StrToBool(const S: string): Boolean;
function UpperCase(const S: string): UTF8String;
procedure Circ2D(X, Y, Radius: Single; Color: LongWord = $FFFFFF; Alpha: Byte = 255; Quality: Word = 32; FX: LongWord = 0);
procedure Rect2D(X, Y, W, H: Single; Color: LongWord = $FFFFFF; Alpha: Byte = 255; FX: LongWord = 0);
procedure Render2D(Texture: zglPTexture; X, Y, W, H, Angle: Single; Frame: Word; Alpha: Byte = 255; FX: LongWord = FX_BLEND);
procedure RenderSprite2D(Texture: zglPTexture; X, Y, W, H, Angle: Single; Alpha: Byte = 255; FX: LongWord = FX_BLEND);
function Point(X, Y: Integer): TPoint;
function GetMouse: TPoint;
implementation
uses Windows, gm_creature;
function Rect(X, Y, Width, Height: Integer): TRect;
begin
Result.Left := X;
Result.Top := Y;
Result.Width := Width;
Result.Height := Height;
end;
procedure SetCam;
begin
Cam.X := PC.Pos.X * 32 - ScreenWidth div 2 + 16;
Cam.Y := PC.Pos.Y * 32 - ScreenHeight div 2 + 16;
end;
function MouseInRect(X, Y, Width, Height: Integer): Boolean;
begin
Result := (GetMouse.X > X) and (GetMouse.Y > Y) and (GetMouse.X < X + Width) and (GetMouse.Y < Y + Height);
end;
function PointInRect(P: TPoint; X, Y, Width, Height: Integer): Boolean;
begin
Result := (P.X > X) and (P.Y > Y) and (P.X < X + Width) and (P.Y < Y + Height);
end;
function StrToPAChar(const Value: string): PAnsiChar;
begin
Result := PAnsiChar(AnsiString(Value));
end;
function A2U8(const S: string; const cp: integer = 1251): UTF8String;
var
wlen, ulen: Integer;
wbuf: PWideChar;
begin
Result := '';
wlen := MultiByteToWideChar(cp, 0, StrToPAChar(S), length(S), NIL, 0); // wlen is the number of UCS2 without NULL terminater.
if wlen = 0 then exit;
wbuf := GetMemory(wlen * sizeof(wchar));
try
MultiByteToWideChar(cp, 0, StrToPAChar(S), length(S), wbuf, wlen);
ulen := WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NIL, 0, NIL, NIL);
setlength(Result, ulen);
WideCharToMultiByte(CP_UTF8, 0, wbuf, wLen, StrToPAChar(Result), uLen, NIL, NIL);
finally
FreeMemory(WBuf);
end;
end;
function Cos(Angle: Integer): Single;
begin
Result := m_Cos(Angle)
// Result := System.Cos(Angle)
end;
function Sin(Angle: Integer): Single;
begin
Result := m_Sin(Angle)
// Result := System.Sin(Angle)
end;
function Angle(x1, y1, x2, y2: Single): Single;
begin
Result := m_Angle(x1, y1, x2, y2)
end;
function GetFileExt(const FileName: string): UTF8String;
begin
Result := file_GetExtension(A2U8(FileName))
end;
function GetDirectory(const FileName: string): UTF8String;
begin
Result := file_GetDirectory(A2U8(FileName))
end;
function GetFileName(const FileName: string): UTF8String;
begin
Result := file_GetName(A2U8(FileName))
end;
function IntToStr(Value: Integer): UTF8String;
begin
Result := u_IntToStr(Value)
end;
procedure SetFrameSize(var Texture: zglPTexture; FrameWidth, FrameHeight: Word);
begin
tex_SetFrameSize(Texture, FrameWidth, FrameHeight)
end;
function LoadTexture(const FileName: string; TransparentColor: LongWord = TEX_NO_COLORKEY; Flags: LongWord = TEX_DEFAULT_2D): TTexture;
begin
Result := tex_LoadFromFile(A2U8(FileName), TransparentColor, Flags)
end;
function LoadFont(const FileName: string): TFont;
begin
Result := font_LoadFromFile(A2U8(FileName))
end;
function GetDist(A, B: TPoint): Single;
begin
// Result := m_Distance(x1, y1, x2, y2)
Result := sqrt(sqr(B.X - A.X) + sqr(B.Y - A.Y));
end;
function MouseDown(Button: Byte): Boolean;
begin
Result := mouse_Down(Button)
end;
function MouseUp(Button: Byte): Boolean;
begin
Result := mouse_Up(Button)
end;
function MouseClick(Button: Byte): Boolean;
begin
Result := mouse_Click(Button)
end;
function MouseDblClick(Button: Byte): Boolean;
begin
Result := mouse_DblClick(Button)
end;
function MouseWheel(Axis: Byte): Boolean;
begin
Result := mouse_Wheel(Axis)
end;
function SetScreenOptions(Width, Height, Refresh: Word; FullScreen, VSync: Boolean): Boolean;
begin
Result := scr_SetOptions(Width, Height, Refresh, FullScreen, VSync);
end;
function KeyDown(KeyCode: Byte): Boolean;
begin
Result := key_Down(KeyCode)
end;
function KeyPress(KeyCode: Byte): Boolean;
begin
Result := key_Press(KeyCode)
end;
procedure ClearMouseState;
begin
mouse_ClearState
end;
procedure ClearKeyState;
begin
key_ClearState
end;
procedure ClearStates;
begin
mouse_ClearState;
key_ClearState;
end;
procedure TextOut(Font: TFont; X, Y : Single; const Text: string; Flags: LongWord = 0); overload;
begin
text_Draw(Font, X, Y, A2U8(Text), Flags)
end;
procedure TextOut(Font: TFont; X, Y, Scale, Step: Single; const Text: string; Alpha: Byte = 255; Color: LongWord = $FFFFFF; Flags: LongWord = 0); overload;
begin
text_DrawEx(Font, X, Y, Scale, Step, A2U8(Text), Alpha, Color, Flags)
end;
function TextWidth(Font: TFont; const Text: string; Step: Single = 0.0): Single;
begin
Result := text_GetWidth(Font, A2U8(Text), Step)
end;
procedure InitCamera2D(out Camera: TCamera2D);
begin
cam2d_Init(Camera)
end;
procedure SetCamera2D(Camera: TPCamera2D);
begin
cam2d_Set(Camera)
end;
function FileGetSize(FileHandle: TFile): LongWord;
begin
Result := file_GetSize(FileHandle)
end;
function FileWrite(FileHandle: TFile; const Buffer; Bytes: LongWord): LongWord;
begin
Result := file_Write(FileHandle, Buffer, Bytes)
end;
function FileOpen(out FileHandle: TFile; const FileName: UTF8String; Mode: Byte): Boolean;
begin
Result := file_Open(FileHandle, FileName, Mode)
end;
function FileRead(FileHandle: TFile; var Buffer; Bytes: LongWord): LongWord;
begin
Result := file_Read(FileHandle, Buffer, Bytes)
end;
procedure FileClose(var FileHandle: TFile);
begin
file_Close(FileHandle)
end;
function StrToBool(const S: string): Boolean;
begin
Result := u_StrToBool(A2U8(S))
end;
function UpperCase(const S: string): UTF8String;
begin
Result := u_StrUp(A2U8(S))
end;
procedure Rect2D(X, Y, W, H: Single; Color: LongWord = $FFFFFF; Alpha: Byte = 255; FX: LongWord = 0);
begin
pr2d_Rect(X, Y, W, H, Color, Alpha, FX)
end;
procedure Circ2D(X, Y, Radius: Single; Color: LongWord = $FFFFFF; Alpha: Byte = 255; Quality: Word = 32; FX: LongWord = 0);
begin
pr2d_Circle(X, Y, Radius, Color, Alpha, Quality, FX);
end;
procedure Render2D(Texture: zglPTexture; X, Y, W, H, Angle: Single; Frame: Word; Alpha: Byte = 255; FX: LongWord = FX_BLEND);
begin
asprite2d_Draw(Texture, X, Y, W, H, Angle, Frame, Alpha, FX)
end;
procedure RenderSprite2D(Texture: zglPTexture; X, Y, W, H, Angle: Single; Alpha: Byte = 255; FX: LongWord = FX_BLEND);
begin
ssprite2d_Draw(Texture, X, Y, W, H, Angle, Alpha, FX);
end;
function Point(X, Y: Integer): TPoint;
begin
Result.X := X;
Result.Y := Y;
end;
function GetMouse: TPoint;
begin
Result := Point(mouse_X, mouse_Y);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2017 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clCryptDataHeader;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils,
{$ELSE}
System.Classes, System.SysUtils,
{$ENDIF}
clUtils;
type
TclCryptEncodingFormat = (efNone, efPem, efSsh2);
TclCryptDataHeader = class(TPersistent)
private
FExtraFields: TStrings;
FContentDomain: string;
FComment: string;
FSubject: string;
FDekInfo: string;
FProcType: string;
procedure SetExtraFields(const Value: TStrings);
function ExtractSsh2Fields(ASource, AFields: TStrings): Integer;
procedure AddSsh2Field(const AField: string; ASource: TStrings; ACharsPerLine: Integer);
protected
function ParsePem(const ASource: string): string; virtual;
function ParseSsh2(const ASource: string): string; virtual;
function BuildPem(ACharsPerLine: Integer): string; virtual;
function BuildSsh2(ACharsPerLine: Integer): string; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Clear; virtual;
function Parse(const ASource: string; AEncodingFormat: TclCryptEncodingFormat): string;
function Build(AEncodingFormat: TclCryptEncodingFormat; ACharsPerLine: Integer): string;
published
property ProcType: string read FProcType write FProcType;
property ContentDomain: string read FContentDomain write FContentDomain;
property DekInfo: string read FDekInfo write FDekInfo;
property Subject: string read FSubject write FSubject;
property Comment: string read FComment write FComment;
property ExtraFields: TStrings read FExtraFields write SetExtraFields;
end;
implementation
uses
clHeaderFieldList;
const
CRLF = #13#10;
LF = #10;
{ TclCryptDataHeader }
procedure TclCryptDataHeader.Assign(Source: TPersistent);
var
src: TclCryptDataHeader;
begin
if (Source is TclCryptDataHeader) then
begin
src := TclCryptDataHeader(Source);
FExtraFields.Assign(src.ExtraFields);
FContentDomain := src.ContentDomain;
FDekInfo := src.DekInfo;
FProcType := src.ProcType;
FComment := src.Comment;
FSubject := src.Subject;
end else
begin
inherited Assign(Source);
end;
end;
procedure TclCryptDataHeader.Clear;
begin
FExtraFields.Clear();
FContentDomain := '';
FDekInfo := '';
FProcType := '';
FComment := '';
FSubject := '';
end;
constructor TclCryptDataHeader.Create;
begin
inherited Create();
FExtraFields := TStringList.Create();
Clear();
end;
destructor TclCryptDataHeader.Destroy;
begin
FExtraFields.Free();
inherited Destroy();
end;
procedure TclCryptDataHeader.SetExtraFields(const Value: TStrings);
begin
FExtraFields.Assign(Value);
end;
function TclCryptDataHeader.Parse(const ASource: string; AEncodingFormat: TclCryptEncodingFormat): string;
begin
Clear();
if (AEncodingFormat = efPem) then
begin
Result := ParsePem(ASource);
end else
if (AEncodingFormat = efSsh2) then
begin
Result := ParseSsh2(ASource);
end else
begin
Assert(False, 'Not supported encoding format');
end;
end;
function TclCryptDataHeader.ParsePem(const ASource: string): string;
var
fieldList: TclHeaderFieldList;
src, knownFields: TStrings;
i: Integer;
begin
if (System.Pos(CRLF + CRLF, ASource) = 0) and (System.Pos(LF + LF, ASource) = 0) then
begin
Result := ASource;
Exit;
end;
fieldList := nil;
src := nil;
knownFields := nil;
try
fieldList := TclHeaderFieldList.Create();
src := TStringList.Create();
src.Text := Trim(ASource);
fieldList.Parse(0, src);
ProcType := fieldList.GetFieldValue('Proc-Type');
ContentDomain := fieldList.GetFieldValue('Content-Domain');
DekInfo := fieldList.GetFieldValue('DEK-Info');
knownFields := TStringList.Create();
knownFields.Add('Proc-Type');
knownFields.Add('Content-Domain');
knownFields.Add('DEK-Info');
for i := 0 to fieldList.FieldList.Count - 1 do
begin
if (FindInStrings(knownFields, fieldList.FieldList[i]) < 0) then
begin
ExtraFields.Add(fieldList.GetFieldName(i) + ': ' + fieldList.GetFieldValue(i));
end;
end;
for i := fieldList.HeaderEnd downto 0 do
begin
src.Delete(i);
end;
Result := src.Text;
finally
knownFields.Free();
src.Free();
fieldList.Free();
end;
end;
function TclCryptDataHeader.ExtractSsh2Fields(ASource, AFields: TStrings): Integer;
var
src, field: string;
begin
AFields.Clear();
field := '';
Result := 0;
while (Result < ASource.Count) do
begin
src := ASource[Result];
if (TextPos('Subject', src) = 1) or
(TextPos('Comment', src) = 1) or
(TextPos('x-', src) = 1) then
begin
if (field <> '') then
begin
AFields.Add(field);
end;
field := src;
Inc(Result);
end else
if (field <> '') and (field[Length(field)] = '\') then
begin
System.Delete(field, Length(field), 1);
field := field + src;
Inc(Result);
end else
begin
Break;
end;
end;
if (field <> '') then
begin
AFields.Add(field);
end;
end;
function TclCryptDataHeader.ParseSsh2(const ASource: string): string;
var
src, fields: TStrings;
i, ind, headerEnd: Integer;
field, name, value: string;
begin
src := nil;
fields := nil;
try
src := TStringList.Create();
SplitText(Trim(ASource), src, []);
fields := TStringList.Create();
headerEnd := ExtractSsh2Fields(src, fields);
i := 0;
while (i < fields.Count) do
begin
field := fields[i];
ind := TextPos(':', field, 1);
if (ind > 0) then
begin
name := System.Copy(field, 1, ind - 1);
value := Trim(System.Copy(field, ind + 1, Length(field)));
if (name = 'Subject') then
begin
Subject := value;
end else
if (name = 'Comment') then
begin
Comment := ExtractQuotedString(value);
end else
begin
ExtraFields.Add(field);
end;
end else
begin
ExtraFields.Add(field);
end;
Inc(i);
end;
Result := '';
i := headerEnd;
while (i < src.Count) do
begin
Result := Result + src[i] + CRLF;
Inc(i);
end;
finally
fields.Free();
src.Free();
end;
end;
function TclCryptDataHeader.Build(AEncodingFormat: TclCryptEncodingFormat; ACharsPerLine: Integer): string;
begin
if (AEncodingFormat = efPem) then
begin
Result := BuildPem(ACharsPerLine);
end else
if (AEncodingFormat = efSsh2) then
begin
Result := BuildSsh2(ACharsPerLine);
end else
begin
Assert(False, 'Not supported encoding format');
end;
end;
function TclCryptDataHeader.BuildPem(ACharsPerLine: Integer): string;
var
fieldList: TclHeaderFieldList;
src: TStrings;
hasData: Boolean;
begin
hasData := (ProcType <> '') or (ContentDomain <> '') or (DekInfo <> '') or (ExtraFields.Count > 0);
if (not hasData) then
begin
Result := '';
Exit;
end;
fieldList := nil;
src := nil;
try
fieldList := TclHeaderFieldList.Create();
fieldList.CharsPerLine := ACharsPerLine;
src := TStringList.Create();
fieldList.Parse(0, src);
fieldList.AddField('Proc-Type', ProcType);
fieldList.AddField('Content-Domain', ContentDomain);
fieldList.AddField('DEK-Info', DekInfo);
fieldList.AddFields(ExtraFields);
fieldList.AddEndOfHeader();
Result := src.Text;
finally
src.Free();
fieldList.Free();
end;
end;
procedure TclCryptDataHeader.AddSsh2Field(const AField: string; ASource: TStrings; ACharsPerLine: Integer);
var
ind, len, wordCnt, wordLen: Integer;
s: string;
begin
len := Length(AField) + Length('\');
wordCnt := len div ACharsPerLine;
if (len mod ACharsPerLine) > 0 then
begin
Inc(wordCnt);
end;
wordLen := Trunc(len / wordCnt);
ind := 1;
while (ind < len) do
begin
s := System.Copy(AField, ind, wordLen);
if (ind + wordLen < len) then
begin
s := s + '\';
end;
ASource.Add(s);
Inc(ind, wordLen);
end;
end;
function TclCryptDataHeader.BuildSsh2(ACharsPerLine: Integer): string;
var
hasData: Boolean;
src: TStrings;
i: Integer;
begin
hasData := (Subject <> '') or (Comment <> '') or (ExtraFields.Count > 0);
if (not hasData) then
begin
Result := '';
Exit;
end;
src := TStringList.Create();
try
if (Subject <> '') then
begin
AddSsh2Field('Subject: ' + Subject, src, ACharsPerLine);
end;
if (Comment <> '') then
begin
AddSsh2Field('Comment: ' + GetQuotedString(Comment), src, ACharsPerLine);
end;
for i := 0 to ExtraFields.Count - 1 do
begin
AddSsh2Field(ExtraFields[i], src, ACharsPerLine);
end;
Result := src.Text;
finally
src.Free();
end;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSCertificate.pas }
{ File version: 5.02 }
{ Description: TLS Certificate }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ 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. }
{ 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 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/11 5.02 Create unit flcTLSCertificate from units }
{ flcTLSHandshake and flcTLSClient. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSCertificate;
interface
uses
{ Utils }
flcStdTypes,
flcCertificateX509,
{ Cipher }
flcCipherRSA;
{ }
{ Certificate }
{ }
type
TTLSCertificateList = array of RawByteString;
procedure TLSCertificateListAppend(var List: TTLSCertificateList; const A: RawByteString);
function EncodeTLSCertificate(
var Buffer; const Size: Integer;
const CertificateList: TTLSCertificateList): Integer;
function DecodeTLSCertificate(
const Buffer; const Size: Integer;
var CertificateList: TTLSCertificateList): Integer;
procedure ParseX509Certificates(
const CertificateList: TTLSCertificateList;
var X509Certificates: TX509CertificateArray);
function GetCertificateRSAPublicKey(
const X509Certificates: TX509CertificateArray;
var RSAPublicKey: TRSAPublicKey): Boolean;
implementation
uses
{ Utils }
flcEncodingASN1,
{ TLS }
flcTLSErrors,
flcTLSOpaqueEncoding;
{ }
{ Certificate }
{ certificate_list : <0..2^24-1> ASN.1Cert; }
{ }
{ ASN.1Cert = <1..2^24-1> opaque; }
{ }
procedure TLSCertificateListAppend(var List: TTLSCertificateList; const A: RawByteString);
var L : Integer;
begin
L := Length(List);
SetLength(List, L + 1);
List[L] := A;
end;
function EncodeTLSCertificate(
var Buffer; const Size: Integer;
const CertificateList: TTLSCertificateList): Integer;
var P : PByte;
N, L, I, M, T : Integer;
C : RawByteString;
begin
Assert(Size >= 0);
N := Size;
P := @Buffer;
// certificate_list
L := Length(CertificateList);
T := 0;
for I := 0 to L - 1 do
Inc(T, 3 + Length(CertificateList[I]));
EncodeTLSLen24(P^, N, T);
Dec(N, 3);
Inc(P, 3);
for I := 0 to L - 1 do
begin
// ASN.1Cert
C := CertificateList[I];
if C = '' then
raise ETLSError.Create(TLSError_InvalidCertificate);
M := EncodeTLSOpaque24(P^, N, C);
Dec(N, M);
Inc(P, M);
end;
Result := Size - N;
end;
function DecodeTLSCertificate(
const Buffer; const Size: Integer;
var CertificateList: TTLSCertificateList): Integer;
var P : PByte;
N, L, M, F : Integer;
C : RawByteString;
begin
Assert(Size >= 0);
N := Size;
P := @Buffer;
// certificate_list
DecodeTLSLen24(P^, N, L);
Dec(N, 3);
Inc(P, 3);
SetLength(CertificateList, 0);
F := 0;
while L > 0 do
begin
// ASN.1Cert
M := DecodeTLSOpaque24(P^, N, C);
Dec(N, M);
Inc(P, M);
Dec(L, M);
Inc(F);
SetLength(CertificateList, F);
CertificateList[F - 1] := C;
end;
Result := Size - N;
end;
procedure ParseX509Certificates(
const CertificateList: TTLSCertificateList;
var X509Certificates: TX509CertificateArray);
var
L : Integer;
I : Integer;
C : RawByteString;
begin
L := Length(CertificateList);
SetLength(X509Certificates, L);
for I := 0 to L - 1 do
begin
C := CertificateList[I];
InitX509Certificate(X509Certificates[I]);
if C <> '' then
try
ParseX509Certificate(C[1], Length(C), X509Certificates[I])
except
raise ETLSError.Create(TLSError_InvalidCertificate);
end;
end;
end;
function GetCertificateRSAPublicKey(
const X509Certificates: TX509CertificateArray;
var RSAPublicKey: TRSAPublicKey): Boolean;
var
I, L, N1, N2 : Integer;
C : PX509Certificate;
S : RawByteString;
PKR : TX509RSAPublicKey;
R : Boolean;
begin
// find RSA public key from certificates
R := False;
L := Length(X509Certificates);
for I := 0 to L - 1 do
begin
C := @X509Certificates[I];
if ASN1OIDEqual(C^.TBSCertificate.SubjectPublicKeyInfo.Algorithm.Algorithm, OID_RSA) then
begin
S := C^.TBSCertificate.SubjectPublicKeyInfo.SubjectPublicKey;
Assert(S <> '');
ParseX509RSAPublicKey(S[1], Length(S), PKR);
R := True;
break;
end;
end;
if not R then
begin
Result := False;
exit;
end;
N1 := NormaliseX509IntKeyBuf(PKR.Modulus);
N2 := NormaliseX509IntKeyBuf(PKR.PublicExponent);
if N2 > N1 then
N1 := N2;
// initialise RSA public key
RSAPublicKeyAssignBuf(RSAPublicKey, N1 * 8,
PKR.Modulus[1], Length(PKR.Modulus),
PKR.PublicExponent[1], Length(PKR.PublicExponent), True);
Result := True;
end;
end.
|
unit FMX.ZDeviceInfo;
{$SCOPEDENUMS ON}
interface
uses
System.SysUtils,
System.DateUtils,
FMX.Platform;
type
TZNetworkConnectionType = (None, Unknown, WIFI, Mobile, Ethernet);
TZMobileDataType = (None, Unknown, n2G, n3G, n4G);
IZDeviceInfoService = interface
['{AA275B1D-28A9-421B-BB3D-A86864A633A0}']
function PlatformVer: string;
function Architecture2: string;
function Device: string;
function MacAddress: string;
function IPAddress: string;
function MobileOperator: string;
function IsIntel: boolean;
function IsNetConnected: boolean;
function NetworkConnectionType: TZNetworkConnectionType;
function MobileDataType: TZMobileDataType;
function IsGPSActive(HIGH_ACCURACY: boolean = false): boolean;
function DeviceID: string;
end;
TZCustomDeviceInfo = class
private const
sPlatform: array [TOSVersion.TPlatform] of string = ('Windows', 'MacOS', 'iOS', 'Android', 'WinRT', 'Linux');
sArchitecture: array [TOSVersion.TArchitecture] of string = ('IntelX86', 'IntelX64', 'ARM32', 'ARM64');
private
FScreenService : IFMXScreenService;
FLocaleService : IFMXLocaleService;
FDeviceInfoService: IZDeviceInfoService;
FTimeZone : TTimeZone;
public
constructor Create; overload;
destructor Destroy; override;
function &Platform: string;
function PlatformT: TOSVersion.TPlatform;
function PlatformVer: string;
function Architecture: string;
function Architecture2: string;
function ArchitectureT: TOSVersion.TArchitecture;
function Device: string;
function MacAddress: string;
function IPAddress: string;
function LangID: string;
function ScreenPhis: string;
function ScreenLogic: string;
function ScreenWidth: Single;
function ScreenHeight: Single;
function Scale: Single;
function MobileOperator: string;
function TimeZone: integer;
function IsIntel: boolean;
function IsNetConnected: boolean;
function NetworkConnectionType: TZNetworkConnectionType;
function MobileDataType: TZMobileDataType;
function IsPortraitOrientation: boolean;
function IsGPSActive(HIGH_ACCURACY: boolean = false): boolean;
function DeviceID: string;
end;
TZDeviceInfo = class(TZCustomDeviceInfo);
const
TZNetworkConnectionTypeString: array [TZNetworkConnectionType] of string = ('None', 'Unknown', 'WIFI', 'Mobile Data',
'Ethernet');
TZMobileDataTypeString: array [TZMobileDataType] of string = ('None', 'Unknown', '2G', '3G', '4G/LTE');
implementation
{ TZCustomDeviceInfo }
uses
FMX.Types,
System.TimeSpan
{$IFDEF MSWINDOWS}
,
FMX.ZDeviceInfo.Win
{$ENDIF}
{$IFDEF ANDROID}
,
FMX.ZDeviceInfo.Android
{$ENDIF}
{$IFDEF IOS}
,
FMX.ZDeviceInfo.iOS
{$ELSE}
{$IFDEF MACOS}
,
FMX.ZDeviceInfo.Mac
{$ENDIF}
{$ENDIF};
function FloatS(const aValue: Single): string;
var
Buf: TFormatSettings;
begin
Buf := FormatSettings;
Buf.DecimalSeparator := '.';
Result := FloatToStr(aValue, Buf)
end;
function TZCustomDeviceInfo.Architecture: string;
begin
Result := sArchitecture[TOSVersion.Architecture];
end;
function TZCustomDeviceInfo.Architecture2: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.Architecture2;
end;
function TZCustomDeviceInfo.ArchitectureT: TOSVersion.TArchitecture;
begin
Result := TOSVersion.Architecture;
end;
constructor TZCustomDeviceInfo.Create;
begin
inherited Create;
TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, FScreenService);
TPlatformServices.Current.SupportsPlatformService(IFMXLocaleService, FLocaleService);
TPlatformServices.Current.SupportsPlatformService(IZDeviceInfoService, FDeviceInfoService);
{$WARNINGS OFF}
FTimeZone := TTimeZone.Create;
{$WARNINGS ON}
end;
destructor TZCustomDeviceInfo.Destroy;
begin
FScreenService := nil;
FLocaleService := nil;
FDeviceInfoService := nil;
FTimeZone.Free;
inherited;
end;
function TZCustomDeviceInfo.Device: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.Device;
end;
function TZCustomDeviceInfo.DeviceID: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.DeviceID;
end;
function TZCustomDeviceInfo.IPAddress: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.IPAddress;
end;
function TZCustomDeviceInfo.IsGPSActive(HIGH_ACCURACY: boolean): boolean;
begin
Result := false;
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.IsGPSActive(HIGH_ACCURACY);
end;
function TZCustomDeviceInfo.IsIntel: boolean;
begin
Result := false;
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.IsIntel;
end;
function TZCustomDeviceInfo.IsNetConnected: boolean;
begin
Result := false;
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.IsNetConnected;
end;
function TZCustomDeviceInfo.IsPortraitOrientation: boolean;
begin
Result := true;
if FScreenService <> nil then
Result := (FScreenService.GetScreenOrientation = TScreenOrientation.Portrait) or
(FScreenService.GetScreenOrientation = TScreenOrientation.InvertedPortrait);
end;
function TZCustomDeviceInfo.LangID: string;
begin
Result := 'en';
if FLocaleService <> nil then
Result := FLocaleService.GetCurrentLangID;
end;
function TZCustomDeviceInfo.MacAddress: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.MacAddress;
end;
function TZCustomDeviceInfo.MobileOperator: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.MobileOperator;
end;
function TZCustomDeviceInfo.NetworkConnectionType: TZNetworkConnectionType;
begin
Result := TZNetworkConnectionType.None;
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.NetworkConnectionType;
end;
function TZCustomDeviceInfo.MobileDataType: TZMobileDataType;
begin
Result := TZMobileDataType.None;
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.MobileDataType;
end;
function TZCustomDeviceInfo.Platform: string;
begin
Result := sPlatform[TOSVersion.Platform];
end;
function TZCustomDeviceInfo.PlatformT: TOSVersion.TPlatform;
begin
Result := TOSVersion.Platform;
end;
function TZCustomDeviceInfo.PlatformVer: string;
begin
Result := '';
if FDeviceInfoService <> nil then
Result := FDeviceInfoService.PlatformVer;
end;
function TZCustomDeviceInfo.Scale: Single;
begin
Result := 1;
if FScreenService <> nil then
Result := FScreenService.GetScreenScale;
end;
function TZCustomDeviceInfo.ScreenWidth: Single;
begin
Result := 0;
if FScreenService <> nil then
Result := FScreenService.GetScreenSize.X;
end;
function TZCustomDeviceInfo.ScreenHeight: Single;
begin
Result := 0;
if FScreenService <> nil then
Result := FScreenService.GetScreenSize.Y;
end;
function TZCustomDeviceInfo.ScreenLogic: string;
begin
Result := '0 x 0';
if FScreenService <> nil then
Result := FloatS(FScreenService.GetScreenSize.Round.X) + ' x ' + FloatS(FScreenService.GetScreenSize.Round.Y);
end;
function TZCustomDeviceInfo.ScreenPhis: string;
begin
Result := '0 x 0';
if FScreenService <> nil then
Result := FloatS(FScreenService.GetScreenSize.Round.X * FScreenService.GetScreenScale) + ' x ' +
FloatS(FScreenService.GetScreenSize.Round.Y * FScreenService.GetScreenScale);
end;
function TZCustomDeviceInfo.TimeZone: integer;
begin
{$WARNINGS OFF}
Result := (((FTimeZone.Local.UtcOffset.Hours * 60) + FTimeZone.Local.UtcOffset.Minutes) * 60) +
FTimeZone.Local.UtcOffset.Seconds;
{$WARNINGS ON}
end;
initialization
RegisterService;
finalization
UnregisterService;
end.
|
unit LzmaTypes;
interface
uses Winapi.Windows;
const
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
SZ_OK = 0;
SZ_ERROR_DATA = 1;
SZ_ERROR_MEM = 2;
SZ_ERROR_CRC = 3;
SZ_ERROR_UNSUPPORTED = 4;
SZ_ERROR_PARAM = 5;
SZ_ERROR_INPUT_EOF = 6;
SZ_ERROR_OUTPUT_EOF = 7;
SZ_ERROR_READ = 8;
SZ_ERROR_WRITE = 9;
SZ_ERROR_PROGRESS = 10;
SZ_ERROR_FAIL = 11;
SZ_ERROR_THREAD = 12;
SZ_ERROR_ARCHIVE = 16;
SZ_ERROR_NO_ARCHIVE = 17;
LZMA_PROPS_SIZE = 5;
{$Z4}
type
TSRes = Integer;
TWRes = UInt32;
PISzAlloc = ^TISzAlloc;
PSzAllocProc = ^TSzAllocProc;
TSzAllocProc = function(Sender: PISzAlloc; size: SIZE_T): Pointer; cdecl;
PSzFreeProc = ^TSzFreeProc;
TSzFreeProc = procedure(Sender: PISzAlloc; address: Pointer); cdecl;
TISzAlloc = record
strict private
SzAlloc: TSzAllocProc;
SzFree: TSzFreeProc;
public
procedure Init;
end;
PISeqInStream = Pointer;
TInStreamReadProc = function(p: PISeqInStream; buf: PByte; var size: SIZE_T): TSRes; cdecl;
PISeqOutStream = Pointer;
TOutStreamWriteProc = function(p: PISeqOutStream; const buf: Pointer; size: SIZE_T): SIZE_T; cdecl;
PICompressProgress = Pointer;
TCompressProgressProc = function(p: PICompressProgress; inSize: UInt64; outSize: UInt64): TSRes; cdecl;
procedure CheckLzma(const aStatus: Integer);
procedure {$ifdef UNDERSCOREIMPORTNAME}_exit{$else}exit{$endif}(const Status: Integer); cdecl; external 'msvcrt.dll';
function HRESULT_FROM_WIN32(x: Integer): HRESULT; cdecl;
implementation
uses System.SysUtils;
function SzAllocProc(Sender: PISzAlloc; size: SIZE_T): Pointer; cdecl;
begin
if size > 0 then
Result := AllocMem(size)
else
Result := nil;
end;
procedure SzFreeProc(Sender: PISzAlloc; address: Pointer); cdecl;
begin
if address <> nil then
FreeMem(address);
end;
procedure CheckLzma(const aStatus: Integer);
begin
if aStatus <> SZ_OK then
raise Exception.CreateFmt('LZMA Error. Code: %d', [aStatus]);
end;
procedure TISzAlloc.Init;
begin
SzAlloc := SzAllocProc;
SzFree := SzFreeProc;
end;
function HRESULT_FROM_WIN32(x: Integer): HRESULT; cdecl;
const
FACILITY_WIN32 = 7;
begin
Result := x;
if Result <> 0 then
Result := ((Result and $0000FFFF) or
(FACILITY_WIN32 shl 16) or HRESULT($80000000));
end;
end.
|
Program Aufgabe6;
{$codepage utf8}
Var Jahr, Wochentag: Integer;
Begin
Write('Bitte gib das Jahr an, für welches du den ersten Wochentag wissen willst: ');
Read(Jahr);
// Quelle fuer die Gaußsche Wochentagsformel: https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Wochentagsformel
Wochentag := (1 + 5 * ((Jahr - 1) mod 4) + 4 * ((Jahr - 1) mod 100) + 6 * ((Jahr - 1) mod 400)) mod 7;
WriteLn();
WriteLn('Sonntag - 0');
WriteLn('Montag - 1');
WriteLn('Dienstag - 2');
WriteLn('Mittwoch - 3');
WriteLn('Donnerstag - 4');
WriteLn('Freitag - 5');
WriteLn('Samstag - 6');
WriteLn();
WriteLn('Der 1.1.', Jahr, ' ist der Wochentag ', Wochentag, '.');
End. |
unit uEntityTV;
interface
type
TEntityTV = class
private
FStatusTela: String;
FIdTv: Integer;
FDescricaoTv: String;
public
Constructor Create;
destructor Destroy; override;
class function New: TEntityTV;
function StatusTela: String; overload;
function StatusTela( aValue: String): TEntityTV; overload;
function IDtv: Integer; overload;
function IDtv( aValue: String): TEntityTV; overload;
function DescricaoTv: String; overload;
function DescricaoTv( aValue: String): TEntityTV; overload;
end;
implementation
uses
System.SysUtils;
{ TEntityTV }
function TEntityTV.IDtv: Integer;
begin
Result := FIdTv;
end;
function TEntityTV.IDtv(aValue: String): TEntityTV;
begin
Result := Self;
FIdTv := StrToInt(aValue);
end;
constructor TEntityTV.Create;
begin
end;
function TEntityTV.DescricaoTv: String;
begin
Result := FDescricaoTv;
end;
function TEntityTV.DescricaoTv(aValue: String): TEntityTV;
begin
Result := Self;
FDescricaoTv := aValue;
end;
destructor TEntityTV.Destroy;
begin
inherited;
end;
class function TEntityTV.New: TEntityTV;
begin
Result := Self.Create;
end;
function TEntityTV.StatusTela: String;
begin
Result := FStatusTela;
end;
function TEntityTV.StatusTela(aValue: String): TEntityTV;
begin
Result := Self;
FStatusTela := aValue;
end;
end.
|
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
PaxCompiler, FMX.TMSBaseControl, FMX.TMSMemo, PaxRunner, PaxInterpreter,
FMX.Layouts, FMX.Memo, FMX.TMSFindDialog, FMX.Objects, FMX.ScrollBox,
FMX.Controls.Presentation, System.Generics.Collections;
type
TForm1 = class(TForm)
TMSFMXMemo1: TTMSFMXMemo;
PaxPascalLanguage1: TPaxPascalLanguage;
PaxCompiler1: TPaxCompiler;
btnSYntaxCheck: TButton;
PaxInterpreter1: TPaxInterpreter;
mmoMsg: TMemo;
procedure btnSYntaxCheckClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mmoMsgDblClick(Sender: TObject);
private
{ Private declarations }
FErrorList : TList<Integer>;
function CheckSyntax(ACode : string) : Boolean;
procedure SelectLine(lNumber : Integer);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.btnSYntaxCheckClick(Sender: TObject);
var
i : integer;
lNumber : integer;
aMsg : string;
begin
mmoMsg.Lines.Clear;
FErrorList.Clear;
if CheckSyntax(TMSFMXMemo1.Lines.Text) then
exit;
lNumber := PaxCompiler1.ErrorLineNumber[0];
SelectLine(lNumber);
for I:=0 to PaxCompiler1.ErrorCount - 1 do
begin
lNumber := PaxCompiler1.ErrorLineNumber[i];
FErrorList.Add(lNumber);
aMsg := 'msg: '+PaxCompiler1.ErrorMessage[i] +
' ln: '+inttostr(lNumber);
mmoMsg.Lines.Add(aMsg);
end;
end;
function TForm1.CheckSyntax(ACode: string): Boolean;
begin
Result := false;
PaxCompiler1.Reset;
PaxCompiler1.RegisterLanguage(PaxPascalLanguage1);
PaxCompiler1.AddModule('1', 'Pascal');
PaxCompiler1.AddCode('1', ACode);
if PaxCompiler1.Compile(PaxInterpreter1) then
exit(True);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FErrorList := TList<Integer>.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(FErrorList);
end;
procedure TForm1.mmoMsgDblClick(Sender: TObject);
var
lNumber : integer;
begin
lNumber := mmoMsg.CaretPosition.Line;
if FErrorList.Count > lNumber then
SelectLine(FErrorList[lNumber]);
end;
procedure TForm1.SelectLine(lNumber: Integer);
var
lineText, temp : string;
posStart, i : integer;
begin
TMSFMXMemo1.ClearSelection;
TMSFMXMemo1.SetCursor(0,lNumber);
TMSFMXMemo1.ActiveLine := lNumber;
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Composites.MemSequence;
interface
uses
Behavior3, Behavior3.Core.Composite, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
TB3MemSequence = class(TB3Composite)
private
protected
public
constructor Create; override;
(**
* Open method.
* @method open
* @param {b3.Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
end;
implementation
{ TB3MemSequence }
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3MemSequence.Create;
begin
inherited;
(**
* Node name. Default to `MemSequence`.
* @property {String} name
* @readonly
**)
Name := 'MemSequence';
end;
procedure TB3MemSequence.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('runningChild', 0, Tick.Tree.Id, Id);
end;
function TB3MemSequence.Tick(Tick: TB3Tick): TB3Status;
var
Child: Integer;
I: Integer;
Status: TB3Status;
begin
Child := Tick.Blackboard.Get('runningChild', Tick.Tree.id, Id).AsInteger;
for I := Child to Children.Count - 1 do
begin
Status := Children[I]._Execute(Tick);
if Status <> Behavior3.Success then
begin
if Status = Behavior3.Running then
Tick.Blackboard.&Set('runningChild', I, Tick.Tree.id, Id);
Result := Status;
Exit;
end;
end;
Result := Behavior3.Success;
end;
end.
|
{ Subroutine SST_W_C_IVAL_UNSPEC (DTYPE)
*
* Write the default "unspecified" initial value for a variable of type DTYPE.
}
module sst_w_c_IVAL_UNSPEC;
define sst_w_c_ival_unspec;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_ival_unspec ( {write "unspecified" initial variable value}
in dtype: sst_dtype_t); {data type descriptor for variable}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
dt_p: sst_dtype_p_t; {pointer to base data type descriptor}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
label
dtype_new;
begin
dt_p := addr(dtype); {init pointer to base data type descriptor}
dtype_new: {back here after create new data type}
case dt_p^.dtype of {what is data type ID of this descriptor}
sst_dtype_int_k: begin
sst_w_c_intrinsic (intr_unspec_int_k);
end;
sst_dtype_enum_k: begin
sst_w_c_intrinsic (intr_unspec_enum_k);
end;
sst_dtype_float_k: begin
sst_w_c_intrinsic (intr_unspec_float_k);
end;
sst_dtype_bool_k: begin
sst_w_c_intrinsic (intr_unspec_bool_k);
end;
sst_dtype_char_k: begin
sst_w_c_intrinsic (intr_unspec_char_k);
end;
sst_dtype_rec_k: begin
if dt_p^.rec_first_p = nil
then begin {this record has no fields}
sst_w.appendn^ ('0', 1);
end
else begin
sst_w.appendn^ ('{', 1);
sst_w_c_ival_unspec (dt_p^.rec_first_p^.field_dtype_p^);
sst_w.appendn^ ('}', 1);
end
;
end;
sst_dtype_array_k: begin
sst_w.appendn^ ('{', 1);
if dt_p^.ar_dtype_rem_p = nil
then sst_w_c_ival_unspec (dt_p^.ar_dtype_ele_p^)
else sst_w_c_ival_unspec (dt_p^.ar_dtype_rem_p^);
sst_w.appendn^ ('}', 1);
end;
sst_dtype_set_k: begin
sst_w_c_intrinsic (intr_unspec_set_k);
end;
sst_dtype_range_k: begin
sst_w_c_ival_unspec (dt_p^.range_dtype_p^);
end;
sst_dtype_pnt_k: begin
sst_w_c_intrinsic (intr_unspec_pnt_k);
end;
sst_dtype_copy_k: begin
dt_p := dt_p^.copy_dtype_p;
goto dtype_new;
end;
otherwise
sys_msg_parm_int (msg_parm[1], ord(dt_p^.dtype));
sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1);
end;
end;
|
unit SearchEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, extctrls, grids;
type
TSearchEvent = procedure(sender:TObject;Value:string) of object;
TSearchEdit = class(TEdit)
private
SearchTimer:TTimer;
FOnSearch: TSearchEvent;
FAttachedGrid: TStringGrid;
procedure SetSearchDelay(const Value: integer);
function GetSearchDelay: integer;
procedure SearchEvent(Sender:TObject);
procedure SetOnSearch(const Value: TSearchEvent);
procedure SetAttachedGrid(const Value: TStringGrid);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent);override;
destructor Destroy;override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure Change; override;
published
{ Published declarations }
property SearchDelay:integer read GetSearchDelay write SetSearchDelay;
property OnSearch:TSearchEvent read FOnSearch write SetOnSearch;
property AttachedGrid:TStringGrid read FAttachedGrid write SetAttachedGrid;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TSearchEdit]);
end;
{ TSearchEdit }
constructor TSearchEdit.create(AOwner: TComponent);
begin
inherited;
SearchTimer := TTimer.Create(self);
SearchTimer.Enabled := false;
SearchTimer.Interval := 400;
SearchTimer.OnTimer := SearchEvent;
end;
destructor TSearchEdit.Destroy;
begin
SearchTimer.free;
inherited;
end;
procedure TSearchEdit.Change;
begin
SearchTimer.enabled := false;
SearchTimer.enabled := true;
inherited;
end;
procedure TSearchEdit.DoEnter;
begin
SearchTimer.enabled := false;
inherited;
end;
procedure TSearchEdit.DoExit;
begin
SearchTimer.enabled := false;
inherited;
end;
function TSearchEdit.GetSearchDelay: integer;
begin
if assigned(SearchTimer) then result := SearchTimer.Interval
else result := 400;
end;
procedure TSearchEdit.KeyDown(var Key: Word; Shift: TShiftState);
var x : integer;
begin
if (assigned(AttachedGrid)) and (shift = []) and (key in [vk_up, vk_down, vk_prior, vk_next]) then
begin
case key of
vk_up : x := attachedGrid.row - 1;
vk_down : x := attachedGrid.row + 1;
vk_prior : x := attachedGrid.row - attachedGrid.VisibleRowCount;
vk_next : x := attachedGrid.row + attachedGrid.VisibleRowCount;
end;
if x < attachedgrid.FixedRows then x := attachedgrid.FixedRows;
if x >= attachedgrid.RowCount then x := attachedGrid.Rowcount - 1;
attachedGrid.Row := x;
key := 0;
end;
inherited;
end;
procedure TSearchEdit.SearchEvent(Sender: TObject);
begin
SearchTimer.enabled := false;
if assigned(FOnSearch) then FOnSearch(self, text);
end;
procedure TSearchEdit.SetAttachedGrid(const Value: TStringGrid);
begin
FAttachedGrid := Value;
end;
procedure TSearchEdit.SetOnSearch(const Value: TSearchEvent);
begin
FOnSearch := Value;
end;
procedure TSearchEdit.SetSearchDelay(const Value: integer);
var n : integer;
begin
if value < 100 then n := 100 else n := value;
if assigned(SearchTimer) then SearchTimer.Interval := n;
end;
end.
|
unit command;
{$mode objfpc}{$H+}
interface
uses
ChannelList, IdSync;
type
{ TCommand }
TCommandProc = procedure of object;
TCommand = class
private
FChannels: TChannelList;
protected
procedure Syncronize(AMethod: TCommandProc);
property Channels: TChannelList read FChannels;
public
constructor Create(AServer: TChannelList);
end;
implementation
{ TCommand }
procedure TCommand.Syncronize(AMethod: TCommandProc);
begin
TIdSync.SynchronizeMethod(AMethod);
end;
constructor TCommand.Create(AServer: TChannelList);
begin
FChannels := AServer;
end;
end.
|
{
Форма редактирования конфигурации в XML файле.
Версия: 0.0.1
}
unit edit_xml_config_form;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, ValEdit,
ICXMLConfig;
type
{ TEditXmlConfigForm }
TEditXmlConfigForm = class(TForm)
ObjectListBox: TListBox;
CtrlSplitter: TSplitter;
PropertyValueListEditor: TValueListEditor;
private
FXmlConfig: TICXMLConfig;
public
{ Запуск редактирования XML конфигурации }
function EditConfig(aXmlConfig: TICXMLConfig): Boolean;
{ Заполнить блок XML файла конфигурации }
function Build(aPath: WideString): Boolean;
end;
var
EditXmlConfigForm: TEditXmlConfigForm;
implementation
{$R *.lfm}
{ Запуск редактирования XML конфигурации }
function TEditXmlConfigForm.EditConfig(aXmlConfig: TICXMLConfig): Boolean;
begin
ShowModal();
end;
{ Заполнить блок XML файла конфигурации }
function TEditXmlConfigForm.Build(aPath: WideString): Boolean;
begin
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.