text stringlengths 14 6.51M |
|---|
unit MainView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls,
Security.User, Security.Matrix, Security.Permission, Security.ChangePassword, Security.Login, Security.Manage
;
type
TForm2 = class(TForm)
FlowPanel: TFlowPanel;
ButtonLogin: TButton;
ButtonChangePassword: TButton;
ButtonPermission: TButton;
ButtonMatrix: TButton;
ButtonUser: TButton;
ButtonManage: TButton;
MemoEvent: TMemo;
Manage: TSecurityManage;
Login: TSecurityLogin;
ChangePassword: TSecurityChangePassword;
Permission: TSecurityPermission;
Matrix: TSecurityMatrix;
User: TSecurityUser;
procedure ButtonLoginClick(Sender: TObject);
procedure OnAuthenticate(const aEmail, aPassword: string; var aAuthenticated: Boolean; var aEmailError, aPasswordError: string);
procedure OnResult(const aResult: Boolean);
procedure ButtonChangePasswordClick(Sender: TObject);
procedure OnChangePassword(const aID: Int64; const aNewPassword: string; var aError: string; var aChanged: Boolean);
procedure ButtonPermissionClick(Sender: TObject);
procedure OnPermission(aID: Int64; aCan, aName: string; var aError: string; var aChanged: Boolean);
procedure ButtonDevClick(Sender: TObject);
procedure ButtonMatrixClick(Sender: TObject);
procedure MatrixMatrix(aID: Int64; aName, aEmail: string; aActive: Boolean; aPassword: string; aMatrixID: Integer; aIsMatrix: Boolean; var aError: string; var aChanged: Boolean);
private
procedure SetLog(Legend: Variant; const Value: Variant);
{ Private declarations }
public
{ Public declarations }
property Log[Legend: Variant]: Variant write SetLog;
end;
var
Form2: TForm2;
implementation
uses System.Hash;
{$R *.dfm}
procedure TForm2.SetLog(Legend: Variant; const Value: Variant);
begin
MemoEvent.Lines.Append(
Format('%20-s = %s', [VarToStr(Legend), VarToStr(Value)])
);
end;
procedure TForm2.ButtonDevClick(Sender: TObject);
begin
Log['LOCAL'] := TButton(Sender).Name + ' Em Desenvolvimento';
end;
procedure TForm2.ButtonLoginClick(Sender: TObject);
begin
with Manage do
begin
// Legendas
Login.ServerIP := '192.168.0.1';
Login.ComputerIP := '192.168.0.12';
Login.Sigla := 'Test';
Login.Version := '1.0.0.1';
Login.UpdatedAt := DateToStr(Date);
// Login.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg');
// Execute
Log['ENTRADA'] := 'Login';
Login.Execute;
end;
end;
procedure TForm2.OnAuthenticate(const aEmail, aPassword: string; var aAuthenticated: Boolean; var aEmailError, aPasswordError: string);
begin
Log['LOCAL'] := 'LoginAuthenticate';
Log['aEmail'] := aEmail;
Log['aPassword'] := aPassword;
Log['aAuthenticated'] := aAuthenticated;
Log['aEmailError'] := aEmailError;
Log['aPasswordError'] := aPasswordError;
if not aEmail.Equals('luisnt') then
aEmailError := 'Login Inválido!';
if not aPassword.Equals('7ujkl05') then
aPasswordError := 'Senha Inválida!';
aAuthenticated := SameStr(aEmailError + aPasswordError, EmptyStr);
end;
procedure TForm2.ButtonChangePasswordClick(Sender: TObject);
begin
with Manage do
begin
// Legendas
ChangePassword.ServerIP := '192.168.0.1';
ChangePassword.ComputerIP := '192.168.0.12';
ChangePassword.Sigla := 'Test';
ChangePassword.Version := '1.0.0.1';
ChangePassword.UpdatedAt := DateToStr(Date);
// ChangePassword.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg');
;
// Config
ChangePassword.ID := 1;
ChangePassword.Password := System.Hash.THashMD5.GetHashString('123').toUpper;
ChangePassword.Usuario := 'LuisNt : Luis Alfredo G Caldas Neto';
// Execute
Log['ENTRADA'] := 'ChangePassword';
ChangePassword.Execute;
end;
end;
procedure TForm2.OnChangePassword(const aID: Int64; const aNewPassword: string; var aError: string; var aChanged: Boolean);
begin
aError := EmptyStr;
Log['LOCAL'] := 'ChangePassword';
Log['aID'] := aID;
Log['aNewPassword'] := aNewPassword;
Log['aError'] := aError;
Log['aChanged'] := aChanged;
aChanged := SameStr(aError, EmptyStr);
end;
procedure TForm2.ButtonPermissionClick(Sender: TObject);
begin
with Manage do
begin
// Legendas
Permission.ServerIP := '192.168.0.1';
Permission.ComputerIP := '192.168.0.12';
Permission.Sigla := 'Test';
Permission.Version := '1.0.0.1';
Permission.UpdatedIn := DateToStr(Date);
// Permission.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg');
// Config
Permission.ID := 0;
Permission.UpdatedAt := Now;
Permission.Can := '01.01.01.00';
Permission.NamePermission := 'Teste de Permissão';
// Execute
Log['ENTRADA'] := 'Permission';
Permission.Execute;
end;
end;
procedure TForm2.OnPermission(aID: Int64; aCan, aName: string; var aError: string; var aChanged: Boolean);
begin
Log['LOCAL'] := 'Permission';
Log['aID'] := aID;
Log['aCan'] := aCan;
Log['aName'] := aName;
Log['aError'] := aError;
Log['aChanged'] := aChanged;
aChanged := true;
end;
procedure TForm2.ButtonMatrixClick(Sender: TObject);
begin
with Manage do
begin
// Legendas
Matrix.ServerIP := '192.168.0.1';
Matrix.ComputerIP := '192.168.0.12';
Matrix.Sigla := 'Test';
Matrix.Version := '1.0.0.1';
Matrix.UpdatedIn := DateToStr(Date);
// Matrix.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg');
// Config
Matrix.ID := 1;
Matrix.UpdatedAt := Now;
Matrix.NameMatrix := 'Teste Matriz';
Matrix.Email := 'teste_matriz@gmail.com';
Matrix.Password := '321321';
Matrix.MatrixID := 1;
Matrix.IsMatrix := true;
Matrix.Active := true;
// Execute
Log['ENTRADA'] := 'Matrix';
Matrix.Execute;
end;
end;
procedure TForm2.MatrixMatrix(aID: Int64; aName, aEmail: string; aActive: Boolean; aPassword: string; aMatrixID: Integer;
aIsMatrix: Boolean; var aError: string; var aChanged: Boolean);
begin
Log['LOCAL'] := 'Matrix';
Log['ID'] := aID;
Log['Name'] := aName;
Log['Email'] := aEmail;
Log['Password'] := aPassword;
Log['MatrixID'] := aMatrixID;
Log['IsMatrix'] := aIsMatrix;
Log['Active'] := aActive;
Log['Error'] := aError;
Log['Changed'] := aChanged;
aChanged := true;
end;
procedure TForm2.OnResult(const aResult: Boolean);
begin
Log['SAIDA: '] := BoolToStr(aResult, true);
end;
initialization
ReportMemoryLeaksOnShutdown := true;
end.
|
unit untSupplierManager;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzPanel,
GridsEh, DBGridEh, Menus, ActnList, ImgList, RzButton, StdCtrls, RzLabel,
Mask, RzEdit, RzDBEdit, DB, DBGridEhGrouping, RzCmboBx, RzDBCmbo;
type
TfrmSupplierManager = class(TForm)
RzToolbar1: TRzToolbar;
pnlTop: TPanel;
pnlCenter: TPanel;
ilSupplierToolbar: TImageList;
actlstSupplierManager: TActionList;
pmSupplierList: TPopupMenu;
btnCreate: TRzToolButton;
btnDelete: TRzToolButton;
btnUpdate: TRzToolButton;
btnOK: TRzToolButton;
btnCancel: TRzToolButton;
btnExit: TRzToolButton;
lblEncode: TRzLabel;
lbl1: TRzLabel;
lbl2: TRzLabel;
lbl3: TRzLabel;
lbl4: TRzLabel;
lbl5: TRzLabel;
lbl6: TRzLabel;
lbl7: TRzLabel;
lbl8: TRzLabel;
lbl9: TRzLabel;
lbl10: TRzLabel;
actCreate: TAction;
actDelete: TAction;
actUpdate: TAction;
N1: TMenuItem;
actDelete1: TMenuItem;
actUpdate1: TMenuItem;
RzLabel1: TRzLabel;
dgeSList: TDBGridEh;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
RzDBEdit1: TRzDBEdit;
RzDBEdit2: TRzDBEdit;
RzDBComboBox1: TRzDBComboBox;
RzDBComboBox2: TRzDBComboBox;
RzDBComboBox3: TRzDBComboBox;
RzDBEdit3: TRzDBEdit;
RzDBEdit4: TRzDBEdit;
RzDBEdit5: TRzDBEdit;
RzDBEdit6: TRzDBEdit;
RzDBEdit7: TRzDBEdit;
RzDBEdit8: TRzDBEdit;
RzDBEdit9: TRzDBEdit;
RzDBEdit10: TRzDBEdit;
RzDBEdit11: TRzDBEdit;
procedure actCreateExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actDeleteExecute(Sender: TObject);
procedure actUpdateExecute(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure dgeSListTitleBtnClick(Sender: TObject; ACol: Integer;
Column: TColumnEh);
private
procedure SetButtonEnable;
public
{ Public declarations }
end;
//var
// frmSupplierManager: TfrmSupplierManager;
implementation
uses untStockCenterDM, untCommonUtil;
{$R *.dfm}
//创建窗口
procedure TfrmSupplierManager.FormCreate(Sender: TObject);
begin
dmStockCenter.qrySupplierList.Open;
end;
//关闭窗口
procedure TfrmSupplierManager.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmStockCenter.qrySupplierList.ReadOnly := True;
dmStockCenter.qrySupplierList.Close;
end;
//设置互斥
procedure TfrmSupplierManager.SetButtonEnable;
begin
//按钮互斥
btnCreate.Enabled := not btnCreate.Enabled;
btnDelete.Enabled := not btnDelete.Enabled;
btnUpdate.Enabled := not btnUpdate.Enabled;
btnOK.Enabled := not btnOK.Enabled;
btnCancel.Enabled := not btnCancel.Enabled;
//编辑框互斥
dmStockCenter.qrySupplierList.ReadOnly := not dmStockCenter.qrySupplierList.ReadOnly;
//列表互斥
dgeSList.Enabled := not dgeSList.Enabled;
end;
//增加
procedure TfrmSupplierManager.actCreateExecute(Sender: TObject);
begin
SetButtonEnable;
if dmStockCenter.qrySupplierList.State <> dsBrowse then
begin
dmStockCenter.qrySupplierList.Cancel;
end;
dmStockCenter.qrySupplierList.Append;
dmStockCenter.qrySupplierList.FieldByName('sn').AsString := getSupplierEncode;
end;
//删除
procedure TfrmSupplierManager.actDeleteExecute(Sender: TObject);
begin
if Application.MessageBox('确定删除记录?', '提示', MB_OKCANCEL +
MB_DEFBUTTON2) = IDOK then
begin
SetButtonEnable;
if dmStockCenter.qrySupplierList.State <> dsBrowse then
begin
dmStockCenter.qrySupplierList.Cancel;
end;
dmStockCenter.qrySupplierList.Delete;
SetButtonEnable;
end;
end;
//更新
procedure TfrmSupplierManager.actUpdateExecute(Sender: TObject);
begin
SetButtonEnable;
if dmStockCenter.qrySupplierList.State <> dsBrowse then
begin
dmStockCenter.qrySupplierList.Cancel;
end;
dmStockCenter.qrySupplierList.Edit;
end;
//确定
procedure TfrmSupplierManager.btnOKClick(Sender: TObject);
begin
if dmStockCenter.qrySupplierList.State in [dsEdit,dsInsert] then
begin
dmStockCenter.qrySupplierList.Post;
end;
SetButtonEnable;
end;
//取消
procedure TfrmSupplierManager.btnCancelClick(Sender: TObject);
begin
if dmStockCenter.qrySupplierList.State in [dsEdit,dsInsert] then
begin
dmStockCenter.qrySupplierList.Cancel;
end;
SetButtonEnable;
end;
procedure TfrmSupplierManager.btnExitClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmSupplierManager.dgeSListTitleBtnClick(Sender: TObject;
ACol: Integer; Column: TColumnEh);
begin
FieldSort(dmStockCenter.qrySupplierList,Column);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.MRUList;
interface
uses
RSConsole.RESTObjects;
const
MRUDBFILE = 'mru.dat'; // do not localize
MRUCAPACITY = 40;
type
TMRUList = class(TObject)
private
FItems: TRESTRequestParamsObjectList;
FAutoSave: boolean;
FFilename: string;
public
constructor Create(const AFilename: string = ''); overload;
destructor Destroy; override;
procedure Clear;
procedure AddItem(AItem: TRESTRequestParams);
function ContainsItem(const AURL: string): boolean;
function RemoveItem(const AURL: string): boolean;
procedure SaveToFile(const AFilename: string = '');
procedure LoadFromFile(const AFilename: string = '');
property AutoSave: boolean read FAutoSave write FAutoSave;
property Items: TRESTRequestParamsObjectList read FItems;
end;
implementation
uses
System.JSON, System.SysUtils, System.Classes, System.Generics.Collections;
{ TMRUList }
constructor TMRUList.Create(const AFilename: string = '');
begin
inherited Create;
FFilename := AFilename;
FAutoSave := (FFilename <> '');
FItems := TRESTRequestParamsObjectList.Create;
FItems.OwnsObjects := True;
if (FFilename <> '') and FileExists(FFilename) then
LoadFromFile(FFilename);
end;
destructor TMRUList.Destroy;
begin
Clear;
FreeAndNIL(FItems);
inherited;
end;
procedure TMRUList.Clear;
begin
FItems.Clear;
end;
procedure TMRUList.AddItem(AItem: TRESTRequestParams);
var
LItem: TRESTRequestParams;
begin
Assert(Assigned(AItem));
// we do not want duplicates in the mru-list
if ContainsItem(AItem.ToString) then
RemoveItem(AItem.ToString);
// ensure that we do not exceed the desired capacity
if FItems.Count > MRUCAPACITY then
FItems.Delete(FItems.Count - 1);
LItem := TRESTRequestParams.Create;
LItem.Assign(AItem);
// as this is a MRU-list, we want the most recent item on top
FItems.Insert(0, LItem);
if FAutoSave then
SaveToFile;
end;
function TMRUList.ContainsItem(const AURL: string): boolean;
var
LItem: TRESTRequestParams;
begin
Result := False;
for LItem in FItems do
if SameText(LItem.ToString, AURL) then
begin
Result := True;
Break;
end;
end;
function TMRUList.RemoveItem(const AURL: string): boolean;
var
LItem: TRESTRequestParams;
begin
Result := False;
for LItem in FItems do
if SameText(LItem.ToString, AURL) then
begin
FItems.Remove(LItem);
Result := True;
Break;
end;
if FAutoSave then
SaveToFile;
end;
procedure TMRUList.LoadFromFile(const AFilename: string = '');
var
LStream: TStringStream;
LRoot: TJSONArray;
LItem: TRESTRequestParams;
LFilename: string;
i: integer;
begin
Clear;
if AFilename <> '' then
LFilename := AFilename
else
LFilename := FFilename;
if (LFilename = '') or not FileExists(LFilename) then
Exit;
LStream := TStringStream.Create;
try
LStream.LoadFromFile(LFilename);
LRoot := TJSONObject.ParseJSONValue(LStream.DataString) AS TJSONArray;
try
for i := 0 to LRoot.Count - 1 do
begin
LItem := TRESTRequestParams.Create;
LItem.FromJSONObject(LRoot.Items[i] AS TJSONObject);
FItems.Add(LItem);
end;
finally
LRoot.Free;
end;
finally
LStream.Free;
end;
LRoot := TJSONArray.Create;
try
for LItem in FItems do
LRoot.Add(LItem.AsJSONObject);
finally
LRoot.Free;
end;
end;
procedure TMRUList.SaveToFile(const AFilename: string = '');
var
LStream: TStringStream;
LRoot: TJSONArray;
LItem: TRESTRequestParams;
LFilename: string;
begin
if AFilename <> '' then
LFilename := AFilename
else
LFilename := FFilename;
if LFilename = '' then
Exit;
LRoot := TJSONArray.Create;
try
for LItem in FItems do
LRoot.Add(LItem.AsJSONObject);
LStream := TStringStream.Create(LRoot.ToString);
try
LStream.SaveToFile(LFilename);
finally
LStream.Free;
end;
finally
LRoot.Free;
end;
end;
end.
|
unit ClassGame;
interface
uses ClassPlayer, ClassHuman, ClassComputer, ClassLetters, ClassBoard,
ClassLetterBoard, ClassScoreBoard, ClassWords, ExtCtrls, Controls, Forms,
StdCtrls;
type TGameType = ( gtDontKnow, gtHvsH, gtHvsC, gtCvsH, gtCvsC );
TGame = class
private
FPlayer1 : TPlayer;
FPlayer2 : TPlayer;
FLetters : TLetters;
FBoard : TBoard;
FLetterBrd : TLetterBoard;
FScoreBrd : TScoreBoard;
FWords : TWords;
FImBoard : TImage;
FImLtrBoard : TImage;
FImScBoard : TImage;
FLabel : TLabel;
FActivePlayer : TPlayer;
FFirstMove : boolean;
FPasses : integer;
function CheckWord( Word : string ) : boolean;
function RulesOK : boolean;
procedure EndGame( StackEmpty : boolean );
public
constructor Create( Board, LetterBoard, ScoreBoard : TImage; Label1 : TLabel );
destructor Destroy; override;
procedure New( GameType : TGameType );
procedure Load( FileName : string );
procedure Save( FileName : string );
procedure OnPlay;
procedure OnTile;
procedure OnChange;
end;
implementation
uses SysUtils, Dialogs, UnitFormWinner, UnitFormNewGame;
//==============================================================================
// Constructor / destructor
//==============================================================================
constructor TGame.Create( Board, LetterBoard, ScoreBoard : TImage; Label1 : TLabel );
begin
inherited Create;
FPlayer1 := nil;
FPlayer2 := nil;
FLetters := TLetters.Create;
FBoard := TBoard.Create( Board );
FLetterBrd := TLetterBoard.Create( LetterBoard );
FScoreBrd := TScoreBoard.Create( ScoreBoard );
FWords := TWords.Create( 'English.pck' );
FImBoard := Board;
FImLtrBoard := LetterBoard;
FImScBoard := ScoreBoard;
FLabel := Label1;
FActivePlayer := nil;
FFirstMove := false;
FPasses := 0;
end;
destructor TGame.Destroy;
begin
FLetters.Free;
FBoard.Free;
FLetterBrd.Free;
FScoreBrd.Free;
FWords.Free;
inherited;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
function TGame.CheckWord( Word : string ) : boolean;
begin
Result := FWords.ExistsWord( Word );
if (not Result) then
MessageDlg( 'Word "'+Word+'" doesn''t exists!' , mtCustom , [mbOk] , 0 );
end;
function TGame.RulesOK : boolean;
const CSur : array[0..3] of
record
dX, dY : integer;
end =
((dX:-1;dY:0),
(dX:0;dY:1),
(dX:1;dY:0),
(dX:0;dY:-1));
var I, J : integer;
Word : string;
New : boolean;
begin
if (FFirstMove) then
begin
Result := false;
for I := 0 to Length( FActivePlayer.LastMove )-1 do
if ((FActivePlayer.LastMove[I].X = 8) and
(FActivePlayer.LastMove[I].Y = 8)) then
begin
Result := true;
break;
end;
if (not Result) then
begin
MessageDlg( 'First word must be placed in the center!' , mtCustom ,
[mbOk] , 0 );
exit;
end;
end
else
begin
Result := false;
for I := 0 to Length( FActivePlayer.LastMove )-1 do
begin
for J := 0 to 3 do
if ((FActivePlayer.LastMove[I].X + CSur[J].dX >= 1) and
(FActivePlayer.LastMove[I].X + CSur[J].dX <= CNumRows) and
(FActivePlayer.LastMove[I].Y + CSur[J].dY >= 1) and
(FActivePlayer.LastMove[I].Y + CSur[J].dY <= CNumCols)) then
if ((FBoard.Letters[FActivePlayer.LastMove[I].Y + CSur[J].dY,FActivePlayer.LastMove[I].X + CSur[J].dX].Letter.C <> #0) and
(not FBoard.Letters[FActivePlayer.LastMove[I].Y + CSur[J].dY,FActivePlayer.LastMove[I].X + CSur[J].dX].ThisTurn)) then
begin
Result := true;
break;
end;
end;
if (not Result) then
begin
MessageDlg( 'Word must be placed near existing one!' , mtCustom ,
[mbOk] , 0 );
exit;
end;
end;
for J := 1 to CNumCols do
begin
I := 1;
repeat
if (FBoard.Letters[I,J].Letter.C <> #0) then
begin
Word := '';
New := false;
repeat
if (FBoard.Letters[I,J].Letter.C = #0) then
break;
if (FBoard.Letters[I,J].ThisTurn) then
New := true;
Word := Word + FBoard.Letters[I,J].Letter.C;
Inc( I );
until (I > CNumRows);
if ((New) and
(Length( Word ) > 1)) then
if (not CheckWord( Word )) then
begin
Result := false;
exit;
end;
end
else
Inc( I );
until I > CNumRows;
end;
for I := 1 to CNumRows do
begin
J := 1;
repeat
if (FBoard.Letters[I,J].Letter.C <> #0) then
begin
Word := '';
New := false;
repeat
if (FBoard.Letters[I,J].Letter.C = #0) then
break;
if (FBoard.Letters[I,J].ThisTurn) then
New := true;
Word := Word + FBoard.Letters[I,J].Letter.C;
Inc( J );
until (J > CNumCols);
if ((New) and
(Length( Word ) > 1)) then
if (not CheckWord( Word )) then
begin
Result := false;
exit;
end;
end
else
Inc( J );
until J > CNumCols;
end;
end;
procedure TGame.EndGame( StackEmpty : boolean );
var Rest1, Rest2 : integer;
Score1, Score2 : integer;
begin
Rest1 := FPlayer1.GetRest;
Rest2 := FPlayer2.GetRest;
Score1 := FPlayer1.Score;
Score2 := FPlayer2.Score;
Dec( Score1 , Rest1 );
if (Score1 < 0) then
Score1 := 0;
Dec( Score2 , Rest2 );
if (Score2 < 0) then
Score2 := 0;
if (StackEmpty) then
begin
if (FActivePlayer = FPlayer1) then
Inc( Score1 , Rest2 )
else
Inc( Score2 , Rest1 );
end;
if (FPlayer1 is THuman) then
FormWinner.Label1.Caption := 'Player 1 : '
else
FormWinner.Label1.Caption := 'Comp : ';
if (FPlayer2 is THuman) then
FormWinner.Label2.Caption := 'Player 2 : '
else
FormWinner.Label2.Caption := 'Comp : ';
FormWinner.Label1.Caption := FormWinner.Label1.Caption + IntToStr( Score1 );
FormWinner.Label2.Caption := FormWinner.Label2.Caption + IntToStr( Score2 );
FormWinner.ShowModal;
New( gtDontKnow );
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TGame.New( GameType : TGameType );
var Result : integer;
begin
if (FPlayer1 <> nil) then
FPlayer1.Free;
if (FPlayer2 <> nil) then
FPlayer2.Free;
if (GameType = gtDontKnow) then
begin
repeat
Result := FormNewGame.ShowModal;
if (Result < 10) then
MessageDlg( 'Please, choose your opponent and click OK!' , mtCustom , [mbOk] , 0 )
until Result > 10;
case (Result) of
11 : GameType := gtHvsH;
12 : GameType := gtHvsC;
21 : GameType := gtCvsH;
22 : GameType := gtCvsC;
end;
end;
case (GameType) of
gtHvsH : begin
FPlayer1 := THuman.Create( FLetters , FBoard , FLetterBrd );
FPlayer2 := THuman.Create( FLetters , FBoard , FLetterBrd );
FScoreBrd.Player1 := pPl1;
FScoreBrd.Player2 := pPl2;
end;
gtCvsH : begin
FPlayer1 := TComputer.Create( FLetters , FBoard , OnPlay , OnTile , FWords );
FPlayer2 := THuman.Create( FLetters , FBoard , FLetterBrd );
FScoreBrd.Player1 := pComp1;
FScoreBrd.Player2 := pPl2;
end;
gtHvsC : begin
FPlayer2 := TComputer.Create( FLetters , FBoard , OnPlay , OnTile , FWords );
FPlayer1 := THuman.Create( FLetters , FBoard , FLetterBrd );
FScoreBrd.Player2 := pComp1;
FScoreBrd.Player1 := pPl1;
end;
gtCvsC : begin
FPlayer1 := TComputer.Create( FLetters , FBoard , OnPlay , OnTile , FWords );
FPlayer2 := TComputer.Create( FLetters , FBoard , OnPlay , OnTile , FWords );
FScoreBrd.Player1 := pComp1;
FScoreBrd.Player2 := pComp1;
end;
end;
FBoard.Clear;
FLetters.Reset;
FScoreBrd.Reset;
FPlayer1.TakeLetters;
FPlayer2.TakeLetters;
FActivePlayer := nil;
FFirstMove := true;
FPasses := 0;
OnPlay;
end;
procedure TGame.Load( FileName : string );
begin
end;
procedure TGame.Save( FileName : string );
begin
end;
procedure TGame.OnPlay;
label Zaciatok;
begin
Zaciatok :
if (FActivePlayer = nil) then
FActivePlayer := FPlayer1
else
begin
if (Length( FActivePlayer.LastMove ) = 0) then
begin
if (FActivePlayer is TComputer) then
FActivePlayer.EndMove;
Inc( FPasses );
if (FPasses = 4) then
begin
EndGame( False );
exit;
end;
end
else
begin
if ((FActivePlayer is THuman) and
(not RulesOK)) then
exit;
FPasses := 0;
FActivePlayer.Score := FActivePlayer.Score + FBoard.GetScore;
if (FActivePlayer.EndMove) then
begin
EndGame( True );
exit;
end;
if (FFirstMove) then
FFirstMove := false;
end;
if (FActivePlayer = FPlayer1) then
begin
FScoreBrd.Score1 := FActivePlayer.Score;
FActivePlayer := FPlayer2
end
else
begin
FScoreBrd.Score2 := FActivePlayer.Score;
FActivePlayer := FPlayer1;
end;
end;
FLetterBrd.SetStack( FActivePlayer.LtrStack );
if (FActivePlayer = FPlayer1) then
FLabel.Caption := 'Player 1'
else
FLabel.Caption := 'Player 2';
Application.ProcessMessages;
FActivePlayer.MakeMove( FFirstMove );
if (FActivePlayer is TComputer) then
goto Zaciatok;
end;
procedure TGame.OnTile;
begin
if (Length( FActivePlayer.LastMove ) = 0) then
begin
FActivePlayer.ChangeLetters;
Dec( FPasses );
OnPlay;
end
else
MessageDlg( 'If you want to change whole rack, you cannot use any letter!' , mtCustom , [mbOk] , 0 )
end;
procedure TGame.OnChange;
begin
if (Length( FActivePlayer.LastMove ) = 0) then
begin
FActivePlayer.ChangeSomeLetters;
Dec( FPasses );
OnPlay;
end
else
MessageDlg( 'If you want to change some tiles, you cannot use any letter!' , mtCustom , [mbOk] , 0 )
end;
end.
|
unit AES_Type;
(*************************************************************************
DESCRIPTION : AES type definitions
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00 16.08.03 we Sepatate unit from AESCrypt
1.10 15.09.03 we with IncProc
1.20 21.09.03 we with Flag, error codes
1.21 05.10.03 we with STD.INC
1.23 05.10.03 we with AES_Err_MultipleIncProcs
1.24 12.06.04 we with AES_Err_NIL_Pointer, const BLKSIZE
1.25 02.07.04 we {$ifdef DLL} stdcall; {$endif}
1.26 29.11.04 we FastInit
1.27 30.11.04 we AES_XorBlock, AESBLKSIZE
1.28 01.12.04 we AES_Err_Data_After_Short_Block
1.29 09.07.06 we Checked: D9-D10
1.30 20.07.08 we Error codes for EAX all-in-one function results
1.31 21.05.09 we CCM error codes
1.32 20.06.10 we CTR_Seek error code
1.33 27.07.10 we AES_Err_Invalid_16Bit_Length
1.34 27.09.10 we GCM error codes
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2002-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
interface
const
AESMaxRounds = 14;
const
AES_Err_Invalid_Key_Size = -1; {Key size <> 128, 192, or 256 Bits}
AES_Err_Invalid_Mode = -2; {Encr/Decr with Init for Decr/Encr}
AES_Err_Invalid_Length = -3; {No full block for cipher stealing}
AES_Err_Data_After_Short_Block = -4; {Short block must be last }
AES_Err_MultipleIncProcs = -5; {More than one IncProc Setting }
AES_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
AES_Err_EAX_Inv_Text_Length = -7; {More than 64K text length in EAX all-in-one for 16 Bit}
AES_Err_EAX_Inv_TAG_Length = -8; {EAX all-in-one tag length not 0..16}
AES_Err_EAX_Verify_Tag = -9; {EAX all-in-one tag does not compare}
AES_Err_CCM_Hdr_length = -10; {CCM header length >= $FF00}
AES_Err_CCM_Nonce_length = -11; {CCM nonce length < 7 or > 13}
AES_Err_CCM_Tag_length = -12; {CCM tag length not in [4,6,8,19,12,14,16]}
AES_Err_CCM_Verify_Tag = -13; {Computed CCM tag does not compare}
AES_Err_CCM_Text_length = -14; {16 bit plain/cipher text length to large}
AES_Err_CTR_SeekOffset = -15; {Negative offset in AES_CTR_Seek}
AES_Err_GCM_Verify_Tag = -17; {GCM all-in-one tag does not compare}
AES_Err_GCM_Auth_After_Final = -18; {Auth after final or multiple finals}
AES_Err_Invalid_16Bit_Length = -20; {BaseAddr + length > $FFFF for 16 bit code}
type
TAESBlock = packed array[0..15] of byte;
PAESBlock = ^TAESBlock;
TKeyArray = packed array[0..AESMaxRounds] of TAESBlock;
TIncProc = procedure(var CTR: TAESBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
TAESContext = packed record
RK : TKeyArray; {Key (encr. or decr.) }
IV : TAESBlock; {IV or CTR }
buf : TAESBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Rounds : word; {Number of rounds }
KeyBits : word; {Number of bits in key }
Decrypt : byte; {<>0 if decrypting key }
Flag : byte; {Bit 1: Short block }
IncProc : TIncProc; {Increment proc CTR-Mode}
end;
const
AESBLKSIZE = sizeof(TAESBlock);
implementation
end.
|
unit ModelliView;
interface
uses
SysUtils, Generics.Collections, Aurelius.Mapping.Attributes, Aurelius.Types.Blob, Aurelius.Types.DynamicProperties, Aurelius.Types.Nullable, Aurelius.Types.Proxy, Aurelius.Criteria.Dictionary,
Modelli;
type
[Entity]
[Table('QCODICIRAD')]
[Id('FPKCODICIRAD', TIdGenerator.None)]
TQCODICIRAD = class
private
[Column('PKCODICIRAD', [TColumnProp.Required], 9, 0)]
FPKCODICIRAD: double;
[Column('CODICE', [TColumnProp.Required], 12)]
FCODICE: string;
[Column('DESCRIZIONE', [TColumnProp.Required], 100)]
FDESCRIZIONE: string;
[Column('LAST_MOD', [])]
FLAST_MOD: Nullable<TDateTime>;
[Column('DATA_INIZIO', [])]
FDATA_INIZIO: Nullable<TDateTime>;
[Column('DATA_FINE', [])]
FDATA_FINE: Nullable<TDateTime>;
[Column('DOSE', [TColumnProp.Required], 8, 3)]
FDOSE: double;
[Column('COMPOSTO', [TColumnProp.Required], 1, 0)]
FCOMPOSTO: double;
[Column('PESO_TECNICO', [TColumnProp.Required], 5, 2)]
FPESO_TECNICO: double;
[Column('PESO_MEDICO', [TColumnProp.Required], 5, 2)]
FPESO_MEDICO: double;
[Column('DURATA', [TColumnProp.Required], 3, 0)]
FDURATA: double;
[Association([TAssociationProp.Lazy], [])]
[JoinColumn('BRANCA', [], 'PKBRANCHE')]
FBRANCA: Proxy<TBRANCHE>;
[Association([TAssociationProp.Lazy], [])]
[JoinColumn('GRSPEC_FK', [], 'PK_GRUPPOSPEC')]
FGRSPEC_FK: Proxy<TGRSPECIFICAZIONI>;
[Association([TAssociationProp.Lazy], [])]
[JoinColumn('IDENT_FK', [], 'IDENT')]
FIDENT_FK: Proxy<TPRESTAZIONI_SPECIALISTICHE>;
[Association([TAssociationProp.Lazy], [])]
[JoinColumn('USER_ID', [], 'PKPERSONALE')]
FUSER_ID: Proxy<TPERSONALE>;
[Association([TAssociationProp.Lazy, TAssociationProp.Required], [])]
[JoinColumn('RADIOLOGIA_FK', [TColumnProp.Required], 'PKRADIOLOGIA')]
FRADIOLOGIA_FK: Proxy<TRADIOLOGIE>;
[Association([TAssociationProp.Lazy, TAssociationProp.Required], [])]
[JoinColumn('CODICIRAD_FK', [TColumnProp.Required], 'PKCODICIRAD')]
FCODICIRAD_FK: Proxy<TCODICIRAD>;
function GetBRANCA: TBRANCHE;
procedure SetBRANCA(const Value: TBRANCHE);
function GetGRSPEC_FK: TGRSPECIFICAZIONI;
procedure SetGRSPEC_FK(const Value: TGRSPECIFICAZIONI);
function GetIDENT_FK: TPRESTAZIONI_SPECIALISTICHE;
procedure SetIDENT_FK(const Value: TPRESTAZIONI_SPECIALISTICHE);
function GetUSER_ID: TPERSONALE;
procedure SetUSER_ID(const Value: TPERSONALE);
function GetRADIOLOGIA_FK: TRADIOLOGIE;
procedure SetRADIOLOGIA_FK(const Value: TRADIOLOGIE);
function GetCODICIRAD_FK: TCODICIRAD;
procedure SetCODICIRAD_FK(const Value: TCODICIRAD);
public
property PKCODICIRAD: double read FPKCODICIRAD write FPKCODICIRAD;
property CODICE: string read FCODICE write FCODICE;
property LAST_MOD: Nullable<TDateTime> read FLAST_MOD write FLAST_MOD;
property DATA_INIZIO: Nullable<TDateTime> read FDATA_INIZIO write FDATA_INIZIO;
property DATA_FINE: Nullable<TDateTime> read FDATA_FINE write FDATA_FINE;
property DOSE: double read FDOSE write FDOSE;
property COMPOSTO: double read FCOMPOSTO write FCOMPOSTO;
property DESCRIZIONE: string read FDESCRIZIONE write FDESCRIZIONE;
property PESO_TECNICO: double read FPESO_TECNICO write FPESO_TECNICO;
property PESO_MEDICO: double read FPESO_MEDICO write FPESO_MEDICO;
property BRANCA: TBRANCHE read GetBRANCA write SetBRANCA;
property GRSPEC_FK: TGRSPECIFICAZIONI read GetGRSPEC_FK write SetGRSPEC_FK;
property IDENT_FK: TPRESTAZIONI_SPECIALISTICHE read GetIDENT_FK write SetIDENT_FK;
property USER_ID: TPERSONALE read GetUSER_ID write SetUSER_ID;
property DURATA: double read FDURATA write FDURATA;
property RADIOLOGIA_FK: TRADIOLOGIE read GetRADIOLOGIA_FK write SetRADIOLOGIA_FK;
property CODICIRAD_FK: TCODICIRAD read GetCODICIRAD_FK write SetCODICIRAD_FK;
end;
implementation
function TQCODICIRAD.GetRADIOLOGIA_FK: TRADIOLOGIE;
begin
result := FRADIOLOGIA_FK.Value;
end;
procedure TQCODICIRAD.SetRADIOLOGIA_FK(const Value: TRADIOLOGIE);
begin
FRADIOLOGIA_FK.Value := Value;
end;
function TQCODICIRAD.GetBRANCA: TBRANCHE;
begin
result := FBRANCA.Value;
end;
procedure TQCODICIRAD.SetBRANCA(const Value: TBRANCHE);
begin
FBRANCA.Value := Value;
end;
function TQCODICIRAD.GetGRSPEC_FK: TGRSPECIFICAZIONI;
begin
result := FGRSPEC_FK.Value;
end;
procedure TQCODICIRAD.SetGRSPEC_FK(const Value: TGRSPECIFICAZIONI);
begin
FGRSPEC_FK.Value := Value;
end;
function TQCODICIRAD.GetIDENT_FK: TPRESTAZIONI_SPECIALISTICHE;
begin
result := FIDENT_FK.Value;
end;
procedure TQCODICIRAD.SetIDENT_FK(const Value: TPRESTAZIONI_SPECIALISTICHE);
begin
FIDENT_FK.Value := Value;
end;
function TQCODICIRAD.GetUSER_ID: TPERSONALE;
begin
result := FUSER_ID.Value;
end;
procedure TQCODICIRAD.SetUSER_ID(const Value: TPERSONALE);
begin
FUSER_ID.Value := Value;
end;
function TQCODICIRAD.GetCODICIRAD_FK: TCODICIRAD;
begin
result := FCODICIRAD_FK.Value;
end;
procedure TQCODICIRAD.SetCODICIRAD_FK(const Value: TCODICIRAD);
begin
FCODICIRAD_FK.Value := Value;
end;
end.
|
unit Winapi.WinError;
{$MINENUMSIZE 4}
interface
const
ERROR_SUCCESS = 0;
ERROR_ACCESS_DENIED = 5;
ERROR_BAD_LENGTH = 24;
ERROR_INVALID_PARAMETER = 87;
ERROR_CALL_NOT_IMPLEMENTED = 120;
ERROR_INSUFFICIENT_BUFFER = 122;
ERROR_ALREADY_EXISTS = 183;
ERROR_MORE_DATA = 234;
WAIT_TIMEOUT = 258;
ERROR_MR_MID_NOT_FOUND = 317;
ERROR_CANT_ENABLE_DENY_ONLY = 629;
ERROR_NO_TOKEN = 1008;
ERROR_IMPLEMENTATION_LIMIT = 1292;
ERROR_NOT_ALL_ASSIGNED = 1300;
ERROR_INVALID_OWNER = 1307;
ERROR_INVALID_PRIMARY_GROUP = 1308;
ERROR_CANT_DISABLE_MANDATORY = 1310;
ERROR_PRIVILEGE_NOT_HELD = 1314;
ERROR_BAD_IMPERSONATION_LEVEL = 1346;
function Succeeded(Status: HRESULT): LongBool; inline;
function HRESULT_CODE(hr: HRESULT): Cardinal; inline;
implementation
function Succeeded(Status: HRESULT): LongBool;
begin
Result := Status and HRESULT($80000000) = 0;
end;
function HRESULT_CODE(hr: HRESULT): Cardinal;
begin
Result := hr and $FFFF;
end;
end.
|
unit frm_plugin_viewer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ComCtrls, ExtCtrls, StdCtrls, u_xml_xplplugin, v_class_combo,
v_msgbody_stringgrid, MStringGrid, MEdit, u_xpl_body;
type
{ TfrmPluginViewer }
TfrmPluginViewer = class(TForm)
btnNewNumeric: TButton;
btnNewDropDown: TButton;
btnNewTextbox: TButton;
cbCommandClasse: TxPLClassCombo;
cbCommandType: TMedit;
cbType: TComboBox;
ckStatus: TCheckBox;
ckListen: TCheckBox;
ckTrigger: TCheckBox;
ckCommand: TCheckBox;
edtMenuItemName: TEdit;
edtCommandName: TEdit;
GroupBox1: TGroupBox;
Label25: TLabel;
Label26: TLabel;
mgMenuItemBody: TBodyMessageGrid;
cbSchemaClasse: TxPLClassCombo;
cbMenuItemClasse: TxPLClassCombo;
edtMaxVal: TEdit;
edtMinVal: TEdit;
edtDevicePlatform: TComboBox;
edtDeviceType_: TComboBox;
edtRegExp: TEdit;
edtPluginVersion: TEdit;
edtPluginURL: TEdit;
edtPluginInfoURL: TEdit;
edtCommandDescription: TEdit;
edtComment: TEdit;
edtDeviceBetaVersion: TEdit;
edtDeviceDescription: TMemo;
edtDeviceInfoURL: TEdit;
edtDeviceDownloadURL: TEdit;
edtDeviceStableVersion: TEdit;
edtDeviceId: TEdit;
cbSchemaType: TMedit;
edtMenuItemType: TMedit;
Label1: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label2: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
sgDropDown: TMStringGrid;
Notebook: TNotebook;
pcCommand: TPageControl;
pgEmpty: TPage;
pgPlugin: TPage;
pgDevice: TPage;
pgMenuItem: TPage;
pgConfigItem: TPage;
pgSchema: TPage;
pgCommand: TPage;
sgConfigItems: TMStringGrid;
sgCommandElements: TMStringGrid;
Panel1: TPanel;
Splitter1: TSplitter;
TabSheet1: TTabSheet;
tbAdd: TToolButton;
tbDel1: TToolButton;
tbDel2: TToolButton;
ToolBar2: TToolBar;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
tbDel: TToolButton;
ToolButton5: TToolButton;
tsTextBox: TTabSheet;
tsDropDownList: TTabSheet;
tsNumeric: TTabSheet;
tbLaunch: TToolButton;
tbLaunch1: TToolButton;
tbSave: TToolButton;
ToolBar1: TToolBar;
ToolBar: TToolBar;
ToolButton1: TToolButton;
tvPlugin: TTreeView;
procedure btnNewDropDownClick(Sender: TObject);
procedure btnNewNumericClick(Sender: TObject);
procedure btnNewTextboxClick(Sender: TObject);
procedure btnSaveDeviceClick(Sender: TObject);
procedure edtDeviceIdEditingDone(Sender: TObject);
procedure edtMaxValExit(Sender: TObject);
procedure edtMinValExit(Sender: TObject);
procedure edtRegExpExit(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure NotebookPageChanged(Sender: TObject);
procedure sgCommandElementsSelectCell(Sender: TObject; aCol, aRow: integer; var CanSelect: boolean);
procedure sgCommandElementsSelectEditor(Sender: TObject; aCol, aRow: integer; var Editor: TWinControl);
procedure sgDropDownExit(Sender: TObject);
procedure tbAddClick(Sender: TObject);
procedure tbDel2Click(Sender: TObject);
procedure tbDelClick(Sender: TObject);
procedure tbLaunchClick(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure tvPluginSelectionChanged(Sender: TObject);
private
{ private declarations }
plugin: TXMLPluginType;
topNode: TTreeNode;
aBody: TxPLBody;
filePath: string;
public
{ public declarations }
end;
procedure ShowFrmPluginViewer(const aFilePath : string);
var
frmPluginViewer: TfrmPluginViewer;
implementation { TfrmPluginViewer }
uses
frm_XMLView,
u_xml_xplplugin_ex,
u_xml,
u_xpl_gui_resource,
u_xpl_schema,
DOM;
procedure ShowFrmPluginViewer(const aFilePath: string);
begin
if not Assigned(FrmPluginViewer) then Application.CreateForm(TFrmPluginViewer, FrmPluginViewer);
FrmPluginViewer.FilePath := aFilePath;
FrmPluginViewer.ShowModal;
end;
procedure TfrmPluginViewer.tbLaunchClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPluginViewer.ToolButton1Click(Sender: TObject);
begin
ShowfrmXMLView(FilePath);
end;
procedure TfrmPluginViewer.tvPluginSelectionChanged(Sender: TObject);
var
aNode: TTreeNode;
i: integer;
aSchema: TxPLSchema;
Elements: TXMLElementsType;
begin
aNode := tvPlugin.Selected;
//NoteBook.ActivePageComponent := pgEmpty;
NoteBook.PageIndex:=6;
tbAdd.Enabled := True;
tbDel.Enabled := (aNode <> nil) and (aNode.Data <> nil) and (aNode <> TopNode);
if aNode = nil then
exit;
if TObject(aNode.Data) is TXMLPluginType then
begin
// NoteBook.ActivePageComponent := pgPlugin;
NoteBook.PageIndex:=0;
edtPluginVersion.Text := TXMLPluginType(aNode.Data).Version;
edtPluginURL.Text := TXMLPluginType(aNode.Data).Plugin_URL;
edtPluginInfoURL.Text := TXMLPluginType(aNode.Data).Info_URL;
end;
if aNode.Text = 'ConfigItems' then
begin //(aNode.Data) is TXMLConfigItemsType then begin
// NoteBook.ActivePageComponent := pgConfigItem;
NoteBook.PageIndex:=3;
sgConfigItems.RowCount := TXMLDeviceType(aNode.Parent.Data).ConfigItems.Count + 1;
for i := 0 to TXMLDeviceType(aNode.Parent.Data).ConfigItems.Count - 1 do
begin
sgConfigItems.Cells[1, i + 1] :=
TXMLDeviceType(aNode.Parent.Data).ConfigItems[i].Name;
sgConfigItems.Cells[2, i + 1] :=
TXMLDeviceType(aNode.Parent.Data).ConfigItems[i].Description;
sgConfigItems.Cells[3, i + 1] :=
TXMLDeviceType(aNode.Parent.Data).ConfigItems[i].Format;
end;
sgConfigItems.SetFocus;
end;
if TObject(aNode.Data) is TDOmElement then
begin
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Device then
begin
tbAdd.Enabled := False;
// NoteBook.ActivePageComponent := pgDevice;
NoteBook.PageIndex :=1;
edtDeviceBetaVersion.Text := TXMLDeviceType(aNode.Data).beta_version;
edtDeviceDescription.Text := TXMLDeviceType(aNode.Data).Description;
edtDeviceInfoURL.Text := TXMLDeviceType(aNode.Data).info_url;
edtDeviceDownloadURL.Text := TXMLDeviceType(aNode.Data).download_url;
edtDevicePlatform.Text := TXMLDeviceType(aNode.Data).platform_;
edtDeviceStableVersion.Text := TXMLDeviceType(aNode.Data).Version;
edtDeviceType_.Text := TXMLDeviceType(aNode.Data).type_;
edtDeviceId.Text := TXMLDeviceType(aNode.Data).Device;
edtDeviceId.SetFocus;
end;
if TDOMElement(aNode.Data).NodeName = K_XML_STR_MenuItem then
begin
tbAdd.Enabled := False;
// NoteBook.ActivePageComponent := pgMenuItem;
NoteBook.PageIndex:=2;
edtMenuItemName.Text := TXMLMenuItemTypeEx(aNode.Data).Name;
aSchema := TXMLMenuItemTypeEx(aNode.Data).Schema;
cbMenuItemClasse.Text := aSchema.Classe;
edtMenuItemType.Text := aSchema.Type_;
aSchema.Destroy;
aBody := TXMLMenuItemTypeEx(aNode.Data).Body;
mgMenuItemBody.Assign(aBody);
end;
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Schema then
begin
tbAdd.Enabled := False;
// NoteBook.ActivePageComponent := pgSchema;
NoteBook.PageIndex := 4;
aSchema := TXMLSchemaTypeEx(aNode.Data).Schema;
cbSchemaClasse.Text := aSchema.Classe;
cbSchemaType.Text := aSchema.Type_;
aSchema.Destroy;
ckCommand.Checked := TXMLSchemaType(aNode.Data).command;
ckStatus.Checked := TXMLSchemaType(aNode.Data).status;
ckListen.Checked := TXMLSchemaType(aNode.Data).listen;
ckTrigger.Checked := TXMLSchemaType(aNode.Data).trigger;
edtComment.Text := TXMLSchemaType(aNode.Data).comment;
end;
if ((TDOMElement(aNode.Data).NodeName = K_XML_STR_COMMAND) or
(TDOMElement(aNode.Data).NodeName = K_XML_STR_TRIGGER)) then
begin
tbAdd.Enabled := False;
// NoteBook.ActivePageComponent := pgCommand;
NoteBook.PageIndex :=5;
edtCommandName.Text := TXMLCommandType(aNode.Data).Name;
edtCommandName.SetFocus;
cbType.Text := TXMLCommandType(aNode.Data).msg_type;
edtCommandDescription.Text := TXMLCommandType(aNode.Data).description;
aSchema := TXMLCommandTypeEx(aNode.Data).Schema;
cbCommandClasse.Text := aSchema.Classe;
cbCommandType.Text := aSchema.Type_;
aSchema.Destroy;
Elements := TXMLCommandType(aNode.Data).elements;
sgCommandElements.Rowcount := 1;
for i := 0 to Elements.Count - 1 do
begin
sgCommandElements.RowAppend(self);
sgCommandElements.Cells[0, i + 1] := Elements[i].Name;
sgCommandElements.Cells[1, i + 1] := Elements[i].label_;
sgCommandElements.Cells[2, i + 1] := Elements[i].control_type;
sgCommandElements.Cells[3, i + 1] := Elements[i].default_;
sgCommandElements.Cells[4, i + 1] := Elements[i].conditional_visibility;
sgCommandElements.Objects[0, i + 1] := Elements[i];
end;
end;
end;
end;
procedure TfrmPluginViewer.FormShow(Sender: TObject);
var
DeviceNode: TTreeNode;
commandsNode, configItemsNode, SchemasNode, TriggersNode, MenuItemsNode: TTreeNode;
node: TTreeNode;
i, j: integer;
begin
tvPlugin.Items.Clear;
Caption := FilePath;
// Notebook.ShowTabs := False;
pcCommand.ShowTabs := False;
tbAdd.Enabled := False;
ToolBar.Images := xPLGUIResource.Images;
ToolBar1.Images := ToolBar.Images;
ToolBar2.Images := ToolBar.Images;
plugin := TXMLPluginType.Create(FilePath);
if plugin.Valid then
begin
topNode := tvPlugin.Items.AddChild(nil, plugin.vendor);
topNode.Data := plugin;
for i := 0 to plugin.Count - 1 do
begin
DeviceNode := tvPlugin.Items.AddChild(topNode, plugin[i].id);
DeviceNode.Data := plugin[i];
CommandsNode := tvPlugin.Items.AddChild(DeviceNode, 'Commands');
SchemasNode := tvPlugin.Items.AddChild(DeviceNode, 'Schemas');
TriggersNode := tvPlugin.Items.AddChild(DeviceNode, 'Triggers');
MenuItemsNode := tvPlugin.Items.AddChild(DeviceNode, 'MenuItems');
configItemsNode := tvPlugin.Items.AddChild(DeviceNode, 'ConfigItems');
configItemsNode.Data := plugin[i].ConfigItems;
if plugin[i].Commands.Count > 0 then
for j := 0 to plugin[i].Commands.Count - 1 do
begin
node := tvPlugin.Items.AddChild(CommandsNode, plugin[i].Commands[j].Name);
node.Data := plugin[i].Commands[j];
end;
if plugin[i].Schemas.Count > 0 then
for j := 0 to plugin[i].Schemas.Count - 1 do
begin
node := tvPlugin.Items.AddChild(SchemasNode, plugin[i].Schemas[j].Name);
node.Data := plugin[i].Schemas[j];
end;
if plugin[i].Triggers.Count > 0 then
for j := 0 to plugin[i].Triggers.Count - 1 do
begin
node := tvPlugin.Items.AddChild(TriggersNode, plugin[i].Triggers[j].Name);
node.Data := plugin[i].Triggers[j];
end;
if plugin[i].MenuItems.Count > 0 then
for j := 0 to plugin[i].MenuItems.Count - 1 do
begin
node := tvPlugin.Items.AddChild(MenuItemsNode, plugin[i].MenuItems[j].Name);
node.Data := plugin[i].MenuItems[j];
end;
end;
tvPlugin.Selected := topnode;
end;
end;
procedure TfrmPluginViewer.NotebookPageChanged(Sender: TObject);
begin
tbSave.Enabled := False;
end;
procedure TfrmPluginViewer.sgCommandElementsSelectCell(Sender: TObject; aCol, aRow: integer; var CanSelect: boolean);
var
aNode: TTreeNode;
i: integer;
begin
aNode := tvPlugin.Selected;
if aNode = nil then exit;
if aNode.Data = nil then exit;
if TXMLCommandType(aNode.Data).Elements.Count = 0 then exit;
if sgCommandElements.Cells[2, aRow] = 'numeric' then begin
pcCommand.ActivePageIndex := 2;
edtMinVal.Text := IntToSTr(TXMLCommandType(aNode.Data).elements[aRow - 1].Min_Val);
edtMaxVal.Text := IntToStr(TXMLCommandType(aNode.Data).elements[aRow - 1].Max_Val);
end
else
if sgCommandElements.Cells[2, aRow] = 'dropdownlist' then begin
pcCommand.ActivePageIndex := 1;
sgDropDown.RowCount := TXMLCommandType(aNode.Data).elements[aRow - 1].Options.Count + 1;
for i := 0 to TXMLCommandType(aNode.Data).elements[aRow - 1].Options.Count - 1 do begin
sgDropDown.Cells[0, i + 1] := TXMLCommandType(aNode.Data).elements[aRow - 1].Options[i].Value;
sgDropDown.Cells[1, i + 1] := TXMLCommandType(aNode.Data).elements[aRow - 1].Options[i].Label_;
end;
end
else
if sgCommandElements.Cells[2, aRow] = 'textbox' then
begin
pcCommand.ActivePageIndex := 0;
edtRegExp.Text := TXMLCommandType(aNode.Data).elements[aRow - 1].RegExp;
end
else
pcCommand.ActivePageIndex := 3;
end;
procedure TfrmPluginViewer.sgCommandElementsSelectEditor(Sender: TObject; aCol, aRow: integer; var Editor: TWinControl);
begin
if aCol = 2 then editor := nil;
end;
procedure TfrmPluginViewer.tbAddClick(Sender: TObject);
var
i: integer;
aNode, NewNode, ConfigNode: TTreeNode;
begin
aNode := tvPlugin.Selected;
if aNode = topNode then
begin
i := TXMLPluginType(aNode.Data).Count;
NewNode := tvPlugin.Items.AddChild(aNode, '');
NewNode.Data := TXMLPluginType(aNode.Data).AddElement(IntToStr(i));
NewNode.Text := TXMLPluginType(aNode.Data)[i].Id;
tvPlugin.Items.AddChild(NewNode, 'Commands');
tvPlugin.Items.AddChild(NewNode, 'ConfigItems');
tvPlugin.Items.AddChild(NewNode, 'Schemas');
tvPlugin.Items.AddChild(NewNode, 'Triggers');
ConfigNode := tvPlugin.Items.AddChild(NewNode, 'MenuItems');
ConfigNode.Data := TXMLPluginType(aNode.Data)[i].ConfigItems;
exit;
end;
if aNode.Parent.Parent <> topNode then
exit; // We must be under the device level
if (aNode.Text = 'MenuItems') then
begin
i := TXMLDeviceType(aNode.Parent.Data).MenuItems.Count;
NewNode := tvPlugin.Items.AddChild(aNode, '');
NewNode.Data := TXMLDeviceType(aNode.Parent.Data).MenuItems.AddElement(IntToStr(i));
NewNode.Text := TXMLDeviceType(aNode.Parent.Data).MenuItems[i].Name;
end;
if (aNode.Text = 'ConfigItems') then
begin
sgCOnfigItems.RowAppend(self);
// NoteBook.ActivePageComponent := pgConfigItem;
NoteBook.PageIndex:=3;
sgConfigItems.RowCount := TXMLDeviceType(aNode.Parent.Data).ConfigItems.Count + 2;
sgConfigItems.SetFocus;
exit;
end;
if (aNode.Text = 'Schemas') then
begin
NewNode := tvPlugin.Items.AddChild(aNode, '');
NewNode.Data := TXMLDeviceType(aNode.Parent.Data).Schemas.AddElement('shema.type');
NewNode.Text := TXMLDeviceType(aNode.Parent.Data).Schemas[i].Name;
end;
if (aNode.Text = 'Commands') then
begin
NewNode := tvPlugin.Items.AddChild(aNode, '');
i := TXMLDeviceType(aNode.Parent.Data).Commands.Count;
NewNode.Data := TXMLDeviceType(aNode.Parent.Data).Commands.AddElement(IntToStr(i));
NewNode.Text := TXMLDeviceType(aNode.Parent.Data).Commands[i].Name;
end;
if (aNode.Text = 'Triggers') then
begin
NewNode := tvPlugin.Items.AddChild(aNode, '');
i := TXMLDeviceType(aNode.Parent.Data).Triggers.Count;
NewNode.Data := TXMLDeviceType(aNode.Parent.Data).Triggers.AddElement(IntToStr(i));
NewNode.Text := TXMLDeviceType(aNode.Parent.Data).Triggers[i].Name;
end;
Plugin.Save;
tvPlugin.Selected := NewNode;
NewNode.Expanded := True;
end;
procedure TfrmPluginViewer.tbDel2Click(Sender: TObject);
var
element: TXMLElementType;
begin
element := TXMLElementType(sgCommandElements.Objects[0, sgCommandElements.Row]);
TXMLCommandType(tvPlugin.Selected.Data).Elements.RootNode.RemoveChild(element);
sgCommandElements.RowDelete(self);
end;
procedure TfrmPluginViewer.tbDelClick(Sender: TObject);
var
aNode: TTreeNode;
begin
aNode := tvPlugin.Selected;
if TObject(aNode.Data) is TXMLConfigItemsType then
begin
sgConfigItems.RowDelete(self);
exit;
end;
if TObject(aNode.Data) is TDOmElement then
begin
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Device then
TXMLPluginType(aNode.Parent.Data).RootNode.RemoveChild(TXMLDeviceType(aNode.Data))
else
if TDOMElement(aNode.Data).NodeName = K_XML_STR_MenuItem then
TXMLDeviceType(aNode.Parent.Parent.Data).MenuItems.RootNode.RemoveChild(TXMLMenuItemType(aNode.Data))
else
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Schema then
TXMLDeviceType(aNode.Parent.Parent.Data).MenuItems.RootNodE.RemoveChild(TXMLSchemaType(aNode.Data))
else
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Command then
TXMLDeviceType(aNode.Parent.Parent.Data).Triggers.RootNode.RemoveChild(TXMLCommandType(aNode.Data))
else
if TDOMElement(aNode.Data).NodeName = K_XML_STR_Trigger then
TXMLDeviceType(aNode.Parent.Parent.Data).Triggers.RootNode.RemoveChild(TXMLCommandType(aNode.Data));
tvPlugin.Selected := aNode.Parent;
tvPlugin.Items.Delete(aNode);
Plugin.Save;
tbDel.Enabled := False;
end;
end;
procedure TfrmPluginViewer.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if assigned(plugin) then Plugin.Destroy;
end;
procedure TfrmPluginViewer.btnSaveDeviceClick(Sender: TObject);
var
i: integer;
configItem: TXMLConfigItemType;
element: TXMLElementType;
begin
if NoteBook.ActivePageComponent = pgDevice then
begin
TXMLDeviceType(tvPlugin.Selected.Data).Description := edtDeviceDescription.Text;
TXMLDeviceType(tvPlugin.Selected.Data).download_url := edtDeviceDownloadURL.Text;
TXMLDeviceType(tvPlugin.Selected.Data).Device := edtDeviceId.Text;
TXMLDeviceType(tvPlugin.Selected.Data).info_url := edtDeviceInfoURL.Text;
TXMLDeviceType(tvPlugin.Selected.Data).beta_version := edtDeviceBetaVersion.Text;
TXMLDeviceType(tvPlugin.Selected.Data).platform_ := edtDevicePlatform.Text;
TXMLDeviceType(tvPlugin.Selected.Data).Version := edtDeviceStableVersion.Text;
TXMLDeviceType(tvPlugin.Selected.Data).type_ := edtDeviceType_.Text;
TXMLDeviceType(tvPlugin.Selected.Data).device := edtDeviceId.Text;
tvPlugin.Selected.Text := TXMLDeviceType(tvPlugin.Selected.Data).Id;
// Reflect modification in treeview
end;
if NoteBook.ActivePageComponent = pgMenuItem then
begin
abody.ResetValues;
mgMenuItemBody.CopyTo(aBody);
TXMLMenuItemTypeEx(tvPlugin.Selected.Data).Set_Body(aBody.RawxPL);
TXMLMenuItemTypeEx(tvPlugin.Selected.Data).Set_Schema(cbMenuItemClasse.Text+'.'+edtMenuItemType.Text);
TXMLMenuItemType(tvPlugin.Selected.Data).Name := edtMenuItemName.Text;
aBody.Destroy;
tvPlugin.Selected.Text := TXMLMenuItemType(tvPlugin.Selected.Data).Name;
end;
if NoteBook.ActivePageComponent = pgPlugin then
begin
TXMLPluginType(tvPlugin.Selected.Data).Version := edtPluginVersion.Text;
TXMLPluginType(tvPlugin.Selected.Data).Plugin_URL := edtPluginURL.Text;
TXMLPluginType(tvPlugin.Selected.Data).Info_URL := edtPluginInfoURL.Text;
end;
if NoteBook.ActivePageComponent = pgConfigItem then
begin
TXMLDeviceType(tvPlugin.Selected.Parent.Data).ConfigItems.EmptyList;
for i := 1 to sgConfigItems.RowCount - 1 do
begin
configItem := TXMLDeviceType(tvPlugin.Selected.Parent.Data).ConfigItems.AddElement(sgConfigItems.Cells[1, i]);
configItem.description := sgConfigItems.Cells[2, i];
configItem.Format := sgConfigItems.Cells[3, i];
end;
end;
if NoteBook.ActivePageComponent = pgSchema then
begin
TXMLSchemaType(tvPlugin.Selected.Data).command := ckCommand.Checked;
TXMLSchemaType(tvPlugin.Selected.Data).comment := edtComment.Text;
TXMLSchemaType(tvPlugin.Selected.Data).status := ckStatus.Checked;
TXMLSchemaType(tvPlugin.Selected.Data).listen := ckListen.Checked;
TXMLSchemaType(tvPlugin.Selected.Data).trigger := ckTrigger.Checked;
TXMLSchemaType(tvPlugin.Selected.Data).Name := cbSchemaClasse.Text + '.' + cbSchemaType.Text;
tvPlugin.Selected.Text := TXMLSchemaType(tvPlugin.Selected.Data).Name;
end;
if NoteBook.ActivePageComponent = pgCommand then
begin
TXMLCommandType(tvPlugin.Selected.Data).Name := edtCommandName.Text;
TXMLCommandType(tvPlugin.Selected.Data).description := edtCommandDescription.Text;
TXMLCommandType(tvPlugin.Selected.Data).msg_schema := cbCommandClasse.Text +'.'+ cbCommandType.Text;
TXMLCommandType(tvPlugin.Selected.Data).msg_type := cbType.Text;
for i := 1 to sgCommandElements.RowCount - 1 do
begin
element := TXMLElementType(sgCommandElements.Objects[0, i]);
element.label_ := sgCommandElements.Cells[1, i];
element.Control_type := sgCommandElements.Cells[2, i];
element.default_ := sgCommandElements.Cells[3, i];
element.conditional_visibility := sgCommandElements.Cells[4, i];
end;
tvPlugin.Selected.Text := TXMLCommandType(tvPlugin.Selected.Data).Name;
end;
if NoteBook.ActivePageComponent = pgCommand then
begin
TXMLCommandType(tvPlugin.Selected.Data).Name := edtCommandName.Text;
TXMLCommandType(tvPlugin.Selected.Data).description := edtCommandDescription.Text;
TXMLCommandType(tvPlugin.Selected.Data).msg_schema := cbCommandClasse.Text + '.' + cbCommandType.Text;
TXMLCommandType(tvPlugin.Selected.Data).msg_type := cbType.Text;
for i := 1 to sgCommandElements.RowCount - 1 do
begin
element := TXMLElementType(sgCommandElements.Objects[0, i]);
element.name:= sgCommandElements.Cells[0,i];
element.label_ := sgCommandElements.Cells[1, i];
element.Control_type := sgCommandElements.Cells[2, i];
element.default_ := sgCommandElements.Cells[3, i];
element.conditional_visibility := sgCommandElements.Cells[4, i];
end;
tvPlugin.Selected.Text := TXMLCommandType(tvPlugin.Selected.Data).Name;
end;
Plugin.Save;
tbSave.Enabled := False;
end;
procedure TfrmPluginViewer.btnNewNumericClick(Sender: TObject);
var
i: integer;
element: TXMLElementType;
begin
sgCommandElements.RowAppend(self);
i := sgCommandElements.RowCount - 1;
element := TXMLCommandType(tvPlugin.Selected.Data).Elements.AddElement('Element_' + IntToStr(i));
sgCommandElements.Cells[2, i] := 'numeric';
sgCommandElements.Objects[0, i] := element;
sgCommandElements.Cells[0, i] := element.Name;
end;
procedure TfrmPluginViewer.btnNewTextboxClick(Sender: TObject);
var
i: integer;
element: TXMLElementType;
begin
sgCommandElements.RowAppend(self);
i := sgCommandElements.RowCount - 1;
element := TXMLCommandType(tvPlugin.Selected.Data).Elements.AddElement('Element_' + IntToStr(i));
sgCommandElements.Cells[2, i] := 'textbox';
sgCommandElements.Objects[0, i] := element;
sgCommandElements.Cells[0, i] := element.Name;
edtRegExp.Text := element.regexp;
end;
procedure TfrmPluginViewer.btnNewDropDownClick(Sender: TObject);
var
i: integer;
element: TXMLElementType;
begin
sgCommandElements.RowAppend(self);
i := sgCommandElements.RowCount - 1;
element := TXMLCommandType(tvPlugin.Selected.Data).Elements.AddElement('Element_' + IntToStr(i));
sgCommandElements.Cells[2, i] := 'dropdownlist';
sgCommandElements.Objects[0, i] := element;
sgCommandElements.Cells[0, i] := element.Name;
end;
procedure TfrmPluginViewer.edtDeviceIdEditingDone(Sender: TObject);
begin
tbSave.Enabled := True;
end;
procedure TfrmPluginViewer.edtMaxValExit(Sender: TObject);
begin
TXMLElementType(sgCommandElements.Objects[0, sgCommandElements.Row]).max_val := StrToInt(edtMaxVal.Text);
end;
procedure TfrmPluginViewer.edtMinValExit(Sender: TObject);
begin
TXMLElementType(sgCommandElements.Objects[0, sgCommandElements.Row]).min_val := StrToInt(edtMinVal.Text);
end;
procedure TfrmPluginViewer.edtRegExpExit(Sender: TObject);
begin
TXMLElementType(sgCommandElements.Objects[0, sgCommandElements.Row]).regexp := edtRegExp.Text;
end;
procedure TfrmPluginViewer.sgDropDownExit(Sender: TObject);
var
element: TXMLElementType;
i: integer;
option: TXMLOptionType;
begin
element := TXMLElementType(sgCommandElements.Objects[0, sgCommandElements.Row]);
element.Options.EmptyList;
for i := 1 to sgDropDown.RowCount - 1 do begin
option := element.Options.AddElement(sgDropDown.Cells[0, i]);
option.label_ := sgDropDown.Cells[1, i];
end;
end;
initialization
{$I frm_plugin_viewer.lrs}
end.
|
program var3zad1;
uses
SysUtils;
type Ychenik=record
FIO : string[40];
God_roj : integer;
Month_roj : string[10];
Day_roj : integer;
Klass : integer;
Predmet : string[20];
end;
YchenikDataBase = file of Ychenik;
procedure CreateDataBase(filename:string);
var dataFile: YchenikDataBase;
card: Ychenik;
answer:char;
begin
assign(dataFile, fileName);
rewrite(dataFile);
repeat
write('Vvedite FIO:');
readln(card.FIO);
write('Vvedite God Rojdeniya:');
readln(card.God_roj);
write('Vvedite Mesyats Rojdeniya:');
readln(card.Month_roj);
write('Vvedite Den Rojdeniya:');
readln(card.Day_roj);
write('Vvedite Klass:');
readln(card.Klass);
write('Vvedite Lyubimiy Predmet:');
readln(card.Predmet);
write(dataFile, card);
write('Continue(Y)?');
readln(answer);
until (answer <> 'y') and (answer <> 'Y');
close(dataFile);
end;
procedure PrintCard(i:integer;card: Ychenik);
begin
writeln(i, '. ', card.FIO, ' ', card.God_roj, ' ', card.Month_roj, ' ', card.Day_roj, ' ', card.Klass, ' ', card.Predmet);
end;
procedure PrintDataBase(fileName:string);
var dataFile: YchenikDataBase;
card: Ychenik;
i:integer;
Klass:integer;
God_roj:integer;
begin
i := 0;
write('Vvedite Klass');
readln(Klass);
write ('Vvedite God Rojdeniya');
readln(God_roj);
assign(dataFile, fileName);
reset(dataFile);
while not eof(dataFile) do
begin
read(dataFile, card);
if (card.Klass=Klass) and (card.God_roj>=God_roj) then
begin
i := i + 1;
PrintCard(i, card);
end;
end;
close(dataFile);
end;
var fileName:string[20];
a: integer;
begin
write('Enter file name:');
readln(fileName);
write('Create(0) or Print(1)?');
readln(a);
if a=0 then
//CreateDataBase('DataBase.txt')
CreateDataBase(fileName)
else
PrintDataBase(fileName);
//PrintDataBase('DataBase.txt');
readln;
end.
|
unit Archive;
interface
uses Classes, SysUtils, Windows;
type
TStoragePoint = array of TPoint;
TArchive = class(TObject)
private
FStoring: Boolean;
FHandle: LongInt;
FError: Integer;
FPoint: TStoragePoint;
FPosition: LongInt;
function GetError: Boolean;
procedure SetPosition(const Value: LongInt);
function GetPosition: LongInt;
function GetFileSize: LongInt;
public
constructor Create(FileName: String; Mode: LongWord);
destructor Destroy; override;
property IsStoring: Boolean read FStoring write FStoring default False;
property IsError: Boolean read GetError default False;
property Points: TStoragePoint read FPoint;
property Position: LongInt read GetPosition write SetPosition;
property Size: LongInt read GetFileSize;
function DataWrite(Data: LongInt): Boolean; overload;
function DataWrite(Data: Double): Boolean; overload;
function DataWrite(Data: TPoint): Boolean; overload;
function DataWrite(Data: TRect): Boolean; overload;
function DataWrite(Data: String): Boolean; overload;
function DataWrite(Data: LOGBRUSH): Boolean; overload;
function DataWrite(Data: LOGPEN): Boolean; overload;
function DataWrite(Data: array of TPoint): Boolean; overload;
function DataRead(var Data: LongInt): Boolean; overload;
function DataRead(var Data: Double): Boolean; overload;
function DataRead(var Data: TPoint): Boolean; overload;
function DataRead(var Data: TRect): Boolean; overload;
function DataRead(var Data: String): Boolean; overload;
function DataRead(var Data: LOGBRUSH): Boolean; overload;
function DataRead(var Data: LOGPEN): Boolean; overload;
function DataRead(Data: Boolean): Boolean; overload;
end;
implementation
{ TArchive }
constructor TArchive.Create(FileName: String; Mode: LongWord);
begin
if not FileExists(FileName) then
FHandle:= FileCreate(FileName)
else
FHandle:= FileOpen(FileName, Mode);
FError:= FHandle;
SetLength(FPoint, 0);
end;
function TArchive.DataRead(var Data: TPoint): Boolean;
var
p: TPoint;
begin
Result:= FileRead(FHandle, p, SizeOf(p)) <> 0;
Data:= P;
end;
function TArchive.DataRead(var Data: TRect): Boolean;
var
RD: TRect;
begin
Result:= FileRead(FHandle, RD, SizeOf(RD)) <> 0;
Data:= RD;
end;
function TArchive.DataRead(var Data: Integer): Boolean;
begin
Result:= FileRead(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataRead(var Data: Double): Boolean;
begin
Result:= FileRead(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataRead(var Data: LOGPEN): Boolean;
var
lp: LOGPEN;
begin
Result:= FileRead(FHandle, lp, SizeOf(lp)) <> 0;
Data:= lp;
end;
function TArchive.DataRead(Data: Boolean): Boolean;
var
i, j: Integer;
p: TPoint;
begin
Result:= FileRead(FHandle, i, SizeOf(i)) <> 0;
if Result then
begin
SetLength(FPoint, i);
for j:= 0 to i - 1 do
begin
Result:= Result and (FileRead(FHandle, p, SizeOf(p)) <> 0);
if not Result then
begin
Finalize(FPoint); FPoint:= nil;
Break;
end;
FPoint[j]:= p;
end;
end;
end;
function TArchive.DataRead(var Data: String): Boolean;
var
i, j: Word;
ch: Char;
s: String;
begin
s:= '';
Result:= FileRead(FHandle, i, SizeOf(i)) <> 0;
if Result then
for j:= 1 to i do
begin
Result:= Result and (FileRead(FHandle, ch, SizeOf(ch)) <> 0);
if not Result then Break;
s:= s + ch;
end;
Data:= s;
end;
function TArchive.DataRead(var Data: LOGBRUSH): Boolean;
var
lb: LOGBRUSH;
begin
Result:= FileRead(FHandle, lb, SizeOf(lb)) <> 0;
Data:= lb;
end;
function TArchive.DataWrite(Data: TPoint): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataWrite(Data: TRect): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataWrite(Data: Integer): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataWrite(Data: Double): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataWrite(Data: LOGPEN): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
function TArchive.DataWrite(Data: array of TPoint): Boolean;
var
i: Integer;
p: TPoint;
begin
i:= Length(Data);
Result:= FileWrite(FHandle, i, SizeOf(i)) <> 0;
if Result then
for i:= 0 to High(Data) do
if Result then
begin
p:= Data[i];
Result:= Result and (FileWrite(FHandle, p, SizeOf(p))<>0)
end
else
Break;
end;
function TArchive.DataWrite(Data: String): Boolean;
var
i: Word;
ch: Char;
begin
i:= Length(Data);
Result:= FileWrite(FHandle, i, SizeOf(i)) <> 0;
if Result then
for i:= 1 to Length(Data) do
if Result then
begin
ch:= Data[i];
Result:= Result and (FileWrite(FHandle, ch, SizeOf(ch))<>0)
end
else
Break;
end;
function TArchive.DataWrite(Data: LOGBRUSH): Boolean;
begin
Result:= FileWrite(FHandle, Data, SizeOf(Data)) <> 0;
end;
destructor TArchive.Destroy;
begin
Finalize(FPoint);
FPoint:= nil;
FileClose(FHandle);
inherited;
end;
function TArchive.GetError: Boolean;
begin
Result:= FError = -1;
end;
function TArchive.GetFileSize: LongInt;
var
currPos: LongInt;
begin
currPos:= FileSeek(FHandle, 0, 0);
FileSeek(FHandle, 0, 0);
Result:= FileSeek(FHandle, 0, 2);
FileSeek(FHandle, currPos, 0);
end;
function TArchive.GetPosition: LongInt;
begin
Result:= FileSeek(FHandle, 0, 1);
end;
procedure TArchive.SetPosition(const Value: LongInt);
begin
FPosition:= FileSeek(FHandle, Value, 0);
end;
end.
|
unit VMProtectSDK;
interface
{$IF NOT DECLARED(PAnsiChar)}
type
PAnsiChar = PUTF8Char;
{$IFEND}
// protection
procedure VMProtectBegin(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectBeginVirtualization(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectBeginMutation(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectBeginUltra(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectBeginVirtualizationLockByKey(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectBeginUltraLockByKey(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
procedure VMProtectEnd; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// utils
function VMProtectIsProtected: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectIsDebuggerPresent(CheckKernelMode: Boolean): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectIsVirtualMachinePresent: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectIsValidImageCRC: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectDecryptStringA(Value: PAnsiChar): PAnsiChar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectDecryptStringW(Value: PWideChar): PWideChar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectFreeString(Value: Pointer): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// licensing
type
TVMProtectDate = packed record
wYear: Word;
bMonth: Byte;
bDay: Byte;
end;
PVMProtectSerialNumberData = ^TVMProtectSerialNumberData;
TVMProtectSerialNumberData = packed record
nState: Longword;
wUserName: array [0..255] of WideChar;
wEMail: array [0..255] of WideChar;
dtExpire: TVMProtectDate;
dtMaxBuild: TVMProtectDate;
bRunningTime: Longword;
nUserDataLength: Byte;
bUserData: array [0..254] of Byte;
end;
const
SERIAL_STATE_SUCCESS = 0;
SERIAL_STATE_FLAG_CORRUPTED = $00000001;
SERIAL_STATE_FLAG_INVALID = $00000002;
SERIAL_STATE_FLAG_BLACKLISTED = $00000004;
SERIAL_STATE_FLAG_DATE_EXPIRED = $00000008;
SERIAL_STATE_FLAG_RUNNING_TIME_OVER = $00000010;
SERIAL_STATE_FLAG_BAD_HWID = $00000020;
SERIAL_STATE_FLAG_MAX_BUILD_EXPIRED = $00000040;
function VMProtectSetSerialNumber(SerialNumber: PAnsiChar): Longword; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectGetSerialNumberState: Longword; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectGetSerialNumberData(Data: PVMProtectSerialNumberData; DataSize: Integer): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectGetCurrentHWID(Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// activation
const
ACTIVATION_OK = 0;
ACTIVATION_SMALL_BUFFER = 1;
ACTIVATION_NO_CONNECTION = 2;
ACTIVATION_BAD_REPLY = 3;
ACTIVATION_BANNED = 4;
ACTIVATION_CORRUPTED = 5;
ACTIVATION_BAD_CODE = 6;
ACTIVATION_ALREADY_USED = 7;
ACTIVATION_SERIAL_UNKNOWN = 8;
ACTIVATION_EXPIRED = 9;
ACTIVATION_NOT_AVAILABLE = 10;
function VMProtectActivateLicense(ActivationCode: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectDeactivateLicense(SerialNumber: PAnsiChar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectGetOfflineActivationString(ActivationCode: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function VMProtectGetOfflineDeactivationString(SerialNumber: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
implementation
{$IFDEF WIN64}
const VMProtectDLLName = 'VMProtectSDK64.dll';
{$ELSE}
{$IFDEF WIN32}
const VMProtectDLLName = 'VMProtectSDK32.dll';
{$ELSE}
{$IFDEF DARWIN}
{$LINKLIB libVMProtectSDK.dylib}
{$ELSE}
{$IFDEF MACOS}
const VMProtectDLLName = 'libVMProtectSDK.dylib';
{$ELSE}
{$IFDEF LINUX32}
const VMProtectDLLName = 'libVMProtectSDK32.so';
{$ELSE}
{$IFDEF LINUX64}
const VMProtectDLLName = 'libVMProtectSDK64.so';
{$ELSE}
{$FATAL Unsupported OS!!!}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
procedure VMProtectBegin(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF};
procedure VMProtectBeginVirtualization(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectBeginVirtualization'{$ENDIF};
procedure VMProtectBeginMutation(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectBeginMutation'{$ENDIF};
procedure VMProtectBeginUltra(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectBeginUltra'{$ENDIF};
procedure VMProtectBeginVirtualizationLockByKey(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectBeginVirtualizationLockByKey'{$ENDIF};
procedure VMProtectBeginUltraLockByKey(MarkerName: PAnsiChar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectBeginUltraLockByKey'{$ENDIF};
procedure VMProtectEnd; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectEnd'{$ENDIF};
function VMProtectIsProtected: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectIsProtected'{$ENDIF};
function VMProtectIsDebuggerPresent(CheckKernelMode: Boolean): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectIsDebuggerPresent'{$ENDIF};
function VMProtectIsVirtualMachinePresent: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectIsVirtualMachinePresent'{$ENDIF};
function VMProtectIsValidImageCRC: Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectIsValidImageCRC'{$ENDIF};
function VMProtectDecryptStringA(Value: PAnsiChar): PAnsiChar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectDecryptStringA'{$ENDIF};
function VMProtectDecryptStringW(Value: PWideChar): PWideChar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectDecryptStringW'{$ENDIF};
function VMProtectFreeString(Value: Pointer): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectFreeString'{$ENDIF};
function VMProtectSetSerialNumber(SerialNumber: PAnsiChar): Longword; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectSetSerialNumber'{$ENDIF};
function VMProtectGetSerialNumberState: Longword; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectGetSerialNumberState'{$ENDIF};
function VMProtectGetSerialNumberData(Data: PVMProtectSerialNumberData; DataSize: Integer): Boolean; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectGetSerialNumberData'{$ENDIF};
function VMProtectGetCurrentHWID(Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectGetCurrentHWID'{$ENDIF};
function VMProtectActivateLicense(ActivationCode: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectActivateLicense'{$ENDIF};
function VMProtectDeactivateLicense(SerialNumber: PAnsiChar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectDeactivateLicense'{$ENDIF};
function VMProtectGetOfflineActivationString(ActivationCode: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectGetOfflineActivationString'{$ENDIF};
function VMProtectGetOfflineDeactivationString(SerialNumber: PAnsiChar; Buffer: PAnsiChar; BufferLen: Integer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external {$IFNDEF DARWIN}VMProtectDLLName{$ENDIF} {$IFDEF MACOS} name '_VMProtectGetOfflineDeactivationString'{$ENDIF};
end.
|
unit untEasyDesignerGridReg;
{$I cxGridVer.inc}
interface
uses
Types, DesignIntf, DesignEditors,
VCLEditors,
cxGridImportDialog,
TypInfo, Classes, SysUtils, Controls, Graphics, ExtCtrls,
{$IFNDEF NONDB}
DB, cxDBData, cxGridDBDataDefinitions, cxGridDBTableView, cxGridDBBandedTableView,
cxGridDBCardView, cxDBExtLookupComboBox,
{$ENDIF}
cxPropEditors, cxEditPropEditors,
cxCustomData,
cxEdit, cxEditRepositoryItems,
cxGridCommon, cxGrid, cxGridLevel,
cxGridCustomView, cxGridCustomTableView,
cxGridTableView,
cxGridBandedTableView,
cxGridCardView,
cxControls,
cxGridStructureNavigator, cxGridEditor,
cxStyles, cxEditRepositoryEditor, cxGridStrs;
const
UnitNamePrefix = '';
cxGridVersion = '4.52';
type
TcxCustomGridViewAccess = class(TcxCustomGridView);
TcxCustomGridTableItemAccess = class(TcxCustomGridTableItem);
TcxCustomGridTableViewAccess = class(TcxCustomGridTableView);
{$IFNDEF NONDB}
TcxGridDBTableViewAccess = class(TcxGridDBTableView);
{$ENDIF}
TcxCustomDataSummaryItemAccess = class(TcxCustomDataSummaryItem);
{ TGridEditor }
type
TGridEditor = class(TComponentEditor)
private
function GetGrid: TcxCustomGrid;
protected
property Grid: TcxCustomGrid read GetGrid;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
implementation
function TGridEditor.GetGrid: TcxCustomGrid;
begin
Result := TcxCustomGrid(Component);
end;
procedure TGridEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
0: ShowGridEditor(Designer, Grid);
1: ShowGridImportDialog(Designer, Grid);
end;
end;
function TGridEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Editor...';
1: Result := 'Import...';
2: Result := '-';
3: Result := 'ExpressQuantumGrid Suite ' + cxGridVersion;
4: Result := 'www.devexpress.com';
end;
end;
function TGridEditor.GetVerbCount: Integer;
begin
Result := 2 + 3;
end;
{ TGridViewRepositoryEditor }
type
TGridViewRepositoryEditor = class(TComponentEditor)
private
function GetGridViewRepository: TcxGridViewRepository;
protected
property GridViewRepository: TcxGridViewRepository read GetGridViewRepository;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
function TGridViewRepositoryEditor.GetGridViewRepository: TcxGridViewRepository;
begin
Result := TcxGridViewRepository(Component);
end;
procedure TGridViewRepositoryEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
//0: GridViewRepository.CreateItem(TcxGridDBTableView).Name := Designer.UniqueName('cxGridDBTableView');
0: ShowViewRepositoryEditor(Designer, GridViewRepository);
end;
end;
function TGridViewRepositoryEditor.GetVerb(Index: Integer): string;
begin
case Index of
//0: Result := 'Create TcxGridDBTableView';
0: Result := 'Editor...';
1: Result := '-';
2: Result := 'ExpressQuantumGrid Suite ' + cxGridVersion;
3: Result := 'www.devexpress.com';
end;
end;
function TGridViewRepositoryEditor.GetVerbCount: Integer;
begin
Result := 4;
end;
{ TcxGridRootLevelStylesEventsProperty }
type
TcxGridRootLevelStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridRootLevelStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomGrid(GetComponent(0)).RootLevelStyles;
end;
{ TcxGridTableItemPropertiesEventsProperty }
type
TcxGridTableItemPropertiesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridTableItemPropertiesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomGridTableItemAccess(GetComponent(0)).Properties;
end;
{ TcxGridTableItemStylesEventsProperty }
type
TcxGridTableItemStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridTableItemStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomGridTableItemAccess(GetComponent(0)).Styles;
end;
{ TcxGridDataControllerEventsProperty }
type
TcxGridDataControllerEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridDataControllerEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomGridView(GetComponent(0)).DataController;
end;
{ TcxGridStylesEventsProperty }
type
TcxGridViewStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridViewStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomGridViewAccess(GetComponent(0)).Styles;
end;
{ TcxGridLevelStylesEventsProperty }
type
TcxGridLevelStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridLevelStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxGridLevel(GetComponent(0)).Styles;
end;
{ TcxGridBandStylesEventsProperty }
type
TcxGridBandStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
function TcxGridBandStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxGridBand(GetComponent(0)).Styles;
end;
(*{ TcxGridOptionsProperty }
type
TcxGridOptionsProperty = class(TComponentProperty)
public
function AllEqual: Boolean; override;
function GetAttributes: TPropertyAttributes; override;
procedure GetProperties(Proc: TGetPropProc); override;
function GetValue: string; override;
end;
function TcxGridOptionsProperty.AllEqual: Boolean;
begin
Result := {inherited AllEqual;//}True;
end;
function TcxGridOptionsProperty.GetAttributes: TPropertyAttributes;
begin
Result := {inherited GetAttributes;//}[paMultiSelect, paSubProperties, paReadOnly, paVolatileSubProperties];
{Result := inherited GetAttributes - [paValueList, paSortList, paRevertable] +
[paReadOnly];}
end;
procedure TcxGridOptionsProperty.GetProperties(Proc: TGetPropProc);
var
I: Integer;
J: Integer;
Components: IDesignerSelections;
begin
inherited;
{Components := TDesignerSelections.Create;
for I := 0 to PropCount - 1 do
begin
J := GetOrdValueAt(I);
if J <> 0 then
Components.Add(TComponent(GetOrdValueAt(I)));
end;
if Components.Count > 0 then
GetComponentProperties(Components, tkAny, Designer, Proc);}
end;
function TcxGridOptionsProperty.GetValue: string;
begin
Result := '[Options]';
end;*)
{ TcxCustomGridTableItemPropertiesProperty }
type
TcxCustomGridTableItemPropertiesProperty = class(TClassProperty)
protected
function HasSubProperties: Boolean;
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
function TcxCustomGridTableItemPropertiesProperty.HasSubProperties: Boolean;
var
I: Integer;
begin
for I := 0 to PropCount - 1 do
begin
Result := TcxCustomGridTableItem(GetComponent(I)).Properties <> nil;
if not Result then Exit;
end;
Result := True;
end;
function TcxCustomGridTableItemPropertiesProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
if not HasSubProperties then
Exclude(Result, paSubProperties);
Result := Result - [paReadOnly] +
[paValueList, paSortList, paRevertable{$IFDEF DELPHI6}, paVolatileSubProperties{$ENDIF}];
end;
function TcxCustomGridTableItemPropertiesProperty.GetValue: string;
begin
if HasSubProperties then
Result := GetRegisteredEditProperties.GetDescriptionByClass(TcxCustomEditProperties(GetOrdValue).ClassType)
//Result := TcxCustomEditProperties(GetOrdValue).ClassName
else
Result := '';
end;
procedure TcxCustomGridTableItemPropertiesProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := 0 to GetRegisteredEditProperties.Count - 1 do
Proc(GetRegisteredEditProperties.Descriptions[I]);
end;
procedure TcxCustomGridTableItemPropertiesProperty.SetValue(const Value: string);
var
APropertiesClass: TcxCustomEditPropertiesClass;
I: Integer;
begin
APropertiesClass := TcxCustomEditPropertiesClass(GetRegisteredEditProperties.FindByClassName(Value));
if APropertiesClass = nil then
APropertiesClass := TcxCustomEditPropertiesClass(GetRegisteredEditProperties.FindByDescription(Value));
{$IFNDEF DELPHI7}
if GetValue <> Value then
ObjectInspectorCollapseProperty;
{$ENDIF}
for I := 0 to PropCount - 1 do
TcxCustomGridTableItem(GetComponent(I)).PropertiesClass := APropertiesClass;
Modified;
end;
{$IFNDEF NONDB}
type
TcxDBDataSummaryItemFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
function TcxDBDataSummaryItemFieldNameProperty.GetDataSource: TDataSource;
begin
Result := (GetComponent(0) as TcxDBDataSummaryItem).DataController.DataSource;
end;
type
TcxGridItemDBDataBindingAccess = class(TcxGridItemDBDataBinding);
TcxGridItemDBDataBindingFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
function TcxGridItemDBDataBindingFieldNameProperty.GetDataSource: TDataSource;
begin
Result := TcxGridItemDBDataBindingAccess(GetComponent(0) as TcxGridItemDBDataBinding).DataController.DataSource;
end;
type
TMasterKeyFieldNamesProperty = class(TFieldNameProperty)
function GetDataSource: TDataSource; override;
end;
function TMasterKeyFieldNamesProperty.GetDataSource: TDataSource;
var
AIDataController: IcxCustomGridDataController;
AParentLevel: TcxGridLevel;
begin
Result := nil;
(GetComponent(0) as TcxCustomDataController).GetInterface(IcxCustomGridDataController, AIDataController);
if AIDataController <> nil then
begin
AParentLevel := AIDataController.GridView.Level as TcxGridLevel;
if AParentLevel <> nil then
AParentLevel := AParentLevel.Parent;
if (AParentLevel <> nil) and (AParentLevel.GridView <> nil) and
(AParentLevel.GridView.DataController is TcxDBDataController) then
Result := (AParentLevel.GridView.DataController as TcxDBDataController).DataSource;
end;
end;
{$ENDIF}
{ TcxCustomGridTableItemProperty }
type
TcxCustomGridTableItemProperty = class(TComponentProperty)
protected
function GetGridView: TcxCustomGridView;
procedure GetGridViewItemNames(AGridView: TcxCustomGridView; Proc: TGetStrProc); virtual;
function InternalGetGridView(APersistent: TPersistent): TcxCustomGridView; virtual; abstract;
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TcxCustomGridTableItemProperty.GetValues(Proc: TGetStrProc);
var
AGridView: TcxCustomGridView;
begin
AGridView := GetGridView;
if AGridView <> nil then
GetGridViewItemNames(AGridView, Proc);
end;
function TcxCustomGridTableItemProperty.GetGridView: TcxCustomGridView;
var
I: Integer;
begin
Result := InternalGetGridView(GetComponent(0));
for I := 1 to PropCount - 1 do
if InternalGetGridView(GetComponent(I)) <> Result then
begin
Result := nil;
Break;
end;
end;
procedure TcxCustomGridTableItemProperty.GetGridViewItemNames(AGridView: TcxCustomGridView;
Proc: TGetStrProc);
var
I: Integer;
begin
if AGridView is TcxCustomGridTableView then
with AGridView as TcxCustomGridTableView do
for I := 0 to ItemCount - 1 do
Proc(Designer.GetComponentName(Items[I]));
end;
{ TcxGridPreviewColumnProperty }
type
TcxGridPreviewColumnProperty = class(TcxCustomGridTableItemProperty)
protected
function InternalGetGridView(APersistent: TPersistent): TcxCustomGridView; override;
end;
function TcxGridPreviewColumnProperty.InternalGetGridView(APersistent: TPersistent):
TcxCustomGridView;
begin
Result := TcxGridPreview(APersistent).GridView;
end;
{ TcxGridTableSummaryItemColumnProperty }
type
TcxGridTableSummaryItemColumnProperty = class(TcxCustomGridTableItemProperty)
protected
function InternalGetGridView(APersistent: TPersistent): TcxCustomGridView; override;
end;
function TcxGridTableSummaryItemColumnProperty.InternalGetGridView(APersistent: TPersistent):
TcxCustomGridView;
begin
Result :=(TcxCustomDataSummaryItemAccess(APersistent).GetDataController as
IcxCustomGridDataController).GridView;
end;
{$IFNDEF NONDB}
{ Ext Lookup }
type
TcxExtLookupComboBoxPropertiesFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
TcxExtLookupComboBoxPropertiesItemColumnProperty = class(TcxCustomGridTableItemProperty)
protected
function InternalGetGridView(APersistent: TPersistent): TcxCustomGridView; override;
end;
TcxExtLookupComboBoxPropertiesViewProperty = class(TComponentProperty)
private
FProc: TGetStrProc;
procedure CheckComponent(const Value: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
function TcxExtLookupComboBoxPropertiesFieldNameProperty.GetDataSource: TDataSource;
var
AProperties: TcxExtLookupComboBoxProperties;
begin
AProperties := GetComponent(0) as TcxExtLookupComboBoxProperties;
if AProperties.DataController <> nil then
Result := AProperties.DataController.DataSource
else
Result := nil;
end;
function TcxExtLookupComboBoxPropertiesItemColumnProperty.InternalGetGridView(APersistent: TPersistent): TcxCustomGridView;
var
AProperties: TcxExtLookupComboBoxProperties;
begin
AProperties := APersistent as TcxExtLookupComboBoxProperties;
Result := AProperties.View;
end;
procedure TcxExtLookupComboBoxPropertiesViewProperty.GetValues(Proc: TGetStrProc);
begin
FProc := Proc;
inherited GetValues(CheckComponent);
end;
procedure TcxExtLookupComboBoxPropertiesViewProperty.CheckComponent(const Value: string);
var
AView: TcxCustomGridTableView;
begin
AView := TcxCustomGridTableView(Designer.GetComponent(Value));
if (AView <> nil) and TcxExtLookupComboBoxProperties.IsViewSupported(AView) then
FProc(Value);
end;
{$ENDIF}
{$IFDEF DELPHI6}
type
TcxGridSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TcxGridLevelSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TcxCustomTableViewSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TcxCustomDBTableViewSelectionEditor = class(TcxCustomTableViewSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TcxCustomGridTableItemSelectionEditor = class(TSelectionEditor)
private
FProc: TGetStrProc;
procedure GetGridTableItem(const S: string);
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
procedure TcxGridSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
Proc(UnitNamePrefix + 'cxStyles');
end;
procedure TcxGridLevelSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
Proc(UnitNamePrefix + 'cxStyles');
end;
procedure TcxCustomTableViewSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
Proc(UnitNamePrefix + 'cxStyles');
Proc('cxCustomData');
Proc(UnitNamePrefix + 'cxGraphics');
Proc('cxFilter');
Proc('cxData');
Proc('cxDataStorage');
Proc(UnitNamePrefix + 'cxEdit');
end;
procedure TcxCustomDBTableViewSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
inherited RequiresUnits(Proc);
Proc('DB');
Proc('cxDBData');
end;
procedure TcxCustomGridTableItemSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
FProc := Proc;
Designer.GetComponentNames(GetTypeData(PTypeInfo(TcxCustomGridTableItem.ClassInfo)),
GetGridTableItem);
end;
procedure TcxCustomGridTableItemSelectionEditor.GetGridTableItem(const S: string);
var
AItem: TcxCustomGridTableItem;
begin
AItem := TcxCustomGridTableItem(Designer.GetComponent(S));
if AItem.Properties <> nil then
FProc({UnitNamePrefix + }GetTypeData(PTypeinfo(AItem.Properties.ClassType.ClassInfo)).UnitName);
end;
{$ENDIF}
procedure DesignerGridRegister;
begin
RegisterComponentEditor(TcxGrid, TGridEditor);
RegisterComponentEditor(TcxGridViewRepository, TGridViewRepositoryEditor);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomGrid, 'RootLevelStylesEvents',
TcxGridRootLevelStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomGridTableItem, 'PropertiesEvents',
TcxGridTableItemPropertiesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomGridTableItem, 'StylesEvents',
TcxGridTableItemStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomGridView, 'DataControllerEvents',
TcxGridDataControllerEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomGridView, 'StylesEvents',
TcxGridViewStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxGridLevel, 'StylesEvents',
TcxGridLevelStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxGridBand, 'StylesEvents',
TcxGridBandStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(string), TcxCustomGridTableItem, 'PropertiesClassName', nil);
RegisterPropertyEditor(TypeInfo(TcxCustomEditProperties), TcxCustomGridTableItem,
'Properties', TcxCustomGridTableItemPropertiesProperty);
RegisterPropertyEditor(TypeInfo(TAlignment), TcxGridBand, 'Alignment', nil);
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxGridPreview,
'Column', TcxGridPreviewColumnProperty);
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxGridTableSummaryItem,
'Column', TcxGridTableSummaryItemColumnProperty);
{$IFNDEF NONDB}
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxGridDBTableSummaryItem,
'Column', TcxGridTableSummaryItemColumnProperty);
// RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxGridDBBandedTableSummaryItem,
// 'Column', TcxGridTableSummaryItemColumnProperty);
{$ENDIF}
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxGridTableSummaryGroupItemLink,
'Column', TcxGridTableSummaryItemColumnProperty);
{$IFNDEF NONDB}
RegisterPropertyEditor(TypeInfo(string), TcxDBDataController, 'DetailKeyFieldNames', TFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBDataController, 'KeyFieldNames', TFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBDataController, 'MasterKeyFieldNames', TMasterKeyFieldNamesProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBDataSummaryItem, 'FieldName', TcxDBDataSummaryItemFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxGridItemDBDataBinding, 'FieldName', TcxGridItemDBDataBindingFieldNameProperty);
{$ENDIF}
RegisterNoIcon([TcxGridLevel,
TcxGridTableView, {$IFNDEF NONDB}TcxGridDBTableView,{$ENDIF}
TcxGridBandedTableView, {$IFNDEF NONDB}TcxGridDBBandedTableView,{$ENDIF}
TcxGridCardView{$IFNDEF NONDB}, TcxGridDBCardView{$ENDIF}]);
RegisterNoIcon([
TcxGridColumn, {$IFNDEF NONDB}TcxGridDBColumn,{$ENDIF}
TcxGridBandedColumn, {$IFNDEF NONDB}TcxGridDBBandedColumn,{$ENDIF}
TcxGridCardViewRow{$IFNDEF NONDB}, TcxGridDBCardViewRow{$ENDIF}]);
RegisterNoIcon([TcxGridTableViewStyleSheet, TcxGridBandedTableViewStyleSheet, TcxGridCardViewStyleSheet]);
RegisterComponents('Easy Grid', [TcxGrid, TcxGridViewRepository]);
// Ext Lookup
{$IFNDEF NONDB}
RegisterComponents('Easy Standard', [TcxExtLookupComboBox]);
RegisterComponents('Easy DB', [TcxDBExtLookupComboBox]);
RegisterEditRepositoryItem(TcxEditRepositoryExtLookupComboBoxItem, cxSEditRepositoryExtLookupComboBoxItem);
RegisterPropertyEditor(TypeInfo(string), TcxExtLookupComboBoxProperties, 'KeyFieldNames', TcxExtLookupComboBoxPropertiesFieldNameProperty);
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableItem), TcxExtLookupComboBoxProperties, 'ListFieldItem', TcxExtLookupComboBoxPropertiesItemColumnProperty);
RegisterPropertyEditor(TypeInfo(TcxCustomGridTableView), TcxExtLookupComboBoxProperties, 'View', TcxExtLookupComboBoxPropertiesViewProperty);
// TODO CLX
RegisterPropertyEditor(TypeInfo(TShortCut), TcxExtLookupComboBoxProperties, 'ClearKey', TShortCutProperty);
{$ENDIF}
{$IFDEF DELPHI6}
RegisterSelectionEditor(TcxCustomGrid, TcxGridSelectionEditor);
RegisterSelectionEditor(TcxGridLevel, TcxGridLevelSelectionEditor);
RegisterSelectionEditor(TcxCustomGridTableView, TcxCustomTableViewSelectionEditor);
{$IFNDEF NONDB}
RegisterSelectionEditor(TcxGridDBTableView, TcxCustomDBTableViewSelectionEditor);
RegisterSelectionEditor(TcxGridDBBandedTableView, TcxCustomDBTableViewSelectionEditor);
RegisterSelectionEditor(TcxGridDBCardView, TcxCustomDBTableViewSelectionEditor);
{$ENDIF}
RegisterSelectionEditor(TcxCustomGridTableItem, TcxCustomGridTableItemSelectionEditor);
{$ENDIF}
end;
initialization
{$IFDEF DELPHI6}
StartClassGroup(TControl);
GroupDescendentsWith(TcxGrid, TControl);
GroupDescendentsWith(TcxGridViewRepository, TControl);
GroupDescendentsWith(TcxGridLevel, TControl);
GroupDescendentsWith(TcxCustomGridView, TControl);
GroupDescendentsWith(TcxCustomGridTableItem, TControl);
GroupDescendentsWith(TcxGridItemDataBinding, TControl);
{$ENDIF}
RegisterStyleSheetClass(TcxGridTableViewStyleSheet);
RegisterStyleSheetClass(TcxGridBandedTableViewStyleSheet);
RegisterStyleSheetClass(TcxGridCardViewStyleSheet);
DesignerGridRegister;
finalization
UnregisterStyleSheetClass(TcxGridCardViewStyleSheet);
UnregisterStyleSheetClass(TcxGridBandedTableViewStyleSheet);
UnregisterStyleSheetClass(TcxGridTableViewStyleSheet);
end.
|
unit internetaccess_inflater_paszlib;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, internetaccess, ZBase, ZStream, ZInflate, bbutils;
type
PTransferBlockWriteEvent = ^TTransferBlockWriteEvent;
TTransferContentInflaterZlib = class(TTransferContentInflater)
stream: z_stream;
buffer: pointer;
headerRead: boolean;
writeUncompressedBlock: TTransferBlockWriteEvent;
pointerToBlockWrite: PTransferBlockWriteEvent;
expectGZIP: boolean;
headerBuffer: string;
procedure writeCompressedBlock(const abuffer; Count: NativeInt);
procedure endTransfer; override;
constructor Create;
destructor Destroy; override;
class procedure injectDecoder(var transfer: TTransfer; const encoding: string); override;
end;
implementation
const buffer_block_size=16384;
var DEBUG_DECOMPRESSION: boolean = false;
type THeader = (hExpectedHeader, hText, hInvalidHeader, hBufferTooSmall);
function getHeaderLength(expectGZip: boolean; p: PByte; length: cardinal; out headerLength: cardinal): THeader;
var
flags: Byte;
skipLength, xlen: cardinal;
begin
if expectGZip then begin
// RFC 1952
skipLength := 10;
if length < 10 then exit(hBufferTooSmall);
if (p[0] <> 31) or (p[1] <> 139) or (p[2] <> 8) then exit(hInvalidHeader); //two check bytes, 8 means deflate algorithm
result := hExpectedHeader;
flags := p[3];
if flags and 1 <> 0 then result := hText; //FTEXT, no compression, but has header
if (flags and 4 <> 0) and (length >= skipLength + 2) then begin //FEXTRA, more header
xlen := p[skipLength] + cardinal(256) * p[skipLength + 1];
if length >= skipLength + 2 + xlen then skipLength += xlen + 2
else exit(hBufferTooSmall);
end;
if flags and 8 <> 0 then begin //FNAME, zero-terminated
while (skipLength <= length) and (p[skipLength] <> 0) do inc(skipLength);
if skipLength <= length then inc(skipLength)
else exit(hBufferTooSmall);
end;
if flags and 16 <> 0 then begin //Fcomment, zero-terminated
while (skipLength <= length) and (p[skipLength] <> 0) do inc(skipLength);
if skipLength <= length then inc(skipLength)
else exit(hBufferTooSmall);
end;
if flags and 2 <> 0 then //FHCRC
inc(skipLength, 2);
end else begin
//RFC 1950
//however, the browser/Server implementation is wrong, so there usually are no header bytes (see https://stackoverflow.com/a/9856879/1501222 )
skipLength := 0;
headerLength := 0;
result := hExpectedHeader;
if length < 2 then exit(hBufferTooSmall);
if p[0] and 15 <> 8 then exit; //8 means deflate algorithm
if p[0] and not 15 > 7 then exit;
if (p[0] * 256 + p[1] ) mod 31 <> 0 then exit; //FLG check bits
skipLength := 2;
if p[1] and 32 <> 0 then skipLength += 4; //dictionary
end;
//writeln(result, skipLength);
if skipLength > length then exit(hBufferTooSmall);
headerLength := skipLength;
end;
procedure TTransferContentInflaterZlib.writeCompressedBlock(const abuffer; Count: NativeInt);
var err:smallint;
headerLength: cardinal;
header: THeader;
procedure raiseError;
var
s: String;
begin
s := zerror(err);
if stream.msg <> '' then s := s + ': ' + stream.msg;
s := s + LineEnding + 'Bytes in: ' + inttostr(stream.total_in) + ' Bytes out: ' + IntToStr(stream.total_out);
s := s + 'Last received: ' + strFromPchar(@abuffer, count).EncodeHex;
raise Edecompressionerror.create(s);
end;
procedure debug;
begin
writeln(strFromPchar(@abuffer, count).EncodeHex);
end;
begin
if DEBUG_DECOMPRESSION then debug;
stream.next_in:=@abuffer;
stream.avail_in:=count;
if not headerRead then begin
if headerBuffer <> '' then begin
headerBuffer := headerBuffer + strFromPchar(@abuffer, count);
stream.next_in:=pbyte(@headerBuffer[1]);
stream.avail_in:=length(headerBuffer);
end;
header := getHeaderLength(expectGZIP, stream.next_in, stream.avail_in, headerLength);
if header = hBufferTooSmall then begin
if stream.next_in=pbyte(@abuffer) then headerBuffer := headerBuffer + strFromPchar(@abuffer, count);
exit;
end;
headerRead := true;
// headerBuffer := ''; do not delete the buffer, it still needs to be read
if header in [hExpectedHeader, hText] then begin
inc(stream.next_in, headerLength);
dec(stream.avail_in, headerLength);
end;
if header in [hInvalidHeader, hText] then begin
writeUncompressedBlock(stream.next_in^, stream.avail_in);
pointerToBlockWrite^ := writeUncompressedBlock;
exit;
end;
end;
while stream.avail_in > 0 do begin
stream.next_out:=self.buffer;
stream.avail_out:= buffer_block_size;
err:=inflate(stream, Z_NO_FLUSH);
if (err<>Z_OK) and (err <> Z_STREAM_END) then
raiseError;
writeUncompressedBlock(self.buffer^, stream.next_out - self.buffer);
if err=Z_STREAM_END then
exit;
end;
end;
procedure TTransferContentInflaterZlib.endTransfer;
var
header: THeader;
tempBuffer: pchar;
headerLength: cardinal;
begin
if (not headerRead) and (headerBuffer <> '') then begin
header := getHeaderLength(expectGZIP, pbyte(@headerBuffer[1]), length(headerBuffer), headerLength);
if header in [hInvalidHeader, hBufferTooSmall] then headerLength := 0;
tempBuffer := @headerBuffer[1] + headerLength;
if header in [hInvalidHeader, hText] then
writeUncompressedBlock(tempBuffer^, length(headerBuffer) - headerLength)
else
writeCompressedBlock(tempBuffer^, length(headerBuffer) - headerLength);
headerBuffer := '';
end;
end;
constructor TTransferContentInflaterZlib.Create;
begin
getmem(buffer,buffer_block_size);
end;
destructor TTransferContentInflaterZlib.Destroy;
begin
Freemem(buffer);
inherited Destroy;
end;
class procedure TTransferContentInflaterZlib.injectDecoder(var transfer: TTransfer; const encoding: string);
var
zlibencoder: TTransferContentInflaterZlib;
encodingIsGZIP: boolean;
err: System.Integer;
begin
case encoding of
'gzip': encodingIsGZIP := true;
'deflate': encodingIsGZIP := false;
else exit;
end;
zlibencoder := TTransferContentInflaterZlib.Create;
zlibencoder.writeUncompressedBlock := transfer.writeBlockCallback;
zlibencoder.pointerToBlockWrite:=@transfer.writeBlockCallback;
zlibencoder.expectGZIP:=encodingIsGZIP;
{if Askipheader then
err:=inflateInit2(Fstream,-MAX_WBITS)
else
err:=inflateInit(Fstream);
}
//inflateInit(zlibencoder.stream);
err := inflateInit2(zlibencoder.stream, -MAX_WBITS);
if err <> Z_OK then
raise Edecompressionerror.Create('Failed to initialize decompression: ' + zerror(err));
transfer.writeBlockCallback := @zlibencoder.writeCompressedBlock;
transfer.inflater := zlibencoder;
DEBUG_DECOMPRESSION := GetEnvironmentVariable('XIDEL_DEBUG_DECOMPRESSION') = 'true';
if DEBUG_DECOMPRESSION then writeln(encodingIsGZIP, ' ', encoding);
end;
initialization
defaultTransferInflater := TTransferContentInflaterZlib;
end.
|
program Main;
var x, y : integer;
procedure PlusXAndY();
begin
x := x + 1;
y := y + 1;
end;
begin { Main }
writeln('enter an integer')
x := readint();
y := 2;
writeln('x+y',x+y)
end. { Main }
|
unit GMGenerics;
interface
uses Generics.Collections, SysUtils;
type
// Почему-то есть списки и массивы дженериков, но нет коллекций.
// Исправим досадное недоразумение
TGMCollection<T: class, constructor> = class(TList<T>)
protected
procedure Notify(const Value: T; Action: TCollectionNotification); override;
public
function Add(): T; virtual;
end;
TGMThreadSafeCollection<T: class, constructor> = class(TGMCollection<T>)
private
FLock: TMultiReadExclusiveWriteSynchronizer;
protected
property Lock: TMultiReadExclusiveWriteSynchronizer read FLock;
public
constructor Create();
destructor Destroy; override;
end;
implementation
{ TGMCollection<T> }
function TGMCollection<T>.Add: T;
begin
Result := T.Create();
inherited Add(Result);
end;
procedure TGMCollection<T>.Notify(const Value: T; Action: TCollectionNotification);
begin
inherited;
if Action = cnRemoved then
Value.DisposeOf;
end;
{ TGMThreadSafeCollection<T> }
constructor TGMThreadSafeCollection<T>.Create;
begin
inherited;
FLock := TMultiReadExclusiveWriteSynchronizer.Create();
end;
destructor TGMThreadSafeCollection<T>.Destroy;
begin
FLock.Free();
inherited;
end;
end.
|
Unit UnAtualizacao;
interface
Uses Classes, DbTables,SysUtils;
Type
TAtualiza = Class
Private
Aux : TQuery;
DataBase : TDataBase;
procedure AtualizaSenha( Senha : string );
procedure AlteraVersoesSistemas;
public
function AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
function AtualizaBanco : Boolean;
constructor criar( aowner : TComponent; ADataBase : TDataBase );
end;
Const
CT_SenhaAtual = '9774';
implementation
Uses FunSql, ConstMsg, FunNumeros, Registry, Constantes, FunString, funvalida, AAtualizaSistema;
{*************************** cria a classe ************************************}
constructor TAtualiza.criar( aowner : TComponent; ADataBase : TDataBase );
begin
inherited Create;
Aux := TQuery.Create(aowner);
DataBase := ADataBase;
Aux.DataBaseName := 'BaseDados';
end;
{*************** atualiza senha na base de dados ***************************** }
procedure TAtualiza.AtualizaSenha( Senha : string );
var
ini : TRegIniFile;
senhaInicial : string;
begin
try
if not DataBase.InTransaction then
DataBase.StartTransaction;
// atualiza regedit
Ini := TRegIniFile.Create('Software\Systec\Sistema');
senhaInicial := Ini.ReadString('SENHAS','BANCODADOS', ''); // guarda senha do banco
Ini.WriteString('SENHAS','BANCODADOS', Criptografa(senha)); // carrega senha do banco
// atualiza base de dados
LimpaSQLTabela(aux);
AdicionaSQLTabela(Aux, 'grant connect, to DBA identified by ''' + senha + '''');
Aux.ExecSQL;
if DataBase.InTransaction then
DataBase.commit;
ini.free;
except
if DataBase.InTransaction then
DataBase.Rollback;
Ini.WriteString('SENHAS','BANCODADOS', senhaInicial);
ini.free;
end;
end;
{*********************** atualiza o banco de dados ****************************}
function TAtualiza.AtualizaBanco : Boolean;
begin
result := true;
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from Cfg_Geral ');
if Aux.FieldByName('I_Ult_Alt').AsInteger < CT_VersaoBanco Then
result := AtualizaTabela(Aux.FieldByName('I_Ult_Alt').AsInteger);
AlteraVersoesSistemas;
end;
{**************************** atualiza a tabela *******************************}
function TAtualiza.AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
var
VpfErro : String;
begin
result := true;
repeat
Try
if VpaNumAtualizacao < 105 Then
begin
VpfErro := '105';
ExecutaComandoSql(Aux,'alter table cadformularios'
+' add C_MOD_TRX CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 105');
ExecutaComandoSql(Aux,'comment on column cadformularios.C_MOD_TRX is ''MODULO DE TRANSFERECIA''');
end;
if VpaNumAtualizacao < 106 Then
begin
VpfErro := '106';
ExecutaComandoSql(Aux,'alter table cadusuarios'
+' add C_MOD_REL char(1) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 106');
ExecutaComandoSql(Aux,'comment on column cadusuarios.c_mod_rel is ''PERMITE CONSULTAR O MODULO DE RELATORIOS''');
end;
if VpaNumAtualizacao < 107 Then
begin
VpfErro := '107';
ExecutaComandoSql(Aux,'alter table cadformularios'
+' add C_MOD_REL char(1) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 107');
ExecutaComandoSql(Aux,'comment on column cadformularios.c_mod_rel is ''cadastros de relatorios''');
end;
if VpaNumAtualizacao < 108 Then
begin
VpfErro := '108';
ExecutaComandoSql(Aux,'alter table cfg_geral'
+' add C_MOD_REL char(10) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 108');
ExecutaComandoSql(Aux,'comment on column CFG_GERAL.C_MOD_REL is ''VERSAO DO MODULO DE RALATORIO''');
end;
if VpaNumAtualizacao < 109 Then
begin
VpfErro := '109';
ExecutaComandoSql(Aux,' alter table cfg_geral'
+' ADD I_DIA_VAL integer NULL, '
+' ADD I_TIP_BAS integer NULL; '
+' update cfg_geral set i_tip_bas = 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 109');
ExecutaComandoSql(Aux,'comment on column cfg_geral.I_DIA_VAL is ''DIAS DE VALIDADE DA BASE DEMO''');
ExecutaComandoSql(Aux,'comment on column cfg_geral.I_TIP_BAS is ''TIPO DA BASE DEMO OU OFICIAL 0 OFICIAL 1 DEMO''');
end;
if VpaNumAtualizacao < 110 Then
begin
VpfErro := '110';
ExecutaComandoSql(Aux,'alter table cfg_financeiro'
+' add I_FRM_CAR INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 110');
ExecutaComandoSql(Aux,'comment on column cfg_financeiro.I_FRM_CAR is ''FORMA DE PAGAMENTO EM CARTEIRA''');
end;
if VpaNumAtualizacao < 111 Then
begin
VpfErro := '111';
ExecutaComandoSql(Aux,' create table MOVFORMAS'
+' ( I_EMP_FIL INTEGER NOT NULL, '
+' I_SEQ_MOV INTEGER NOT NULL, '
+' I_NRO_LOT INTEGER NULL, '
+' I_LAN_REC INTEGER NULL, '
+' I_LAN_APG INTEGER NULL, '
+' I_COD_FRM INTEGER NULL, '
+' C_NRO_CHE CHAR(20) NULL, '
+' N_VLR_MOV NUMERIC(17,3) NULL, '
+' C_NRO_CON CHAR(13) NULL, '
+' C_NRO_BOL CHAR(20) NULL, '
+' C_NOM_CHE CHAR(50) NULL, '
+' PRIMARY KEY(I_EMP_FIL, I_SEQ_MOV)) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 111');
ExecutaComandoSql(Aux,'comment on column movformas.I_EMP_FIL is ''CODIGO DA FILIAL''');
ExecutaComandoSql(Aux,'comment on column movformas.I_SEQ_MOV is ''SEQUENCIAL DO MOVIMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.I_NRO_LOT is ''NUMERO DO LOTE''');
ExecutaComandoSql(Aux,'comment on column movformas.I_LAN_REC is ''LANCAMENTO DO CONTAS A RECEBER''');
ExecutaComandoSql(Aux,'comment on column movformas.I_LAN_APG is ''LANCAMENTO DO CONTAS A PAGAR''');
ExecutaComandoSql(Aux,'comment on column movformas.I_COD_FRM is ''CODIGO DA FORMA DE PAGAMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_CHE is ''NUMERO DO CHEQUE''');
ExecutaComandoSql(Aux,'comment on column movformas.N_VLR_MOV is ''VALOR DO MOVIMENTO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_CON is ''NUMERO DA CONTA''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NRO_BOL is ''NUMERO DO BOLETO''');
ExecutaComandoSql(Aux,'comment on column movformas.C_NOM_CHE is ''NOMINAL DO CHEQUE''');
end;
if VpaNumAtualizacao < 112 Then
begin
VpfErro := '112';
ExecutaComandoSql(Aux,'create unique index MOVFORMAS_pk on'
+' MOVFORMAS(I_EMP_FIL, I_SEQ_MOV ASC) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 112');
end;
if VpaNumAtualizacao < 113 Then
begin
VpfErro := '113';
ExecutaComandoSql(Aux,'create table CADHISTORICOCLIENTE'
+' ( I_COD_HIS INTEGER NOT NULL, '
+' C_DES_HIS char(40) NULL, '
+' D_ULT_ALT DATE NULL, '
+' PRIMARY KEY(I_COD_HIS) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 113');
ExecutaComandoSql(Aux,'comment on table CADHISTORICOCLIENTE is ''TABELA DO HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column CADHISTORICOCLIENTE.I_COD_HIS is ''CODIGO HISTORICO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column CADHISTORICOCLIENTE.C_DES_HIS is ''DESCRICAO DO HISTORICO DO CLIENTE''');
end;
if VpaNumAtualizacao < 114 Then
begin
VpfErro := '114';
ExecutaComandoSql(Aux,'create table MOVHISTORICOCLIENTE'
+' ( I_SEQ_HIS INTEGER NOT NULL, '
+' I_COD_HIS INTEGER NULL, '
+' I_COD_CLI INTEGER NULL, '
+' I_COD_USU INTEGER NULL, '
+' D_DAT_HIS DATE NULL, '
+' L_HIS_CLI LONG VARCHAR NULL, '
+' D_DAT_AGE DATE NULL, '
+' L_HIS_AGE LONG VARCHAR NULL, '
+' D_ULT_ALT DATE NULL, '
+' PRIMARY KEY(I_SEQ_HIS) ) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 114');
ExecutaComandoSql(Aux,'comment on table MOVHISTORICOCLIENTE is ''TABELA DO HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_SEQ_HIS is ''SEQUENCIAL DO MOV HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_COD_HIS is ''CODIGO HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.I_COD_CLI is ''CODIGO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.D_DAT_HIS is ''DATA DO HISTORICO''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.L_HIS_CLI is ''HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.D_DAT_AGE is ''DATA DA AGENDA DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVHISTORICOCLIENTE.L_HIS_AGE is ''HISTORICO DA AGENDA''');
end;
if VpaNumAtualizacao < 115 Then
begin
VpfErro := '115';
ExecutaComandoSql(Aux,' alter table MOVHISTORICOCLIENTE '
+' add foreign key CADHISTORICOCLIENTE_FK(I_COD_HIS) '
+' references CADHISTORICOCLIENTE(I_COD_HIS) '
+' on update restrict on delete restrict ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 115');
end;
if VpaNumAtualizacao < 116 Then
begin
VpfErro := '116';
ExecutaComandoSql(Aux,' alter table MOVHISTORICOCLIENTE '
+' add foreign key CADCLIENTE_FK101(I_COD_CLI) '
+' references CADCLIENTES(I_COD_CLI) '
+' on update restrict on delete restrict ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 116');
end;
if VpaNumAtualizacao < 117 Then
begin
VpfErro := '117';
ExecutaComandoSql(Aux,'alter table cfg_geral'
+' add L_ATU_IGN long varchar null; '
+' update cfg_geral '
+' set L_ATU_IGN = null; ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 117');
ExecutaComandoSql(Aux,'comment on column cfg_geral.L_ATU_IGN is ''ATUALIZACOES IGNORADAS''');
end;
if VpaNumAtualizacao < 118 Then
begin
VpfErro := '118';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add H_HOR_AGE TIME NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 118');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_AGE is ''HORA AGENDADA''');
end;
if VpaNumAtualizacao < 119 Then
begin
VpfErro := '119';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add C_SIT_AGE char(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 119');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_AGE is ''HORA AGENDADA''');
end;
if VpaNumAtualizacao < 120 Then
begin
VpfErro := '120';
ExecutaComandoSql(Aux,' alter table movhistoricocliente '
+' add H_HOR_HIS TIME NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 120');
ExecutaComandoSql(Aux,'comment on column movhistoricocliente.H_HOR_HIS is ''HORA HISTORICO''');
end;
if VpaNumAtualizacao < 121 Then
begin
VpfErro := '121';
ExecutaComandoSql(Aux,' alter table movcontasareceber '
+' add N_VLR_CHE numeric(17,3) NULL, '
+' add C_CON_CHE char(15) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 121');
ExecutaComandoSql(Aux,'comment on column movcontasareceber.N_VLR_CHE is ''VALOR DO CHEQUE''');
ExecutaComandoSql(Aux,'comment on column movcontasareceber.C_CON_CHE is ''CONTA DO CHEQUE''');
end;
if VpaNumAtualizacao < 122 Then
begin
VpfErro := '122';
ExecutaComandoSql(Aux,'create table CADCODIGO'
+' ( I_EMP_FIL INTEGER NULL, '
+' I_LAN_REC INTEGER NULL, '
+' I_LAN_APG INTEGER NULL, '
+' I_LAN_EST INTEGER NULL, '
+' I_LAN_BAC INTEGER NULL, '
+' I_LAN_CON INTEGER NULL ) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 122');
end;
if VpaNumAtualizacao < 123 Then
begin
VpfErro := '123';
ExecutaComandoSql(Aux,'alter table cfg_modulo'
+' add FLA_MALACLIENTE CHAR(1) NULL, '
+' add FLA_AGENDACLIENTE CHAR(1) NULL, '
+' add FLA_PEDIDO CHAR(1) NULL, '
+' add FLA_ORDEMSERVICO CHAR(1) NULL ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 123');
end;
if VpaNumAtualizacao < 124 Then
begin
VpfErro := '124';
ExecutaComandoSql(Aux,'alter table cadorcamentos'
+' add I_NRO_PED integer NULL, '
+' add I_NRO_ORC integer NULL, '
+' add C_TIP_CAD char(1) NULL, '
+' add I_PRA_ENT integer NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 124');
end;
if VpaNumAtualizacao < 125 Then
begin
VpfErro := '125';
ExecutaComandoSql(Aux,
' update cadorcamentos ' +
' set i_nro_orc = i_lan_orc , ' +
' i_nro_ped = i_lan_orc ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 125');
end;
if VpaNumAtualizacao < 126 Then
begin
VpfErro := '126';
ExecutaComandoSql(Aux,
' create index FK_CADORCAMENTOS_5586 on '
+' CadOrcamentos( I_NRO_PED ASC ); '
+' create index FK_CADORCAMENTOS_5590 on '
+' CadOrcamentos( I_NRO_ORC ASC ); ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 126');
end;
if VpaNumAtualizacao < 127 Then
begin
VpfErro := '127';
ExecutaComandoSql(Aux,
' update cadorcamentos ' +
' set C_TIP_CAD = ''O'' ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 127');
end;
if VpaNumAtualizacao < 128 Then
begin
VpfErro := '128';
ExecutaComandoSql(Aux,
// Table: CADMARCAS
' create table CADMARCAS ' +
' ( ' +
' I_COD_MAR integer not null, ' +
' C_NOM_MAR char(50) not null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_MAR) ' +
' ); ' +
' comment on table CADMARCAS is ''CADMARCAS''; ' +
' comment on column CADMARCAS.I_COD_MAR is ''CODIGO DA MARCA''; ' +
' comment on column CADMARCAS.C_NOM_MAR is ''NOME DA MARCA''; ' +
' comment on column CADMARCAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
// Table: CADCOR
' create table CADCOR ' +
' ( ' +
' I_COD_COR integer not null, ' +
' C_NOM_COR char(30) not null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_COR) ' +
' ); ' +
' comment on table CADCOR is ''CADCOR''; ' +
' comment on column CADCOR.I_COD_COR is ''CODIGO DA COR''; ' +
' comment on column CADCOR.C_NOM_COR is ''NOME DA COR''; ' +
' comment on column CADCOR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
// Table: CADMODELO
' create table CADMODELO ' +
' ( ' +
' I_COD_MOD integer not null, ' +
' C_NOM_MOD char(50) null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_MOD) ' +
' ); ' +
' comment on table CADMODELO is ''MODELOS''; ' +
' comment on column CADMODELO.I_COD_MOD is ''CODIGO DO MODELO''; ' +
' comment on column CADMODELO.C_NOM_MOD is ''NOME DO MODELO''; ' +
' comment on column CADMODELO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
// Table: CADTIPO
' create table CADTIPO ' +
' ( ' +
' I_COD_TIP integer not null, ' +
' C_NOM_TIP char(30) not null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_TIP) ' +
' ); ' +
' comment on table CADTIPO is ''TIPOS DE EQUIPAMENTO OS''; ' +
' comment on column CADTIPO.I_COD_TIP is ''CODIGO DO TIPO''; ' +
' comment on column CADTIPO.C_NOM_TIP is ''NOME DO TIPO''; ' +
' comment on column CADTIPO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 128');
end;
if VpaNumAtualizacao < 129 Then
begin
VpfErro := '129';
aux.sql.clear;
aux.sql.add(
// ExecutaComandoSql(Aux,
// Table: CADORDEMSERVICO
' create table CADORDEMSERVICO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_COD_SIT integer null, ' +
' I_COD_CLI integer null, ' +
' I_SEQ_PRO integer null, ' +
' D_DAT_CAD date null, ' +
' D_DAT_AGE date null, ' +
' H_HOR_AGE time null, ' +
' C_CLI_PRO varchar(60) null, ' +
' C_OBS_EQU varchar(250) null, ' +
' N_TEM_GAS numeric(17,3) null, ' +
' N_VLR_HOR numeric(17,3) null, ' +
' I_COD_FRM integer null, ' +
' I_COD_PAG integer null, ' +
' D_DAT_FEC date null, ' +
' C_CLI_REC char(40) null, ' +
' D_DAT_EMP date null, ' +
' D_DAT_DEV date null, ' +
' primary key (I_EMP_FIL, I_COD_ORS) ' +
' ); ' +
' comment on table CADORDEMSERVICO is ''ORDEM DE SERVICO''; ' +
' comment on column CADORDEMSERVICO.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column CADORDEMSERVICO.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column CADORDEMSERVICO.I_COD_SIT is ''CODIGO DA SITUACAO''; ' +
' comment on column CADORDEMSERVICO.I_COD_CLI is ''CODIGO DO CLIENTE''; ' +
' comment on column CADORDEMSERVICO.I_SEQ_PRO is ''CODIGO DO PRODUTO, PARA EMPRESTIMO''; ' +
' comment on column CADORDEMSERVICO.D_DAT_CAD is ''DATA DE CADASTRO''; ' +
' comment on column CADORDEMSERVICO.D_DAT_AGE is ''DATA DE AGENDA PARA VISITA''; ' +
' comment on column CADORDEMSERVICO.H_HOR_AGE is ''HORA DE AGENDA PARA VISITA''; ' +
' comment on column CADORDEMSERVICO.C_CLI_PRO is ''ENDERECO DO CLIENTE PROXIMA A..''; ' +
' comment on column CADORDEMSERVICO.C_OBS_EQU is ''OBSERVACAO GERAL DO CAD''; ' +
' comment on column CADORDEMSERVICO.N_TEM_GAS is ''TEMPO GASTO PARA O OS''; ' +
' comment on column CADORDEMSERVICO.N_VLR_HOR is ''VALOR HORA''; ' +
' comment on column CADORDEMSERVICO.I_COD_FRM is ''CODIGO DA FORMA DE PAGAMENTO''; ' +
' comment on column CADORDEMSERVICO.I_COD_PAG is ''CODIGO DA CONDICAO DE PAGAMENTO''; ' +
' comment on column CADORDEMSERVICO.D_DAT_FEC is ''DATA DE FECHAMENTO DA OS, ENTREGA''; ' +
' comment on column CADORDEMSERVICO.C_CLI_REC is ''PESSOA QUE RECEBEU O EQUIPAMENTO''; ' +
' comment on column CADORDEMSERVICO.D_DAT_EMP is ''DATA DO EMPRESTIMO''; ' +
' comment on column CADORDEMSERVICO.D_DAT_DEV is ''DATA DA DEVOLUCAO''; ' );
aux.ExecSQL;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 129');
end;
if VpaNumAtualizacao < 130 Then
begin
VpfErro := '130';
ExecutaComandoSql(Aux,
// Table: MOVORDEMSERVICO
' create table MOVORDEMSERVICO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_SEQ_PRO integer null, ' +
' I_COD_EMP integer null, ' +
' I_COD_SER integer null, ' +
' I_COD_USU integer null, ' +
' N_QTD_MOV numeric(17,3) null, ' +
' N_VLR_UNI numeric(17,3) null, ' +
' N_VLR_TOT numeric(17,3) null, ' +
' C_COD_UNI char(2) null, ' +
' L_OBS_MOV long varchar null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV ) ' +
' ); ' +
' comment on table MOVORDEMSERVICO is ''ORDEM SERVICO''; ' +
' comment on column MOVORDEMSERVICO.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVORDEMSERVICO.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVORDEMSERVICO.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column MOVORDEMSERVICO.I_COD_EMP is ''COdigo do Empresa''; ' +
' comment on column MOVORDEMSERVICO.I_COD_SER is ''CODIGO DO SERVICO''; ' +
' comment on column MOVORDEMSERVICO.I_COD_USU is ''CODIGO DO USUARIO''; ' +
' comment on column MOVORDEMSERVICO.N_QTD_MOV is ''QUNTIDADE DE SERVICO OU PRODUTO''; ' +
' comment on column MOVORDEMSERVICO.N_VLR_UNI is ''VALOR UNITARIO DO SERVICO OU PRODUTO''; ' +
' comment on column MOVORDEMSERVICO.N_VLR_TOT is ''VALOR TOTAL DO SERVICO OU PRODUTO''; ' +
' comment on column MOVORDEMSERVICO.C_COD_UNI is ''UNIDADE DO SERVICO''; ' +
' comment on column MOVORDEMSERVICO.L_OBS_MOV is ''OBSERVACAO''; ' +
// Table: MOVTERCEIROOS
' create table MOVTERCEIROOS ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_CLI integer null, ' +
' D_DAT_COM date null, ' +
' I_NOT_COM integer null, ' +
' I_NOT_REM integer null, ' +
' I_NOT_FOR integer null, ' +
' D_DAT_REM date null, ' +
' D_DAT_RET date null, ' +
' N_VLR_SER numeric(17,3) null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV ) ' +
' ); ' +
' comment on table MOVTERCEIROOS is ''TERCEIROS DA OS''; ' +
' comment on column MOVTERCEIROOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVTERCEIROOS.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVTERCEIROOS.I_COD_CLI is ''CODIGO DO CLIENTE''; ' +
' comment on column MOVTERCEIROOS.D_DAT_COM is ''DATA DE COMPRA, CASO GARANTIA''; ' +
' comment on column MOVTERCEIROOS.I_NOT_COM is ''NRO DA NOTA DE COMPRA CASO GARANTIA''; ' +
' comment on column MOVTERCEIROOS.I_NOT_REM is ''NOTA DE REMESSA PARA CONSERTO''; ' +
' comment on column MOVTERCEIROOS.I_NOT_FOR is ''NOTA DE DEVOLUCAO DO FORNECEDOR''; ' +
' comment on column MOVTERCEIROOS.D_DAT_REM is ''DATA DA REMESSA PARA CONSERTO''; ' +
' comment on column MOVTERCEIROOS.D_DAT_RET is ''DATA DE RETORNO''; ' +
' comment on column MOVTERCEIROOS.N_VLR_SER is ''VALOR DO SERVICO''; ' +
// Table: CADEQUIPAMENTOS
' create table CADEQUIPAMENTOS ' +
' ( ' +
' I_COD_EQU integer not null, ' +
' C_NOM_EQU char(50) not null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_EQU) ' +
' ); ' +
' comment on table CADEQUIPAMENTOS is ''EQUIPAMENTOS''; ' +
' comment on column CADEQUIPAMENTOS.I_COD_EQU is ''CODIGO DA EQUIPAMENTO''; ' +
' comment on column CADEQUIPAMENTOS.C_NOM_EQU is ''NOME DO EQUIPAMENTO''; ' +
' comment on column CADEQUIPAMENTOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 130');
end;
if VpaNumAtualizacao < 131 Then
begin
VpfErro := '131';
ExecutaComandoSql(Aux,
' alter table CADORDEMSERVICO ' +
' add foreign key FK_CADORDEM_REF_13281_CADSITUA (I_COD_SIT) ' +
' references CADSITUACOES (I_COD_SIT) on update restrict on delete restrict; ' +
' alter table CADORDEMSERVICO ' +
' add foreign key FK_CADORDEM_REF_13282_CADCLIEN (I_COD_CLI) ' +
' references CADCLIENTES (I_COD_CLI) on update restrict on delete restrict; ' +
' alter table CADORDEMSERVICO ' +
' add foreign key FK_CADORDEM_REF_13283_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table MOVORDEMSERVICO ' +
' add foreign key FK_MOVORDEM_REF_77_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' +
' alter table MOVORDEMSERVICO ' +
' add foreign key FK_MOVORDEM_REF_13284_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table MOVORDEMSERVICO ' +
' add foreign key FK_MOVORDEM_REF_13284_CADSERVI (I_COD_EMP, I_COD_SER) ' +
' references CADSERVICO (I_COD_EMP, I_COD_SER) on update restrict on delete restrict; ' +
' alter table MOVTERCEIROOS ' +
' add foreign key FK_MOVTERCE_REF_84_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 131');
end;
if VpaNumAtualizacao < 132 Then
begin
VpfErro := '132';
ExecutaComandoSql(Aux,
' create unique index CADMARCAS_PK on CADMARCAS (I_COD_MAR asc); ' +
' create unique index CADCOR_PK on CADCOR (I_COD_COR asc); ' +
' create unique index CADMODELO_PK on CADMODELO (I_COD_MOD asc); ' +
' create unique index CADTIPO_PK on CADTIPO (I_COD_TIP asc); ' +
' create unique index CADORDEMSERVICO_PK on CADORDEMSERVICO (I_EMP_FIL asc, I_COD_ORS asc); ' +
' create unique index MOVORDEMSERVICO_PK on MOVORDEMSERVICO (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' +
' create unique index MOVTERCEIROOS_PK on MOVTERCEIROOS (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' +
' create index Ref_132816_FK on CADORDEMSERVICO (I_COD_SIT asc); ' +
' create index Ref_132820_FK on CADORDEMSERVICO (I_COD_CLI asc); ' +
' create index Ref_132835_FK on CADORDEMSERVICO (I_SEQ_PRO asc); ' +
' create index Ref_77_FK on MOVORDEMSERVICO (I_EMP_FIL asc, I_COD_ORS asc); ' +
' create index Ref_132840_FK on MOVORDEMSERVICO (I_SEQ_PRO asc); ' +
' create index Ref_132844_FK on MOVORDEMSERVICO (I_COD_EMP asc, I_COD_SER asc); ' +
' create index Ref_84_FK on MOVTERCEIROOS (I_EMP_FIL asc, I_COD_ORS asc); ' +
' create unique index CADEQUIPAMENTOS_PK on CADEQUIPAMENTOS (I_COD_EQU asc); ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 132');
end;
if VpaNumAtualizacao < 133 Then
begin
VpfErro := '133';
ExecutaComandoSql(Aux,' alter table cfg_geral'
+' add c_mos_dec as char(1) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 133');
end;
if VpaNumAtualizacao < 134 Then
begin
VpfErro := '134';
ExecutaComandoSql(Aux,' alter table MovOrcamentos'
+' add N_DES_PRO numeric(17,3) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 134');
end;
if VpaNumAtualizacao < 135 Then
begin
VpfErro := '135';
ExecutaComandoSql(Aux,' ALTER TABLE MOVORCAMENTOS '
+' MODIFY n_vlr_pro NUMERIC(18,5); '
+' ALTER TABLE MOVNOTASFISCAIS '
+' MODIFY n_vlr_pro NUMERIC(18,5); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 135');
end;
if VpaNumAtualizacao < 136 Then
begin
VpfErro := '136';
ExecutaComandoSql(Aux,' alter table CadOrcamentos'
+' add N_VLR_PER numeric(17,3) null, '
+' add C_DES_ACR CHAR(1) null, '
+' add C_VLR_PER CHAR(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 136');
end;
if VpaNumAtualizacao < 137 Then
begin
VpfErro := '137';
ExecutaComandoSql(Aux,' alter table CadOrdemServico'
+' add C_COD_PRO char(20) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 137');
end;
if VpaNumAtualizacao < 138 Then
begin
VpfErro := '138';
ExecutaComandoSql(Aux,' alter table MovOrdemServico '
+' add C_COD_PRO char(20) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 138');
end;
if VpaNumAtualizacao < 139 Then
begin
VpfErro := '139';
ExecutaComandoSql(Aux,' ALTER TABLE cadOrdemServico '
+' add D_ULT_ALT date null; '
+' ALTER TABLE MovOrdemServico '
+' add D_ULT_ALT date null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 139');
end;
if VpaNumAtualizacao < 140 Then
begin
VpfErro := '140';
ExecutaComandoSql(Aux,' ALTER TABLE MovOrdemServico '
+' drop L_OBS_MOV ; '
+' ALTER TABLE CadOrdemServico '
+' add L_OBS_MOV long varchar null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 140');
end;
if VpaNumAtualizacao < 141 Then
begin
VpfErro := '141';
ExecutaComandoSql(Aux,' ALTER TABLE CadContasaReceber '
+' add I_COD_VEN integer null ; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 141');
end;
if VpaNumAtualizacao < 142 Then
begin
VpfErro := '142';
ExecutaComandoSql(Aux,' ALTER TABLE CadOrdemServico '
+' add C_SIT_ORS char(1) null ; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 142');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.C_SIT_ORS is ''SITUACAO DA ORDEM DE SERVICO''');
end;
if VpaNumAtualizacao < 143 Then
begin
VpfErro := '143';
ExecutaComandoSql(Aux,' ALTER TABLE CadOrdemServico '
+' add N_TOT_PRO numeric(17,3) null, '
+' add N_TOT_SER numeric(17,3) null, '
+' add N_TOT_TER numeric(17,3) null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 143');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.N_TOT_PRO is ''TOTAL DOS PRODUTOS''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.N_TOT_SER is ''TOTAL DOS SERVICO''');
end;
if VpaNumAtualizacao < 144 Then
begin
VpfErro := '144';
ExecutaComandoSql(Aux,' alter table CadOrdemServico'
+' add N_VLR_PER numeric(17,3) null, '
+' add C_DES_ACR CHAR(1) null, '
+' add C_VLR_PER CHAR(1) null, '
+' add N_TOT_ORS numeric(17,3) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 144');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.N_VLR_PER is ''DESCONTO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.C_DES_ACR is ''DESCONTO OU ACRESCIMO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.C_VLR_PER is ''VALOR OU PERCENTUAL''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.N_TOT_ORS is ''VALOR TOTAL DA ORDEM DE SERVICO''');
end;
if VpaNumAtualizacao < 145 Then
begin
VpfErro := '145';
ExecutaComandoSql(Aux,' alter table CadOrdemServico'
+' add N_TOT_HOR numeric(17,3) null, '
+' add L_OBS_TER LONG VARCHAR null; '
+' alter table MovTerceiroOS '
+' add N_VLR_COB numeric(17,3) null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 145');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.N_TOT_HOR is ''TOTAL DE HORAS TRABALHADA''');
ExecutaComandoSql(Aux,'comment on column MovTerceiroOS.N_VLR_COB is ''VALOR DA COBRANCA''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.L_OBS_TER is ''OBSERVACAO DO TERCEIRO''');
end;
if VpaNumAtualizacao < 146 Then
begin
VpfErro := '146';
ExecutaComandoSql(Aux,'create table CFG_SERVICOS '
+' ( C_USA_TER char(1) NULL, '
+' I_QTD_ORS integer null ); ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 146');
ExecutaComandoSql(Aux,'comment on column CFG_SERVICOS.C_USA_TER is ''USAR TERCEIRO NA OS''');
ExecutaComandoSql(Aux,'comment on column CFG_SERVICOS.I_QTD_ORS is ''QUANTIDADE DE ITEMS, EQUI, TIPO, MODELO ETC''');
end;
if VpaNumAtualizacao < 147 Then
begin
VpfErro := '147';
aux.sql.clear;
aux.sql.add(
// ExecutaComandoSql(Aux,
// Table: CADORDEMSERVICO
' create table MOVEQUIPAMENTOOS ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_EQU integer null, ' +
' I_COD_MAR integer null, ' +
' I_COD_MOD integer null, ' +
' I_COD_COR integer null, ' +
' I_COD_TIP integer null, ' +
' C_ACE_EQU varchar(100) null, ' +
' C_GAR_EQU char(1) null, ' +
' C_ORC_EQU char(1) null, ' +
' C_NRO_NOT char(40) null, ' +
' C_DEF_APR varchar(250) null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV) ' +
' ); ' +
' comment on table MOVEQUIPAMENTOOS is ''EQUIPAMENTOS DA ORDEM DE SERVICO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_EQU is ''CODIGO DA EQUIPAMENTO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_MAR is ''CODIGO DA MARCA''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_MOD is ''CODIGO DO MODELO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_COR is ''CODIGO DA COR''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_TIP is ''CODIGO DO TIPO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_ACE_EQU is ''ACESSORIOS DO EQUIPAMENTO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_GAR_EQU is ''POSSUI GARANTIA S/N''; ' +
' comment on column MOVEQUIPAMENTOOS.C_ORC_EQU is ''FAZER ORCAMENTO S/N''; ' +
' comment on column MOVEQUIPAMENTOOS.C_DEF_APR is ''DEFEITO APRESENTADO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_NRO_NOT is ''NUMERO DA NOTA CASO GARANTIA''; ' );
aux.ExecSQL;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 147');
end;
if VpaNumAtualizacao < 148 Then
begin
VpfErro := '148';
ExecutaComandoSql(Aux,
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_73A_CADTIPO (I_COD_TIP) ' +
' references CADTIPO (I_COD_TIP) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_69A_CADCOR (I_COD_COR) ' +
' references CADCOR (I_COD_COR) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_65A_CADMODEL (I_COD_MOD) ' +
' references CADMODELO (I_COD_MOD) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_61A_CADMARCA (I_COD_MAR) ' +
' references CADMARCAS (I_COD_MAR) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_13281A_CADEQUIP (I_COD_EQU) ' +
' references CADEQUIPAMENTOS (I_COD_EQU) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_MOVORDEM_REF_77A_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' +
' create index Ref_73A_FK on MOVEQUIPAMENTOOS (I_COD_TIP asc); ' +
' create index Ref_69A_FK on MOVEQUIPAMENTOOS (I_COD_COR asc); ' +
' create index Ref_65A_FK on MOVEQUIPAMENTOOS (I_COD_MOD asc); ' +
' create index Ref_61A_FK on MOVEQUIPAMENTOOS (I_COD_MAR asc); ' +
' create index Ref_132813A_FK on MOVEQUIPAMENTOOS (I_COD_EQU asc); ' +
' create unique index MOVEQUIPAMENTOOS_PK on MOVEQUIPAMENTOOS (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 148');
end;
if VpaNumAtualizacao < 149 Then
begin
VpfErro := '149';
ExecutaComandoSql(Aux,' ALTER TABLE MovEquipamentoOS '
+' add D_ULT_ALT date null; '
+' ALTER TABLE MovTerceiroOS '
+' add D_ULT_ALT date null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 149');
end;
if VpaNumAtualizacao < 150 Then
begin
VpfErro := '150';
ExecutaComandoSql(Aux,' ALTER TABLE MovEquipamentoOS '
+' add N_QTD_EQU numeric(17,3) null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 150');
end;
if VpaNumAtualizacao < 151 Then
begin
VpfErro := '151';
aux.sql.clear;
aux.sql.add(
' create table MOVESTOUROOS ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_EQU integer null, ' +
' I_COD_MAR integer null, ' +
' I_COD_MOD integer null, ' +
' I_COD_COR integer null, ' +
' I_COD_TIP integer null, ' +
' I_SEQ_PRO integer null, ' +
' I_COD_EMP integer null, ' +
' I_COD_SER integer null, ' +
' N_QTD_MOV numeric(17,3) null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_EMP_FIL, I_SEQ_MOV) ' +
' ); ' +
' comment on table MOVESTOUROOS is ''ESTOURO DA ORDEM DE SERVICO''; ' +
' comment on column MOVESTOUROOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVESTOUROOS.I_COD_EQU is ''CODIGO DA EQUIPAMENTO''; ' +
' comment on column MOVESTOUROOS.I_COD_MAR is ''CODIGO DA MARCA''; ' +
' comment on column MOVESTOUROOS.I_COD_MOD is ''CODIGO DO MODELO''; ' +
' comment on column MOVESTOUROOS.I_COD_COR is ''CODIGO DA COR''; ' +
' comment on column MOVESTOUROOS.I_COD_TIP is ''CODIGO DO TIPO''; ' +
' comment on column MOVESTOUROOS.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column MOVESTOUROOS.I_COD_EMP is ''COdigo do Empresa''; ' +
' comment on column MOVESTOUROOS.I_COD_SER is ''CODIGO DO SERVICO''; ' +
' comment on column MOVESTOUROOS.N_QTD_MOV is ''QUANTIDADE DE SERVICO OU PRODUTO''; ' +
' comment on column MOVESTOUROOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_13281_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_13281_CADSERVI (I_COD_EMP, I_COD_SER) ' +
' references CADSERVICO (I_COD_EMP, I_COD_SER) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_731_CADTIPO (I_COD_TIP) ' +
' references CADTIPO (I_COD_TIP) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_691_CADCOR (I_COD_COR) ' +
' references CADCOR (I_COD_COR) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_651_CADMODEL (I_COD_MOD) ' +
' references CADMODELO (I_COD_MOD) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_611_CADMARCA (I_COD_MAR) ' +
' references CADMARCAS (I_COD_MAR) on update restrict on delete restrict; ' +
' alter table MOVESTOUROOS ' +
' add foreign key FK_MOVEST_REF_13282_CADEQUIP (I_COD_EQU) ' +
' references CADEQUIPAMENTOS (I_COD_EQU) on update restrict on delete restrict; ' +
' create index Ref_7311_FK on MOVESTOUROOS (I_COD_TIP asc); ' +
' create index Ref_6111_FK on MOVESTOUROOS (I_COD_COR asc); ' +
' create index Ref_6522_FK on MOVESTOUROOS (I_COD_MOD asc); ' +
' create index Ref_6567_FK on MOVESTOUROOS (I_COD_MAR asc); ' +
' create index Ref_1321T_FK on MOVESTOUROOS (I_COD_EQU asc); ' +
' create unique index MOVEESTOUROOS_PK on MOVESTOUROOS (I_EMP_FIL asc, I_SEQ_MOV asc); ' );
aux.ExecSQL;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 151');
end;
if VpaNumAtualizacao < 152 Then
begin
VpfErro := '152';
ExecutaComandoSql(Aux,' ALTER TABLE MovEstouroOS '
+' add C_COD_PRO char(20) null, '
+' add C_COD_UNI char(2) null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 152');
end;
if VpaNumAtualizacao < 153 Then
begin
VpfErro := '153';
ExecutaComandoSql(Aux,' alter table CadOrdemServico'
+' add I_COD_USU integer null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 153');
ExecutaComandoSql(Aux,' comment on column CadOrdemServico.I_COD_USU is ''CODIGO USUARIO''; ' );
end;
if VpaNumAtualizacao < 154 Then
begin
VpfErro := '154';
ExecutaComandoSql(Aux,' alter table CadOrdemServico'
+' add C_OBS_ABE Varchar(200) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 154');
ExecutaComandoSql(Aux,' comment on column CadOrdemServico.c_obs_abe is ''OBSERVACAO DA ABERTURA''; ' );
end;
if VpaNumAtualizacao < 155 Then
begin
VpfErro := '155';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+' add L_TEX_ORS Long Varchar null, '
+' add I_TIP_REL integer null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 155');
ExecutaComandoSql(Aux,' comment on column CadOrdemServico.c_obs_abe is ''OBSERVACAO DA ABERTURA''; ' );
end;
if VpaNumAtualizacao < 156 Then
begin
VpfErro := '156';
ExecutaComandoSql(Aux,' alter table CFG_PRODUTO '
+' add C_PRO_NUM CHAR(1) null; '
+' update CFG_PRODUTO set c_pro_num = ''F''');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 156');
ExecutaComandoSql(Aux,' comment on column CFG_PRODUTO.C_PRO_NUM is ''NAO PERMITE USAR CARACTER NO CODIGO DO PRODUTO''; ' );
end;
if VpaNumAtualizacao < 157 Then
begin
VpfErro := '157';
ExecutaComandoSql(Aux,'create table CADTIPOENTREGA'
+' ( I_COD_ENT INTEGER NOT NULL, '
+' C_DES_ENT char(40) NULL, '
+' PRIMARY KEY(I_COD_ENT))');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 157');
ExecutaComandoSql(Aux,'comment on table CADTIPOENTREGA is ''TIPOS DE ENTREGA''');
ExecutaComandoSql(Aux,'comment on column CADTIPOENTREGA.I_COD_ENT is ''CODIGO DA ENTREGA''');
ExecutaComandoSql(Aux,'comment on column CADTIPOENTREGA.C_DES_ENT is ''DESCRICAO DA ENTREGA''');
end;
if VpaNumAtualizacao < 158 Then
begin
VpfErro := '158';
ExecutaComandoSql(Aux,'create unique index CADTIPOENTREGA_pk on'
+' CADTIPOENTREGA(I_COD_ENT ASC) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 158');
end;
if VpaNumAtualizacao < 159 Then
begin
VpfErro := '159';
ExecutaComandoSql(Aux,' alter table CadOrdemServico '
+' add I_COD_ENT integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 159');
ExecutaComandoSql(Aux,' comment on column CadOrdemServico.I_COD_ENT is ''TIPO DE ENTREGA''; ' );
end;
if VpaNumAtualizacao < 160 Then
begin
VpfErro := '160';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add foreign key FK_CADTIPO_REF_699_CADENTREGA(I_COD_ENT) ' +
' references CADTIPOENTREGA(I_COD_ENT) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 159');
end;
if VpaNumAtualizacao < 161 Then
begin
VpfErro := '161';
ExecutaComandoSql(Aux,' create unique index CADOrdemServico_FK_CADTIPO_857 on'
+' CADORDEMSERVICO(I_COD_ENT ASC) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 161');
end;
if VpaNumAtualizacao < 162 Then
begin
VpfErro := '162';
ExecutaComandoSql(Aux,' alter table movterceiroos '
+' add C_DES_PRO char(100) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 162');
ExecutaComandoSql(Aux,' comment on column movterceiroos.C_DES_PRO is ''DESCRICAO DO PRODUTO ENVIADO AO TERCEIRO''; ' );
end;
if VpaNumAtualizacao < 163 Then
begin
VpfErro := '163';
ExecutaComandoSql(Aux,' alter table CADICMSECF '
+' add C_TIP_CAD char(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 163');
ExecutaComandoSql(Aux,' comment on column CADICMSECF.C_TIP_CAD is ''TIPO DE CADASTRO SERVICO OU PRODUTO S/P''; ' );
end;
if VpaNumAtualizacao < 164 Then
begin
VpfErro := '164';
ExecutaComandoSql(Aux,' alter table movserviconota '
+' add N_ALI_SER numeric(8,3) null, '
+' add I_NUM_ITE integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 164');
ExecutaComandoSql(Aux,' comment on column movserviconota.n_ali_ser is ''ALICOTA DO SERVICO''; ' );
ExecutaComandoSql(Aux,' comment on column movserviconota.i_num_ite is ''NUMERO DO ITEM''; ' );
end;
if VpaNumAtualizacao < 165 Then
begin
VpfErro := '165';
ExecutaComandoSql(Aux,' alter table CADCODIGO '
+' add I_COD_PRO INTEGER NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 165');
end;
if VpaNumAtualizacao < 166 Then
begin
VpfErro := '166';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_CST_NOT char(2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 166');
end;
if VpaNumAtualizacao < 167 Then
begin
VpfErro := '167';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_GER_NRO char(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 167');
end;
if VpaNumAtualizacao < 168 Then
begin
VpfErro := '168';
ExecutaComandoSql(Aux,' alter table cfg_servicos '
+' add I_REL_PED integer NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 168');
end;
if VpaNumAtualizacao < 169 Then
begin
VpfErro := '169';
ExecutaComandoSql(Aux,' alter table movnatureza '
+' add C_MOS_FAT char(1) NULL; '
+' Update movnatureza set c_mos_fat = ''S'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 169');
end;
if VpaNumAtualizacao < 170 Then
begin
VpfErro := '170';
ExecutaComandoSql(Aux,' alter table CFG_PRODUTO '
+' add C_ADI_FIL char(1) NULL; '
+' Update CFG_PRODUTO set C_ADI_FIL = ''T'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 170');
end;
if VpaNumAtualizacao < 171 Then
begin
VpfErro := '171';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+' add C_INA_CLI char(1) NULL, '
+' add C_MOS_DES char(1) NULL, '
+' add N_PER_DES numeric(8,3) null; '
+' Update CFG_SERVICOS set C_INA_CLI = ''F'' ');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 171');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.c_ina_cli is ''CALCULA A INADINPLENCIA DO CLIENTE NO CADASTRO DE UM NOVO PEDIDO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.c_mos_des is ''MOSTRA DESCONTO REFERENTE A ULTIMA COMPRA''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.n_per_des is ''PERCENTUAL DE DESCONTO REFERENTE A ULTIMA COMPRA''; ' );
end;
if VpaNumAtualizacao < 172 Then
begin
VpfErro := '172';
ExecutaComandoSql(Aux,' alter table CADSERVICO '
+ ' add N_PER_COM numeric(17,3) NULL ');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 172');
ExecutaComandoSql(Aux,' comment on column CADSERVICO.N_PER_COM is ''PERCENTUAL DE COMISSAO''; ' );
end;
if VpaNumAtualizacao < 173 Then
begin
VpfErro := '173';
ExecutaComandoSql(Aux,' create table MOVCLIENTEVENDEDOR '
+' ( I_COD_VEN INTEGER NOT NULL, '
+' I_COD_CLI INTEGER NOT NULL, '
+' PRIMARY KEY(I_COD_VEN,I_COD_CLI)) ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 173');
ExecutaComandoSql(Aux,'comment on table MOVCLIENTEVENDEDOR is ''CLIENTES POR VENDEDOR''');
ExecutaComandoSql(Aux,'comment on column MOVCLIENTEVENDEDOR.I_COD_VEN is ''CODIGO DO VENDEDOR''');
ExecutaComandoSql(Aux,'comment on column MOVCLIENTEVENDEDOR.I_COD_CLI is ''CODIGO DO CLIENTE''');
end;
if VpaNumAtualizacao < 174 Then
begin
VpfErro := '174';
ExecutaComandoSql(Aux,' alter table cfg_financeiro '
+ ' add C_OPE_HOM CHAR(3) NULL ');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 174');
ExecutaComandoSql(Aux,' comment on column cfg_financeiro.C_OPE_HOM is ''OPERACAO BANCARIA HOME BANKING ''; ' );
end;
if VpaNumAtualizacao < 175 Then
begin
VpfErro := '175';
ExecutaComandoSql(Aux,' alter table cadclientes '
+ ' add N_DES_VEN numeric(8,3) NULL ');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 175');
ExecutaComandoSql(Aux,' comment on column cadclientes.N_DES_VEN is ''DESCONTO NA VENDA''; ' );
end;
if VpaNumAtualizacao < 176 Then
begin
VpfErro := '176';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+ ' add C_CAB_ORC char(1) NULL, ' +
' add I_ALT_CAB integer NULL, ' +
' add I_ALT_ROD integer NULL ');
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 176');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.C_CAB_ORC is ''MOSTRXA CABECALHO DA IMPRESSAO DE ORCAMENTO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.I_ALT_CAB is ''ALTURA DO CABECALHO DA IMPRESSAO DE ORCAMENTO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.I_ALT_ROD is ''ALTURA DO RODAPE DA IMPRESSAO DE ORCAMENTO''; ' );
end;
if VpaNumAtualizacao < 177 Then
begin
VpfErro := '177';
ExecutaComandoSql(Aux,'alter table movnatureza'
+' add C_DES_NOT char(40) null ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 177');
ExecutaComandoSql(Aux,' UPDATE MOVNATUREZA NAT ' +
' SET C_DES_NOT = (SELECT MAX(C_NOM_NAT) ' +
' FROM CADNATUREZA NAT1 WHERE NAT.C_COD_NAT = NAT1.C_COD_NAT) ');
ExecutaComandoSql(Aux,'comment on column movnatureza.c_des_not is ''CAMPO DE DESCRICAO DA NOTA''');
end;
if VpaNumAtualizacao < 178 Then
begin
VpfErro := '178';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+ ' add L_TEX_ORC LONG VARCHAR NULL, ' +
' add C_DES_PED char(1) NULL, ' +
' add C_DES_ORC char(1) NULL ' );
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 178');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.L_TEX_ORC is ''TEXTO A SER IMPRESSO NA IMPRESSAO DE ORCAMENTO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.C_DES_PED is ''MOSTRAR DESCONTO PARA ITENS DE PEDIDO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.C_DES_ORC is ''MOSTRAR DESCONTO PARA ITENS DE ORCAMENTO''; ' );
end;
if VpaNumAtualizacao < 179 Then
begin
VpfErro := '179';
ExecutaComandoSql(Aux,' alter table CFG_PRODUTO '
+' add C_MAS_SER CHAR(1) null; '
+' update CFG_PRODUTO set C_MAS_SER = ''T''');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 179');
ExecutaComandoSql(Aux,' comment on column CFG_PRODUTO.C_MAS_SER is ''UTILIZAR A MASCARA DE EMPRESA FILIAL PARA GERAR O CODIGO''; ' );
end;
if VpaNumAtualizacao < 180 Then
begin
VpfErro := '180';
ExecutaComandoSql(Aux,' alter table CADCLIENTES '
+' add C_END_COB CHAR(50) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 180');
ExecutaComandoSql(Aux,' comment on column CADCLIENTES.C_END_COB is ''ENDERECO PARA COBRANCA''; ' );
end;
if VpaNumAtualizacao < 181 Then
begin
VpfErro := '181';
ExecutaComandoSql(Aux,' alter table CADNOTAFISCAIS '
+' add C_NRO_PED CHAR(20) null');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 181');
ExecutaComandoSql(Aux,' comment on column CADNOTAFISCAIS.c_nro_ped is ''NRO DO PEDIDO''; ' );
end;
if VpaNumAtualizacao < 182 Then
begin
VpfErro := '182';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+ ' add L_TEX_PED LONG VARCHAR NULL ' );
ExecutaComandoSql(Aux,' Update CFG_GERAL set I_Ult_Alt = 182');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.L_TEX_PED is ''TEXTO A SER IMPRESSO NA IMPRESSAO NO PEDIDO''; ' );
end;
if VpaNumAtualizacao < 183 Then
begin
VpfErro := '183';
ExecutaComandoSql(Aux,' alter table CADNOTAFISCAIS '
+' add C_NRO_ORC CHAR(20) null');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 183');
ExecutaComandoSql(Aux,' comment on column CADNOTAFISCAIS.c_nro_orc is ''NRO DO ORCAMENTO''; ' );
end;
if VpaNumAtualizacao < 184 Then
begin
VpfErro := '184';
ExecutaComandoSql(Aux,'alter table CADORCAMENTOS'
+' ADD I_QTD_IMP integer NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 184');
ExecutaComandoSql(Aux,'comment on column CADORCAMENTOS.I_QTD_IMP is ''QUANTIDADE DE IMPRESSOES''');
end;
if VpaNumAtualizacao < 185 Then
begin
VpfErro := '185';
ExecutaComandoSql(Aux,' alter table MOVCLIENTEVENDEDOR '
+ ' ADD D_ULT_ALT date null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 185');
ExecutaComandoSql(Aux,'comment on column MOVCLIENTEVENDEDOR.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''');
end;
if VpaNumAtualizacao < 186 Then
begin
VpfErro := '186';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+' add C_VEN_PED char(1) null, '
+' add C_VEN_ORC char(1) null; '
+' alter table CFG_FISCAL '
+' add C_TRA_VEN char(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 186');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.C_VEN_PED is ''TRANCAR OU NAO A ALTERACAO DO VENDEDOR DO PEDIDO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.C_VEN_ORC is ''TRANCAR OU NAO A ALTERACAO DO VENDEDOR DO PEDIDO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_FISCAL.C_TRA_VEN is ''TRANCAR OU NAO A ALTERACAO DO VENDEDOR DO CUPOM E NOTA FISCAL''; ' );
end;
if VpaNumAtualizacao < 187 Then
begin
VpfErro := '187';
ExecutaComandoSql(Aux,' alter table CadNotaFiscais '
+' add I_COD_USU integer null; '
+' alter table CadOrcamentos '
+' add I_COD_USU integer null; '
+' alter table CadClientes '
+' add I_COD_USU integer null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 187');
ExecutaComandoSql(Aux,' comment on column CadNotaFiscais.I_COD_USU is ''USUARIO QUE CADASTROU''; ' );
ExecutaComandoSql(Aux,' comment on column CadOrcamentos.I_COD_USU is ''USUARIO QUE CADASTROU''; ' );
ExecutaComandoSql(Aux,' comment on column CadClientes.I_COD_USU is ''USUARIO QUE CADASTROU''; ' );
end;
if VpaNumAtualizacao < 188 Then
begin
VpfErro := '188';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+' add I_PAG_PED integer null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 188');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.I_PAG_PED is ''TAMANHO DA PAGINA DA IMPRESSORA MATRICIAL DOS PEDIDOS''; ' );
end;
if VpaNumAtualizacao < 189 Then
begin
VpfErro := '189';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS '
+' add I_PAG_ORC integer null, '
+' add I_IMP_ORC integer null;'
+' update cfg_servicos set i_imp_orc = 1' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 189');
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.I_PAG_ORC is ''TAMANHO DA PAGINA DA IMPRESSORA MATRICIAL DOS ORCAMENTOS''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_SERVICOS.I_IMP_ORC is ''TIPO DA IMPRESSORA DE ORCAMENTOS''; ' );
end;
if VpaNumAtualizacao < 190 Then
begin
VpfErro := '190';
ExecutaComandoSql(Aux,' create table MOVCOMPOSICAOPRODUTO ' +
' ( '+
' I_PRO_COM integer not null, ' +
' I_SEQ_PRO integer not null, ' +
' C_COD_UNI char(2) null, ' +
' N_QTD_PRO numeric(17,3) null, ' +
' I_COD_EMP integer null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_PRO_COM, I_SEQ_PRO) ' +
' ); ' +
' comment on table MOVCOMPOSICAOPRODUTO is ''COMPOSICAO DO PRODUTO''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.I_PRO_COM is ''CODIGO DO PRODUTO DE COMPOSICAO''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.C_COD_UNI is ''CODIGO DA UNIDADE''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.N_QTD_PRO is ''QUANTIDADE DE PRODUTOS''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.I_COD_EMP is ''CODIGO DA EMPRESA''; ' +
' comment on column MOVCOMPOSICAOPRODUTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' alter table MOVCOMPOSICAOPRODUTO ' +
' add foreign key FK_MOVCOMPO_REF_14026_CADUNIDA (C_COD_UNI) ' +
' references CADUNIDADE (C_COD_UNI) on update restrict on delete restrict; ' +
' alter table MOVCOMPOSICAOPRODUTO ' +
' add foreign key FK_MOVCOMPO_REF_14179_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table MOVCOMPOSICAOPRODUTO ' +
' add foreign key FK_MOVCOMPO_REF_14256_CADPRODU (I_PRO_COM) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' create unique index MOVCOMPOSICAOPRODUTO_PK on MOVCOMPOSICAOPRODUTO (I_PRO_COM asc, I_SEQ_PRO asc); ' +
' create index Ref_140261_FK on MOVCOMPOSICAOPRODUTO (C_COD_UNI asc); ' +
' create index Ref_141796_FK on MOVCOMPOSICAOPRODUTO (I_SEQ_PRO asc); ' +
' create index Ref_142569_FK on MOVCOMPOSICAOPRODUTO (I_PRO_COM asc); ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 190' );
end;
if VpaNumAtualizacao < 191 Then
begin
VpfErro := '191';
ExecutaComandoSql(Aux,' alter table cadprodutos '
+' add C_PRO_COM char(1) null; '
+' update CADPRODUTOS set C_PRO_COM = ''N''' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 191');
ExecutaComandoSql(Aux,' comment on column cadprodutos.c_pro_com is ''SE O PRODUTO E COMPOSTO''; ' );
end;
if VpaNumAtualizacao < 192 Then
begin
VpfErro := '192';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_NOT_SUB char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 192');
ExecutaComandoSql(Aux,' comment on column CFG_FISCAL.C_NOT_SUB is ''PERMITIR EXCLUIR NOTAS COM NUMEROS SUBSEQUENTES''; ' );
end;
if VpaNumAtualizacao < 193 Then
begin
VpfErro := '193';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_TOT_NOT char(1) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 193');
ExecutaComandoSql(Aux,' comment on column CFG_FISCAL.C_TOT_NOT is ''PERMITIR ALTERAR O TOTAL DA NOTA''; ' );
end;
if VpaNumAtualizacao < 194 Then
begin
VpfErro := '194';
ExecutaComandoSql(Aux, ' create table MOVCAIXAESTOQUE( ' +
' I_EMP_FIL integer not null, ' +
' I_NRO_CAI integer not null, ' +
' I_SEQ_PRO integer null , ' +
' I_SEQ_NOT integer null , ' +
' C_COD_PRO Char(20) null , ' +
' I_PES_CAI numeric(17,4) null , ' +
' D_DAT_ENT date null , ' +
' D_DAT_SAI date null , ' +
' N_VLR_SAI numeric(17,4) null , ' +
' C_OBS_CAI varchar(100) null , ' +
' C_SIT_CAI char(1) null , ' +
' C_NRO_REC char(20) null , ' +
' C_COD_BAR char(25) null , ' +
' primary key (I_EMP_FIL, I_NRO_CAI) ); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 194');
end;
if VpaNumAtualizacao < 195 Then
begin
VpfErro := '195';
ExecutaComandoSql(Aux, ' comment on table MOVCAIXAESTOQUE is ''MOVIMENTO DE CAIXA PARA ESTOQUES''; ' +
' comment on column MOVCAIXAESTOQUE.I_EMP_FIL is ''CODIGO DA EMPRESA FILIAL''; ' +
' comment on column MOVCAIXAESTOQUE.I_NRO_CAI is ''NUMERO DA CAIXA''; ' +
' comment on column MOVCAIXAESTOQUE.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column MOVCAIXAESTOQUE.I_SEQ_NOT is ''NUMERO SEQUENCIAL DA NOTA''; ' +
' comment on column MOVCAIXAESTOQUE.I_PES_CAI is ''PESO DA CAIXA''; ' +
' comment on column MOVCAIXAESTOQUE.D_DAT_ENT is ''DATA DE ENTREGA''; ' +
' comment on column MOVCAIXAESTOQUE.D_DAT_SAI is ''DATA DE SAIDA''; ' +
' comment on column MOVCAIXAESTOQUE.N_VLR_SAI is ''VALOR DA SAIDA''; ' +
' comment on column MOVCAIXAESTOQUE.C_OBS_CAI is ''OBSERVACAO''; ' +
' comment on column MOVCAIXAESTOQUE.C_SIT_CAI is ''SITUACAO DA CAIXA''; ' +
' comment on column MOVCAIXAESTOQUE.C_NRO_REC is ''NUMERO DO RECIBO''; ' +
' comment on column MOVCAIXAESTOQUE.C_COD_BAR is ''CODIGO DA BARRAS''; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 195');
end;
if VpaNumAtualizacao < 196 Then
begin
VpfErro := '196';
ExecutaComandoSql(Aux, ' create unique index MOVCAIXAESTOQUE_PK on MOVCAIXAESTOQUE (I_EMP_FIL asc, I_NRO_CAI asc); ' +
' create index Ref_144353_FK on MOVCAIXAESTOQUE (I_SEQ_PRO asc); ' +
' create index Ref_145121_FK on MOVCAIXAESTOQUE (I_EMP_FIL asc, I_SEQ_NOT asc); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 196');
end;
if VpaNumAtualizacao < 197 Then
begin
VpfErro := '197';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_DUP_PRO char(1) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 197');
ExecutaComandoSql(Aux,' comment on column CFG_FISCAL.C_DUP_PRO is ''PERMITIR DUPLICAR PRODUTO NA NOTA FISCAL''; ' );
end;
if VpaNumAtualizacao < 198 Then
begin
VpfErro := '198';
ExecutaComandoSql(Aux,' alter table cfg_fiscal '
+' add C_TRU_TOT char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 198');
ExecutaComandoSql(Aux,' comment on column CFG_FISCAL.C_TRU_TOT is ''TRUNCA O VALOR DOS DECIMAIS NO TOTAL DA NOTA''; ' );
end;
if VpaNumAtualizacao < 199 Then
begin
VpfErro := '199';
ExecutaComandoSql(Aux,' alter table cfg_geral ' +
' add C_ALT_CAP char(1) null, ' +
' add C_ALT_CAR char(1) null, ' +
' add C_ALT_NFS char(1) null, ' +
' add C_ALT_PED char(1) null, ' +
' add C_ALT_ORC char(1) null, ' +
' add C_ALT_EST char(1) null, ' +
' add C_ALT_COS char(1) null, ' +
' add C_ALT_BAN char(1) null, ' +
' add C_ALT_ORS char(1) null, ' +
' add C_ALT_NFE char(1) null, ' +
' add C_ALT_PRE char(1) null, ' +
' add C_ALT_PLA char(1) null, ' +
' add C_ALT_NAT char(1) null, ' +
' add C_ALT_PRO char(1) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 199');
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_CAP is ''NAO/SIM PERMITIR A ALTERACAO DO CONTAS A PAGAR''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_CAR is ''NAO/SIM PERMITIR A ALTERACAO DO CONTAS A RECEBER''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_NFS is ''NAO/SIM PERMITIR A ALTERACAO DA NOTA FISCAL SAIDA''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_PED is ''NAO/SIM PERMITIR A ALTERACAO DO PEDIDO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_ORC is ''NAO/SIM PERMITIR A ALTERACAO DO ORCAMENTO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_EST is ''NAO/SIM PERMITIR A ALTERACAO DO ESTOQUE''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_COS is ''NAO/SIM PERMITIR A ALTERACAO DA COMISSOES''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_BAN is ''NAO/SIM PERMITIR A ALTERACAO DOS BANCOS ''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_ORS is ''NAO/SIM PERMITIR A ALTERACAO DOS ORCAMENTOS''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_NFE is ''NAO/SIM PERMITIR A ALTERACAO DO NOTA FISCAL DE ENTRADA''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_PRE is ''NAO/SIM PERMITIR A ALTERACAO DO PRECO DO PRECO''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_PLA is ''NAO/SIM PERMITIR A ALTERACAO DO PLANO DE CONTAS''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_NAT is ''NAO/SIM PERMITIR A ALTERACAO DAS NATUREZAS''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_GERAL.C_ALT_PRO is ''NAO/SIM PERMITIR A ALTERACAO DOS PRODUTOS''; ' );
end;
if VpaNumAtualizacao < 200 Then
begin
VpfErro := '200';
ExecutaComandoSql(Aux,' create table MOVTABELAPRECOCLIENTE( '
+' I_EMP_FIL integer not null, '
+' I_SEQ_MOV integer not null, '
+' I_COD_TAB integer null, '
+' I_COD_EMP integer null, '
+' I_COD_CLI integer null, '
+' I_TAB_SER integer null, '
+' primary key (I_EMP_FIL, I_SEQ_MOV) ); ' );
ExecutaComandoSql(Aux,' alter table MOVTABELAPRECOCLIENTE ' +
' add foreign key FK_MOVTABELA_REF_155_CLIENTES(I_COD_CLI) ' +
' references CADCLIENTES(I_COD_CLI) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' alter table MOVTABELAPRECOCLIENTE ' +
' add foreign key FK_MOVTABELA_REF_160_PRE_PRO(I_COD_EMP, I_COD_TAB) ' +
' references CADTABELAPRECO(I_COD_EMP, I_COD_TAB) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' alter table MOVTABELAPRECOCLIENTE ' +
' add foreign key FK_MOVTABELA_REF_170_PRE_PRO(I_COD_EMP, I_TAB_SER) ' +
' references CADTABELAPRECO(I_COD_EMP, I_COD_TAB) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' create index MOVTABELAPRECO_PK on MOVTABELAPRECOCLIENTE(I_EMP_FIL, I_SEQ_MOV asc); ' );
ExecutaComandoSql(Aux,' create index MOVTABELAPRECO_FK_123 on MOVTABELAPRECOCLIENTE(I_COD_CLI asc); ' );
ExecutaComandoSql(Aux,' create index MOVTABELAPRECO_FK_124 on MOVTABELAPRECOCLIENTE(I_COD_EMP,I_COD_TAB asc); ' );
ExecutaComandoSql(Aux,' create index MOVTABELAPRECO_FK_125 on MOVTABELAPRECOCLIENTE(I_COD_EMP,I_TAB_SER asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 200');
end;
if VpaNumAtualizacao < 201 Then
begin
VpfErro := '201';
ExecutaComandoSql(Aux,' ALTER TABLE MOVTABELAPRECOCLIENTE '
+' add D_ULT_ALT date null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 201');
end;
if VpaNumAtualizacao < 202 Then
begin
VpfErro := '202';
ExecutaComandoSql(Aux,' alter table cfg_geral ' +
' add C_EXP_FIL char(1) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 202');
end;
if VpaNumAtualizacao < 203 Then
begin
VpfErro := '203';
ExecutaComandoSql(Aux,' alter table cfg_fiscal ' +
' add C_DEV_CUP char(100) null; ' +
' update cfg_fiscal set c_dev_cup = ''Nota fiscal de devolução referente ao Cupom Fiscal nº''' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 203');
end;
if VpaNumAtualizacao < 204 Then
begin
VpfErro := '204';
ExecutaComandoSql(Aux,' alter table cadfiliais ' +
' add C_PER_CAD char(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 204');
end;
if VpaNumAtualizacao < 205 Then
begin
VpfErro := '205';
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_TRA_INA char(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 205');
end;
if VpaNumAtualizacao < 206 Then
begin
VpfErro := '206';
ExecutaComandoSql(Aux,' alter table cadNotaFiscais ' +
' add C_INF_NOT Varchar(100) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 206');
end;
if VpaNumAtualizacao < 207 Then
begin
VpfErro := '207';
ExecutaComandoSql(Aux,' alter table MOVCAIXAESTOQUE ' +
' add I_COD_USU integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 207');
end;
if VpaNumAtualizacao < 208 Then
begin
VpfErro := '208';
ExecutaComandoSql(Aux,' alter table CFG_FISCAL ' +
' add C_MOD_CAI char(1) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 208');
end;
if VpaNumAtualizacao < 209 Then
begin
VpfErro := '209';
ExecutaComandoSql(Aux,' alter table cadinventario ' +
' add D_ULT_ALT date null, '+
' add C_NOM_IVE char(40) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 209');
end;
if VpaNumAtualizacao < 210 then
begin
VpfErro := '210';
ExecutaComandoSql(Aux,' alter table Movinventario ' +
' add D_ULT_ALT date null, '+
' add C_COD_UNI char(2) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 210');
end;
if VpaNumAtualizacao < 211 then
begin
VpfErro := '211';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' add I_TIP_TRI integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 211');
ExecutaComandoSql(Aux,' comment on column CadProdutos.I_TIP_TRI is ''0 - Sujeito ICMS, 1 - Substituicao Tributaria, 2 - Isento, 3 - Não Incidencia''; ' );
end;
if VpaNumAtualizacao < 212 then
begin
VpfErro := '212';
ExecutaComandoSql(Aux,' delete CADICMSECF ');
ExecutaComandoSql(Aux,' alter table CadIcmsECF ' +
' add C_REG_IMP char(20) not null, ' +
' add I_TIP_IMP integer not null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 212');
end;
if VpaNumAtualizacao < 213 then
begin
VpfErro := '213';
ExecutaComandoSql(Aux,' drop index CADICMSECF_PK; ');
ExecutaComandoSql(Aux,' alter TABLE CADICMSECF drop primary key ');
ExecutaComandoSql(Aux,' alter table CADICMSECF add primary key (c_cod_icm, c_reg_imp, i_tip_imp); ' );
ExecutaComandoSql(Aux,' create index CADICMSECF_PK on CADICMSECF(c_cod_icm, c_reg_imp, i_tip_imp asc); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 213');
aviso('A T E N Ç Ã O - Caso você utilize equipamento de cupom fiscal, antes de usar o sistema vá ao modulo configurções de sistema no menu impressões / configurações da impressora fiscal e utilize o botão atualiza tabela ICMS ');
end;
if VpaNumAtualizacao < 214 then
begin
VpfErro := '214';
ExecutaComandoSql(Aux,' alter table Movinventario ' +
' add C_COD_PRO char(20) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 214');
end;
if VpaNumAtualizacao < 215 then
begin
VpfErro := '215';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' add N_QTD_COM numeric(8,3) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 215');
ExecutaComandoSql(Aux,' comment on column CadProdutos.N_QTD_COM is ''Quantidade que ser referencia a composicao do produto''; ' );
end;
if VpaNumAtualizacao < 216 then
begin
VpfErro := '216';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' add D_DAT_VAL date null, ' +
' add I_QTD_CAI integer null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 216');
end;
if VpaNumAtualizacao < 217 then
begin
VpfErro := '217';
ExecutaComandoSql(Aux,' alter table MovQdadeProduto ' +
' add N_EST_MAX numeric(8,3) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 217');
end;
if VpaNumAtualizacao < 218 then
begin
VpfErro := '218';
ExecutaComandoSql(Aux,' alter table cfg_produto ' +
' add C_CLA_PAD char(20) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 218');
end;
if VpaNumAtualizacao < 219 then
begin
VpfErro := '219';
ExecutaComandoSql(Aux,' alter table CadClientes ' +
' add C_IMP_BOL char(1) null, ' +
' add N_DES_BOL numeric(8,3) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 219');
end;
if VpaNumAtualizacao < 220 then
begin
VpfErro := '220';
ExecutaComandoSql(Aux,' alter table CFG_PRODUTO ' +
' add C_CFG_VEN char(20) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 220');
end;
if VpaNumAtualizacao < 221 then
begin
VpfErro := '221';
ExecutaComandoSql(Aux,' alter table cadordemservico ' +
' add D_DAT_PRE date null, ' +
' add C_NOM_USU char(40) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 221');
end;
if VpaNumAtualizacao < 222 then
begin
VpfErro := '222';
ExecutaComandoSql(Aux,' alter table cadnotafiscais ' +
' add C_PRA_PAG Varchar(40) null, ' +
' add C_END_COB Varchar(40) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 222');
end;
if VpaNumAtualizacao < 223 then
begin
VpfErro := '223';
ExecutaComandoSql(Aux,' alter table grupo_Exportacao ' +
' add C_NAO_RES char(1) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 223');
end;
if VpaNumAtualizacao < 224 then
begin
VpfErro := '224';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' add N_VLR_MAX numeric(17,3) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 224');
end;
if VpaNumAtualizacao < 225 then
begin
VpfErro := '225';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' delete D_DAT_VAL; ' +
' alter table CadProdutos ' +
' add I_DAT_VAL integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 225');
end;
if VpaNumAtualizacao < 226 then
begin
VpfErro := '226';
ExecutaComandoSql(Aux,' alter table CadClientes ' +
' add I_COD_FRM integer null, ' +
' add I_COD_PAG integer null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 226');
end;
if VpaNumAtualizacao < 227 then
begin
VpfErro := '227';
ExecutaComandoSql(Aux,' alter table MovNotasFiscais ' +
' modify c_cod_cst char(3) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 227');
end;
if VpaNumAtualizacao < 228 then
begin
VpfErro := '228';
ExecutaComandoSql(Aux,' alter table MovCaixaEstoque ' +
' add C_TIP_CAI char(1) null, ' +
' add I_SEQ_CAI integer null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 228');
end;
if VpaNumAtualizacao < 229 then
begin
VpfErro := '229';
ExecutaComandoSql(Aux,' alter table MovQdadeProduto ' +
' add N_CUS_COM numeric(17,3) null; ' +
' alter table CFG_Produto ' +
' add C_TIP_CUS char(6) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 229');
ExecutaComandoSql(Aux,' comment on column MovQdadeProduto.N_CUS_COM is ''Custo de compra''; ' );
ExecutaComandoSql(Aux,' comment on column CFG_Produto.C_TIP_CUS is ''MARCA OS TIPO DE ITENS DE CUSTO''; ' );
end;
if VpaNumAtualizacao < 230 then
begin
VpfErro := '230';
ExecutaComandoSql(Aux,' alter table cadItensCusto ' +
' add C_ADI_CAD char(1) null, '+
' add N_VLR_PAD numeric(17,3) null, ' +
' add N_PER_PAD numeric(8,3) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 230');
ExecutaComandoSql(Aux,' comment on column cadItensCusto.C_ADI_CAD is ''ADICIONA O ITEM DE CUSTO AUTOMATICAMENTE AO CADASTRAR O PRODUTO''; ' );
ExecutaComandoSql(Aux,' comment on column cadItensCusto.N_VLR_PAD is ''VALOR PADRAO''; ' );
ExecutaComandoSql(Aux,' comment on column cadItensCusto.N_PER_PAD is ''PERCENTUAL PADRAO''; ' );
end;
if VpaNumAtualizacao < 231 then
begin
VpfErro := '231';
ExecutaComandoSql(Aux,' alter table cadItensCusto ' +
' add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 231');
end;
if VpaNumAtualizacao < 232 then
begin
VpfErro := '232';
ExecutaComandoSql(Aux,' alter table cfg_produto ' +
' add C_TIP_IND char(1) null; '+
' alter table cadoperacaoestoque ' +
' add I_OPE_BAI integer null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 232');
ExecutaComandoSql(Aux,' comment on column cfg_produto.C_TIP_IND is ''SE O ESTOQUE SERA DO TIPO INDUSTRIALIZADO''; ' );
ExecutaComandoSql(Aux,' comment on column cadoperacaoestoque.I_OPE_BAI is ''OPERACAO DE BAIXA CASO PRODUTO INDUSTRIALIZADO''; ' );
end;
if VpaNumAtualizacao < 233 then
begin
VpfErro := '233';
ExecutaComandoSql(Aux,' alter table MovComposicaoproduto ' +
' add C_UNI_PAI char(2) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 233');
end;
if VpaNumAtualizacao < 234 then
begin
VpfErro := '234';
ExecutaComandoSql(Aux,' alter table cfg_geral ' +
' add C_ALT_COR char(1) null; ' +
' alter table cadfiliais ' +
' add C_COR_FIL char(10) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 234');
end;
if VpaNumAtualizacao < 235 then
begin
VpfErro := '235';
ExecutaComandoSql(Aux,' alter table cadfiliais ' +
' add L_TEX_CAB Long varchar null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 235');
end;
if VpaNumAtualizacao < 236 then
begin
VpfErro := '236';
ExecutaComandoSql(Aux,' alter table movequipamentoOS ' +
' add C_VOL_ENT char(10) null; ' +
' alter table cadordemservico ' +
' add T_HOR_PRE time null');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 236');
ExecutaComandoSql(Aux,' comment on column movequipamentoOS.C_VOL_ENT is ''VOLTAGEM PADRAO DE ENTRADA''; ' );
ExecutaComandoSql(Aux,' comment on column cadordemservico.T_HOR_PRE is ''HORA PREVISTA''; ' );
end;
if VpaNumAtualizacao < 237 then
begin
VpfErro := '237';
ExecutaComandoSql(Aux,' alter table cadcontasapagar ' +
' add I_CON_ORC integer null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 237');
ExecutaComandoSql(Aux,' comment on column cadcontasapagar.I_CON_ORC is ''IDENTIFICA ORCAMENTO DE CONTAS A PAGAR 0 - CP / 1 ORC''; ' );
end;
if VpaNumAtualizacao < 238 then
begin
VpfErro := '238';
ExecutaComandoSql(Aux,' alter table CFG_MODULO ' +
' add FLA_INVENTARIO CHAR(1) null, '+
' add FLA_INTERNET CHAR(1) NULL, ' +
' add FLA_PREVISAO CHAR(1) NULL ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 238');
ExecutaComandoSql(Aux,' comment on column cadcontasapagar.I_CON_ORC is ''IDENTIFICA ORCAMENTO DE CONTAS A PAGAR''; ' );
end;
if VpaNumAtualizacao < 239 Then
begin
VpfErro := '239';
ExecutaComandoSql(Aux,'create table MOVREDUCOESICMS '
+' ( I_COD_RED INTEGER NOT NULL, '
+' C_EST_RED char(2) not Null, '
+' C_DES_RED char(40) NULL, '
+' N_PER_RED numeric(17,6) NULL, '
+' PRIMARY KEY(I_COD_RED, C_EST_RED) ) ');
ExecutaComandoSql(Aux,' create index MOVREDUCOESICMS_PK on MOVREDUCOESICMS(I_COD_RED, C_EST_RED asc); ' );
ExecutaComandoSql(Aux,' alter table CADPRODUTOS ' +
' add I_COD_RED INTEGER null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 239');
ExecutaComandoSql(Aux,'comment on table MOVREDUCOESICMS is ''TABELA DREDUCAO DE ICMS''');
ExecutaComandoSql(Aux,'comment on column MOVREDUCOESICMS.I_COD_RED is ''CODIGO HISTORICO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVREDUCOESICMS.C_DES_RED is ''DESCRICAO DO HISTORICO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column MOVREDUCOESICMS.N_PER_RED is ''PERCENTUAL DA REDUCAO''');
ExecutaComandoSql(Aux,'comment on column MOVREDUCOESICMS.C_EST_RED is ''ESTADO DA REDUCAO''');
end;
if VpaNumAtualizacao < 240 then
begin
VpfErro := '240';
ExecutaComandoSql(Aux,' alter table MOVREDUCOESICMS ' +
' add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 240');
end;
if VpaNumAtualizacao < 241 then
begin
VpfErro := '241';
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_HIS_PED CHAR(1) null ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 241');
ExecutaComandoSql(Aux,'comment on column cfg_servicos.C_HIS_PED is ''MOSTRAR HISTORICO AUTOMATICO NO PEDIDO''');
end;
if VpaNumAtualizacao < 242 Then
begin
VpfErro := '242';
ExecutaComandoSql(Aux,'create table CADCONTATOS '
+' ( D_ULT_ALT date NULL, '
+' I_COD_CLI integer not Null, '
+' I_COD_CON integer not NULL, '
+' C_DEP_CON char(20)NULL, '
+' C_EMA_CON char(40)Null, '
+' C_FAX_CON char(15)NULL, '
+' C_FON_CON char(15)NULL, '
+' C_NOM_CON char(30)NULL, '
+' PRIMARY KEY(I_COD_CLI, I_COD_CON) ) ');
ExecutaComandoSql(Aux,' create index CADCONTATOS_PK on CADCONTATOS(I_COD_CLI, I_COD_CON asc); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 242');
ExecutaComandoSql(Aux,'comment on table CADCONTATOS is ''TABELA DE CONTATOS DE CLIENTES''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.D_DAT_ALT is ''DATA DA ULTIMA ALTERACAO''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.I_COD_CLI is ''CODIGO DO CLIENTE''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.I_COD_CON is ''CODIGO DO CONTATO''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.C_DEP_CON is ''DEPARTAMENTO DO CONTATO''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.C_EMA_CON is ''E-MAIL DO CONTATO''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.C_FAX_CON is ''FAX''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.C_FON_CON is ''TELEFONE''');
ExecutaComandoSql(Aux,'comment on column CADCONTATOS.C_NOM_CON is ''NOME DO CONTATO''');
end;
if VpaNumAtualizacao < 243 Then
begin
VpfErro := '243';
ExecutaComandoSql(Aux, ' alter table MOVCAIXAESTOQUE ' +
' add I_NRO_NOT integer null, ' +
' add C_SER_NOT char(2) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 243');
ExecutaComandoSql(Aux,'comment on column MOVCAIXAESTOQUE.I_NRO_NOT is ''NUMERO DA NOTA FISCAL''');
ExecutaComandoSql(Aux,'comment on column MOVCAIXAESTOQUE.C_SER_NOT is ''SERIE DA NOTA''');
end;
if VpaNumAtualizacao < 244 Then
begin
VpfErro := '244';
ExecutaComandoSql(Aux, ' alter table movcomposicaoproduto ' +
' modify N_QTD_PRO numeric(17,8) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 244');
end;
if VpaNumAtualizacao < 245 Then
begin
VpfErro := '245';
ExecutaComandoSql(Aux, ' create table CADCICLOPRODUTO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_SEQ_CIC integer not null, ' +
' I_SEQ_PRO integer not null, ' +
' C_COD_UNI char(2) null , ' +
' N_CIC_PRO numeric(17,8) null , ' +
' N_PES_CIC numeric(17,8) null , ' +
' N_QTD_CIC numeric(17,8) null , ' +
' D_ULT_ALT date null , ' +
' C_UNI_TEM char(1) null , ' +
' primary key (I_EMP_FIL, I_SEQ_CIC, I_SEQ_PRO) ' +
' ); ' +
' comment on table CADCICLOPRODUTO is ''CADASTRO DE CLICLOS DE PRODUTO''; ' +
' comment on column CADCICLOPRODUTO.I_EMP_FIL is ''CODIGO EMPRESA FILIAL''; ' +
' comment on column CADCICLOPRODUTO.I_SEQ_CIC is ''SEQUENCIAL DE CICLO''; ' +
' comment on column CADCICLOPRODUTO.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column CADCICLOPRODUTO.C_COD_UNI is ''CODIGO DA UNIDADE''; ' +
' comment on column CADCICLOPRODUTO.N_CIC_PRO is ''CICLO DO PRODUTO POR TEMPO''; ' +
' comment on column CADCICLOPRODUTO.N_PES_CIC is ''PESO DO PRODUTO''; ' +
' comment on column CADCICLOPRODUTO.N_QTD_CIC is ''QUANTIDADE DE PRODUTO POR CICLO''; ' +
' comment on column CADCICLOPRODUTO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' comment on column CADCICLOPRODUTO.C_UNI_TEM is ''UNIDADE DE TEMPO''; ' +
' create table CADMAQUINAS ' +
' ( ' +
' I_COD_MAQ integer not null, ' +
' C_NOM_MAQ char(40) null , ' +
' N_PER_CIC numeric(17,8) null , ' +
' D_ULT_ALT date null , ' +
' primary key (I_COD_MAQ) ' +
' ); ' +
' comment on table CADMAQUINAS is ''CADASTRO DE MAQUINAS''; ' +
' Comment on column CADMAQUINAS.I_COD_MAQ is ''CODIGO DA MAQUINA''; ' +
' comment on column CADMAQUINAS.C_NOM_MAQ is ''NOME DA MAQUINA''; ' +
' comment on column CADMAQUINAS.N_PER_CIC is ''PERCENTUAL DE DESCONTO OU ACRESCIMO NO CLICO DE PRODUCAO''; ' +
' comment on column CADMAQUINAS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' create table CADORDEMPRODUCAO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_NRO_ORP integer not null, ' +
' I_SEQ_PRO integer null , ' +
' I_COD_MAQ integer null , ' +
' I_COD_SIT integer null , ' +
' I_LAN_ORC integer null , ' +
' D_DAT_EMI date null , ' +
' D_DAT_ENT date null , ' +
' D_DAT_PRO date null , ' +
' N_QTD_PRO numeric(17,8) null , ' +
' N_QTD_SAC numeric(17,8) null , ' +
' N_PES_CIC numeric(17,8) null , ' +
' N_CIC_PRO numeric(17,8) null , ' +
' N_TOT_HOR numeric(17,8) null , ' +
' I_NRO_PED integer null , ' +
' L_OBS_ORP long varchar null , ' +
' D_ULT_ALT date null , ' +
' primary key (I_EMP_FIL, I_NRO_ORP) ' +
' ); ' +
' comment on table CADORDEMPRODUCAO is ''CADASTRO DE ORDEM DE PRODUCAO''; ' +
' comment on column CADORDEMPRODUCAO.I_EMP_FIL is ''CODIGO DA FILIAL''; ' +
' comment on column CADORDEMPRODUCAO.I_NRO_ORP is ''CODIGO DA ORDEM DE PRODUCAO''; ' +
' comment on column CADORDEMPRODUCAO.I_SEQ_PRO is ''CODIGO DO PRODUTO''; ' +
' comment on column CADORDEMPRODUCAO.I_COD_MAQ is ''CODIGO DA MAQUINA''; ' +
' comment on column CADORDEMPRODUCAO.I_COD_SIT is ''CODIGO DA SITUACAO''; ' +
' comment on column CADORDEMPRODUCAO.I_LAN_ORC is ''NUMERO DE LANCAMENTO SEQUENCIAL''; ' +
' comment on column CADORDEMPRODUCAO.D_DAT_EMI is ''DATA DE EMISSAO''; ' +
' comment on column CADORDEMPRODUCAO.D_DAT_ENT is ''DATA DE ENTREGA''; ' +
' comment on column CADORDEMPRODUCAO.D_DAT_PRO is ''DATA PARA PRODUZIR''; ' +
' comment on column CADORDEMPRODUCAO.N_QTD_PRO is ''QUANTIDADE A PRODUZIR''; ' +
' comment on column CADORDEMPRODUCAO.N_QTD_SAC is ''QUANTIDADE DE SACO''; ' +
' comment on column CADORDEMPRODUCAO.N_PES_CIC is ''PECO DO CICLO''; ' +
' comment on column CADORDEMPRODUCAO.N_CIC_PRO is ''CICLO DE PRODUCAO''; ' +
' comment on column CADORDEMPRODUCAO.N_TOT_HOR is ''TOTAL DE HORAS DA PRODUCAO''; ' +
' comment on column CADORDEMPRODUCAO.I_NRO_PED is ''NUMERO DO PEDIDO''; ' +
' comment on column CADORDEMPRODUCAO.L_OBS_ORP is ''L_OBS_ORP''; ' +
' comment on column CADORDEMPRODUCAO.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' alter table CADCICLOPRODUTO ' +
' add foreign key FK_CADCICLO_REF_15174_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table CADCICLOPRODUTO ' +
' add foreign key FK_CADCICLO_REF_15176_CADUNIDA (C_COD_UNI) ' +
' references CADUNIDADE (C_COD_UNI) on update restrict on delete restrict; ' +
' alter table CADORDEMPRODUCAO ' +
' add foreign key FK_CADORDEM_REF_15174_CADPRODU (I_SEQ_PRO) ' +
' references CADPRODUTOS (I_SEQ_PRO) on update restrict on delete restrict; ' +
' alter table CADORDEMPRODUCAO ' +
' add foreign key FK_CADORDEM_REF_15177_CADMAQUI (I_COD_MAQ) ' +
' references CADMAQUINAS (I_COD_MAQ) on update restrict on delete restrict; ' +
' alter table CADORDEMPRODUCAO ' +
' add foreign key FK_CADORDEM_REF_15178_CADSITUA (I_COD_SIT) ' +
' references CADSITUACOES (I_COD_SIT) on update restrict on delete restrict; ' +
' alter table CADORDEMPRODUCAO ' +
' add foreign key FK_CADORDEM_REF_15179_CADORCAM (I_EMP_FIL, I_LAN_ORC) ' +
' references CADORCAMENTOS (I_EMP_FIL, I_LAN_ORC) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 245');
end;
if VpaNumAtualizacao < 246 Then
begin
VpfErro := '246';
ExecutaComandoSql(Aux, ' create unique index CADCICLOPRODUTO_PK on CADCICLOPRODUTO (I_EMP_FIL asc, I_SEQ_CIC asc, I_SEQ_PRO asc); ' +
' create index Ref_151744_FK on CADCICLOPRODUTO (I_SEQ_PRO asc); ' +
' create index Ref_151762_FK on CADCICLOPRODUTO (C_COD_UNI asc); ' +
' create unique index CADMAQUINAS_PK on CADMAQUINAS (I_COD_MAQ asc); ' +
' create unique index CADORDEMPRODUCAO_PK on CADORDEMPRODUCAO (I_EMP_FIL asc, I_NRO_ORP asc); ' +
' create index Ref_151748_FK on CADORDEMPRODUCAO (I_SEQ_PRO asc); ' +
' create index Ref_151771_FK on CADORDEMPRODUCAO (I_COD_MAQ asc); ' +
' create index Ref_151785_FK on CADORDEMPRODUCAO (I_COD_SIT asc); ' +
' create index Ref_151791_FK on CADORDEMPRODUCAO (I_EMP_FIL asc, I_LAN_ORC asc); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 246');
end;
if VpaNumAtualizacao < 247 Then
begin
VpfErro := '247';
ExecutaComandoSql(Aux,' alter table cadprofissoes ' +
' add C_TIP_CAD char(1) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 247');
end;
if VpaNumAtualizacao < 248 Then
begin
VpfErro := '248';
ExecutaComandoSql(Aux,' alter table cadOrdemProducao ' +
' add C_COD_PRO char(20) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 248');
end;
if VpaNumAtualizacao < 249 Then
begin
VpfErro := '249';
ExecutaComandoSql(Aux,' alter table cfg_fiscal ' +
' add C_SER_AUT char(1) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 249');
end;
if VpaNumAtualizacao < 250 Then
begin
VpfErro := '250';
ExecutaComandoSql(Aux,' alter table cadnotafiscais ' +
' modify N_PES_BRU numeric(17,3) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 250');
end;
if VpaNumAtualizacao < 251 Then
begin
VpfErro := '251';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add I_COD_ATE integer null; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add C_NRO_SER char(20) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 251');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.I_COD_ATE is ''CODIGO DO ATENTENDE''');
ExecutaComandoSql(Aux,'comment on column MOVEQUIPAMENTOOS.C_NRO_SER is ''NUMERO DE SERIE DO EQUIPAMENTO''');
end;
if VpaNumAtualizacao < 252 Then
begin
VpfErro := '252';
ExecutaComandoSql(Aux,' alter table CadContatos ' +
' add D_ULT_ALT date null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 252');
end;
if VpaNumAtualizacao < 253 Then
begin
VpfErro := '253';
ExecutaComandoSql(Aux,' alter table CFG_MODULO ' +
' add FLA_PCP char(1) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 253');
end;
if VpaNumAtualizacao < 254 Then
begin
VpfErro := '254';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add C_NON_AVI char(30) null, ' +
' add D_DAT_AVI date null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 254');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.C_NON_AVI is ''NOME DO USUARIO QUE FOI AVISADO DO TERMINO DO SERVIÇO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemServico.D_DAT_AVI is ''DATA DE AVISO DE TERMINO''');
end;
if VpaNumAtualizacao < 255 Then
begin
VpfErro := '255';
ExecutaComandoSql(Aux,' alter table MOVCAIXAESTOQUE ' +
' add D_DAT_PRO date null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 255');
end;
if VpaNumAtualizacao < 256 Then
begin
VpfErro := '256';
ExecutaComandoSql(Aux,' alter table MOVCAIXAESTOQUE ' +
' modify C_COD_BAR Varchar(70) null; ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 256');
end;
if VpaNumAtualizacao < 257 Then
begin
VpfErro := '257';
ExecutaComandoSql(Aux,' drop index MOVCAIXAESTOQUE_PK ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 257');
end;
if VpaNumAtualizacao < 258 Then
begin
VpfErro := '258';
ExecutaComandoSql(Aux,' alter TABLE MOVCAIXAESTOQUE drop primary key ');
ExecutaComandoSql(Aux,' alter TABLE MOVCAIXAESTOQUE modify i_seq_pro integer not null ');
ExecutaComandoSql(Aux,' alter table MOVCAIXAESTOQUE add primary key (i_emp_fil,i_nro_cai,i_seq_pro) ' );
ExecutaComandoSql(Aux,' create index MOVCAIXAESTOQUE_PK on MOVCAIXAESTOQUE(i_emp_fil,i_nro_cai,i_seq_pro asc) ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 258');
end;
if VpaNumAtualizacao < 259 Then
begin
VpfErro := '259';
ExecutaComandoSql(Aux,'alter table movnotasfiscais ' +
' add I_QTD_CAI integer null; ');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 259');
end;
if VpaNumAtualizacao < 260 Then
begin
VpfErro := '260';
ExecutaComandoSql(Aux,' create index EmissaoCP_10 on CADNOTAFISCAIS (D_DAT_EMI asc); ' );
ExecutaComandoSql(Aux,' create index EmissaoCP_10 on CADCONTASARECEBER(D_DAT_EMI asc); ' );
ExecutaComandoSql(Aux,' create index EmissaoCP_10 on CADCONTASAPAGAR(D_DAT_EMI asc); ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 260');
end;
if VpaNumAtualizacao < 261 Then
begin
VpfErro := '261';
ExecutaComandoSql(Aux,' alter table CadOrdemProducao ' +
' add C_TIP_ORP CHAR(1) null, ' +
' add D_DAT_FEC date null, ' +
' add D_DAT_INI date null, ' +
' add D_DAT_FIM date null, '+
' add N_QTD_TER numeric(17,4) null ');
ExecutaComandoSql(Aux,'comment on column CadOrdemProducao.C_TIP_ORP is ''TIPO DE ORDEM PRODUCAO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemProducao.D_DAT_FEC is ''DATA DE FECHAMENTO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemProducao.D_DAT_INI is ''DATA DE INICIO DE PRODUCAO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemProducao.D_DAT_FIM is ''DATA DE FIM DFE PRODUCAO''');
ExecutaComandoSql(Aux,'comment on column CadOrdemProducao.N_QTD_TER is ''QUANTIDADE JA TERMINADA NA PRODUCAO''');
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 261');
end;
except
FAtualizaSistema.MostraErro(Aux.sql,'cfg_geral');
Erro(VpfErro + ' - OCORREU UM ERRO DURANTE A ATUALIZAÇAO DO SISTEMA inSIG.');
result := false;
exit;
end;
until result;
end;
{********************* altera as versoes do sistema ***************************}
procedure TAtualiza.AlteraVersoesSistemas;
begin
ExecutaComandoSql(Aux,'Update Cfg_Geral ' +
'set C_Mod_Fat = '''+ VersaoFaturamento + ''',' +
' C_Mod_Pon = '''+ VersaoPontoLoja + ''','+
' C_Mod_Est = ''' + VersaoEstoque + ''',' +
' C_Mod_Cai = '''+ VersaoCaixa +''',' +
' C_Mod_Fin = ''' + VersaoFinanceiro+''','+
' C_CON_USU = ''' + VersaoConfiguracaoAmbiente+''','+
' C_Mod_TRX = ''' + VersaoTrasnferencia+''',' +
' C_Mod_REL = ''' + VersaoRelatorios+''',' +
' C_CON_SIS = ''' + VersaoConfiguracaoSistema+'''');
end;
end.
|
unit sFormatsettingsForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ButtonPanel, ComCtrls, StdCtrls, Spin, ExtCtrls, Buttons, sCtrls;
type
{ TFormatSettingsForm }
TFormatSettingsForm = class(TForm)
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
BtnCurrency: TBitBtn;
ButtonPanel: TButtonPanel;
CbLongDateFormat: TComboBox;
CbLongTimeFormat: TComboBox;
CbPosCurrencyFormat: TComboBox;
CbNegCurrencyFormat: TComboBox;
CbShortDateFormat: TComboBox;
CbShortTimeFormat: TComboBox;
EdCurrencySymbol: TEdit;
EdCurrencyDecimals: TSpinEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
LblCurrencySymbol: TLabel;
LblCurrencySymbol1: TLabel;
LblDateTimeSample: TLabel;
LblDecimalSeparator: TLabel;
LblDateSeparator: TLabel;
LblTimeSeparator: TLabel;
LblLongDayNames: TLabel;
LblLongMonthNames: TLabel;
LblNumFormat1: TLabel;
LblNumFormat2: TLabel;
LblNumFormat3: TLabel;
LblNumFormat4: TLabel;
LblPosCurrencyFormat: TLabel;
LblNegCurrencyFormat: TLabel;
LblShortDayNames: TLabel;
LblShortMonthNames: TLabel;
LblThousandSeparator: TLabel;
PageControl: TPageControl;
PgCurrency: TTabSheet;
PgDateTime: TTabSheet;
PgNumber: TTabSheet;
procedure BtnCurrencyClick(Sender: TObject);
procedure DateTimeFormatChange(Sender: TObject);
procedure EdCurrencySymbolChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure PageControlChange(Sender: TObject);
private
FSampleDateTime: TDateTime;
FDateFormatSample: String;
FTimeFormatSample: String;
FEdLongMonthNames: TMonthDayNamesEdit;
FEdShortMonthNames: TMonthDayNamesEdit;
FEdLongDayNames: TMonthDayNamesEdit;
FEdShortDayNames: TMonthDayNamesEdit;
FCbDecimalSeparator: TFormatSeparatorCombo;
FCbThousandSeparator: TFormatSeparatorCombo;
FCbDateSeparator: TFormatSeparatorCombo;
FCbTimeSeparator: TFormatSeparatorCombo;
function GetFormatSettings: TFormatSettings;
procedure SetFormatSettings(const AValue: TFormatSettings);
function ValidData(out AControl: TWinControl; out AMsg: String): Boolean;
public
{ public declarations }
property FormatSettings: TFormatSettings read GetFormatSettings write SetFormatSettings;
end;
var
FormatSettingsForm: TFormatSettingsForm;
implementation
{$R *.lfm}
uses
fpsUtils, fpsNumFormat,
sCurrencyForm;
const
CURR_VALUE = 100.0;
var
PageIndex: Integer = 0; // stores the previously selected page index (to open the form always with previously used page)
{ TFormatSettingsForm }
procedure TFormatSettingsForm.DateTimeFormatChange(Sender: TObject);
var
fs: TFormatSettings;
ctrl: TWinControl;
dt: TDateTime;
s: String;
begin
fs := GetFormatSettings;
dt := FSampleDateTime;
ctrl := ActiveControl;
if (ctrl = CbLongDateFormat) then
begin
FDateFormatSample := fs.LongDateFormat;
s := FormatDateTime(FDateFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample date:'#13 + s;
end
else
if (ctrl = CbShortDateFormat) then
begin
FDateFormatSample := fs.ShortDateFormat;
s := FormatDateTime(FDateFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample date:'#13 + s;
end
else
if (ctrl = FCbDateSeparator) then begin
s := FormatDateTime(FDateFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample date:'#13 + s;
end
else
if (ctrl = CbLongTimeFormat) then
begin
FTimeFormatSample := fs.LongTimeFormat;
s := FormatDateTime(FTimeFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample time:'#13 + s;
end
else
if (ctrl = CbShortTimeFormat) then
begin
FTimeFormatSample := fs.ShortTimeFormat;
s := FormatDateTime(FTimeFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample time:'#13 + s;
end
else
if (ctrl = FCbTimeSeparator) then
begin
s := FormatDateTime(FTimeFormatSample, dt, fs);
LblDateTimeSample.Caption := 'Sample time:'#13 + s;
{
end
else
begin
s := AnsiToUTF8(FormatDateTime('c', dt, fs));
LblDateTimeSample.Caption := 'Sample date/time:'#13 + s;
}
end;
LblDateTimeSample.Visible := (PageControl.Activepage = PgDateTime) and
((FDateFormatSample <> '') or (FTimeFormatSample <> ''));
// Application.ProcessMessages;
end;
procedure TFormatSettingsForm.BtnCurrencyClick(Sender: TObject);
var
F: TCurrencyForm;
begin
F := TCurrencyForm.Create(nil);
try
F.CurrencySymbol := EdCurrencySymbol.Text;
if F.ShowModal = mrOK then
EdCurrencySymbol.Text := F.CurrencySymbol;
finally
F.Free;
end;
end;
procedure TFormatSettingsForm.EdCurrencySymbolChange(Sender: TObject);
var
currSym: String;
begin
currSym := EdCurrencySymbol.Text;
BuildCurrencyFormatList(CbPosCurrencyFormat.Items, true, CURR_VALUE, currSym);
BuildCurrencyFormatList(CbNegCurrencyFormat.Items, false, CURR_VALUE, currSym);
end;
procedure TFormatSettingsForm.FormCloseQuery(Sender: TObject;
var CanClose: boolean);
begin
Unused(Sender, CanClose);
PageIndex := PageControl.ActivePageIndex;
end;
procedure TFormatSettingsForm.FormCreate(Sender: TObject);
const
DROPDOWN_COUNT = 32;
var
w: Integer;
begin
PageControl.ActivePageIndex := PageIndex;
CbLongDateFormat.DropdownCount := DROPDOWN_COUNT;
CbShortDateFormat.DropdownCount := DROPDOWN_COUNT;
CbLongTimeFormat.DropdownCount := DROPDOWN_COUNT;
CbShortTimeFormat.DropdownCount := DROPDOWN_COUNT;
CbPosCurrencyFormat.DropdownCount := DROPDOWN_COUNT;
CbNegCurrencyFormat.DropdownCount := DROPDOWN_COUNT;
w := CbLongDateFormat.Width;
FCbDecimalSeparator := TFormatSeparatorCombo.Create(self);
with FCbDecimalSeparator do
begin
Parent := PgNumber;
Left := CbLongDateFormat.Left;
Width := w;
Top := CbLongDateFormat.Top;
TabOrder := 0;
SeparatorKind := skDecimal;
end;
LblDecimalSeparator.FocusControl := FCbDecimalSeparator;
FCbThousandSeparator := TFormatSeparatorCombo.Create(self);
with FCbThousandSeparator do
begin
Parent := PgNumber;
Left := FCbDecimalSeparator.Left;
Width := w;
Top := FCBDecimalSeparator.Top + 32;
TabOrder := FCbDecimalSeparator.TabOrder + 1;
SeparatorKind := skThousand;
end;
LblThousandSeparator.FocusControl := FCbThousandSeparator;
FCbDateSeparator := TFormatSeparatorCombo.Create(self);
with FCbDateSeparator do
begin
Parent := PgDateTime;
Left := CbShortDateFormat.Left;
Width := w;
Top := CbShortDateFormat.Top + 32;
TabOrder := CbShortDateFormat.TabOrder + 1;
SeparatorKind := skDate;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
end;
LblDateSeparator.FocusControl := FCbDateSeparator;
FEdLongMonthNames := TMonthDayNamesEdit.Create(self);
with FEdLongMonthNames do
begin
Parent := PgDateTime;
Left := CbShortDateFormat.Left;
{$IFDEF LCL_FULLVERSION AND LCL_FULLVERSION > 1020600}
Width := w;
{$ELSE}
Width := w - Button.Width;
{$ENDIF}
Top := CbShortDateFormat.Top + 32*2;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
TabOrder := CbShortDateFormat.TabOrder + 2;
end;
LblLongMonthNames.FocusControl := FEdLongMonthNames;
FEdShortMonthNames := TMonthDayNamesEdit.Create(self);
with FEdShortMonthNames do
begin
Parent := PgDateTime;
Left := CbShortDateFormat.Left;
Width := FEdLongMonthNames.Width;
Top := CbShortDateFormat.Top + 32*3;
TabOrder := CbShortDateFormat.TabOrder + 3;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
end;
LblShortMonthNames.FocusControl := FEdShortMonthNames;
FEdLongDayNames := TMonthDayNamesEdit.Create(self);
with FEdLongDayNames do
begin
Parent := PgDateTime;
Left := CbShortDateformat.Left;
Width := FEdLongMonthNames.Width;
Top := CbShortDateFormat.Top + 32*4;
TabOrder := CbShortDateFormat.TabOrder + 4;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
end;
LblLongDayNames.FocusControl := FEdLongDayNames;
FEdShortDayNames := TMonthDayNamesEdit.Create(self);
with FEdShortDayNames do
begin
Parent := PgDateTime;
Left := CbShortDateFormat.Left;
Width := FEdLongMonthNames.Width;
Top := CbShortDateFormat.Top + 32*5;
TabOrder := CbShortDateFormat.TabOrder + 5;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
end;
LblShortDayNames.FocusControl := FEdShortDayNames;
FCbTimeSeparator := TFormatSeparatorCombo.Create(self);
with FCbTimeSeparator do
begin
Parent := PgDateTime;
Left := CbShortTimeFormat.Left;
Width := w;
Top := CbShortTimeFormat.Top + 32;
TabOrder := CbShortTimeFormat.TabOrder + 1;
SeparatorKind := skTime;
OnChange := @DateTimeFormatChange;
OnEnter := @DateTimeFormatChange;
end;
LblTimeSeparator.FocusControl := FCbTimeSeparator;
FDateFormatSample := '';
FTimeFormatSample := '';
FSampleDateTime := now();
LblDateTimeSample.Visible := false;
// Published property not available in old Laz versions
EdCurrencyDecimals.Alignment := taRightJustify;
end;
procedure TFormatSettingsForm.OKButtonClick(Sender: TObject);
var
msg: String;
C: TWinControl;
cParent: TWinControl;
begin
if not ValidData(C, msg) then
begin
cParent := C.Parent;
while (cParent <> nil) and not (cParent is TTabSheet) do
cParent := cParent.Parent;
PageControl.ActivePage := cParent as TTabSheet;
if C.CanFocus then C.SetFocus;
MessageDlg(msg, mtError, [mbOK], 0);
ModalResult := mrNone;
end;
end;
procedure TFormatSettingsForm.PageControlChange(Sender: TObject);
begin
LblDateTimeSample.Visible := (PageControl.Activepage = PgDateTime) and
((FDateFormatSample <> '') or (FTimeFormatSample <> ''));
end;
function TFormatSettingsForm.GetFormatSettings: TFormatSettings;
begin
Result := DefaultFormatSettings;
// --- Number format parameters --
// Decimal separator
Result.DecimalSeparator := FCbDecimalSeparator.Separator;
// Thousand separator
Result.ThousandSeparator := FCbThousandSeparator.Separator;
if Result.DecimalSeparator = '.' then
Result.ListSeparator := ','
else if Result.DecimalSeparator = ',' then
Result.ListSeparator := ';';
// --- Currency format parameters ---
// Currency symbol
Result.CurrencyString := EdCurrencySymbol.Text;
// Currency decimal places
Result.CurrencyDecimals := EdCurrencyDecimals.Value;
// Positive currency format
Result.CurrencyFormat := CbPosCurrencyFormat.ItemIndex;
// Negative currency format
Result.NegCurrFormat := CbNegCurrencyFormat.ItemIndex;
// --- Date format parameters ---
// Long date format string
Result.LongDateFormat := CbLongDateFormat.Text;
// Short date format string
Result.ShortDateFormat := CbShortDateFormat.Text;
// Date separator
Result.DateSeparator := FCbDateSeparator.Separator;
// Long month names
FEdLongMonthNames.GetNames(Result.LongMonthNames);
// Short month names
FEdShortMonthNames.GetNames(Result.ShortMonthNames);
// Long day names
FEdLongDayNames.GetNames(Result.LongDayNames);
// Short day names
FEdShortDayNames.GetNames(Result.ShortDayNames);
// --- Time format parameters ---
// Long time format string
Result.LongTimeFormat := CbLongTimeFormat.Text;
// Short time format string
Result.ShortTimeFormat := CbShortTimeFormat.Text;
// Time separator
Result.TimeSeparator := FCbTimeSeparator.Separator;
end;
procedure TFormatSettingsForm.SetFormatSettings(const AValue: TFormatSettings);
var
i: Integer;
begin
// --- Number format parameters ---
FCbDecimalSeparator.Separator := AValue.DecimalSeparator;
FCbThousandSeparator.Separator := AValue.ThousandSeparator;
// --- Currency format parameters ---
// Currency symbol
EdCurrencySymbol.Text := AValue.CurrencyString;
// Currency decimal places
EdCurrencyDecimals.Value := AValue.CurrencyDecimals;
// Positive currency format
CbPosCurrencyFormat.ItemIndex := AValue.CurrencyFormat;
// Negative currency format
CbNegCurrencyFormat.ItemIndex := AValue.NegCurrFormat;
// --- Date format parameters ---
// Long date format string
i := CbLongDateFormat.Items.IndexOf(AValue.LongDateFormat);
if i = -1 then
CbLongDateFormat.ItemIndex := CbLongDateFormat.Items.Add(AValue.LongDateFormat)
else
CbLongDateFormat.ItemIndex := i;
// Short date format string
i := CbShortDateFormat.Items.IndexOf(AValue.ShortDateFormat);
if i = -1 then
CbShortDateFormat.ItemIndex := CbShortDateFormat.items.Add(AValue.ShortDateFormat)
else
CbShortDateFormat.ItemIndex := i;
// Date separator
FCbDateSeparator.Separator := AValue.DateSeparator;
// Long month names
FEdLongMonthNames.SetNames(AValue.LongMonthNames, 12, false, 'Error');
// Short month names
FEdShortMonthNames.SetNames(AValue.ShortMonthNames, 12, true, 'Error');
// Long day names
FEdLongDayNames.SetNames(AValue.LongDayNames, 7, false, 'Error');
// Short month names
FEdShortDayNames.SetNames(AValue.ShortDayNames, 7, true, 'Error');
// --- Time format parameters ---
// Long time format string
i := CbLongTimeFormat.items.IndexOf(AValue.LongTimeFormat);
if i = -1 then
CbLongTimeFormat.ItemIndex := CbLongTimeFormat.Items.Add(AValue.LongTimeFormat)
else
CbLongTimeFormat.ItemIndex := i;
// Short time format string
i := cbShortTimeFormat.Items.IndexOf(AValue.ShortTimeFormat);
if i = -1 then
CbShortTimeFormat.itemIndex := CbShortTimeFormat.Items.Add(AValue.ShortTimeFormat);
// Time separator
FCbTimeSeparator.Separator := AValue.TimeSeparator;
end;
function TFormatSettingsForm.ValidData(out AControl: TWinControl;
out AMsg: String): Boolean;
begin
Result := false;
if FCbDecimalSeparator.Separator = FCbThousandSeparator.Separator then
begin
AControl := FCbDecimalSeparator;
AMsg := 'Decimal and thousand separators cannot be the same.';
exit;
end;
Result := true;
end;
//initialization
// {$I sformatsettingsform.lrs}
end.
|
unit frmUserNew;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, uUserInfo;
type
TfUserNew = class(TForm)
pgc1: TPageControl;
ts1: TTabSheet;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl6: TLabel;
lbl7: TLabel;
edtLognName: TEdit;
edtName: TEdit;
edtDesc: TEdit;
edtPass: TEdit;
edtYesPass: TEdit;
ts2: TTabSheet;
lbl4: TLabel;
lbl5: TLabel;
cbbGroup: TComboBox;
lvGroup: TListView;
btnOK: TButton;
btnCancel: TButton;
lblNotice: TLabel;
procedure btnCancelClick(Sender: TObject);
procedure cbbGroupChange(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
FUserInfo : TUser;
procedure ShowRights;
public
{ Public declarations }
procedure ShowInfo(AUserInfo : TUser);
procedure SaveInfo;
end;
var
fUserNew: TfUserNew;
implementation
uses
uUserControl, xFunction;
{$R *.dfm}
{ TfUserNew }
procedure TfUserNew.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfUserNew.btnOKClick(Sender: TObject);
procedure CheckUser;
begin
if UserControl.CheckUNameExists(Trim(edtLognName.Text)) then
begin
MessageBox(0, '该名称已存在,请使用其他名称!', '错误', mrok);
pgc1.ActivePageIndex := 0;
edtLognName.SetFocus;
end
else
begin
ModalResult := mrOk;
end;
end;
begin
if Trim(edtLognName.Text) = '' then
begin
MessageBox(0, '名称不能为空!', '错误', mrok);
pgc1.ActivePageIndex := 0;
edtLognName.SetFocus;
end
else if edtPass.Text <> edtYesPass.Text then
begin
MessageBox(0, '两次输入的密码不一致,请重新输入!', '错误', mrok);
pgc1.ActivePageIndex := 0;
edtPass.SetFocus;
end
else
begin
if Assigned(FUserInfo) then
begin
if Assigned(UserControl) then
begin
if FUserInfo.ID = -1 then
begin
CheckUser;
end
else
begin
if FUserInfo.Embedded then
ModalResult := mrCancel
else
begin
if FUserInfo.LoginName <> Trim(edtLognName.Text) then
CheckUser
else
ModalResult := mrOk;
end;
end;
end;
end;
end;
end;
procedure TfUserNew.cbbGroupChange(Sender: TObject);
begin
ShowRights;
end;
procedure TfUserNew.SaveInfo;
begin
if Assigned(FUserInfo) then
begin
FUserInfo.LoginName := Trim( edtLognName.Text );
FUserInfo.FullName := edtName.Text;
FUserInfo.Description := edtDesc.Text;
if edtPass.Visible then
FUserInfo.Password := Trim( edtPass.Text ) ;
with cbbGroup do
FUserInfo.GroupID := TUserGroup( Items.Objects[ ItemIndex ] ).ID;
end;
end;
procedure TfUserNew.ShowInfo(AUserInfo: TUser);
var
AGroupList : TStringList;
i : integer;
begin
FUserInfo := AUserInfo;
if Assigned(FUserInfo) then
begin
if Assigned(UserControl) then
begin
AGroupList := UserControl.UserGroupList;
cbbGroup.Clear;
cbbGroup.Items.Clear;
for i := 0 to AGroupList.Count - 1 do
begin
cbbGroup.Items.AddObject(TUserGroup(AGroupList.Objects[i]).GroupName,
AGroupList.Objects[i]);
end;
if cbbGroup.Items.Count > 0 then
cbbGroup.ItemIndex := 0;
edtLognName.Text := FUserInfo.LoginName;
edtName.Text := FUserInfo.FullName;
edtDesc.Text := FUserInfo.Description;
if FUserInfo.ID <> -1 then
begin
for i := 0 to AGroupList.Count - 1 do
begin
with TUserGroup(AGroupList.Objects[i]) do
begin
if FUserInfo.GroupID = ID then
begin
cbbGroup.ItemIndex := i;
Break;
end;
end;
end;
// 隐藏密码修改
lbl6.Visible := False;
lbl7.Visible := False;
edtPass.Visible := False;
edtYesPass.Visible := False;
end;
ShowRights;
if FUserInfo.Embedded then
begin
ts1.Enabled := False;
ts2.Enabled := False;
lblNotice.Caption := '系统内置,不能编辑修改';
lblNotice.Visible := True;
end;
end;
end;
end;
procedure TfUserNew.ShowRights;
var
oGroup : TUserGroup;
i : Integer;
begin
// 读取当前组的权限
if cbbGroup.ItemIndex = -1 then
Exit;
with cbbGroup do
oGroup := TUserGroup( Items.Objects[ ItemIndex ] );
// 显示权限
lvGroup.Clear;
for i := 0 to oGroup.Rights.Count - 1 do
with lvGroup.Items.Add, TUserRight( oGroup.Rights.Objects[ i ] ) do
begin
Caption := RightName;
SubItems.Add( Description );
end;
end;
end.
|
{
Version 12
Copyright (c) 1995-2008 by L. David Baldwin,
Copyright (c) 2008-2010 by HtmlViewer Team
Copyright (c) 2011-2012 by Bernd Gabriel
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.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit HtmlIndentation;
interface
uses
{$ifdef LCL}
LclIntf, IntfGraphics, FpImage, LclType, LResources, LMessages, HtmlMisc,
{$else}
Windows,
{$endif}
SysUtils, Contnrs, Math, //Classes, //Graphics, ClipBrd, Controls, Messages, Variants, Types,
HtmlGlobals;
//------------------------------------------------------------------------------
// TSketchMap manages the placing of floating boxes and the flow of inline
// elements around the floating boxes.
//------------------------------------------------------------------------------
type
EIndentationException = class(Exception);
// BG, 27.08.2011: copied and modified IndentRec of HtmlViewer11
TIndentation = class
private
// all coordinates relative to the containing box: (x=0, y=0) is the upper left edge of the containing box.
FX: Integer; // if left indentation: the first available x-coordinate to the right of this indentation.
// if right indentation: the first unavailable x-coordinate due to this indentation.
FYT: Integer; // top Y inclusive coordinate of this indentation.
FYB: Integer; // bottom Y exclusive coordinate of this indentation.
public
constructor Create(X, YT, YB: Integer);
property X: Integer read FX;
property YT: Integer read FYT;
property YB: Integer read FYB;
end;
// BG, 27.08.2011:
TIndentationList = class(TObjectList)
private
function getIndentation(Index: Integer): TIndentation;
public
function GetMaxYB: Integer;
property Items[Index: Integer]: TIndentation read getIndentation; default;
end;
// BG, 27.08.2011: copied and modified TIndentManager of HtmlViewer11
TSketchMap = class
private
L: TIndentationList; // list of left/top hand indentations.
R: TIndentationList; // list of right/bottom hand indentations.
Width: Integer; // width of the managed box.
function LeftEdge(Y: Integer): Integer;
function RightEdge(Y: Integer): Integer;
public
constructor Create(Width: Integer);
destructor Destroy; override;
function AddLeft(YT, YB, W: Integer): TIndentation;
function AddRight(YT, YB, W: Integer): TIndentation;
function AlignLeft(var Y: Integer; W: Integer; SpW: Integer = 0; SpH: Integer = 0): Integer;
function AlignRight(var Y: Integer; W: Integer; SpW: Integer = 0; SpH: Integer = 0): Integer;
function GetNextWiderY(Y: Integer): Integer;
function GetClearY: Integer; overload;
function GetClearLeftY: Integer; overload;
function GetClearRightY: Integer; overload;
end;
ESketchMapStackException = class(EIndentationException);
// BG, 28.08.2011:
TSketchMapStack = class
private
FStack: TStack;
function getTop: TSketchMap;
public
constructor Create;
destructor Destroy; override;
procedure Push(IM: TSketchMap);
function Pop: TSketchMap;
property Top: TSketchMap read getTop;
end;
implementation
{ TIndentation }
//-- BG ---------------------------------------------------------- 27.08.2011 --
constructor TIndentation.Create(X, YT, YB: Integer);
begin
inherited Create;
FX := X;
FYT := YT;
FYB := YB;
end;
{ TIndentationList }
//-- BG ---------------------------------------------------------- 27.08.2011 --
function TIndentationList.getIndentation(Index: Integer): TIndentation;
begin
Result := Get(Index);
end;
//-- BG ---------------------------------------------------------- 27.08.2011 --
function TIndentationList.GetMaxYB: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to Count - 1 do
with Items[I] do
if YB > Result then
Result := YB;
end;
{ TIndentationManager }
//-- BG ---------------------------------------------------------- 27.08.2011 --
constructor TSketchMap.Create(Width: Integer);
begin
inherited Create;
Self.Width := Width;
R := TIndentationList.Create;
L := TIndentationList.Create;
end;
//-- BG ---------------------------------------------------------- 27.08.2011 --
destructor TSketchMap.Destroy;
begin
R.Free;
L.Free;
inherited Destroy;
end;
//-- BG ---------------------------------------------------------- 05.02.2011 --
function TSketchMap.AddLeft(YT, YB, W: Integer): TIndentation;
// Adds the indentation due to a box floating to the left.
// Returns the added indentation with Result.X being the first pixel to the right of the box.
// Thus Result.X is the right x-coordinate of the box and Result.X - W the left.
begin
Result := TIndentation.Create(LeftEdge(YT) + W, YT, YB);
L.Add(Result);
end;
//-- BG ---------------------------------------------------------- 05.02.2011 --
function TSketchMap.AddRight(YT, YB, W: Integer): TIndentation;
// Adds the indentation due to a box floating to the right.
// Returns the added indentation with Result.X being the first pixel of the box.
// Thus Result.X is the left x-coordinate of the box and Result.X + W the right.
begin
Result := TIndentation.Create(RightEdge(YT) - W, YT, YB);
R.Add(Result);
end;
////-- BG ---------------------------------------------------------- 23.02.2011 --
//procedure TSketchMap.Init(Width: Integer);
//begin
// Self.Width := Width;
// R.Clear;
// L.Clear;
//end;
const
BigY = 9999999;
//-- BG ---------------------------------------------------------- 23.02.2011 --
function TSketchMap.LeftEdge(Y: Integer): Integer;
// Returns the right most left indentation at Y.
// If there are no left indentations at Y, returns 0.
var
I: Integer;
IR: TIndentation;
MinX: Integer;
begin
Result := -MaxInt;
MinX := 0;
for I := 0 to L.Count - 1 do
begin
IR := L.Items[I];
if (Y >= IR.YT) and (Y < IR.YB) and (Result < IR.X) then
Result := IR.X;
end;
if Result = -MaxInt then
Result := MinX;
end;
//-- BG ---------------------------------------------------------- 23.02.2011 --
function TSketchMap.RightEdge(Y: Integer): Integer;
// Returns the left most right indentation at Y.
// If there are no indentations at Y, returns Width.
var
I: Integer;
IR: TIndentation;
begin
Result := MaxInt;
for I := 0 to R.Count - 1 do
begin
IR := R.Items[I];
if (Y >= IR.YT) and (Y < IR.YB) and (Result > IR.X) then
Result := IR.X;
end;
if Result = MaxInt then
Result := Width;
end;
//------------------------------------------------------------------------------
function TSketchMap.GetClearY: Integer;
// Returns the bottom most bottom of all floating boxes.
begin
Result := Max(L.GetMaxYB, R.GetMaxYB);
end;
//-- BG ---------------------------------------------------------- 27.08.2011 --
function TSketchMap.GetClearLeftY: Integer;
// Returns the bottom most bottom of all boxes floating to the left.
begin
Result := L.GetMaxYB;
end;
//-- BG ---------------------------------------------------------- 27.08.2011 --
function TSketchMap.GetClearRightY: Integer;
// Returns the bottom most bottom of all boxes floating to the right.
begin
Result := R.GetMaxYB;
end;
//-- BG ---------------------------------------------------------- 06.02.2011 --
function TSketchMap.AlignLeft(var Y: Integer; W, SpW, SpH: Integer): Integer;
// Returns the aligned Y position of a box of width W starting at Y.
// Result is > Y, if available width at Y is too small for the block and optional additional space Sp
// Additional space e.g. for a textRec between aligned images.
var
I, CL, CR, LX, RX, XL, XR, YY, MinX: Integer;
begin
Result := LeftEdge(Y);
if Result + W + SpW > RightEdge(Y) then
begin
// too wide, must find a wider place below:
if (SpH > 0) and (Result + W <= RightEdge(Y + SpH)) then
begin
// fits into area below space Sp
Inc(Y, SpH);
end
else
begin
// too small, must find a wider place below:
YY := Y;
MinX := 0;
CL := Y;
XL := Result; // valium for the compiler
for I := L.Count - 1 downto 0 do
with L.Items[I] do
begin
if (YB > Y) and ((YB < CL) or (CL = Y)) then
begin
if X = LeftEdge(YB - 1) then
begin
// This is the right most left indentation
LX := LeftEdge(YB);
RX := RightEdge(YB) - W;
if YY < YB then
YY := YB;
if RX >= LX then
begin
CL := YB;
XL := LX;
end;
end;
end;
end;
CR := Y;
XR := Result; // valium for the compiler
for I := R.Count - 1 downto 0 do
with R.Items[I] do
begin
if (YB > Y) and ((YB < CR) or (CR = Y)) then
begin
if X = RightEdge(YB - 1) then
begin
// This is the left most right indentation
LX := LeftEdge(YB);
RX := RightEdge(YB) - W;
if YY < YB then
YY := YB;
if RX >= LX then
begin
CR := YB;
XR := LX;
end;
end;
end;
end;
if CL = Y then
begin
if CR = Y then
begin
// no better place found, just append at the end.
Y := YY;
Result := MinX;
end
else
begin
Y := CR;
Result := XR;
end
end
else if CR = Y then
begin
Y := CL;
Result := XL;
end
else if CL < CR then
begin
Y := CL;
Result := XL;
end
else
begin
Y := CR;
Result := XR;
end;
end;
end;
end;
function TSketchMap.AlignRight(var Y: Integer; W, SpW, SpH: Integer): Integer;
// Returns the aligned Y position of a box of width W starting at Y.
// Result is > Y, if available width at Y is too small for the block and optional additional space Sp
// Additional space e.g. for a textRec between aligned images.
var
I, CL, CR, LX, RX, XL, XR, YY, MaxX: Integer;
begin
Result := RightEdge(Y) - W;
if Result < LeftEdge(Y) + SpW then
begin
// too small, must find a wider place below:
if (SpH > 0) and (Result >= LeftEdge(Y + SpH)) then
begin
// fits into area below space Sp
Inc(Y, SpH);
end
else
begin
YY := Y;
MaxX := Width - W;
CL := Y;
XL := Result; // valium for the compiler
for I := L.Count - 1 downto 0 do
with L.Items[I] do
begin
if (YB > Y) and ((YB < CL) or (CL = Y)) then
begin
if X = LeftEdge(YB - 1) then
begin
// This is the right most left indentation
LX := LeftEdge(YB);
RX := RightEdge(YB) - W;
if YY < YB then
YY := YB;
if RX >= LX then
begin
CL := YB;
XL := RX;
end;
end;
end;
end;
CR := Y;
XR := Result; // valium for the compiler
for I := R.Count - 1 downto 0 do
with R.Items[I] do
begin
if (YB > Y) and ((YB < CR) or (CR = Y)) then
begin
if X = RightEdge(YB - 1) then
begin
// This is the left most right indentation
LX := LeftEdge(YB);
RX := RightEdge(YB) - W;
if YY < YB then
YY := YB;
if RX >= LX then
begin
CR := YB;
XR := RX;
end;
end;
end;
end;
if CL = Y then
begin
if CR = Y then
begin
// no better place found, just append at the end.
Y := YY;
Result := MaxX;
end
else
begin
Y := CR;
Result := XR;
end
end
else if CR = Y then
begin
Y := CL;
Result := XL;
end
else if CL < CR then
begin
Y := CL;
Result := XL;
end
else
begin
Y := CR;
Result := XR;
end;
end;
end;
end;
function TSketchMap.GetNextWiderY(Y: Integer): Integer;
// Returns the next Y value which offers a wider space or Y if none
var
I, CL, CR: Integer;
begin
CL := Y;
for I := 0 to L.Count - 1 do
with L.Items[I] do
if (YB > Y) and ((YB < CL) or (CL = Y)) then
CL := YB;
CR := Y;
for I := 0 to R.Count - 1 do
with R.Items[I] do
if (YB > Y) and ((YB < CR) or (CR = Y)) then
CR := YB;
if CL = Y then
Result := CR
else if CR = Y then
Result := CL
else
Result := Min(CL, CR);
end;
{ TIndentationManagerStack }
//-- BG ---------------------------------------------------------- 17.12.2011 --
constructor TSketchMapStack.Create;
begin
inherited Create;
FStack := TStack.Create;
end;
//-- BG ---------------------------------------------------------- 28.08.2011 --
destructor TSketchMapStack.Destroy;
begin
while Top <> nil do
Pop.Free;
FStack.Free;
end;
//-- BG ---------------------------------------------------------- 17.12.2011 --
function TSketchMapStack.getTop: TSketchMap;
begin
if FStack.AtLeast(1) then
Result := FStack.Peek
else
Result := nil;
end;
//-- BG ---------------------------------------------------------- 28.08.2011 --
function TSketchMapStack.Pop: TSketchMap;
begin
if Top = nil then
raise ESketchMapStackException.Create('Cannot pop from empty stack.');
Result := FStack.Pop;
end;
//-- BG ---------------------------------------------------------- 28.08.2011 --
procedure TSketchMapStack.Push(IM: TSketchMap);
begin
if IM = nil then
raise ESketchMapStackException.Create('Must not push nil onto the stack.');
FStack.Push(IM);
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Seagate.NotSSD;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TSeagateNotSSDSMARTSupport = class(TSMARTSupport)
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(const SMARTList: TSMARTValueList): Boolean;
override;
end;
implementation
{ TSeagateNotSSDSMARTSupport }
function TSeagateNotSSDSMARTSupport.GetTypeName: String;
begin
result := 'Smart';
end;
function TSeagateNotSSDSMARTSupport.IsSSD: Boolean;
begin
result := false;
end;
function TSeagateNotSSDSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(FindAtFirst('STT', IdentifyDevice.Model)) and
(Find('ST', IdentifyDevice.Model)) and
(not CheckIsSSDInCommonWay(IdentifyDevice));
end;
function TSeagateNotSSDSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := true;
end;
function TSeagateNotSSDSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TSeagateNotSSDSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
begin
FillChar(result, SizeOf(result), 0);
end;
end.
|
unit iaExample.CDE.ParallelTask;
interface
uses
System.Classes,
System.SyncObjs;
type
TExampleParallelTask = class(TThread)
private
fCDE:TCountdownEvent;
protected
procedure Execute(); override;
procedure DoSomeWork();
public
constructor Create(const pCDE:TCountdownEvent);
end;
implementation
uses
System.SysUtils;
constructor TExampleParallelTask.Create(const pCDE:TCountdownEvent);
begin
fCDE := pCDE;
FreeOnTerminate := True;
inherited Create(False);
end;
procedure TExampleParallelTask.Execute();
begin
NameThreadForDebugging('ExampleCDEWorkerThread');
DoSomeWork();
fCDE.Signal();
end;
procedure TExampleParallelTask.DoSomeWork();
begin
Sleep(Random(2000));
end;
end.
|
unit Security4D.UnitTest.Authenticator;
interface
uses
System.SysUtils,
Security4D,
Security4D.Impl,
Security4D.UnitTest.Credential;
type
TAuthenticator = class(TSecurityProvider, IAuthenticator)
private
fAuthenticated: Boolean;
fAuthenticatedUser: IUser;
protected
function GetAuthenticatedUser: IUser;
procedure Authenticate(user: IUser);
procedure Unauthenticate;
public
procedure AfterConstruction; override;
end;
implementation
{ TAuthenticator }
procedure TAuthenticator.AfterConstruction;
begin
inherited;
fAuthenticated := False;
fAuthenticatedUser := nil;
end;
procedure TAuthenticator.Authenticate(user: IUser);
var
username, password: string;
begin
fAuthenticated := False;
fAuthenticatedUser := nil;
if not Assigned(user) then
raise EAuthenticationException.Create('User not set to security layer.');
username := TCredential(user.Attribute).Username;
password := TCredential(user.Attribute).Password;
if (username.Equals('bob')) and (password.Equals('bob')) then
fAuthenticated := True
else if (username.Equals('jeff')) and (password.Equals('jeff')) then
fAuthenticated := True
else if (username.Equals('nick')) and (password.Equals('nick')) then
fAuthenticated := True;
if fAuthenticated then
fAuthenticatedUser := user
else
raise EAuthenticationException.Create('Unauthenticated user.');
end;
function TAuthenticator.GetAuthenticatedUser: IUser;
begin
Result := fAuthenticatedUser;
end;
procedure TAuthenticator.Unauthenticate;
begin
fAuthenticated := False;
fAuthenticatedUser := nil;
end;
end.
|
unit adot.Win.HookClassMethods;
// AH: Simple API to hook some method calls of some classes.
// Based on the code from SQLite3i18n.pas (Synopse SQLite3 database framework).
// According to this unit, "hook logic was inspired from GetText()".
// So initially it is based on GetText library.
interface
uses
Windows, SysUtils, System.Generics.Collections, System.Generics.Defaults;
type
{
Low level API for hooking of any method/procedure at specified address. Example:
var
FormDoCreate: TPatchRecord; // global var
Type THookedForm = class(TCustomForm)
procedure HookedDoCreate; // this method will be called instead of standard TCustomForm.DoCreate
end;
procedure THookedForm.HookedDoCreate;
begin
Caption := Caption + ' before'; // do something before original code will be called
FormDoCreate.DisableHook;
try
DoCreate; // call original procedure (without hook, otherwise we get infinite cycle and stack overflow).
finally
FormDoCreate.EnableHook;
end;
Caption := Caption + ' after'; // do something when original code already executed
end;
initialization // install hook at unit initialization
FormDoCreate.InstallHook(@THookedForm.DoCreate, @THookedForm.HookedDoCreate);
finalization // uninstall hook at unit deinitialization (not neccessary in this case, just for demonstration)
FormDoCreate.RemoveHook;
}
PPatchCode = ^TPatchCode;
TPatchCode = packed record
Jump : byte; // asm opcode to patch an existing routine (JMP xxx)
Offset : integer;
end;
TPatchRecord = record
NewCode, OriginalCode: TPatchCode;
PatchPos: PPatchCode;
HookInstalled: string; // HookInstalled<>'' after successfull InstallHook
procedure InstallHook(AOriginalProc, AHookProc: pointer);
procedure UninstallHook;
function Installed: Boolean; {$IFNDEF DEBUG}inline;{$ENDIF}
procedure DisableHook; {$IFNDEF DEBUG}inline;{$ENDIF}
procedure EnableHook; {$IFNDEF DEBUG}inline;{$ENDIF}
end;
(*
// Example (manager for hooking of TdxBarManagerMDIStateHelper.DoActiveChildChanged):
unit HookDxBarMethods;
interface
uses
dxBar, HookClassMethods, System.SysUtils, Winapi.Windows;
type
TOnDoActiveChildChanged = reference to procedure(
AObj: TdxBarManagerMDIStateHelper;
const ANewActiveChild, AOldActiveChild: HWND;
ABeforeOriginalCode: Boolean);
TdxBarManagerMDIStateHelperHook = class(TdxBarManagerMDIStateHelper)
public
procedure Hook_DoActiveChildChanged(const ANewActiveChild, AOldActiveChild: HWND);
end;
var
DoActiveChildChanged_HookManager: TMethodHookManager<TOnDoActiveChildChanged>;
implementation
procedure TdxBarManagerMDIStateHelperHook.Hook_DoActiveChildChanged(
const ANewActiveChild, AOldActiveChild: HWND);
var
h: TOnDoActiveChildChanged;
begin
for h in DoActiveChildChanged_HookManager.Handlers.Values do
h(Self, ANewActiveChild, AOldActiveChild, True);
DoActiveChildChanged_HookManager.DisableHook;
try
inherited DoActiveChildChanged(ANewActiveChild, AOldActiveChild);
finally
DoActiveChildChanged_HookManager.EnableHook;
end;
for h in DoActiveChildChanged_HookManager.Handlers.Values do
h(Self, ANewActiveChild, AOldActiveChild, False);
end;
initialization
DoActiveChildChanged_HookManager := TMethodHookManager<TOnDoActiveChildChanged>.Create(
@TdxBarManagerMDIStateHelperHook.DoActiveChildChanged,
@TdxBarManagerMDIStateHelperHook.Hook_DoActiveChildChanged);
finalization
FreeAndNil(DoActiveChildChanged_HookManager);
end.
// Hot to use such manager:
procedure OnDoActiveChildChanged(AObj: TdxBarManagerMDIStateHelper;
const ANewActiveChild, AOldActiveChild: HWND; ABeforeOriginalCode: Boolean);
begin
// ...
end;
initialization
DoActiveChildChanged_HookManager.RegHook(OnDoActiveChildChanged);
*)
TMethodHookManager<T> = class
protected
class var
IdCounter: int64;
var
Patch: TPatchRecord;
public
Handlers: TDictionary<int64, T>;
constructor Create(AOriginalProc, AHookProc: pointer);
destructor Destroy; override;
procedure DisableHook;
procedure EnableHook;
// user-friendly interface to hook
function RegHook(AHandler: T):Int64;
function UnregHook(const AHookId: int64):Boolean;
end;
implementation
function TPatchRecord.Installed: Boolean;
begin
result := HookInstalled<>'';
end;
procedure TPatchRecord.InstallHook(AOriginalProc, AHookProc: pointer);
var
OldProtect: Cardinal;
begin
PatchPos := AOriginalProc;
OriginalCode := PatchPos^;
NewCode.Jump := $E9; // Jmp opcode
NewCode.Offset := PByte(AHookProc)-PByte(PatchPos)-SizeOf(TPatchCode);
if not VirtualProtect(PatchPos, SizeOf(TPatchCode), PAGE_EXECUTE_READWRITE, @OldProtect) then
RaiseLastOSError;
// Empty static function may have single "RET" instruction.
// For patch we need 5 bytes at least, so we can't patch such functions.
Assert(PByte(PatchPos)^<>$C3, 'Too short to patch...');
EnableHook;
HookInstalled := 'Y';
end;
procedure TPatchRecord.UninstallHook;
begin
if Installed then
begin
HookInstalled := '';
DisableHook;
end;
end;
procedure TPatchRecord.EnableHook;
begin
PatchPos^ := NewCode;
end;
procedure TPatchRecord.DisableHook;
begin
PatchPos^ := OriginalCode;
end;
{ TMethodHookManager<T> }
constructor TMethodHookManager<T>.Create(AOriginalProc, AHookProc: pointer);
begin
Handlers := TDictionary<int64, T>.Create;
Patch.InstallHook(AOriginalProc, AHookProc);
end;
destructor TMethodHookManager<T>.Destroy;
begin
if Patch.Installed then
Patch.DisableHook;
FreeAndNil(Handlers);
inherited;
end;
function TMethodHookManager<T>.RegHook(AHandler: T): Int64;
begin
inc(IdCounter);
Result := IdCounter;
Handlers.Add(Result, AHandler);
end;
procedure TMethodHookManager<T>.DisableHook;
begin
Patch.DisableHook;
end;
procedure TMethodHookManager<T>.EnableHook;
begin
Patch.EnableHook;
end;
function TMethodHookManager<T>.UnregHook(const AHookId: int64): Boolean;
begin
Result := Handlers.ContainsKey(AHookId);
if Result then
Handlers.Remove(AHookId);
end;
end.
|
unit UntAguarde;
interface
uses
System.UITypes,
System.SysUtils,
FMX.Types,
FMX.Controls,
FMX.StdCtrls,
FMX.Objects,
FMX.Forms,
FMX.Effects,
FMX.Layouts,
FMX.Edit,
FMX.Graphics,
FMX.Dialogs;
type
TAguarde = class
private
class var FAguarde : TRectangle;
class var FLytEdit : TLayout;
class var FFundo : TPanel;
class var FAniLoading : TAniIndicator;
class var FLabelMessage : TLabel;
class procedure TrocaCorPFundo(Sender: TObject);
public
class procedure Show(const AMessage: string = '');
class procedure ChangeMessage(const aMessage: string = '');
class procedure Hide;
end;
implementation
{ TAguarde }
class procedure TAguarde.ChangeMessage(const AMessage: string);
begin
if (Assigned(FLabelMessage)) and(FLabelMessage <> nil) then
try
FLabelMessage.Text := AMessage;
except
end;
end;
class procedure TAguarde.Hide;
begin
if (Assigned(FAguarde)) then
begin
FFundo.AnimateFloat('OPACITY', 0);
FAguarde.AnimateFloatWait('OPACTIY', 0);
try
if Assigned(fAniLoading) then
fAniLoading.DisposeOf;
if Assigned(fLabelMessage) then
fLabelMessage.DisposeOf;
if Assigned(FFundo) then
FFundo.DisposeOf;
if Assigned(FAguarde) then
FAguarde.DisposeOf;
except on E:Exception do
begin
ShowMessage(E.Message);
end;
end;
FFundo := nil;
FAguarde := nil;
FAniLoading := nil;
FLabelMessage := nil;
end;
end;
class procedure TAguarde.Show(const AMessage: string);
begin
FFundo := TPanel.Create(Application.MainForm);
FFundo.Parent := Application.MainForm;//AParent;
FFundo.Visible := True;
FFundo.Align := TAlignLayout.Contents;
FFundo.OnApplyStyleLookup := TrocaCorPFundo;
FAguarde := TRectangle.Create(Application.MainForm);
FAguarde.Parent := Application.MainForm;
FAguarde.Visible := True;
FAguarde.Height := 75;
FAguarde.Width := 275;
FAguarde.XRadius := 10;
FAguarde.YRadius := 10;
FAguarde.Position.X := (TForm(Application.MainForm).ClientWidth - FAguarde.Width) / 2;
FAguarde.Position.Y := (TForm(Application.MainForm).ClientHeight - FAguarde.Height) / 2;
FAguarde.Stroke.Kind := TBrushKind.None;
FAniLoading := TAniIndicator.Create(Application.MainForm);
FAniLoading.Visible := False;
FAniLoading.Enabled := False;
FAniLoading.Align := TAlignLayout.Left;
FAniLoading.Parent := FAguarde;
FAniLoading.Margins.Right := 10;
FAniLoading.Align := TAlignLayout.MostRight;
FAniLoading.Enabled := True;
FAniLoading.Visible := True;
with TLabel.Create(FAguarde) do
begin
Parent := FAguarde;
Align := TAlignLayout.Top;
Margins.Left := 10;
Margins.Top := 10;
Margins.Right := 10;
Height := 28;
StyleLookup := 'embossedlabel';
Text := 'Por favor, aguarde!';
Trimming := TTextTrimming.ttCharacter;
end;
FLabelMessage := TLabel.Create(Application.MainForm);
FLabelMessage.Parent := FAguarde;
FLabelMessage.Align := TAlignLayout.Client;
FLabelMessage.Margins.Left := 10;
FLabelMessage.Margins.Top := 10;
FLabelMessage.Margins.Right := 10;
FLabelMessage.Font.Size := 12;
FLabelMessage.StyledSettings := [TStyledSetting.ssFamily, TStyledSetting.ssStyle, TStyledSetting.ssFontColor];
FLabelMessage.Text := AMessage;
FLabelMessage.VertTextAlign := TTextAlign.taLeading;
FLabelMessage.Trimming := TTextTrimming.ttCharacter;
with TShadowEffect.Create(FAguarde) do
begin
Parent := FAguarde;
Enabled := True;
end;
FFundo.Opacity := 0;
FAguarde.Opacity := 0;
FFundo.Visible := True;
FAguarde.Visible := True;
FFundo.AnimateFloat('OPACITY', 0.5);
FAguarde.AnimateFloatWait('OPACITY', 1);
FAguarde.BringToFront;
FAguarde.SetFocus;
end;
class procedure TAguarde.TrocaCorPFundo(Sender: TObject);
var
Rectangle : TRectangle;
begin
Rectangle := (Sender as TFmxObject).Children[0] as TRectangle;
Rectangle.Fill.Color := TAlphaColors.Black;
end;
end.
|
unit Vigilante.Infra.Build.JSONDataAdapter.Impl;
interface
uses
System.JSON, Vigilante.Infra.Build.JSONDataAdapter, Vigilante.Aplicacao.SituacaoBuild,
Module.ValueObject.URL;
type
TBuildJSONDataAdapter = class(TInterfacedObject, IBuildJSONDataAdapter)
private
FJSON: TJSONObject;
FSituacaoBuild: TSituacaoBuild;
FBuildZero: integer;
FUltimoBuild: integer;
FUltimoCompleto: integer;
FUltimoEstavel: integer;
FUltimoSucesso: integer;
FUltimoInstavel: integer;
FUltimoSemSucesso: integer;
FUltimoFalhou: integer;
FURLUltimoBuild: IURL;
function TemValor(const AJSON: TJSONValue): boolean;
procedure CarregarBuildZero;
procedure CarregarUltimoBuild;
procedure CarregarUltimo(const ANode: string; out ANumero: integer);
function PegarNumeroDoBuild(const ABuild: TJSONObject): integer;
procedure CarregarSituacao;
procedure CarregarURLUltimoBuild;
protected
function GetBuilding: boolean;
function GetNome: string;
function GetSituacao: TSituacaoBuild;
function GetURL: string;
function GetBuildAtual: integer;
function GetUltimoBuildFalha: integer;
function GetUltimoBuildSucesso: integer;
function GetURLUltimoBuild: IURL;
public
constructor Create(const AJSON: TJSONObject);
end;
implementation
uses
System.SysUtils, System.Generics.Collections, Module.ValueObject.URL.Impl;
constructor TBuildJSONDataAdapter.Create(const AJSON: TJSONObject);
begin
FJSON := AJSON;
CarregarBuildZero;
CarregarUltimoBuild;
CarregarSituacao;
CarregarURLUltimoBuild;
end;
procedure TBuildJSONDataAdapter.CarregarBuildZero;
var
_build: TJSONArray;
_buildItem: TJSONObject;
begin
_build := FJSON.GetValue('builds') as TJSONArray;
_buildItem := _build.Items[0] as TJSONObject;
if not TemValor(_buildItem) then
Exit;
FBuildZero := PegarNumeroDoBuild(_buildItem);
end;
procedure TBuildJSONDataAdapter.CarregarUltimoBuild;
begin
CarregarUltimo('lastBuild', FUltimoBuild);
CarregarUltimo('lastCompletedBuild', FUltimoCompleto);
CarregarUltimo('lastFailedBuild', FUltimoFalhou);
CarregarUltimo('lastStableBuild', FUltimoEstavel);
CarregarUltimo('lastSuccessfulBuild', FUltimoSucesso);
CarregarUltimo('lastUnstableBuild', FUltimoInstavel);
CarregarUltimo('lastUnsuccessfulBuild', FUltimoSemSucesso);
end;
procedure TBuildJSONDataAdapter.CarregarURLUltimoBuild;
var
_lastBuild: TJSONObject;
_url: TJSONValue;
begin
_lastBuild := FJSON.GetValue('lastBuild') as TJSONObject;
if not TemValor(_lastBuild) then
Exit;
_url := _lastBuild.GetValue('url');
if not TemValor(_url) then
Exit;
FURLUltimoBuild := TURL.Create(_url.Value);
end;
procedure TBuildJSONDataAdapter.CarregarUltimo(const ANode: string;
out ANumero: integer);
var
_node: TJSONValue;
begin
ANumero := -1;
_node := FJSON.GetValue(ANode);
if not TemValor(_node) then
Exit;
ANumero := PegarNumeroDoBuild(_node as TJSONObject);
end;
function TBuildJSONDataAdapter.TemValor(const AJSON: TJSONValue): boolean;
begin
Result := False;
if not Assigned(AJSON) then
Exit;
if AJSON.Value.Equals('null') then
Exit;
Result := True;
end;
procedure TBuildJSONDataAdapter.CarregarSituacao;
var
_buildSemSucesso: boolean;
_buildCompletou: boolean;
_buildSucesso: boolean;
_buildFalha: boolean;
_buildAbortado: boolean;
begin
_buildCompletou := (FUltimoBuild = FUltimoCompleto);
_buildSemSucesso := (FUltimoBuild = FUltimoSemSucesso);
_buildFalha := _buildCompletou and _buildSemSucesso
and (FUltimoBuild = FUltimoFalhou);
_buildAbortado := _buildCompletou and _buildSemSucesso
and (FUltimoBuild <> FUltimoFalhou);
_buildSucesso := _buildCompletou and (FUltimoBuild = FUltimoEstavel)
or (FUltimoBuild = FUltimoSucesso);
if _buildSucesso then
begin
FSituacaoBuild := sbSucesso;
Exit;
end;
if _buildFalha then
begin
FSituacaoBuild := sbFalhou;
Exit;
end;
if _buildAbortado then
begin
FSituacaoBuild := sbAbortado;
Exit;
end;
if not _buildCompletou then
begin
FSituacaoBuild := sbProgresso;
Exit;
end;
FSituacaoBuild := sbUnknow;
end;
function TBuildJSONDataAdapter.PegarNumeroDoBuild(const ABuild: TJSONObject): integer;
var
_number: TJSONValue;
begin
Result := -1;
_number := ABuild.GetValue('number');
if not TemValor(_number) then
Exit;
Result := _number.AsType<integer>;
end;
function TBuildJSONDataAdapter.GetBuildAtual: integer;
begin
Result := FBuildZero;
end;
function TBuildJSONDataAdapter.GetBuilding: boolean;
begin
Result := FSituacaoBuild = sbProgresso;
end;
function TBuildJSONDataAdapter.GetNome: string;
begin
Result := FJSON.GetValue('displayName').Value;
end;
function TBuildJSONDataAdapter.GetSituacao: TSituacaoBuild;
begin
Result := FSituacaoBuild;
end;
function TBuildJSONDataAdapter.GetUltimoBuildFalha: integer;
begin
Result := FUltimoFalhou;
end;
function TBuildJSONDataAdapter.GetUltimoBuildSucesso: integer;
begin
Result := FUltimoSucesso;
end;
function TBuildJSONDataAdapter.GetURL: string;
begin
Result := FJSON.GetValue('url').Value;
end;
function TBuildJSONDataAdapter.GetURLUltimoBuild: IURL;
begin
Result := FURLUltimoBuild;
end;
end.
|
unit eSocial.Classes.Events;
interface
type
TEventsSplitViewChangeEvent = class
private
FOpened: Boolean;
procedure SetOpened(const Value: Boolean);
public
property Opened : Boolean read FOpened write SetOpened;
end;
implementation
{ TEventsSplitViewChangeEvent }
procedure TEventsSplitViewChangeEvent.SetOpened(const Value: Boolean);
begin
FOpened := Value;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 2000, 2001 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit ApacheHTTP;
interface
uses Classes, HTTPD, HTTPApp;
type
TApacheRequest = class(TWebRequest)
private
FContent: string;
FContentType: string;
FRequest_rec: Prequest_rec;
protected
function GetStringVariable(Index: Integer): string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
public
constructor Create(var r: request_rec);
function GetFieldByName(const Name: string): string; override;
function ReadClient(var Buffer; Count: Integer): Integer; override;
function ReadString(Count: Integer): string; override;
function TranslateURI(const URI: string): string; override;
function WriteClient(var Buffer; Count: Integer): Integer; override;
function WriteString(const AString: string): Boolean; override;
function WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean; override;
end;
TApacheResponse = class(TWebResponse)
private
FStatusCode: integer;
FReturnCode: integer;
FStringVariables: array[0..MAX_STRINGS - 1] of string;
FIntegerVariables: array[0..MAX_INTEGERS - 1] of Integer;
FDateVariables: array[0..MAX_DATETIMES - 1] of TDateTime;
FContent: string;
FLogMsg: string;
FSent: Boolean;
protected
function GetContent: string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetLogMessage: string; override;
function GetStatusCode: Integer; override;
function GetStringVariable(Index: Integer): string; override;
procedure SetContent(const Value: string); override;
procedure SetDateVariable(Index: Integer; const Value: TDateTime); override;
procedure SetIntegerVariable(Index: Integer; Value: Integer); override;
procedure SetLogMessage(const Value: string); override;
procedure SetStatusCode(Value: Integer); override;
procedure SetStringVariable(Index: Integer; const Value: string); override;
procedure InitResponse; virtual;
public
constructor Create(HTTPRequest: TWebRequest);
procedure SendResponse; override;
procedure SendRedirect(const URI: string); override;
procedure SendStream(AStream: TStream); override;
function Sent: Boolean; override;
property ReturnCode: integer read FReturnCode write FReturnCode;
end;
implementation
uses SysUtils, Math;
// TApacheRequest methods
constructor TApacheRequest.Create(var r: request_rec);
begin
FRequest_rec := @r;
FContent := '';
FContentType := FRequest_rec^.content_type;
// The ancestor's constructor must be called after fRequest_rec is initialized
inherited Create;
end;
function TApacheRequest.GetFieldByName(const Name: string): string;
begin
Result := ap_table_get(FRequest_rec^.headers_in, pchar(Name));
end;
function TApacheRequest.GetStringVariable(Index: Integer): string;
const
MaxChunkSize = 10240;
var
len, BytesRead, Size: Integer;
p, buf: pchar;
begin
case Index of
0: Result := FRequest_rec^.method;
1: Result := FRequest_rec^.protocol;
2: Result := FRequest_rec^.unparsed_uri;
3: Result := FRequest_rec^.args;
4: Result := FRequest_rec^.path_info;
5: Result := FRequest_rec^.filename;
7: Result := ''; // Request Date
8: Result := ap_table_get(FRequest_rec^.headers_in, 'Accept');
9: Result := ap_table_get(FRequest_rec^.headers_in, 'From');
10: Result := FRequest_rec^.hostname;
12: Result := ap_table_get(FRequest_rec^.headers_in, 'Referer');
13: Result := ap_table_get(FRequest_rec^.headers_in, 'User-Agent');
14: Result := FRequest_rec^.content_encoding;
15: Result := ap_table_get(FRequest_rec^.headers_in, 'Content-Type');
16: Result := ap_table_get(FRequest_rec^.headers_in, 'Content-Length');
19: Result := ''; // Expires
20: Result := ap_table_get(FRequest_rec^.headers_in, 'Title');
21: Result := FRequest_rec^.connection^.remote_ip;
22: Result := ap_get_remote_host(FRequest_rec^.connection, FRequest_rec^.per_dir_config, REMOTE_HOST);
23: begin
Result := FRequest_rec^.unparsed_uri;
p := Strscan(pchar(Result), '?');
if p <> nil then
len := p - pchar(Result)
else
len := length(Result);
Result := copy(Result, 1, len - length(PathInfo));
end;
24: Result := IntToStr(ap_get_server_port(FRequest_rec));
25: begin
if FContent = '' then
begin
ap_setup_client_block(FRequest_rec, REQUEST_CHUNKED_DECHUNK);
if ap_should_client_block(FRequest_rec) = 1 then
begin
BytesRead := 0;
SetLength(FContent, ContentLength);
buf := PChar(FContent);
Size := ContentLength;
while BytesRead < ContentLength do
begin
len := ap_get_client_block(FRequest_rec, buf, Min(MaxChunkSize, Size));
if len = 0 then
break;
Inc(BytesRead, len);
Inc(buf, len);
Dec(Size, len);
end;
SetLength(FContent, BytesRead);
end;
end;
Result := FContent;
end;
26: Result := ap_table_get(FRequest_rec^.headers_in, 'Connection');
27: Result := ap_table_get(FRequest_rec^.headers_in, 'Cookie');
else
Result := '';
end;
end;
function TApacheRequest.GetDateVariable(Index: Integer): TDateTime;
var
Value: string;
begin
Value := GetStringVariable(Index);
if Value <> '' then
Result := ParseDate(Value)
else Result := -1;
end;
function TApacheRequest.GetIntegerVariable(Index: Integer): Integer;
var
Value: string;
begin
Value := GetStringVariable(Index);
if Value <> '' then
Result := StrToInt(Value)
else Result := -1;
end;
function TApacheRequest.ReadClient(var Buffer; Count: Integer): Integer;
begin
// Use content property instead
Result := -1;
end;
function TApacheRequest.ReadString(Count: Integer): string;
var
Len: Integer;
begin
SetLength(Result, Count);
Len := ReadClient(Pointer(Result)^, Count);
SetLength(Result, Len);
end;
function TApacheRequest.TranslateURI(const URI: string): string;
begin
Result := ap_server_root_relative(FRequest_rec^.pool, pchar(URI));
{$IFDEF MSWINDOWS}
Result := UnixPathToDosPath(Result);
{$ENDIF}
end;
function TApacheRequest.WriteClient(var Buffer; Count: Integer): Integer;
begin
Result := 0;
if Count > 0 then
Result := ap_rwrite(Buffer, Count, FRequest_rec)
end;
function TApacheRequest.WriteString(const AString: string): Boolean;
begin
Result := true;
if Astring <> '' then
Result := ap_rputs(pchar(Astring), FRequest_rec) = length(Astring)
end;
function TApacheRequest.WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean;
begin
FRequest_rec.status := StatusCode;
ap_send_http_header(FRequest_rec);
Result := true;
end;
// TApacheResponse methods
constructor TApacheResponse.Create(HTTPRequest: TWebRequest);
begin
inherited Create(HTTPRequest);
InitResponse;
end;
procedure TApacheResponse.InitResponse;
begin
if FHTTPRequest.ProtocolVersion = '' then
Version := '1.0';
StatusCode := HTTP_OK;
ReturnCode := AP_OK;
LastModified := -1;
Expires := -1;
Date := -1;
ContentType := 'text/html';
end;
function TApacheResponse.GetContent: string;
begin
Result := FContent;
end;
function TApacheResponse.GetDateVariable(Index: Integer): TDateTime;
begin
if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then
Result := FDateVariables[Index]
else Result := 0.0;
end;
function TApacheResponse.GetIntegerVariable(Index: Integer): Integer;
begin
if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then
Result := FIntegerVariables[Index]
else Result := -1;
end;
function TApacheResponse.GetLogMessage: string;
begin
Result := fLogMsg;
end;
function TApacheResponse.GetStatusCode: Integer;
begin
result := FStatusCode;
end;
function TApacheResponse.GetStringVariable(Index: Integer): string;
begin
if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then
Result := FStringVariables[Index];
end;
function TApacheResponse.Sent: Boolean;
begin
Result := FSent;
end;
procedure TApacheResponse.SetContent(const Value: string);
begin
FContent := Value;
if ContentStream = nil then
ContentLength := Length(FContent);
end;
procedure TApacheResponse.SetDateVariable(Index: Integer; const Value: TDateTime);
begin
if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then
if Value <> FDateVariables[Index] then
FDateVariables[Index] := Value;
end;
procedure TApacheResponse.SetIntegerVariable(Index: Integer; Value: Integer);
begin
if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then
if Value <> FIntegerVariables[Index] then
FIntegerVariables[Index] := Value;
end;
procedure TApacheResponse.SetLogMessage(const Value: string);
begin
FLogMsg := Value;
end;
procedure TApacheResponse.SetStatusCode(Value: Integer);
begin
if FStatusCode <> Value then
begin
FStatusCode := Value;
ReasonString := StatusString(Value);
end;
end;
procedure TApacheResponse.SetStringVariable(Index: Integer; const Value: string);
begin
if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then
FStringVariables[Index] := Value;
end;
procedure TApacheResponse.SendResponse;
var
i: Integer;
ServerMsg: string;
procedure AddHeaderItem(const Key, Value: string);
begin
if (Key <> '') and (Value <> '') then
with TApacheRequest(FHTTPRequest) do
ap_table_set(FRequest_rec.headers_out, pchar(Key), pchar(Value));
end;
procedure AddCustomHeaders;
var
i: integer;
Name: string;
begin
for i := 0 to FCustomHeaders.Count - 1 do
begin
Name := FCustomHeaders.Names[I];
addHeaderItem(Name, FCustomHeaders.values[Name]);
end;
end;
begin
if HTTPRequest.ProtocolVersion <> '' then
begin
if StatusCode > 0 then
ServerMsg := Format('%d %s', [StatusCode, ReasonString]);
AddHeaderItem('Allow', Allow); {do not localize}
for I := 0 to Cookies.Count - 1 do
begin
if (Cookies[I].HeaderValue <> '') then
with TApacheRequest(FHTTPRequest) do
ap_table_add(FRequest_rec.headers_out, pchar('Set-Cookie'), {do not localize}
PChar(Cookies[I].HeaderValue));
end;
AddHeaderItem('Derived-From', DerivedFrom); {do not localize}
if Expires > 0 then
AddHeaderItem(Format(FormatDateTime(sDateFormat + ' "GMT"', {do not localize}
Expires), [DayOfWeekStr(Expires), MonthStr(Expires)]), 'Expires: %s'); {do not localize}
if LastModified > 0 then
AddHeaderItem(Format(FormatDateTime(sDateFormat +
' "GMT"', LastModified), [DayOfWeekStr(LastModified), {do not localize}
MonthStr(LastModified)]), 'Last-Modified: %s'); {do not localize}
AddHeaderItem('Title', Title); {do not localize}
AddHeaderItem('WWW-Authenticate', FormatAuthenticate); {do not localize}
AddCustomHeaders;
AddHeaderItem('Content-Version', ContentVersion); {do not localize}
if ContentType <> '' then
TApacheRequest(FHTTPRequest).FRequest_rec.content_type := ap_pstrdup(TApacheRequest(FHTTPRequest).FRequest_rec.pool, pchar(ContentType));
if ContentEncoding <> '' then
TApacheRequest(FHTTPRequest).FRequest_rec.content_encoding := ap_pstrdup(TApacheRequest(FHTTPRequest).FRequest_rec.pool, pchar(ContentEncoding));
if (Content <> '') or (ContentStream <> nil) then
AddHeaderItem('Content-Length', IntToStr(ContentLength)); {do not localize}
HTTPRequest.WriteHeaders(StatusCode, ServerMsg, '');
end;
if ContentStream = nil then
HTTPRequest.WriteString(Content)
else if ContentStream <> nil then
begin
SendStream(ContentStream);
ContentStream := nil; // Drop the stream
end;
FSent := True;
end;
procedure TApacheResponse.SendRedirect(const URI: string);
begin
with TApacheRequest(FHTTPRequest) do
begin
ap_table_set(FRequest_rec.headers_out, 'Location', pchar(URI)); {do not localize}
FStatusCode := REDIRECT;
end;
FSent := False;
end;
procedure TApacheResponse.SendStream(AStream: TStream);
var
Buffer: array[0..8191] of Byte;
BytesToSend: Integer;
begin
while AStream.Position < AStream.Size do
begin
BytesToSend := AStream.Read(Buffer, SizeOf(Buffer));
FHTTPRequest.WriteClient(Buffer, BytesToSend);
end;
end;
end.
|
unit NsLibSSH2Const;
{
version 1.0
}
interface
uses
Windows, libssh2_sftp, SysUtils;
const
AUTH_NONE = 0;
AUTH_PASSWORD = 1;
AUTH_PUBLICKEY = 2;
// Default values
DEFAULT_EMPTY_STR = '';
DEFAULT_SSH_PORT = 22;
DEFAULT_LOCAL_HOST = '127.0.0.1';
DEFAULT_REMOTE_HOST = '192.168.1.1';
DEFAULT_LOCAL_PORT = 3389;
DEFAULT_REMOTE_PORT = 3389;
// Max counts
MAX_CONNECTION_ATTEMPTS = 10;
MAX_POOL_SIZE = 4;
FTP_PACKET_SIZE = 102400;
// Statuses
ST_CONNECTED = 'Connected';
ST_DISCONNECTED = 'Disconnected';
ST_SESSION_CLOSED = 'Session closed normally';
// Results
INVALID_POOL_ITEM_INDEX = -1;
// Error messages
ER_WSAERROR = 'WSAStartup failed with error: %d';
ER_LIBSSH2_INIT = 'libssh2 initialization failed with error: %d';
ER_OPEN_SOCKET = 'Failed to open socket';
ER_IP_INCORRECT = 'IP address is incorrect';
ER_CONNECT = 'Failed to connect to server';
ER_SESSION_INIT = 'Could not initialize SSH session';
ER_SESSION_START = 'Error when starting up SSH session: %d';
ER_AUTH_METHOD = 'No supported authentication methods found';
ER_PUBKEY = 'Authentication by public key failed';
ER_PASSWORD = 'Authentication by password failed';
ER_SESSION_UNAVAILABLE = 'Session is not available';
ER_BINDING = 'Cannot bind socket with IP address: %d';
ER_SOCKET_LISTEN = 'Socket cannot listen';
ER_FTP_OPEN = 'Unable to open SFTP session';
ER_FTP_OPENFILE = 'Unable to open file with SFTP: %d';
ER_DEST_NOT_EXISTS = 'Destination folder not exists';
ER_CHANNEL_OPEN = 'Unable to open a channel';
ER_FAILED_PTY = 'Failed requesting pty';
ER_REQUEST_SHELL = 'Unable to request shell on allocated pty';
implementation
end.
|
unit Contatos2.entidade.contatos;
interface
Type
Tcontatos = class
Private
Fid : integer;
Fnome : string;
Ftelefone : string;
Fcelular : string;
Femail : string;
procedure SetCelular(const Value: string);
procedure SetEmail(const Value: string);
procedure Setid(const Value: integer);
procedure Setnome(const Value: string);
procedure Settelefone(const Value: string);
Public
Property id : integer read Fid write Setid;
Property nome : string read Fnome write Setnome;
Property telefone : string read Ftelefone write Settelefone;
Property Celular : string read FCelular write SetCelular;
Property Email : string read FEmail write SetEmail;
end;
implementation
{ Tcontatos }
procedure Tcontatos.SetCelular(const Value: string);
begin
FCelular := Value;
end;
procedure Tcontatos.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure Tcontatos.Setid(const Value: integer);
begin
Fid := Value;
end;
procedure Tcontatos.Setnome(const Value: string);
begin
Fnome := Value;
end;
procedure Tcontatos.Settelefone(const Value: string);
begin
Ftelefone := Value;
end;
end.
|
unit CBROrderPaytPresenter;
interface
uses CustomPresenter, db, EntityServiceIntf, CoreClasses, CBRConst, sysutils,
UIClasses;
const
ENT = 'CBR_ORD_DESK';
COMMAND_ORDER_CLOSE = '{D51BCA3E-FFF8-46A9-99B3-7F08456C3A2A}';
COMMAND_PRECHECK = '{DD4685CD-482C-4E37-A60E-49DB8A756AC2}';
COMMAND_PAYT_CHANGED = '{64031CB0-DBC0-489A-980D-34B94B1B3087}';
type
ICBROrderPaytView = interface
['{1DE7E4AC-1306-4661-87ED-396196986516}']
procedure LinkHeadData(ADataSet: TDataSet);
procedure LinkItemsData(ADataSet: TDataSet);
function GetSummPayt: double;
end;
TCBROrderPaytPresenter = class(TCustomPresenter)
const
PRECHECK_REPORT = 'reports.precheck';
private
function GetEVHead: IEntityView;
function GetEVItems: IEntityView;
function View: ICBROrderPaytView;
procedure CmdOrderClose(Sender: TObject);
procedure CmdPrecheck(Sender: TObject);
procedure CmdPaytChanged(Sender: TObject);
protected
function OnGetWorkItemState(const AName: string; var Done: boolean): Variant; override;
procedure OnViewReady; override;
end;
implementation
{ TCBROrderPaytPresenter }
procedure TCBROrderPaytPresenter.CmdOrderClose(Sender: TObject);
var
nextActionID: string;
nextAction: IActivity;
callerWI: TWorkItem;
begin
GetEVHead.Save;
callerWI := WorkItem.Root.WorkItems.Find(CallerURI);
if callerWI = nil then
callerWI := WorkItem.Parent;
if ViewInfo.OptionExists('ReloadCaller') then
callerWI.Commands[COMMAND_RELOAD].Execute;
nextAction := nil;
nextActionID := WorkItem.State['NEXT_ACTION'];
if nextActionID <> '' then
nextAction := WorkItem.Activities[nextActionID];
if Assigned(nextAction) then
nextAction.Params.Assign(WorkItem);
CloseView;
if Assigned(nextAction) then
nextAction.Execute(callerWI);
end;
procedure TCBROrderPaytPresenter.CmdPaytChanged(Sender: TObject);
var
ds: TDataSet;
summPayt: double;
summRet: double;
begin
WorkItem.Commands[COMMAND_ORDER_CLOSE].Status := csDisabled;
summPayt := View.GetSummPayt;
ds := GetEVHead.DataSet;
ds.Edit;
ds.FieldByName('SUMM_PAYT').AsFloat := summPayt;
summRet := ds.FieldByName('SUMM_PAYT').AsFloat - ds.FieldByName('SUMM').AsFloat;
if summRet > 0 then
ds.FieldByName('SUMM_RET').AsFloat := summRet
else
ds.FieldByName('SUMM_RET').AsFloat := 0;
ds.Post;
if ds.FieldByName('SUMM_PAYT').AsFloat >= ds.FieldByName('SUMM').AsFloat then
WorkItem.Commands[COMMAND_ORDER_CLOSE].Status := csEnabled;
end;
procedure TCBROrderPaytPresenter.CmdPrecheck(Sender: TObject);
var
activity: IActivity;
begin
activity := WorkItem.Activities[PRECHECK_REPORT];
activity.Params['ID'] := WorkItem.State['ID'];
activity.Params['LaunchMode'] := 2;
activity.Execute(WorkItem);
end;
function TCBROrderPaytPresenter.GetEVHead: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('Payt', WorkItem);
end;
function TCBROrderPaytPresenter.GetEVItems: IEntityView;
begin
Result := (WorkItem.Services[IEntityService] as IEntityService).
Entity[ENT].GetView('Items', WorkItem);
end;
function TCBROrderPaytPresenter.OnGetWorkItemState(const AName: string;
var Done: boolean): Variant;
begin
end;
procedure TCBROrderPaytPresenter.OnViewReady;
begin
inherited;
ViewTitle := 'Оплата заказа';
GetEVHead.Load([WorkItem.State['ID']]);
GetEVItems.Load([WorkItem.State['ID']]);
View.LinkHeadData(GetEVHead.DataSet);
View.LinkItemsData(GetEVItems.DataSet);
WorkItem.Commands[COMMAND_ORDER_CLOSE].Status := csDisabled;
WorkItem.Commands[COMMAND_ORDER_CLOSE].SetHandler(CmdOrderClose);
WorkItem.Commands[COMMAND_PAYT_CHANGED].SetHandler(CmdPaytChanged);
WorkItem.Commands[COMMAND_PRECHECK].SetHandler(CmdPrecheck);
end;
function TCBROrderPaytPresenter.View: ICBROrderPaytView;
begin
Result := GetView as ICBROrderPaytView;
end;
end.
|
unit SimulatorMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IniFiles, AppConfigFile, ProgramLogFile, GMGlobals,
ConnParamsStorage, ActiveX, GmSqlQuery, CheckConnStr, Vcl.StdCtrls, Vcl.ExtCtrls, Generics.Collections,
Math, GMConst, Vcl.ComCtrls;
type
TForm1 = class(TForm)
Timer1: TTimer;
leLastDT: TLabeledEdit;
Button1: TButton;
eInitialHours: TEdit;
ProgressBar1: TProgressBar;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
q: TGMSqlQuery;
lstChn: TList<int>;
udtDataStart: ULong;
function ReadAndCheckSQLParams: bool;
function ReadINI: bool;
function MainConnectSQL(Params: TZConnectionParams): bool;
procedure InitialWriteData(hours: int);
procedure ReadChnList;
procedure AddChn(q: TGMSqlQuery; obj: pointer);
function OneChnWriteSql(ID_Prm: int; udt: LongWord): string;
function AllChnsChnWriteSql(udt: LongWord): string;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AddChn(q: TGMSqlQuery; obj: pointer);
begin
lstChn.Add(q.FieldByName('ID_Prm').AsInteger);
end;
procedure TForm1.ReadChnList();
begin
lstChn.Clear();
ReadFromQuery('select ID_Prm from Params where ID_Src = ' + IntToStr(SRC_AI) + ' order by ID_Prm', nil, AddChn);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
q.Free();
lstChn.Free();
end;
function TForm1.OneChnWriteSql(ID_Prm: int; udt: LongWord): string;
begin
Result := Format('perform WriteVal(%d, %d, %d);'#13#10, [ID_Prm, udt, (udt - udtDataStart) div UTC_MINUTE mod ID_Prm]);
end;
function TForm1.AllChnsChnWriteSql(udt: LongWord): string;
var i: int;
begin
Result := '';
for i := 0 to lstChn.Count - 1 do
Result := Result + OneChnWriteSql(lstChn[i], udt);
end;
procedure TForm1.InitialWriteData(hours: int);
var
udt: LongWord;
sql: string;
begin
udtDataStart := NowGM() - hours * UTC_HOUR;
udt := udtDataStart;
while udt < NowGM() do
begin
sql := AllChnsChnWriteSql(udt);
ExecPLSQL(sql);
udt := udt + UTC_MINUTE;
ProgressBar1.Position := Floor((udt - udtDataStart) / (NowGM() - udtDataStart) * 100);
Form1.Refresh();
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
InitialWriteData(StrToInt(eInitialHours.Text));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetMainConfigFileClass(TGMServerMainConfigFile);
q := TGMSqlQuery.Create();
lstChn := TList<int>.Create();
if not ReadINI() then
begin
Application.Terminate();
Exit;
end;
ReadChnList();
udtDataStart := LocalToUTC(Now());
end;
function TForm1.MainConnectSQL(Params: TZConnectionParams): bool;
begin
Result := false;
try
CheckConnStrDlg := TCheckConnStrDlg.Create(Application);
Result := CheckConnStrDlg.CheckConnectionString(Params);
except
on e: Exception do
ShowMessageBox('Ошибка соединения с SQL: ' + e.Message);
end;
end;
function TForm1.ReadAndCheckSQLParams(): bool;
var Params: TZConnectionParams;
begin
Result := GMMainConfigFile.ReadSQLConnectionParams(Params);
if not Result then Exit;
Result := MainConnectSQL(Params);
if not Result then Exit;
SetGlobalSQLConnectionParams(Params);
end;
function TForm1.ReadINI: bool;
begin
Result := (GMMainConfigFile.CheckMainINIFile() = iftINI) and ReadAndCheckSQLParams();
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
ExecPLSQL(AllChnsChnWriteSql(NowGM()));
leLastDT.Text := DateTimeToStr(Now());
end;
end.
|
unit Unit2;
interface
Uses Classes, Graphics, ExtCtrls;
type TPole = Array[1..10000] of integer;
PPole = ^TPole;
TSort = class(TThread)
private
PaintBox : TPaintBox;
Pole, Pole2 : TPole;
PocetPrvkov : Word;
Co, SCim : Word;
Farba : TColor;
procedure UkazVymenu;
procedure NakresliCiaruSynchro;
procedure NakresliCiaruSynchro2;
protected
procedure Execute; override;
procedure Vymen( A , B : Word );
procedure Nakresli( A : Word; NFarba : TColor );
procedure Nakresli2( A : Word; NFarba : TColor );
procedure Sort( var Pole : TPole ); virtual; abstract;
procedure UkazVsetkyPrvky;
public
constructor Create( Box : TPaintBox; var SortPole : TPole; Pocet : Word );
end;
TBubbleSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
TQuickSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
TSelectionSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
TShellSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
TRadixSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
TMergeSort = class( TSort )
protected
procedure Sort( var Pole : TPole ); override;
end;
procedure NakresliCiaru( Velkost , Kde : Word; Farba : TColor; Paint : TPaintBox );
implementation
Uses Unit1;
procedure NakresliCiaru( Velkost , Kde : Word; Farba : TColor; Paint : TPaintBox );
begin
With Paint.Canvas do
begin
Pen.Color := Farba;
PolyLine( [Point(4+Round(Kde * ( (Paint.Width-8) / PocetPrvkov )), Paint.Height - 5 ) ,
Point(4+Round(Kde * ( (Paint.Width-8) / PocetPrvkov )), Paint.Height - 5 - Round(((Paint.Height-10) / 500) * Velkost)) ]);
end;
end;
{---------------------- Trieda S O R T -----------------------------}
constructor TSort.Create( Box : TPaintBox; var SortPole : TPole; Pocet : Word );
begin
inherited Create( False );
PaintBox := Box;
Pole := SortPole;
FreeOnTerminate := True;
PocetPrvkov := Pocet;
UkazVsetkyPrvky;
end;
procedure TSort.Execute;
begin
Sort( Pole );
end;
procedure TSort.UkazVsetkyPrvky;
var a : Word;
begin
PaintBox.Repaint;
for a := 1 to PocetPrvkov do
NakresliCiaru( Pole[ a ] , a , clGreen , PaintBox );
end;
procedure TSort.UkazVymenu;
begin
NakresliCiaru( Pole[ SCim ] , Co , clBtnFace , PaintBox );
NakresliCiaru( Pole[ Co ] , SCim , clBtnFace , PaintBox );
NakresliCiaru( Pole[ Co ] , Co , clGreen , PaintBox );
NakresliCiaru( Pole[ Scim ] , Scim , clGreen , PaintBox );
end;
procedure TSort.Vymen( a , b : Word );
var c : Word;
begin
c := Pole[ a ];
Pole[ a ] := Pole[ b ];
Pole[ b ] := c;
Co := a;
SCim := b;
Synchronize( UkazVymenu );
end;
procedure TSort.NakresliCiaruSynchro;
begin
NakresliCiaru( Pole[Co] , Co , Farba , PaintBox );
end;
procedure TSort.Nakresli( A : Word; NFarba : TColor );
begin
Co := A;
Farba := NFarba;
Synchronize( NakresliCiaruSynchro );
end;
procedure TSort.NakresliCiaruSynchro2;
begin
NakresliCiaru( Pole2[Co] , Co , Farba , PaintBox );
end;
procedure TSort.Nakresli2( A : Word; NFarba : TColor );
begin
Co := A;
Farba := NFarba;
Synchronize( NakresliCiaruSynchro2 );
end;
{---------------------- Trieda BUBBLE S O R T -----------------------------}
procedure TBubbleSort.Sort( var Pole : TPole );
var a, b : Word;
begin
for a := PocetPrvkov downto 1 do
for b := 1 to PocetPrvkov - 1 do
if Pole[ b ] > Pole[ b + 1 ] then
begin
Vymen( b , b + 1 );
if Terminated then Exit;
end;
KohoZrusit := 1;
end;
{---------------------- Trieda QUICK S O R T -----------------------------}
procedure TQuickSort.Sort( var Pole : TPole );
procedure QuickSort(var Pole: TPole; iLo, iHi: Integer);
var
Lo, Hi, Mid : Integer;
begin
Lo := iLo;
Hi := iHi;
Mid := Pole[(Lo + Hi) div 2];
repeat
while Pole[Lo] < Mid do Inc(Lo);
while Pole[Hi] > Mid do Dec(Hi);
if Lo <= Hi then
begin
Vymen( Lo , Hi );
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > iLo then QuickSort( Pole, iLo, Hi);
if Lo < iHi then QuickSort( Pole, Lo, iHi);
if Terminated then Exit;
end;
begin
QuickSort( Pole , 1, PocetPrvkov);
KohoZrusit := 2;
end;
{---------------------- Trieda SELECTION S O R T -----------------------------}
procedure TSelectionSort.Sort( var Pole : TPole );
var
I, J : Integer;
begin
for I := 1 to PocetPrvkov - 1 do
for J := PocetPrvkov downto I + 1 do
if Pole[I] > Pole[J] then
begin
Vymen( I , J );
if Terminated then Exit;
end;
KohoZrusit := 3;
end;
{---------------------- Trieda SHELL S O R T -----------------------------}
procedure TShellSort.Sort( var Pole : TPole );
var a,b,c,d : integer;
begin
c := 1;
repeat
c := 3*c + 1;
until c > PocetPrvkov;
repeat
c := c div 3;
for a := c+1 to PocetPrvkov do
begin
d := Pole[a];
b := a;
while (b > c) and (pole[b-c] > d) do
begin
Nakresli( b , clBtnFace );
pole[b] := pole[b-c];
Nakresli( b , clGreen );
b := b - c;
end;
Nakresli( b , clBtnFace );
pole[b] := d;
Nakresli( b , clGreen );
end
until c = 1;
KohoZrusit := 4;
end;
{---------------------- Trieda RADIX S O R T -----------------------------}
procedure TRadixSort.Sort( var Pole : TPole );
var a, b, c : integer;
Mocnina, Poc : Word;
begin
Pole2 := Pole;
Mocnina := 0;
for a := 1 to 3 do
begin
poc := 1;
if a = 1 then mocnina := 1
else mocnina := mocnina * 10;
for b := 0 to 9 do
for c := 1 to PocetPrvkov do
if ( Pole[c] div mocnina) mod 10 = b then
begin
Nakresli2( poc , clBtnFace );
pole2[poc] := pole[c];
Nakresli2( poc , clGreen );
inc(poc);
end;
Pole := Pole2;
end;
KohoZrusit := 5;
end;
{---------------------- Trieda MERGE S O R T -----------------------------}
procedure TMergeSort.Sort( var Pole : TPole );
procedure Merge( i, j : integer );
var a,l,p1,p2,poc : word;
begin
l := i + ( (j - i) div 2 );
if j-i > 1 then
begin
Merge( i , l );
Merge( l + 1, j );
end;
if j-i = 0 then exit;
poc := 1;
p1 := i;
p2 := l + 1;
while true do
if pole[p1] > pole[p2] then
begin
pole2[poc] := pole[p2];
inc(p2);
inc(poc);
if p2 > j then
begin
for a := p1 to l do
begin
pole2[poc] := pole[a];
inc(poc);
end;
break;
end;
end
else
begin
pole2[poc] := pole[p1];
inc(p1);
inc(poc);
if p1 > l then
begin
for a := p2 to j do
begin
pole2[poc] := pole[a];
inc(poc);
end;
break;
end;
end;
for a := 1 to poc-1 do
begin
Nakresli( i+a-1 , clBtnFace);
pole[i+a-1] := pole2[a];
Nakresli( i+a-1 , clGreen );
pole2[a] := 0;
end;
end;
begin
Pole2 := Pole;
Merge( 1 , PocetPrvkov );
KohoZrusit := 6;
end;
end.
|
unit TextEditFormUn;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, osFrm, Menus, StdActns, ImgList, ActnList, osActionList,
ComCtrls, ToolWin, ExtCtrls, StdCtrls, Buttons;
type
TTextEditForm = class(TosForm)
EditCut: TEditCut;
EditCopy: TEditCopy;
EditPaste: TEditPaste;
EditSelectAll: TEditSelectAll;
EditUndo: TEditUndo;
EditDelete: TEditDelete;
SearchFind: TSearchFind;
SearchFindNext: TSearchFindNext;
SearchReplace: TSearchReplace;
SearchFindFirst: TSearchFindFirst;
FileOpen: TFileOpen;
FileSaveAs: TFileSaveAs;
FileExit: TFileExit;
MainMenu: TMainMenu;
File2: TMenuItem;
Exit2: TMenuItem;
SaveAs2: TMenuItem;
N5: TMenuItem;
Open2: TMenuItem;
New2: TMenuItem;
Edit1: TMenuItem;
N1: TMenuItem;
Find1: TMenuItem;
N2: TMenuItem;
Paste1: TMenuItem;
Copy1: TMenuItem;
Cut1: TMenuItem;
N6: TMenuItem;
Undo1: TMenuItem;
FileNew: TAction;
Memo: TMemo;
ControlBar: TControlBar;
MainToolbar: TToolBar;
NewButton: TToolButton;
OpenButton: TToolButton;
SaveButton: TToolButton;
ToolButton11: TToolButton;
CutButton: TToolButton;
CopyButton: TToolButton;
PasteButton: TToolButton;
DeleteButton: TToolButton;
ToolButton4: TToolButton;
FindButton: TToolButton;
FileSaveAndExit: TAction;
SalveAndCloseButton: TBitBtn;
procedure FileNewExecute(Sender: TObject);
procedure EditCutExecute(Sender: TObject);
procedure EditCopyExecute(Sender: TObject);
procedure EditPasteExecute(Sender: TObject);
procedure EditSelectAllExecute(Sender: TObject);
procedure EditUndoExecute(Sender: TObject);
procedure EditDeleteExecute(Sender: TObject);
procedure MemoChange(Sender: TObject);
procedure FileSaveAndExitExecute(Sender: TObject);
protected
FResult: TModalResult;
private
FChanged: boolean;
function GetStrings: TStringList;
procedure SetStrings(const Value: TStringList);
function GetText: string;
procedure SetText(const value: string);
public
property Strings: TStringList read GetStrings write SetStrings;
property Text: string read GetText write SetText;
property IsChanged : boolean read FChanged;
function Execute: boolean;
end;
var
TextEditForm: TTextEditForm;
implementation
{$R *.dfm}
function TTextEditForm.Execute: boolean;
begin
FResult := mrCancel;
ShowModal;
if (FResult = mrCancel) and (IsChanged) then
if MessageDlg('O texto foi alterado. Deseja salvá-lo?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
FResult := mrOK;
Result := (FResult = mrOK);
end;
procedure TTextEditForm.FileNewExecute(Sender: TObject);
begin
inherited;
Memo.Clear;
end;
procedure TTextEditForm.EditCutExecute(Sender: TObject);
begin
inherited;
Memo.CutToClipboard;
end;
procedure TTextEditForm.EditCopyExecute(Sender: TObject);
begin
inherited;
Memo.CopyToClipboard;
end;
procedure TTextEditForm.EditPasteExecute(Sender: TObject);
begin
inherited;
Memo.PasteFromClipboard;
end;
procedure TTextEditForm.EditSelectAllExecute(Sender: TObject);
begin
inherited;
Memo.SelectAll;
end;
procedure TTextEditForm.EditUndoExecute(Sender: TObject);
begin
inherited;
Memo.Undo;
end;
procedure TTextEditForm.EditDeleteExecute(Sender: TObject);
begin
inherited;
Memo.ClearSelection;
end;
function TTextEditForm.GetStrings: TStringList;
begin
Result := TStringList(Memo.Lines);
end;
procedure TTextEditForm.SetStrings(const Value: TStringList);
begin
Memo.Lines.Clear;
Memo.Lines.AddStrings(Value);
FChanged := False;
FileSaveAndExit.Enabled := False;
end;
procedure TTextEditForm.MemoChange(Sender: TObject);
begin
inherited;
FChanged := True;
FileSaveAndExit.Enabled := True;
end;
function TTextEditForm.GetText: string;
begin
Result := Memo.Lines.Text;
end;
procedure TTextEditForm.SetText(const value: string);
begin
Memo.Lines.Clear;
Memo.Lines.Text := Value;
FChanged := False;
FileSaveAndExit.Enabled := False;
end;
procedure TTextEditForm.FileSaveAndExitExecute(Sender: TObject);
begin
inherited;
FResult := mrOK;
Close;
end;
end.
|
unit PlayerExporters;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
SqlDB,
fpjson,
PlayerThreads;
type
{ TPlayerExporter }
TPlayerProcessEvent = procedure(Sender: TObject;
const AProcessedCount: Integer) of object;
TPlayerExporter = class
private
FCount: Integer;
FExported, FFailed: Boolean;
FOnFinish: TNotifyEvent;
FOnProcess: TPlayerProcessEvent;
FSessionID, FDir: String;
FProcessedCount: Integer;
procedure CalcTripsForSession;
protected
function CreateQuery(const SQLResource: String = ''): TSQLQuery;
procedure DoFinish; virtual;
procedure DoProcess; virtual;
public
constructor Create(ASessionID: String);
destructor Destroy; override;
function ExportData: TPlayerThreadManager;
property Count: Integer read FCount;
property Exported: Boolean read FExported;
property SessionID: String read FSessionID;
property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
property OnProcess: TPlayerProcessEvent read FOnProcess write FOnProcess;
end;
{ TPlayerExporterManager }
TPlayerExporterManager = class(TPlayerThreadManager)
private
FExporter: TPlayerExporter;
FQuery: TSQLQuery;
FData: TJSONArray;
procedure AddTrip;
procedure GenerateHtml;
protected
function GetNextThread: TPlayerThread; override;
procedure Execute; override;
public
constructor Create(AExporter: TPlayerExporter);
destructor Destroy; override;
procedure Interrupt(const Force: Boolean = False); override;
procedure SaveJson(const FileName: String; AJson: TJSONData);
property Exporter: TPlayerExporter read FExporter;
end;
{ TPlayerExporterThread }
TPlayerExporterThread = class(TPlayerThread)
private
FTripID: Integer;
FQuery: TSQLQuery;
FTracks, FPoints: TJSONArray;
function GetManager: TPlayerExporterManager;
procedure ExportPoints;
procedure ExportTracks;
protected
procedure Execute; override;
public
constructor Create(AManager: TPlayerThreadManager;
const ATripID: Integer);
destructor Destroy; override;
property Manager: TPlayerExporterManager read GetManager;
property TripID: Integer read FTripID;
end;
implementation
uses
Math, DB, dmxPlayer, PlayerLogger, PlayerOptions, FileUtil, PlayerSessionStorage;
{ TPlayerExporterThread }
function TPlayerExporterThread.GetManager: TPlayerExporterManager;
begin
Result:=inherited Manager as TPlayerExporterManager;
end;
procedure TPlayerExporterThread.ExportPoints;
var
Field: TField;
Point: TJSONObject;
begin
LoadTextFromResource(FQuery.SQL, 'GET_POINTS');
FQuery.Open;
while not FQuery.EOF do
begin
if Terminated then Break;
Point:=TJSONObject.Create;
for Field in FQuery.Fields do
Point.Strings[Field.FieldName]:=Field.AsString;
FPoints.Add(Point);
FQuery.Next;
end;
FQuery.Close;
end;
procedure TPlayerExporterThread.ExportTracks;
var
Track: TJSONObject;
begin
FQuery.Open;
while not FQuery.EOF do
begin
if Terminated then Break;
Track:=TJSONObject.Create;
Track.Strings['filename']:=FQuery.FieldByName('filename').AsString;
Track.Integers['rn']:=FQuery.FieldByName('trip_rn').AsInteger;
Track.Integers['start_id']:=FQuery.FieldByName('start_id').AsInteger;
Track.Integers['end_id']:=FQuery.FieldByName('end_id').AsInteger;
FTracks.Add(Track);
FQuery.Next;
end;
FQuery.Close;
end;
procedure TPlayerExporterThread.Execute;
begin
try
ExportTracks;
ExportPoints;
if not Terminated then
begin
Manager.SaveJson(Format('%stracks_%d.json', [Manager.Exporter.FDir, FTripID]), FTracks);
Manager.SaveJson(Format('%spoints_%d.json', [Manager.Exporter.FDir, FTripID]), FPoints);
Synchronize(@Manager.Exporter.DoProcess);
end;
except
on E: Exception do
begin
logger.Log('error on exporter trip %d, session %s, text: %s',
[FTripID, Manager.Exporter.FSessionID, E.Message]);
Manager.Exporter.FFailed:=True;
Manager.Interrupt(True);
end;
end;
end;
constructor TPlayerExporterThread.Create(AManager: TPlayerThreadManager;
const ATripID: Integer);
begin
inherited Create(AManager);
FTripID:=ATripID;
FTracks:=TJSONArray.Create;
FPoints:=TJSONArray.Create;
FQuery:=Manager.Exporter.CreateQuery('GET_TRIPS_TRACKS');
FQuery.ParamByName('trip_id').AsInteger:=FTripID;
end;
destructor TPlayerExporterThread.Destroy;
begin
FQuery.Free;
FTracks.Free;
FPoints.Free;
inherited;
end;
{ TPlayerExporterManager }
procedure TPlayerExporterManager.AddTrip;
var
obj: TJSONObject;
Duration: Integer;
begin
obj:=TJSONObject.Create;
Duration:=FQuery.FieldByName('duration').AsInteger;
obj.Integers['id']:=FQuery.FieldByName('id').AsInteger;
obj.Strings['started_at']:=FQuery.FieldByName('started_at').AsString;
obj.Strings['duration']:=Format('%d:%d', [Duration div 3600, (Duration mod 3600) div 60]);
obj.Strings['distance']:=FloatToStr(RoundTo(FQuery.FieldByName('distance').AsFloat / 1000, -2));
obj.Strings['avg_speed']:=FloatToStr(RoundTo(FQuery.FieldByName('avg_speed').AsFloat, -2));
obj.Strings['size']:=FloatToStr(RoundTo(FQuery.FieldByName('size_mb').AsFloat / 1024, -2));
FData.Add(obj);
(FQuery.FieldByName('gpx') as TBlobField).SaveToFile(
Format('%s%d.gpx', [Exporter.FDir, FQuery.FieldByName('id').AsInteger])
);
end;
procedure TPlayerExporterManager.GenerateHtml;
var
Html: TStringList;
begin
Html:=TStringList.Create;
try
Html.LoadFromFile('html/dist/index.html');
Html.Text:=Html.Text.Replace('bundle.js', '../../../html/dist/bundle.js')
.Replace('{{trips}}', FData.AsJson)
.Replace('{{tracks}}', '');
Html.SaveToFile(FExporter.FDir + 'index.html');
finally
Html.Free;
end;
end;
function TPlayerExporterManager.GetNextThread: TPlayerThread;
var
id: Integer;
begin
if FQuery.EOF then Result:=nil else
begin
id:=FQuery.FieldByName('id').AsInteger;
AddTrip;
logger.Log('starting new exporter thread: trip %d for session %s',
[id, Exporter.FSessionID]);
Result:=TPlayerExporterThread.Create(Self, id);
SaveJson(Format('%strips.json', [Exporter.FDir]), FData);
FQuery.Next;
end
end;
procedure TPlayerExporterManager.Execute;
begin
try
try
inherited;
if FQuery.EOF then
begin
Exporter.FExported:=True;
GenerateHtml;
end;
except
on E: Exception do
begin
logger.Log('error on exporting session %s, text: %s',
[Exporter.FSessionID, E.Message]);
FExporter.FFailed:=True;
Interrupt(True);
end;
end;
finally
Synchronize(@FExporter.DoFinish);
end;
end;
constructor TPlayerExporterManager.Create(AExporter: TPlayerExporter);
begin
FExporter:=AExporter;
FQuery:=Exporter.CreateQuery('GET_TRIPS_LIST');
FQuery.ParamByName('session_id').AsString:=Exporter.SessionID;
FQuery.Open;
FData:=TJSONArray.Create;
inherited Create;
end;
destructor TPlayerExporterManager.Destroy;
begin
FQuery.Close;
FQuery.Free;
FData.Free;
inherited;
end;
procedure TPlayerExporterManager.Interrupt(const Force: Boolean);
var
List: TList;
Index: Integer;
CurThread: TPlayerExporterThread;
begin
inherited;
if not Force then Exit;
List:=ThreadList.LockList;
try
for Index:=0 to List.Count - 1 do
begin
CurThread:=TPlayerExporterThread(List[Index]);
CurThread.Terminate;
end;
finally
ThreadList.UnlockList;
end;
end;
procedure TPlayerExporterManager.SaveJson(const FileName: String;
AJson: TJSONData);
var
List: TStringList;
begin
List:=TStringList.Create;
try
List.Text:=AJson.AsJSON;
List.SaveToFile(FileName);
finally
List.Free;
end;
end;
{ TPlayerExporter }
procedure TPlayerExporter.CalcTripsForSession;
var
Query: TSQLQuery;
begin
Query:=CreateQuery('GET_TRIPS_COUNT');
Query.ParamByName('session_id').AsString:=FSessionID;
Query.Open;
try
FCount:=0;
if not Query.IsEmpty then FCount:=Query.FieldByName('cc').AsInteger;
finally
Query.Close;
end;
end;
function TPlayerExporter.CreateQuery(const SQLResource: String): TSQLQuery;
begin
Result:=TSQLQuery.Create(dmPlayer);
Result.DataBase:=dmPlayer.Connection;
Result.Transaction:=dmPlayer.Transaction;
if SQLResource <> '' then
LoadTextFromResource(Result.SQL, SQLResource);
end;
procedure TPlayerExporter.DoFinish;
begin
if @FOnFinish <> nil then
FOnFinish(Self);
end;
procedure TPlayerExporter.DoProcess;
begin
Inc(FProcessedCount);
if @FOnProcess <> nil then
FOnProcess(Self, FProcessedCount);
end;
constructor TPlayerExporter.Create(ASessionID: String);
begin
inherited Create;
FExported:=False;
FSessionID:=ASessionID;
FDir:=IncludeTrailingPathDelimiter(opts.TempDir);
FDir:=IncludeTrailingPathDelimiter(FDir + 'html');
FDir:=IncludeTrailingPathDelimiter(FDir + ASessionID);
DeleteDirectory(FDir, False);
logger.log('recreating dir: %s', [FDir]);
ForceDirectories(FDir);
CalcTripsForSession;
end;
destructor TPlayerExporter.Destroy;
begin
logger.Log('export finished: %s', [FSessionID]);
inherited;
end;
function TPlayerExporter.ExportData: TPlayerThreadManager;
begin
logger.Log('exporting session: %s', [FSessionID]);
FProcessedCount:=0;
FFailed:=False;
if FCount = 0 then Exit;
Result:=TPlayerExporterManager.Create(Self);
Result.Start;
end;
end.
|
{**********************************************}
{ TeeChart and TeeTree TCanvas3D component }
{ Copyright (c) 1999-2004 by David Berneda }
{ All Rights Reserved }
{**********************************************}
unit TeCanvas;
{$I TeeDefs.inc}
interface
{$DEFINE TEEWINDOWS}
{$DEFINE TEEPLANEFLOAT} // optimize TCanvas3D.PlaneFour3D method
Uses {$IFNDEF LINUX}
{$IFDEF TEEWINDOWS}
Windows,
{$ENDIF}
{$IFDEF TEEVCL}
Messages,
{$ENDIF}
{$ENDIF}
{$IFDEF TEEVCL}
Classes, SysUtils,
{$ENDIF}
{$IFDEF CLX}
Qt, QGraphics, QStdCtrls, QControls, QComCtrls, Types,
{$ELSE}
{$IFDEF TEEVCL}
Controls, StdCtrls, Graphics,
{$ENDIF}
{$ENDIF}
{$IFDEF CLR}
System.ComponentModel,
{$ENDIF}
TypInfo;
Const
TeePiStep:Double = Pi/180.0;
{$NODEFINE TeePiStep} { for C++ Builder }
TeeDefaultPerspective = 15;
TeeMinAngle = 270;
{$IFNDEF D6}
clMoneyGreen = TColor($C0DCC0);
clSkyBlue = TColor($F0CAA6);
clCream = TColor($F0FBFF);
clMedGray = TColor($A4A0A0);
{$ENDIF}
{$IFDEF CLX}
clMoneyGreen = TColor($C0DCC0);
clSkyBlue = TColor($F0CAA6);
clCream = TColor($F0FBFF);
clMedGray = TColor($A4A0A0);
{$IFDEF LINUX}
TA_LEFT = 0;
TA_RIGHT = 2;
TA_CENTER = 6;
TA_TOP = 0;
TA_BOTTOM = 8;
PATCOPY = 0;
{$ENDIF}
{$ENDIF}
NumCirclePoints = 64;
{$IFNDEF TEEWINDOWS}
DEFAULT_CHARSET = 1;
ANTIALIASED_QUALITY = 4;
TA_LEFT = 0;
bs_Solid=0;
{$ENDIF}
{$IFNDEF TEEVCL}
clGray=0;
clDkGray=0;
clWhite=$FFFFFF;
clSilver=0;
clDefault=-1;
clNone=-2;
clBlack=0;
clYellow=$FFFF;
pf24Bit=0;
pfDevice=1;
CM_MOUSELEAVE=10000;
CM_SYSCOLORCHANGE=10001;
{$ENDIF}
var
TeeDefaultConePercent : Integer=0;
type
{$IFNDEF TEEWINDOWS}
TPoint=packed record
X,Y: Integer;
end;
TRect = packed record
case Integer of
0: (Left, Top, Right, Bottom: Integer);
1: (TopLeft, BottomRight: TPoint);
end;
HDC=Integer;
HPen=Integer;
HRgn=Integer;
TRGBTRIPLE = packed record
rgbtBlue: Byte;
rgbtGreen: Byte;
rgbtRed: Byte;
end;
COLORREF = LongWord;
TLogBrush=packed record
lbStyle:Integer;
lbColor:TColor;
lbHatch:Integer;
end;
{$ENDIF}
{$IFNDEF TEEVCL}
{$DEFINE TEECANVASLOCKS}
TNotifyEvent = procedure(Sender: TObject) of object;
TPersistent = class(TObject)
public
Procedure Assign(Source:TPersistent); virtual;
end;
TComponent=class(TPersistent);
TCreateParams=class
end;
TColor=Integer;
PColor = ^TColor;
TGraphicObject=class(TPersistent)
private
FOnChange : TNotifyEvent;
public
procedure Changed;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
end;
TPenStyle=(psSolid,psDash,psDot,psDashDot,psDashDotDot,psClear,psInsideFrame);
TPenMode = (pmBlack, pmWhite, pmNop, pmNot, pmCopy, pmNotCopy,
pmMergePenNot, pmMaskPenNot, pmMergeNotPen, pmMaskNotPen, pmMerge,
pmNotMerge, pmMask, pmNotMask, pmXor, pmNotXor);
TPen=class(TGraphicObject)
private
FColor : TColor;
FStyle : TPenStyle;
FWidth : Integer;
FMode : TPenMode;
FOnChange : TNotifyEvent;
public
Handle : HPen;
property Color: TColor read FColor write FColor;
property Mode:TPenMode read FMode write FMode;
property Style: TPenStyle read FStyle write FStyle;
property Width: Integer read FWidth write FWidth;
end;
TGraphic=class(TPersistent)
public
Palette : Integer;
Width, Height : Integer;
Empty : Boolean;
end;
PByteArray = ^TByteArray;
TByteArray = array[0..32767] of Byte;
TCanvas=class;
{$IFNDEF VCL}
TRGBTripleArray=packed array[0..0] of TRGBTriple;
{$ENDIF}
TBitmap=class(TGraphic)
private
public
PixelFormat : Integer;
IgnorePalette : Boolean;
Canvas : TCanvas;
ScanLine:Array of Pointer;
end;
TPicture=class(TGraphicObject)
public
Graphic:TGraphic;
Bitmap:TBitmap;
end;
TBrushStyle=(bsClear, bsSolid,bsDiagonal);
TBrush=class(TGraphicObject)
private
FColor : TColor;
FBitmap : TBitmap;
FStyle : TBrushStyle;
public
Handle : HBrush;
property Bitmap:TBitmap read FBitmap write FBitmap;
property Color: TColor read FColor write FColor;
property Style: TBrushStyle read FStyle write FStyle;
end;
TFontStyle=(fsBold, fsItalic, fsUnderline, fsStrikeThrough);
TFontStyles=set of TFontStyle;
TFont=class(TGraphicObject)
private
FColor : TColor;
FHeight : Integer;
FName : String;
FStyle : TFontStyles;
FSize: Integer;
FSet : Integer;
public
PixelsPerInch : Integer;
Handle : HFont;
property CharSet : Integer read FSet write FSet;
property Color: TColor read FColor write FColor;
property Height : Integer read FHeight write FHeight;
property Name : String read FName write FName;
property Size:Integer read FSize write FSize;
property Style:TFontStyles read FStyle write FStyle;
end;
TCanvas=class(TObject)
private
FOnChange:TNotifyEvent;
FOnChanging:TNotifyEvent;
function GetPixel(X, Y: Integer): TColor;
procedure SetPixel(X, Y: Integer; Value: TColor);
public
Pen:TPen;
Brush:TBrush;
Font:TFont;
Handle : HDC;
procedure CopyRect(const Dest: TRect; Canvas: TCanvas; const Source: TRect);
function TextExtent(const Text: string): TSize;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
property OnChanging:TNotifyEvent read FOnChange write FOnChange;
procedure Draw(X, Y: Integer; Graphic: TGraphic);
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic);
property Pixels[X, Y: Integer]: TColor read GetPixel write SetPixel;
end;
TStrings=class(TComponent);
TCursor=Integer;
TFiler=class
end;
TCustomPanel=class(TComponent)
protected
procedure AssignTo(Dest: TPersistent); virtual;
procedure CreateParams(var Params: TCreateParams); virtual;
Procedure DefineProperties(Filer:TFiler); virtual; // obsolete
public
Constructor Create(AOwner: TComponent); virtual;
end;
TMouseButton=(mbLeft,mbMiddle,mbRight);
TBorderStyle=(bsSingle);
{$ENDIF}
{$IFDEF CLX}
// Fake class to support TUpDown in CLX
// Inherits from CLX TSpinEdit control.
TUDBtnType=(btNext, btPrev);
TUDOrientation=(udHorizontal, udVertical);
TUpDown=class(TSpinEdit)
private
FAssociate : TComponent;
FOrientation : TUDOrientation;
FThousands : Boolean;
IChangingText : Boolean;
OldChanged : TNotifyEvent;
Procedure DoChangeEdit;
Procedure ChangedEdit(Sender:TObject);
Procedure GetOldChanged;
function GetPosition: Integer;
procedure SetPosition(const AValue: Integer);
procedure SetAssociate(const AValue: TComponent);
protected
procedure Change(AValue: Integer); override;
Procedure Loaded; override;
public
Constructor Create(AOwner:TComponent); override;
published
property Associate:TComponent read FAssociate write SetAssociate;
property Orientation: TUDOrientation read FOrientation write FOrientation default udVertical;
property Position:Integer read GetPosition write SetPosition default 0;
property Thousands: Boolean read FThousands write FThousands default True;
end;
{$ENDIF}
TPenEndStyle=(esRound,esSquare,esFlat);
TChartPen=class(TPen)
private
FEndStyle : TPenEndStyle;
FSmallDots : Boolean;
FVisible : Boolean;
{$IFDEF CLR}
[EditorBrowsable(EditorBrowsableState.Never)]
{$ENDIF}
Function IsEndStored:Boolean;
{$IFDEF CLR}
[EditorBrowsable(EditorBrowsableState.Never)]
{$ENDIF}
Function IsVisibleStored:Boolean;
procedure SetEndStyle(const Value: TPenEndStyle);
Procedure SetSmallDots(Value:Boolean);
Procedure SetVisible(Value:Boolean);
protected
DefaultEnd : TPenEndStyle;
DefaultVisible : Boolean;
public
Constructor Create(OnChangeEvent:TNotifyEvent);
Procedure Assign(Source:TPersistent); override;
procedure Hide;
procedure Show;
published
property EndStyle:TPenEndStyle read FEndStyle write SetEndStyle stored IsEndStored;
property SmallDots:Boolean read FSmallDots write SetSmallDots default False;
property Visible:Boolean read FVisible write SetVisible stored IsVisibleStored;
end;
TChartHiddenPen=class(TChartPen)
public
Constructor Create(OnChangeEvent:TNotifyEvent);
published
property Visible default False;
end;
TDottedGrayPen=class(TChartPen)
public
Constructor Create(OnChangeEvent:TNotifyEvent);
published
property Color default clGray;
property Style default psDot;
end;
TDarkGrayPen=class(TChartPen)
public
Constructor Create(OnChangeEvent:TNotifyEvent);
published
property Color default clDkGray;
end;
TWhitePen=class(TChartPen)
public
Constructor Create(OnChangeEvent:TNotifyEvent);
published
property Color default clWhite;
end;
TChartBrush=class(TBrush)
private
FImage : TPicture;
Function GetImage:TPicture;
procedure SetImage(Value:TPicture);
public
Constructor Create(OnChangeEvent:TNotifyEvent); {$IFDEF CLR}virtual;{$ENDIF}
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
Procedure Clear;
published
property Color default clDefault;
property Image:TPicture read GetImage write SetImage;
end;
TTeeView3DScrolled=procedure(IsHoriz:Boolean) of object;
TTeeView3DChangedZoom=procedure(NewZoom:Integer) of object;
TView3DOptions = class(TPersistent)
private
FElevation : Integer;
FFontZoom : Integer;
FHorizOffset : Integer;
FOrthogonal : Boolean;
FOrthoAngle : Integer;
FPerspective : Integer;
FRotation : Integer;
FTilt : Integer;
FVertOffset : Integer;
FZoom : Integer;
FZoomText : Boolean;
FOnScrolled : TTeeView3DScrolled;
FOnChangedZoom:TTeeView3DChangedZoom;
{$IFDEF TEEVCL}
FParent : TWinControl;
{$ENDIF}
Procedure SetElevation(Value:Integer);
Procedure SetFontZoom(Value:Integer);
Procedure SetPerspective(Value:Integer);
Procedure SetRotation(Value:Integer);
Procedure SetTilt(Value:Integer);
Procedure SetHorizOffset(Value:Integer);
Procedure SetVertOffset(Value:Integer);
Procedure SetOrthoAngle(Value:Integer);
Procedure SetOrthogonal(Value:Boolean);
Procedure SetZoom(Value:Integer);
Procedure SetZoomText(Value:Boolean);
Procedure SetBooleanProperty(Var Variable:Boolean; Value:Boolean);
Procedure SetIntegerProperty(Var Variable:Integer; Value:Integer);
protected
function CalcOrthoRatio:Double;
public
Constructor Create({$IFDEF TEEVCL}AParent:TWinControl{$ENDIF});
Procedure Repaint;
Procedure Assign(Source:TPersistent); override;
{$IFDEF TEEVCL}
property Parent:TWinControl read FParent write FParent;
{$ENDIF}
property OnChangedZoom:TTeeView3DChangedZoom read FOnChangedZoom
write FOnChangedZoom;
property OnScrolled:TTeeView3DScrolled read FOnScrolled write FOnScrolled;
published
property Elevation:Integer read FElevation write SetElevation default 345;
property FontZoom:Integer read FFontZoom write SetFontZoom default 100;
property HorizOffset:Integer read FHorizOffset write SetHorizOffset default 0;
property OrthoAngle:Integer read FOrthoAngle write SetOrthoAngle default 45;
property Orthogonal:Boolean read FOrthogonal write SetOrthogonal default True;
property Perspective:Integer read FPerspective
write SetPerspective default TeeDefaultPerspective;
property Rotation:Integer read FRotation write SetRotation default 345;
property Tilt:Integer read FTilt write SetTilt default 0;
property VertOffset:Integer read FVertOffset write SetVertOffset default 0;
property Zoom:Integer read FZoom write SetZoom default 100;
property ZoomText:Boolean read FZoomText write SetZoomText default True;
end;
TTeeCanvas=class;
TTeeTransparency=0..100;
TTeeBlend=class
private
FBitmap : TBitmap;
FCanvas : TTeeCanvas;
FRect : TRect;
IValidSize : Boolean;
public
Constructor Create(ACanvas:TTeeCanvas; Const R:TRect);
Destructor Destroy; override;
Procedure DoBlend(Transparency:TTeeTransparency);
Procedure SetRectangle(Const R:TRect);
end;
TCanvas3D=class;
TTeeShadow=class(TPersistent)
private
FColor : TColor;
FHorizSize : Integer;
FSmooth : Boolean;
FTransparency : TTeeTransparency;
FVertSize : Integer;
IOnChange : TNotifyEvent;
IBlend : TTeeBlend;
procedure Changed;
procedure FinishBlending(ACanvas:TTeeCanvas);
function GetSize: Integer;
function IsColorStored: Boolean;
function IsHorizStored: Boolean;
function IsVertStored: Boolean;
Function PrepareCanvas(ACanvas:TCanvas3D; const R:TRect;
Z:Integer=0):Boolean;
Procedure SetColor(Value:TColor);
Procedure SetHorizSize(Value:Integer);
Procedure SetIntegerProperty(Var Variable:Integer; Const Value:Integer);
procedure SetSize(const Value: Integer);
procedure SetSmooth(const Value: Boolean);
procedure SetTransparency(Value: TTeeTransparency);
Procedure SetVertSize(Value:Integer);
{$IFDEF CLR}
public
{$ELSE}
protected
{$ENDIF}
DefaultColor : TColor;
DefaultSize : Integer;
public
Constructor Create(AOnChange:TNotifyEvent);
Procedure Assign(Source:TPersistent); override;
procedure Draw(ACanvas:TCanvas3D; Const Rect:TRect); overload;
procedure Draw(ACanvas:TCanvas3D; Const Rect:TRect; Z:Integer); overload;
procedure DrawEllipse(ACanvas:TCanvas3D; Const Rect:TRect; Z:Integer=0);
property Size:Integer read GetSize write SetSize;
published
property Color:TColor read FColor write SetColor stored IsColorStored;
property HorizSize:Integer read FHorizSize write SetHorizSize stored IsHorizStored;
property Smooth:Boolean read FSmooth write SetSmooth default True; // 7.0
property Transparency:TTeeTransparency read FTransparency write SetTransparency default 0;
property VertSize:Integer read FVertSize write SetVertSize stored IsVertStored;
end;
TFourPoints=Array[0..3] of TPoint;
TPointArray=Array of TPoint;
TGradientDirection = (gdTopBottom, gdBottomTop,
gdLeftRight, gdRightLeft,
gdFromCenter, gdFromTopLeft,
gdFromBottomLeft, gdRadial,
gdDiagonalUp, gdDiagonalDown ); // 7.0
TCustomTeeGradient=class(TPersistent)
private
FBalance : Integer;
FDirection : TGradientDirection;
FEndColor : TColor;
FMidColor : TColor;
FRadialX : Integer;
FRadialY : Integer;
FStartColor : TColor;
FVisible : Boolean;
IHasMiddle : Boolean;
Procedure DrawRadial(Canvas:TTeeCanvas; Rect:TRect);
Function GetMidColor:TColor;
Procedure SetBalance(Value:Integer);
Procedure SetColorProperty(Var Variable:TColor; const Value:TColor);
Procedure SetDirection(Value:TGradientDirection);
Procedure SetEndColor(Value:TColor);
Procedure SetIntegerProperty(Var Variable:Integer; Value:Integer);
Procedure SetMidColor(Value:TColor);
procedure SetRadialX(const Value: Integer);
procedure SetRadialY(const Value: Integer);
Procedure SetStartColor(Value:TColor);
Procedure SetVisible(Value:Boolean);
protected
IChanged : TNotifyEvent;
procedure DoChanged;
public
Constructor Create(ChangedEvent:TNotifyEvent); virtual;
Procedure Assign(Source:TPersistent); override;
Procedure Draw(Canvas:TTeeCanvas; Const Rect:TRect; RoundRectSize:Integer=0); overload;
Procedure Draw(Canvas:TTeeCanvas; var P:TFourPoints); overload;
Procedure Draw(Canvas:TCanvas3D; var P:TFourPoints; Z:Integer); overload;
procedure Draw(Canvas:TCanvas3D; var P:TPointArray; Z:Integer; Is3D:Boolean); overload; // 7.0
property Changed:TNotifyEvent read IChanged write IChanged;
Procedure UseMiddleColor;
{ to be published }
property Balance:Integer read FBalance write SetBalance default 50;
property Direction:TGradientDirection read FDirection write SetDirection default gdTopBottom;
property EndColor:TColor read FEndColor write SetEndColor default clYellow;
property MidColor:TColor read GetMidColor write SetMidColor default clNone;
property RadialX:Integer read FRadialX write SetRadialX default 0;
property RadialY:Integer read FRadialY write SetRadialY default 0;
property StartColor:TColor read FStartColor write SetStartColor default clWhite;
property Visible:Boolean read FVisible write SetVisible default False;
end;
TTeeGradient=class(TCustomTeeGradient)
published
property Balance;
property Direction;
property EndColor;
property MidColor;
property RadialX;
property RadialY;
property StartColor;
property Visible;
end;
TTeeFontGradient=class(TTeeGradient)
private
FOutline : Boolean;
Procedure SetBooleanProperty( Var Variable:Boolean;
Const Value:Boolean);
procedure SetOutline(const Value: Boolean);
published
property Outline:Boolean read FOutline write SetOutline default False;
end;
TTeeFont=class(TFont)
private
FGradient : TTeeFontGradient;
FInterCharSize : Integer;
FOutLine : TChartHiddenPen;
FShadow : TTeeShadow;
ICanvas : TTeeCanvas;
function GetGradient: TTeeFontGradient;
function GetOutLine: TChartHiddenPen;
Function GetShadow: TTeeShadow;
Function IsColorStored:Boolean;
Function IsHeightStored:Boolean;
Function IsNameStored:Boolean;
Function IsStyleStored:Boolean;
Procedure SetInterCharSize(Value:Integer);
Procedure SetOutLine(Value:TChartHiddenPen);
Procedure SetShadow(Value:TTeeShadow);
procedure SetGradient(const Value: TTeeFontGradient);
protected
IDefColor : TColor;
IDefStyle : TFontStyles;
public
Constructor Create(ChangedEvent:TNotifyEvent);
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override;
published
{$IFNDEF CLX}
property Charset default DEFAULT_CHARSET;
{$ENDIF}
property Color stored IsColorStored;
property Gradient:TTeeFontGradient read GetGradient write SetGradient;
property Height stored IsHeightStored;
property InterCharSize:Integer read FInterCharSize
write SetInterCharSize default 0;
property Name stored IsNameStored;
property OutLine:TChartHiddenPen read GetOutLine write SetOutLine;
{$IFDEF CLX}
property Pitch default fpVariable;
{$ENDIF}
property Shadow:TTeeShadow read GetShadow write SetShadow;
property Style stored IsStyleStored;
{$IFDEF CLX}
property Weight default 40;
{$ENDIF}
end;
TCanvasBackMode = ( cbmNone,cbmTransparent,cbmOpaque );
TCanvasTextAlign = Integer;
TTeeCanvasHandle={$IFDEF CLX}QPainterH{$ELSE}HDC{$ENDIF};
TTeeCanvas=class {$IFDEF CLR}abstract{$ENDIF}
private
FCanvas : TCanvas;
FFont : TFont;
FPen : TPen;
FBrush : TBrush;
FMetafiling : Boolean;
ITransp : Integer;
Function GetFontHeight:Integer; // 7.0
Procedure InternalDark(Const AColor:TColor; Quantity:Byte);
protected
FBounds : TRect; // 7.0, moved from TeeCanvas3D
IFont : TTeeFont;
Procedure SetCanvas(ACanvas:TCanvas);
function GetBackColor:TColor; virtual; abstract;
Function GetBackMode:TCanvasBackMode; virtual; abstract;
Function GetHandle:TTeeCanvasHandle; virtual; abstract;
Function GetMonochrome:Boolean; virtual; abstract;
Function GetPixel(x,y:Integer):TColor; virtual; abstract;
Function GetSupportsFullRotation:Boolean; virtual; abstract;
Function GetTextAlign:TCanvasTextAlign; virtual; abstract;
Function GetUseBuffer:Boolean; virtual; abstract;
Procedure SetBackColor(Color:TColor); virtual; abstract;
Procedure SetBackMode(Mode:TCanvasBackMode); virtual; abstract;
Procedure SetMonochrome(Value:Boolean); virtual; abstract;
procedure SetPixel(X, Y: Integer; Value: TColor); virtual; abstract;
procedure SetTextAlign(Align:TCanvasTextAlign); virtual; abstract;
Procedure SetUseBuffer(Value:Boolean); virtual; abstract;
public
FontZoom : Double; // % of zoom of all font sizes
Procedure AssignBrush(ABrush:TChartBrush; ABackColor:TColor);
Procedure AssignBrushColor(ABrush:TChartBrush; AColor,ABackColor:TColor);
procedure AssignVisiblePen(APen:TPen);
procedure AssignVisiblePenColor(APen:TPen; AColor:TColor); virtual; // 7.0
procedure AssignFont(AFont:TTeeFont);
Procedure ResetState;
Function BeginBlending(const R:TRect; Transparency:TTeeTransparency):TTeeBlend; virtual;
procedure EndBlending(Blend:TTeeBlend); virtual;
{ 2d }
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); virtual; abstract;
procedure Donut( XCenter,YCenter,XRadius,YRadius:Integer;
Const StartAngle,EndAngle,HolePercent:Double); virtual; abstract;
procedure Draw(X, Y: Integer; Graphic: TGraphic); virtual; abstract;
procedure Ellipse(const R:TRect); overload;
procedure Ellipse(X1, Y1, X2, Y2: Integer); overload; virtual; abstract;
procedure FillRect(const Rect: TRect); virtual; abstract;
procedure Frame3D( var Rect: TRect; TopColor,BottomColor: TColor;
Width: Integer); virtual;
procedure LineTo(X,Y:Integer); virtual; abstract;
procedure MoveTo(X,Y:Integer); virtual; abstract;
procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); virtual; abstract;
procedure Rectangle(const R:TRect); overload;
procedure Rectangle(X0,Y0,X1,Y1:Integer); overload; virtual; abstract;
procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); overload; virtual; abstract;
procedure RoundRect(Const R:TRect; X,Y:Integer); overload;
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); overload; virtual; abstract;
Procedure TextOut(X,Y:Integer; const Text:String); virtual; abstract;
Function TextWidth(Const St:String):Integer; virtual;
Function TextHeight(Const St:String):Integer; virtual;
{ 2d extra }
procedure ClipRectangle(Const Rect:TRect); overload; virtual; abstract;
Procedure ClipRectangle(Const Rect:TRect; RoundSize:Integer); overload; virtual;
Procedure ClipEllipse(Const Rect:TRect; Inverted:Boolean=False); virtual;
Procedure ClipPolygon(Var Points:Array of TPoint; NumPoints:Integer); virtual;
// Returns modified Points array with sorted points that define
// biggest convex polygon.
// Written by Peter Bone : peterbone@hotmail.com
function ConvexHull(var Points : TPointArray) : Boolean;
Procedure DoHorizLine(X0,X1,Y:Integer); virtual; abstract;
Procedure DoRectangle(Const Rect:TRect); // obsolete
Procedure DoVertLine(X,Y0,Y1:Integer); virtual; abstract;
procedure EraseBackground(const Rect: TRect); virtual; abstract;
Procedure GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50); virtual; abstract;
Procedure Invalidate; virtual; abstract;
Procedure Line(X0,Y0,X1,Y1:Integer); overload; virtual; abstract;
Procedure Line(const FromPoint,ToPoint:TPoint); overload;
{$IFDEF D5}
Procedure Polyline(const Points:Array of TPoint); overload; virtual; abstract;
{$ELSE}
Procedure Polyline(const Points:TPointArray); overload; virtual; abstract;
{$ENDIF}
Procedure Polygon(const Points: Array of TPoint); virtual; abstract;
procedure RotateLabel( x,y:Integer; Const St:String;
RotDegree:Double); virtual; abstract; // 7.0
property SupportsFullRotation:Boolean read GetSupportsFullRotation;
procedure UnClipRectangle; virtual; abstract;
// properties
property BackColor:TColor read GetBackColor write SetBackColor;
property BackMode:TCanvasBackMode read GetBackMode write SetBackMode;
property Bounds:TRect read FBounds;
property Brush:TBrush read FBrush;
property Font:TFont read FFont;
property FontHeight:Integer read GetFontHeight;
property Handle:TTeeCanvasHandle read GetHandle;
property Metafiling:Boolean read FMetafiling write FMetafiling;
property Monochrome:Boolean read GetMonochrome write SetMonochrome;
property Pen:TPen read FPen;
property Pixels[X, Y: Integer]: TColor read GetPixel write SetPixel;
property ReferenceCanvas:TCanvas read FCanvas write SetCanvas;
property TextAlign:TCanvasTextAlign read GetTextAlign write SetTextAlign;
property UseBuffer:Boolean read GetUseBuffer write SetUseBuffer;
end;
// 2D
TFloatPoint=packed record
{$IFDEF CLR}
public
{$ENDIF}
X : Double;
Y : Double;
end;
// 3D
TPoint3DFloat=packed record
{$IFDEF CLR}
public
{$ENDIF}
X : Double;
Y : Double;
Z : Double;
end;
TPoint3D =packed record x,y,z:Integer; end;
TTrianglePoints =Array[0..2] of TPoint;
TTrianglePoints3D=Array[0..2] of TPoint3D;
TTriangleColors3D=Array[0..2] of TColor;
TCirclePoints =Array[0..NumCirclePoints-1] of TPoint;
TTeeCanvasCalcPoints=Function( x,z:Integer; Var P0,P1:TPoint3D;
Var Color0,Color1:TColor):Boolean of object;
TTeeCanvasSurfaceStyle=(tcsSolid,tcsWire,tcsDot);
TCanvas3D=class {$IFDEF CLR}abstract{$ENDIF} (TTeeCanvas)
private
F3DOptions : TView3DOptions;
IDisabledRotation : Integer;
protected
FIsOrthogonal : Boolean; // 6.01, moved from private due to RotateTool
GradientZ : Integer; // 7.0, used at TGLCanvas
procedure CalcPieAngles(X1,Y1,X2,Y2,X3,Y3,X4,Y4:Integer; var Theta,Theta2:Extended);
Function GetPixel3D(X,Y,Z:Integer):TColor; virtual; abstract;
Function GetSupports3DText:Boolean; virtual; abstract;
procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); virtual; abstract;
public
RotationCenter : TPoint3DFloat;
{ 3d }
Function CalcRect3D(Const R:TRect; Z:Integer):TRect;
Procedure Calculate2DPosition(Var x,y:Integer; z:Integer); virtual; abstract;
Function Calculate3DPosition(const P:TPoint3D):TPoint; overload; // 7.0
Function Calculate3DPosition(P:TPoint; z:Integer):TPoint; overload;
Function Calculate3DPosition(x,y,z:Integer):TPoint; overload; virtual; abstract;
Function FourPointsFromRect(Const R:TRect; Z:Integer):TFourPoints;
Function RectFromRectZ(Const R:TRect; Z:Integer):TRect;
Function InitWindow( DestCanvas:TCanvas; A3DOptions:TView3DOptions;
ABackColor:TColor;
Is3D:Boolean;
Const UserRect:TRect):TRect; virtual; abstract;
Procedure Assign(Source:TCanvas3D); virtual;
Procedure Projection(MaxDepth:Integer; const Bounds,Rect:TRect); virtual; abstract;
Procedure ShowImage( DestCanvas,DefaultCanvas:TCanvas;
Const UserRect:TRect); virtual; abstract;
Function ReDrawBitmap:Boolean; virtual; abstract;
Procedure Arrow( Filled:Boolean; Const FromPoint,ToPoint:TPoint;
ArrowWidth,ArrowHeight,Z:Integer); virtual; abstract;
procedure ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); virtual; abstract;
procedure Cone( Vertical:Boolean; Left,Top,Right,Bottom,Z0,Z1:Integer;
Dark3D:Boolean; ConePercent:Integer); virtual; abstract;
Procedure Cube( Left,Right,Top,Bottom,Z0,Z1:Integer;
DarkSides:Boolean=True); overload; virtual; abstract;
Procedure Cube( const R:TRect; Z0,Z1:Integer;
DarkSides:Boolean=True); overload;
procedure Cylinder( Vertical:Boolean; Left,Top,Right,Bottom,Z0,Z1:Integer;
Dark3D:Boolean); virtual; abstract;
procedure DisableRotation; virtual;
procedure EllipseWithZ(X1, Y1, X2, Y2, Z: Integer); virtual; abstract;
procedure EnableRotation; virtual;
Procedure HorizLine3D(Left,Right,Y,Z:Integer); virtual; abstract;
Procedure VertLine3D(X,Top,Bottom,Z:Integer); virtual; abstract;
Procedure ZLine3D(X,Y,Z0,Z1:Integer); virtual; abstract;
procedure FrontPlaneBegin; virtual;
procedure FrontPlaneEnd; virtual;
Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); overload; virtual; abstract;
Procedure LineWithZ(const FromPoint,ToPoint:TPoint; Z:Integer); overload;
procedure MoveTo3D(X,Y,Z:Integer); overload; virtual; abstract;
procedure MoveTo3D(const P:TPoint3D); overload; // 7.0
procedure LineTo3D(X,Y,Z:Integer); overload; virtual; abstract;
procedure LineTo3D(const P:TPoint3D); overload; // 7.0
procedure Pie3D( XCenter,YCenter,XRadius,YRadius,Z0,Z1:Integer;
Const StartAngle,EndAngle:Double;
DarkSides,DrawSides:Boolean;
DonutPercent:Integer=0;
Gradient:TCustomTeeGradient=nil); virtual; abstract;
procedure Plane3D(Const A,B:TPoint; Z0,Z1:Integer); virtual; abstract;
procedure PlaneWithZ(const P:TFourPoints; Z:Integer); overload;
procedure PlaneWithZ(P1,P2,P3,P4:TPoint; Z:Integer); overload; virtual; abstract;
procedure PlaneFour3D(Var Points:TFourPoints; Z0,Z1:Integer); virtual; abstract;
procedure PolygonWithZ(Points: Array of TPoint; Z:Integer); virtual; abstract;
procedure Polyline(const Points: Array of TPoint; Z:Integer); overload; virtual; abstract;
procedure Pyramid( Vertical:Boolean; Left,Top,Right,Bottom,z0,z1:Integer;
DarkSides:Boolean); virtual; abstract;
Procedure PyramidTrunc(Const R:TRect; StartZ,EndZ:Integer;
TruncX,TruncZ:Integer); virtual; abstract;
Procedure Rectangle(Const R:TRect; Z:Integer); overload;
Procedure Rectangle(X0,Y0,X1,Y1,Z:Integer); overload;
Procedure RectangleWithZ(Const Rect:TRect; Z:Integer); virtual; abstract;
Procedure RectangleY(Left,Top,Right,Z0,Z1:Integer); virtual; abstract;
Procedure RectangleZ(Left,Top,Bottom,Z0,Z1:Integer); virtual; abstract;
procedure RotatedEllipse(Left,Top,Right,Bottom,Z:Integer; Const Angle:Double);
procedure RotateLabel3D( x,y,z:Integer; Const St:String;
RotDegree:Double); virtual; abstract; // 7.0
procedure Sphere(x,y,z:Integer; Const Radius:Double); virtual; abstract;
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic; Z:Integer); overload;
Procedure Surface3D( Style:TTeeCanvasSurfaceStyle;
SameBrush:Boolean; NumXValues,NumZValues:Integer;
CalcPoints:TTeeCanvasCalcPoints ); virtual; abstract;
Procedure TextOut3D(x,y,z:Integer; const Text:String); virtual; abstract;
procedure Triangle3D( Const Points:TTrianglePoints3D;
Const Colors:TTriangleColors3D); virtual; abstract;
procedure TriangleWithZ(Const P1,P2,P3:TPoint; Z:Integer); virtual; abstract;
property Pixels3D[X,Y,Z:Integer]:TColor read GetPixel3D write SetPixel3D;
property Supports3DText:Boolean read GetSupports3DText;
property View3DOptions:TView3DOptions read F3DOptions write F3DOptions;
end;
TTeeCanvas3D=class(TCanvas3D)
private
FXCenter : Integer;
FYCenter : Integer;
FZCenter : Integer;
FXCenterOffset : Integer;
FYCenterOffset : Integer;
s1 : Extended;
s2 : Extended;
s3 : Extended;
c1 : Extended;
c2 : Extended;
c3 : Extended;
c2s3 : Double;
c2c3 : Double;
tempXX : Double;
tempYX : Double;
tempXZ : Double;
tempYZ : Double;
FWas3D : Boolean;
FBitmap : TBitmap;
{$IFDEF TEEBITMAPSPEED}
IBitmapCanvas : TTeeCanvasHandle;
{$ENDIF}
FDirty : Boolean;
FMonochrome : Boolean;
FTextAlign : TCanvasTextAlign;
IHasPerspec : Boolean;
IHasTilt : Boolean;
IOrthoX : Double;
IOrthoY : Double;
IZoomPerspec : Double;
IZoomFactor : Double;
IZoomText : Boolean;
procedure InternalCylinder(Vertical:Boolean; Left,Top,Right,Bottom,
Z0,Z1:Integer; Dark3D:Boolean; ConePercent:Integer);
protected
FBufferedDisplay : Boolean;
FIs3D : Boolean;
IPoints : TFourPoints;
{ 2d }
function GetBackColor:TColor; override;
Function GetBackMode:TCanvasBackMode; override;
Function GetHandle:TTeeCanvasHandle; override;
Function GetMonochrome:Boolean; override;
Function GetPixel(X, Y: Integer):TColor; override;
Function GetPixel3D(X,Y,Z:Integer):TColor; override;
Function GetSupports3DText:Boolean; override;
Function GetSupportsFullRotation:Boolean; override;
Function GetTextAlign:TCanvasTextAlign; override;
Function GetUseBuffer:Boolean; override;
Procedure PolygonFour; virtual;
Procedure SetBackColor(Color:TColor); override;
Procedure SetBackMode(Mode:TCanvasBackMode); override;
Procedure SetMonochrome(Value:Boolean); override;
procedure SetPixel(X, Y: Integer; Value: TColor); override;
procedure SetTextAlign(Align:TCanvasTextAlign); override;
Procedure SetUseBuffer(Value:Boolean); override;
Procedure DeleteBitmap; virtual;
Procedure TransferBitmap(ALeft,ATop:Integer; ACanvas:TCanvas); virtual;
{ 3d private }
Procedure Calc3DTPoint(Var P:TPoint; z:Integer);
Function Calc3DTPoint3D(Const P:TPoint3D):TPoint;
Procedure Calc3DPoint(Var P:TPoint; x,y,z:Integer); overload;
Procedure Calc3DPoint(Var P:TPoint; x,y:Double; z:Integer); overload;
{ 3d }
procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); override;
Procedure Calc3DPos(var x,y:Integer; z:Integer); overload;
Procedure CalcPerspective(const Rect:TRect);
{$IFNDEF CLR}
Procedure CalcTrigValues;
{$ENDIF}
public
{ almost public... }
Procedure Calculate2DPosition(Var x,y:Integer; z:Integer); override;
Function Calculate3DPosition(x,y,z:Integer):TPoint; override;
{ public }
Constructor Create;
Destructor Destroy; override;
{$IFDEF CLR}
Procedure CalcTrigValues;
{$ENDIF}
Function InitWindow( DestCanvas:TCanvas;
A3DOptions:TView3DOptions;
ABackColor:TColor;
Is3D:Boolean;
Const UserRect:TRect):TRect; override;
Function ReDrawBitmap:Boolean; override;
Procedure ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); override;
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Donut( XCenter,YCenter,XRadius,YRadius:Integer;
Const StartAngle,EndAngle,HolePercent:Double); override;
procedure Draw(X, Y: Integer; Graphic: TGraphic); override;
procedure Ellipse(X1, Y1, X2, Y2: Integer); override;
procedure EraseBackground(const Rect: TRect); override;
procedure FillRect(const Rect: TRect); override;
procedure LineTo(X,Y:Integer); override;
procedure MoveTo(X,Y:Integer); override;
procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Rectangle(X0,Y0,X1,Y1:Integer); override;
procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); override;
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); override;
Procedure TextOut(X,Y:Integer; const Text:String); override;
{ 2d extra }
procedure ClipRectangle(Const Rect:TRect); override;
procedure ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); override;
procedure DisableRotation; override;
Procedure DoHorizLine(X0,X1,Y:Integer); override;
Procedure DoVertLine(X,Y0,Y1:Integer); override;
procedure EnableRotation; override;
Procedure GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50); override;
Procedure Invalidate; override;
Procedure Line(X0,Y0,X1,Y1:Integer); override;
{$IFDEF D5}
Procedure Polyline(const Points:Array of TPoint); override;
{$ELSE}
Procedure Polyline(const Points:TPointArray); override;
{$ENDIF}
Procedure Polygon(const Points: Array of TPoint); override;
procedure RotateLabel(x,y:Integer; const St:String; RotDegree:Double); override;
procedure RotateLabel3D( x,y,z:Integer;
const St:String; RotDegree:Double); override;
procedure UnClipRectangle; override;
property XCenter:Integer read FXCenter write FXCenter;
property YCenter:Integer read FYCenter write FYCenter;
property ZCenter:Integer read FZCenter write FZCenter;
{ 3d }
Procedure Projection(MaxDepth:Integer; const Bounds,Rect:TRect); override;
Procedure Arrow( Filled:Boolean; Const FromPoint,ToPoint:TPoint;
ArrowWidth,ArrowHeight,Z:Integer); override;
procedure Cone( Vertical:Boolean; Left,Top,Right,Bottom,Z0,Z1:Integer;
Dark3D:Boolean; ConePercent:Integer); override;
Procedure Cube(Left,Right,Top,Bottom,Z0,Z1:Integer; DarkSides:Boolean=True); override;
procedure Cylinder( Vertical:Boolean; Left,Top,Right,Bottom,Z0,Z1:Integer;
Dark3D:Boolean); override;
procedure EllipseWithZ(X1, Y1, X2, Y2, Z: Integer); override;
procedure GetCirclePoints(var P:TCirclePoints; X1, Y1, X2, Y2, Z: Integer);
Procedure RectangleZ(Left,Top,Bottom,Z0,Z1:Integer); override;
Procedure RectangleY(Left,Top,Right,Z0,Z1:Integer); override;
Procedure HorizLine3D(Left,Right,Y,Z:Integer); override;
procedure LineTo3D(X,Y,Z:Integer); override;
Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); override;
procedure MoveTo3D(X,Y,Z:Integer); override;
procedure Pie3D( XCenter,YCenter,XRadius,YRadius,Z0,Z1:Integer;
Const StartAngle,EndAngle:Double;
DarkSides,DrawSides:Boolean; DonutPercent:Integer=0;
Gradient:TCustomTeeGradient=nil); override;
procedure Plane3D(Const A,B:TPoint; Z0,Z1:Integer); override;
procedure PlaneWithZ(P1,P2,P3,P4:TPoint; Z:Integer); override;
procedure PlaneFour3D(Var Points:TFourPoints; Z0,Z1:Integer); override;
procedure PolygonWithZ(Points: Array of TPoint; Z:Integer); override;
procedure Polyline(const Points: Array of TPoint; Z:Integer); override;
procedure Pyramid( Vertical:Boolean; Left,Top,Right,Bottom,z0,z1:Integer;
DarkSides:Boolean); override;
Procedure PyramidTrunc(Const R:TRect; StartZ,EndZ:Integer;
TruncX,TruncZ:Integer); override;
Procedure RectangleWithZ(Const Rect:TRect; Z:Integer); override;
procedure Sphere(x,y,z:Integer; Const Radius:Double); override;
Procedure Surface3D( Style:TTeeCanvasSurfaceStyle;
SameBrush:Boolean;
NumXValues,NumZValues:Integer;
CalcPoints:TTeeCanvasCalcPoints ); override;
Procedure TextOut3D(X,Y,Z:Integer; const Text:String); override;
procedure Triangle3D( Const Points:TTrianglePoints3D;
Const Colors:TTriangleColors3D); override;
procedure TriangleWithZ(Const P1,P2,P3:TPoint; Z:Integer); override;
Procedure VertLine3D(X,Top,Bottom,Z:Integer); override;
Procedure ZLine3D(X,Y,Z0,Z1:Integer); override;
property Bitmap:TBitmap read FBitmap;
end;
Function ApplyDark(Color:TColor; HowMuch:Byte):TColor;
Function ApplyBright(Color:TColor; HowMuch:Byte):TColor;
Function Point3D(x,y,z:Integer):TPoint3D;
Procedure SwapDouble(Var a,b:Double); { exchanges a and b }
Procedure SwapInteger(Var a,b:Integer); { exchanges a and b }
Procedure RectSize(Const R:TRect; Var RectWidth,RectHeight:Integer);
Procedure RectCenter(Const R:TRect; Var X,Y:Integer);
Function RectFromPolygon(Const Points:Array of TPoint; NumPoints:Integer):TRect;
Function RectFromTriangle(Const Points:TTrianglePoints):TRect;
Procedure ClipCanvas(ACanvas:TCanvas; Const Rect:TRect);
Procedure UnClipCanvas(ACanvas:TCanvas);
// These Clipxxx routines are now deprecated...
// Use TTeeCanvas.Clipxxx equivalent methods.
Procedure ClipEllipse(ACanvas:TTeeCanvas; Const Rect:TRect);
Procedure ClipRoundRectangle(ACanvas:TTeeCanvas; Const Rect:TRect; RoundSize:Integer);
Procedure ClipPolygon(ACanvas:TTeeCanvas; Var Points:Array of TPoint; NumPoints:Integer);
Const TeeCharForHeight = 'W'; { <-- this is used to calculate Text Height }
DarkerColorQuantity : Byte=128; { <-- for dark 3D sides }
DarkColorQuantity : Byte=64;
{$IFDEF TEEVCL}
type
TButtonGetColorProc=function:TColor of object;
TTeeButton = class(TButton)
private
{$IFNDEF CLX}
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
{$ENDIF}
protected
Instance : TObject;
Info : {$IFDEF CLR}TPropInfo{$ELSE}PPropInfo{$ENDIF};
Procedure DrawSymbol(ACanvas:TTeeCanvas); virtual; // abstract;
{$IFNDEF CLX}
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
{$IFDEF TEEWINDOWS}
procedure PaintWindow(DC: HDC); override;
{$ENDIF}
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
{$ELSE}
procedure Painting(Sender: QObjectH; EventRegion: QRegionH); override;
{$ENDIF}
public
Procedure LinkProperty(AInstance:TObject; Const PropName:String);
published
{ Published declarations }
property Height default 25;
property Width default 75;
end;
TButtonColor = class(TTeeButton)
private
Function GetTeeColor : TColor;
procedure SetTeeColor(Const Value:TColor); // 7.0
protected
procedure DrawSymbol(ACanvas:TTeeCanvas); override;
public
GetColorProc : TButtonGetColorProc;
procedure Click; override;
property SymbolColor:TColor read GetTeeColor write SetTeeColor;
end;
TComboFlat=class(TComboBox)
private
{$IFNDEF CLX}
Inside: Boolean;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
{$IFNDEF CLR}
procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
{$ENDIF}
{$ENDIF}
public
Constructor Create(AOwner:TComponent); override;
{$IFNDEF D6}
procedure AddItem(Item: String; AObject: TObject);
{$ENDIF}
published
property Style default csDropDownList;
property Height default 21;
property ItemHeight default 13;
property ItemIndex;
end;
{$ENDIF}
{$IFNDEF D5}
procedure FreeAndNil(var Obj);
{$ENDIF}
{$IFNDEF TEEVCL}
procedure FreeAndNil(var Obj);
function StrToInt(const S: string): Integer;
function ColorToRGB(Color: TColor): Longint;
{$ENDIF}
var IsWindowsNT:Boolean=False;
GetDefaultFontSize:Integer=0;
GetDefaultFontName:String='';
{$IFDEF LINUX}
Function GetRValue(Color:Integer):Byte;
Function GetGValue(Color:Integer):Byte;
Function GetBValue(Color:Integer):Byte;
Function RGB(r,g,b:Integer):TColor;
{$ENDIF}
{$IFDEF CLX}
Function TeeCreatePenSmallDots(AColor:TColor):QPenH;
{$ELSE}
Function TeeCreatePenSmallDots(AColor:TColor):HPen;
{$ENDIF}
Procedure TeeSetTeePen(FPen:TPen; APen:TChartPen; AColor:TColor; Handle:TTeeCanvasHandle);
// Converts ABitmap pixels into Gray Scale (levels of gray)
Procedure TeeGrayScale(ABitmap:TBitmap; Inverted:Boolean; AMethod:Integer); { 5.02 }
Function TeePoint(aX,aY:Integer):TPoint; { compatibility with D6 CLX }
function PointInRect(Const Rect:TRect; x,y:Integer):Boolean; { compatibility with D6 CLX }
function TeeRect(Left,Top,Right,Bottom:Integer):TRect; { compatibility with D6 CLX }
Function OrientRectangle(Const R:TRect):TRect;
Function PolygonBounds(Const P:TPointArray):TRect; // 7.0
// Default color depth
Const TeePixelFormat={$IFDEF CLX}pf32Bit{$ELSE}pf24Bit{$ENDIF};
{$IFDEF CLX}
type
TRGBTriple=packed record
rgbtBlue : Byte;
rgbtGreen : Byte;
rgbtRed : Byte;
rgbtAlpha : Byte; // Linux ?
end;
{$ENDIF}
Function RGBValue(Color:TColor):TRGBTriple;
{$IFDEF TEEVCL}
{ Show the TColorDialog, return new color if changed }
Function EditColor(AOwner:TComponent; AColor:TColor):TColor;
{ Show the TColorDialog, return True if color changed }
Function EditColorDialog(AOwner:TComponent; var AColor:TColor):Boolean;
{$ENDIF}
// Returns point "ATo" minus ADist pixels from AFrom point.
Function PointAtDistance(AFrom,ATo:TPoint; ADist:Integer):TPoint;
// Returns True when 3 first points in P are "face-viewing".
Function TeeCull(const P:TFourPoints):Boolean; overload;
Function TeeCull(const P0,P1,P2:TPoint):Boolean; overload;
// Draws SRC bitmap with smooth stretch to Dst bitmap
type TSmoothStretchOption = (ssBestQuality, ssBestPerformance);
procedure SmoothStretch(Src, Dst: TBitmap); overload;
procedure SmoothStretch(Src, Dst: TBitmap; Option: TSmoothStretchOption); overload;
// Returns Sqrt( Sqr(x)+Sqr(y) )
Function TeeDistance(const x,y:Double):Double; // 7.0 changed to "double"
{ Used at EditColor function, for the Color Editor dialog }
var TeeCustomEditColors:TStrings=nil;
{$IFNDEF LINUX}
TeeFontAntiAlias:Integer=ANTIALIASED_QUALITY;
{$ENDIF}
{$IFNDEF CLX}
TeeSetDCBrushColor:function(DC: HDC; Color: COLORREF): COLORREF; stdcall;
TeeSetDCPenColor:function(DC: HDC; Color: COLORREF): COLORREF; stdcall;
{$ENDIF}
// Load a DLL, compatible with Delphi 4 and up.
{$IFNDEF LINUX}
Function TeeLoadLibrary(Const FileName:String):HInst;
// Free Library, but do not free library in Windows 95 (lock bug)
Procedure TeeFreeLibrary(hLibModule: HMODULE);
{$ENDIF}
var
TeeNumCylinderSides:Integer=16;
implementation
Uses {$IFDEF CLR}
System.Runtime.InteropServices,
System.Drawing,
System.Drawing.Drawing2D,
{$ENDIF}
{$IFDEF TEEVCL}
{$IFDEF CLX}
QForms, QDialogs,
{$ELSE}
Forms, Dialogs,
{$ENDIF}
{$ENDIF}
Math,
{$IFNDEF CLX}
{$IFDEF D6}
Types,
{$ENDIF}
{$ENDIF}
TeeConst;
type PPoints = ^TPoints;
TPoints = Array[0..0] of TPoint;
{$IFNDEF CLX}
var WasOldRegion : Boolean=False;
OldRegion : HRgn=0;
{$ENDIF}
{$IFNDEF TEEWINDOWS}
procedure InflateRect(var R:TRect; x,y:Integer);
begin
Inc(R.Left,-x);
Inc(R.Right,x);
Inc(R.Top,-y);
Inc(R.Bottom,y);
end;
{$ENDIF}
Function TeeCull(const P:TFourPoints):Boolean;
begin
result:=TeeCull(P[0],P[1],P[2]);
end;
Function TeeCull(const P0,P1,P2:TPoint):Boolean;
begin
result:=( ((P0.x-P1.x) * (P2.y-P1.y)) -
((P2.x-P1.x) * (P0.y-P1.y))
) < 0;
end;
Function TeePoint(aX,aY:Integer):TPoint;
begin
with result do
begin
X:=aX;
Y:=aY;
end;
end;
function PointInRect(Const Rect:TRect; x,y:Integer):Boolean;
begin
result:=(x>=Rect.Left) and (y>=Rect.Top) and
(x<=Rect.Right) and (y<=Rect.Bottom); // 7.0
end;
function TeeRect(Left,Top,Right,Bottom:Integer):TRect;
begin
result.Left :=Left;
result.Top :=Top;
result.Bottom:=Bottom;
result.Right :=Right;
end;
// Makes sure the R rectangle Left is smaller than Right and
// Top is smaller than Bottom. Returns corrected rectangle.
Function OrientRectangle(Const R:TRect):TRect;
{$IFDEF CLR}
var tmp : Integer;
{$ENDIF}
begin
result:=R;
with result do
begin
if Left>Right then
{$IFDEF CLR}
begin
tmp:=Left; Left:=Right; Right:=tmp;
end;
{$ELSE}
SwapInteger(Left,Right);
{$ENDIF}
if Top>Bottom then
{$IFDEF CLR}
begin
tmp:=Top; Top:=Bottom; Bottom:=tmp;
end;
{$ELSE}
SwapInteger(Top,Bottom);
{$ENDIF}
end;
end;
Function Point3D(x,y,z:Integer):TPoint3D;
begin
result.x:=x;
result.y:=y;
result.z:=z;
end;
Procedure RectSize(Const R:TRect; Var RectWidth,RectHeight:Integer);
begin
With R do
begin
RectWidth :=Right-Left;
RectHeight:=Bottom-Top;
end;
end;
Procedure RectCenter(Const R:TRect; Var X,Y:Integer);
begin
With R do
begin
X:=(Left+Right) div 2;
Y:=(Top+Bottom) div 2;
end;
end;
// Returns the minimum left / top and the
// maximum right / bottom for all the points in "P" polygon
Function PolygonBounds(Const P:TPointArray):TRect;
var t : Integer;
begin
result:=TeeRect(0,0,0,0);
if Length(P)>0 then
With result do
begin
TopLeft:=P[0];
BottomRight:=TopLeft;
for t:=0 to Length(P)-1 do
begin
if P[t].X<Left then Left:=P[t].X
else
if P[t].X>Right then Right:=P[t].X;
if P[t].Y<Top then Top:=P[t].Y
else
if P[t].Y>Bottom then Bottom:=P[t].Y;
end;
end;
end;
{ TChartPen }
Constructor TChartPen.Create(OnChangeEvent:TNotifyEvent);
begin
inherited Create;
FVisible:=True;
DefaultVisible:=True;
DefaultEnd:=esRound;
OnChange:=OnChangeEvent;
{$IFDEF CLX}
ReleaseHandle;
Width:=1;
{$ENDIF}
end;
Procedure TChartPen.Assign(Source:TPersistent);
begin
if Source is TChartPen then
begin
FVisible :=TChartPen(Source).Visible;
FSmallDots:=TChartPen(Source).SmallDots;
FEndStyle :=TChartPen(Source).EndStyle; { 5.01 }
end;
{$IFDEF CLX}
if not Assigned(Handle) then ReleaseHandle;
{$ENDIF}
inherited;
end;
procedure TChartPen.Hide;
begin
Visible:=False;
end;
procedure TChartPen.Show;
begin
Visible:=True;
end;
Function TChartPen.IsEndStored:Boolean;
begin
result:=FEndStyle<>DefaultEnd;
end;
Function TChartPen.IsVisibleStored:Boolean;
begin
result:=FVisible<>DefaultVisible;
end;
procedure TChartPen.SetEndStyle(const Value: TPenEndStyle);
begin
if FEndStyle<>Value then
begin
FEndStyle:=Value;
Changed;
end;
end;
Procedure TChartPen.SetSmallDots(Value:Boolean);
begin
if FSmallDots<>Value then
begin
FSmallDots:=Value;
Changed;
end;
end;
Procedure TChartPen.SetVisible(Value:Boolean);
Begin
if FVisible<>Value then
begin
FVisible:=Value;
Changed;
end;
end;
{ TChartHiddenPen }
Constructor TChartHiddenPen.Create(OnChangeEvent:TNotifyEvent);
Begin
inherited;
FVisible:=False;
DefaultVisible:=False;
end;
{ TDottedGrayPen }
Constructor TDottedGrayPen.Create(OnChangeEvent:TNotifyEvent);
Begin
inherited;
Color:=clGray;
Style:=psDot;
end;
{ TDarkGrayPen }
Constructor TDarkGrayPen.Create(OnChangeEvent:TNotifyEvent);
Begin
inherited;
Color:=clDkGray;
end;
{ TChartBrush }
Constructor TChartBrush.Create(OnChangeEvent:TNotifyEvent);
Begin
inherited Create;
Color:=clDefault;
OnChange:=OnChangeEvent;
end;
Destructor TChartBrush.Destroy;
begin
FImage.Free;
inherited;
end;
Procedure TChartBrush.Assign(Source:TPersistent);
begin
if Source is TChartBrush then
Image.Assign(TChartBrush(Source).FImage);
inherited;
end;
Procedure TChartBrush.Clear; // 7.0
begin
Style:=bsClear;
Image:=nil;
end;
procedure TChartBrush.SetImage(Value: TPicture);
begin
if Assigned(Value) then Image.Assign(Value)
else FreeAndNil(FImage);
Changed;
end;
Function TChartBrush.GetImage:TPicture;
begin
if not Assigned(FImage) then
begin
FImage:=TPicture.Create;
FImage.OnChange:=OnChange;
end;
result:=FImage;
end;
{ TView3DOptions }
Constructor TView3DOptions.Create({$IFDEF TEEVCL}AParent:TWinControl{$ENDIF});
begin
inherited Create;
{$IFDEF TEEVCL}
FParent :=AParent;
{$ENDIF}
FOrthogonal :=True;
FOrthoAngle :=45;
FFontZoom :=100; { % } // 7.0
FZoom :=100; { % }
FZoomText :=True;
FRotation :=345;
FElevation :=345;
FPerspective :=TeeDefaultPerspective; { % }
end;
Procedure TView3DOptions.Repaint;
begin
{$IFDEF TEEVCL}
FParent.Invalidate;
{$ENDIF}
end;
Procedure TView3DOptions.SetIntegerProperty(Var Variable:Integer; Value:Integer);
begin
if Variable<>Value then
begin
Variable:=Value;
Repaint;
end;
end;
Procedure TView3DOptions.SetBooleanProperty(Var Variable:Boolean; Value:Boolean);
begin
if Variable<>Value then
begin
Variable:=Value;
Repaint;
end;
end;
Procedure TView3DOptions.SetElevation(Value:Integer);
begin
SetIntegerProperty(FElevation,Value);
end;
Procedure TView3DOptions.SetFontZoom(Value:Integer);
begin
SetIntegerProperty(FFontZoom,Value);
end;
Procedure TView3DOptions.SetPerspective(Value:Integer);
begin
SetIntegerProperty(FPerspective,Value);
end;
Procedure TView3DOptions.SetRotation(Value:Integer);
begin
SetIntegerProperty(FRotation,Value);
end;
Procedure TView3DOptions.SetTilt(Value:Integer);
begin
SetIntegerProperty(FTilt,Value);
end;
Procedure TView3DOptions.SetHorizOffset(Value:Integer);
begin
if FHorizOffset<>Value then
begin
FHorizOffset:=Value;
Repaint;
if Assigned(FOnScrolled) then FOnScrolled(True);
end;
end;
Procedure TView3DOptions.SetVertOffset(Value:Integer);
begin
if FVertOffset<>Value then
begin
FVertOffset:=Value;
Repaint;
if Assigned(FOnScrolled) then FOnScrolled(False);
end;
end;
Procedure TView3DOptions.SetOrthoAngle(Value:Integer);
begin
SetIntegerProperty(FOrthoAngle,Value);
end;
Procedure TView3DOptions.SetOrthogonal(Value:Boolean);
begin
SetBooleanProperty(FOrthogonal,Value);
end;
Procedure TView3DOptions.SetZoom(Value:Integer);
begin
if FZoom<>Value then
begin
if Assigned(FOnChangedZoom) then FOnChangedZoom(Value);
FZoom:=Value;
Repaint;
end;
end;
Procedure TView3DOptions.SetZoomText(Value:Boolean);
begin
SetBooleanProperty(FZoomText,Value);
end;
Procedure TView3DOptions.Assign(Source:TPersistent);
begin
if Source is TView3DOptions then
With TView3DOptions(Source) do
begin
Self.FElevation :=FElevation;
Self.FFontZoom :=FFontZoom;
Self.FHorizOffset :=FHorizOffset;
Self.FOrthoAngle :=FOrthoAngle;
Self.FOrthogonal :=FOrthogonal;
Self.FPerspective :=FPerspective;
Self.FRotation :=FRotation;
Self.FTilt :=FTilt;
Self.FVertOffset :=FVertOffset;
Self.FZoom :=FZoom;
Self.FZoomText :=FZoomText;
end;
end;
function TView3DOptions.CalcOrthoRatio: Double;
var tmpSin : Extended;
tmpCos : Extended;
tmpAngle : Extended;
begin
if Orthogonal then
begin
tmpAngle:=OrthoAngle;
if tmpAngle>90 then tmpAngle:=180-tmpAngle;
SinCos(tmpAngle*TeePiStep,tmpSin,tmpCos);
result:=tmpSin/tmpCos;
end
else result:=1;
end;
{ TTeeCanvas }
Procedure TTeeCanvas.InternalDark(Const AColor:TColor; Quantity:Byte);
var tmpColor : TColor;
begin
tmpColor:=ApplyDark(AColor,Quantity);
if FBrush.Style=bsSolid then FBrush.Color:=tmpColor
else BackColor:=tmpColor;
end;
Function TTeeCanvas.GetFontHeight:Integer;
begin
result:=TextHeight(TeeCharForHeight);
end;
Procedure TTeeCanvas.SetCanvas(ACanvas:TCanvas);
begin
FCanvas:=ACanvas;
FPen :=FCanvas.Pen;
FFont :=FCanvas.Font;
FBrush :=FCanvas.Brush;
{$IFNDEF CLR}
{$IFNDEF CLX}
{$IFNDEF TEECANVASLOCKS}
FPen.OwnerCriticalSection:=nil;
FFont.OwnerCriticalSection:=nil;
FBrush.OwnerCriticalSection:=nil;
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
Procedure TTeeCanvas.ResetState;
begin
With FPen do
begin
Color:=clBlack;
Width:=1;
Style:=psSolid;
end;
With FBrush do
begin
Color:=clWhite;
Style:=bsSolid;
end;
With FFont do
begin
Color:=clBlack;
Style:=[];
{$IFNDEF CLX}
CharSet:=DEFAULT_CHARSET;
{$ENDIF}
Name:=GetDefaultFontName;
Size:=GetDefaultFontSize;
end;
ITransp:=0; // 6.02
IFont:=nil; // 6.02
BackColor:=clWhite;
BackMode:=cbmTransparent;
TextAlign:=TA_LEFT; { 5.01 }
end;
Procedure TTeeCanvas.AssignBrush(ABrush:TChartBrush; ABackColor:TColor);
begin
AssignBrushColor(ABrush,ABackColor,ABrush.Color);
end;
{$IFDEF CLX}
Procedure SetTextColor(Handle:QPainterH; Color:Integer);
var QC : QColorH;
begin
QC:=QColor(Color);
try
QPen_setColor(QPainter_pen(Handle), QC);
finally
QColor_destroy(QC);
end;
end;
{$ENDIF}
Procedure TTeeCanvas.AssignBrushColor(ABrush:TChartBrush; AColor,ABackColor:TColor);
begin
if Monochrome then AColor:=clWhite;
if Assigned(ABrush.FImage) and Assigned(ABrush.FImage.Graphic) then
begin
Brush.Style:=bsClear;
Brush.Bitmap:=ABrush.Image.Bitmap;
{$IFDEF TEEWINDOWS}
SetTextColor(Handle,ColorToRGB(AColor));
{$ENDIF}
BackMode:=cbmOpaque;
BackColor:=ABackColor;
end
else
begin
Brush.Bitmap:=nil;
if AColor<>Brush.Color then { 5.02 }
Brush.Color:=AColor;
if ABrush.Style<>Brush.Style then { 5.02 }
Brush.Style:=ABrush.Style;
if ABackColor=clNone then BackMode:=cbmTransparent { 5.02 }
else
begin
BackMode:=cbmOpaque;
BackColor:=ABackColor;
end;
end;
end;
procedure TTeeCanvas.AssignVisiblePen(APen:TPen);
begin
AssignVisiblePenColor(APen,APen.Color);
end;
Procedure TTeeCanvas.Rectangle(Const R:TRect);
begin
With R do Rectangle(Left,Top,Right,Bottom);
end;
Procedure TTeeCanvas.DoRectangle(Const Rect:TRect); // obsolete
begin
Rectangle(Rect);
end;
Function RGBValue(Color:TColor):TRGBTriple;
begin
with result do
begin
rgbtRed:=Byte(Color);
rgbtGreen:=Byte(Color shr 8);
rgbtBlue:=Byte(Color shr 16);
end;
end;
{$IFDEF TEEWINDOWS}
Function TeeCreatePenSmallDots(AColor:TColor):{$IFDEF CLX}QPenH{$ELSE}HPen{$ENDIF};
{$IFNDEF CLX}
Var LBrush : TLogBrush;
{$ENDIF}
begin
{$IFDEF CLX}
result:=QPen_create(QColor(AColor),1,PenStyle_DotLine);
{$ELSE}
LBrush.lbStyle:=bs_Solid;
LBrush.lbColor:=ColorToRGB(AColor);
LBrush.lbHatch:=0;
result:=ExtCreatePen( PS_COSMETIC or PS_ALTERNATE,1,LBrush,0,nil );
{$ENDIF}
end;
Procedure TeeSetTeePen(FPen:TPen; APen:TChartPen; AColor:TColor; Handle:TTeeCanvasHandle);
{$IFNDEF CLX}
const
PenStyles: array[TPenStyle] of Word =
(PS_SOLID, PS_DASH, PS_DOT, PS_DASHDOT, PS_DASHDOTDOT, PS_NULL,
PS_INSIDEFRAME);
PenModes: array[TPenMode] of Word =
(R2_BLACK, R2_WHITE, R2_NOP, R2_NOT, R2_COPYPEN, R2_NOTCOPYPEN, R2_MERGEPENNOT,
R2_MASKPENNOT, R2_MERGENOTPEN, R2_MASKNOTPEN, R2_MERGEPEN, R2_NOTMERGEPEN,
R2_MASKPEN, R2_NOTMASKPEN, R2_XORPEN, R2_NOTXORPEN);
var LBrush : TLogBrush;
{$ENDIF}
{$IFNDEF CLX}
var tmpEnd : Integer;
{$ENDIF}
begin
if APen.SmallDots then
begin
FPen.Handle:=TeeCreatePenSmallDots(AColor);
FPen.Mode:=APen.Mode; // 6.02
end
else
{$IFNDEF CLX}
if APen.Width>1 then
begin
FPen.Assign(APen);
FPen.Color:=AColor;
{$IFNDEF CLR}
LBrush.lbStyle:=bs_Solid;
LBrush.lbColor:=ColorToRGB(AColor);
LBrush.lbHatch:=0;
Case APen.EndStyle of { 5.01 }
esRound : tmpEnd:=PS_ENDCAP_ROUND or PS_JOIN_ROUND;
esSquare: tmpEnd:=PS_ENDCAP_SQUARE or PS_JOIN_BEVEL;
else tmpEnd:=PS_ENDCAP_FLAT or PS_JOIN_MITER;
end;
FPen.Handle:=ExtCreatePen( PS_GEOMETRIC or
PenStyles[APen.Style] or tmpEnd,APen.Width,LBrush,0,nil);
// This helps SVG exporting when Pen.Width>1, but breaks drawing dotted pens
// SelectObject(Handle, ExtCreatePen( PS_GEOMETRIC or
// PenStyles[APen.Style] or tmpEnd,APen.Width,LBrush,0,nil));
SetROP2(Handle, PenModes[APen.Mode]);
// FPen.Mode:=APen.Mode;
{$ENDIF}
end
else
{$ENDIF}
begin
FPen.Assign(APen);
// speed optimizations ?
//if APen.Style<>FPen.Style then FPen.Style:=APen.Style;
//if APen.Width<>FPen.Width then FPen.Width:=APen.Width;
//if APen.Mode<>FPen.Mode then FPen.Mode:=APen.Mode;
if FPen.Color<>AColor then FPen.Color:=AColor;
end;
end;
{$ENDIF}
procedure TTeeCanvas.AssignVisiblePenColor(APen:TPen; AColor:TColor);
begin
if MonoChrome then AColor:=clBlack;
if not (APen is TChartPen) then
begin
FPen.Assign(APen);
FPen.Color:=AColor;
end
else
if TChartPen(APen).Visible then
begin
{$IFNDEF CLX}
if IsWindowsNT and (not SupportsFullRotation) then
TeeSetTeePen(FPen,TChartPen(APen),AColor,Handle) { only valid in Windows-NT }
else
{$ENDIF}
begin
FPen.Assign(APen);
//if APen.Style<>FPen.Style then FPen.Style:=APen.Style;
//if APen.Width<>FPen.Width then FPen.Width:=APen.Width;
//if APen.Mode<>FPen.Mode then FPen.Mode:=APen.Mode;
FPen.Color:=AColor;
{$IFDEF CLX}
if FPen.Style<>psSolid then BackMode:=cbmTransparent;
{$ENDIF}
end;
end
else FPen.Style:=psClear;
end;
Procedure TTeeCanvas.AssignFont(AFont:TTeeFont);
{$IFNDEF CLX}
var tmp : TTeeCanvasHandle;
{$ENDIF}
Begin
With FFont do
begin
AFont.PixelsPerInch:=PixelsPerInch;
Assign(AFont);
if FontZoom<>100 then // 6.01
Size:=Round(Size*FontZoom*0.01);
end;
if MonoChrome then FFont.Color:=clBlack;
{$IFNDEF CLX}
tmp:=Handle;
{$IFDEF TEEWINDOWS}
if GetTextCharacterExtra(tmp)<>AFont.InterCharSize then
SetTextCharacterExtra(tmp,AFont.InterCharSize);
{$ENDIF}
{$ENDIF}
IFont:=AFont;
AFont.ICanvas:=Self;
end;
Function TTeeCanvas.TextWidth(Const St:String):Integer;
begin
{$IFNDEF CLX}
result:=FCanvas.TextExtent(St).cx;
{$ELSE}
result:=FCanvas.TextWidth(St);
{$ENDIF}
if Assigned(IFont) and Assigned(IFont.FShadow) then
Inc(result,Abs(IFont.FShadow.HorizSize));
end;
Function TTeeCanvas.TextHeight(Const St:String):Integer;
Begin
{$IFNDEF CLX}
result:=FCanvas.TextExtent(St).cy;
{$ELSE}
result:=FCanvas.TextHeight(St);
{$ENDIF}
if Assigned(IFont) and Assigned(IFont.FShadow) then
Inc(result,Abs(IFont.FShadow.VertSize));
end;
procedure TTeeCanvas.Ellipse(const R:TRect);
begin
with R do Ellipse(Left,Top,Right,Bottom);
end;
procedure TTeeCanvas.Frame3D( var Rect: TRect; TopColor,BottomColor: TColor;
Width: Integer);
var TopRight : TPoint;
BottomLeft : TPoint;
{$IFNDEF D5}
P : TTrianglePoints;
{$ENDIF}
begin
FPen.Width:=1;
FPen.Style:=psSolid;
Dec(Rect.Bottom);
Dec(Rect.Right);
while Width > 0 do
begin
Dec(Width);
with Rect do
begin
TopRight.X := Right;
TopRight.Y := Top;
BottomLeft.X := Left;
BottomLeft.Y := Bottom;
FPen.Color := TopColor;
{$IFDEF D5}
Polyline([BottomLeft,TopLeft,TopRight]);
{$ELSE}
P[0]:=BottomLeft;
P[1]:=TopLeft;
P[2]:=TopRight;
// this is due to a D4 bug...
{$IFNDEF CLX}
Windows.Polyline(FCanvas.Handle, PPoints(@P)^, High(P) + 1);
{$ELSE}
FCanvas.Polyline(Points);
{$ENDIF}
{$ENDIF}
FPen.Color := BottomColor;
Dec(BottomLeft.X);
{$IFDEF D5}
Polyline([TopRight,BottomRight,BottomLeft]);
{$ELSE}
P[0]:=TopRight;
P[1]:=BottomRight;
P[2]:=BottomLeft;
// this is due to a D4 bug...
{$IFNDEF CLX}
Windows.Polyline(FCanvas.Handle, PPoints(@P)^, High(P) + 1);
{$ELSE}
FCanvas.Polyline(Points);
{$ENDIF}
{$ENDIF}
end;
InflateRect(Rect, -1, -1);
end;
Inc(Rect.Bottom);
Inc(Rect.Right);
end;
procedure TTeeCanvas.RoundRect(const R: TRect; X,Y:Integer);
begin
with R do RoundRect(Left,Top,Right,Bottom,X,Y);
end;
procedure TTeeCanvas.Line(const FromPoint, ToPoint: TPoint);
begin
Line(FromPoint.X,FromPoint.Y,ToPoint.X,ToPoint.Y)
end;
Function TTeeCanvas.BeginBlending(const R: TRect;
Transparency: TTeeTransparency):TTeeBlend;
begin
ITransp:=Transparency;
result:=TTeeBlend.Create(Self,R);
end;
procedure TTeeCanvas.EndBlending(Blend:TTeeBlend);
begin
Blend.DoBlend(ITransp);
Blend.Free;
end;
{ TCanvas3D }
Procedure TCanvas3D.Assign(Source:TCanvas3D);
begin
Monochrome:=Source.Monochrome;
end;
function TCanvas3D.CalcRect3D(const R: TRect; Z: Integer): TRect;
begin
result.TopLeft:=Calculate3DPosition(R.TopLeft,Z);
result.BottomRight:=Calculate3DPosition(R.BottomRight,Z);
end;
Function TCanvas3D.Calculate3DPosition(const P:TPoint3D):TPoint;
begin
result:=Calculate3DPosition(P.X,P.Y,P.Z)
end;
Function TCanvas3D.Calculate3DPosition(P:TPoint; z:Integer):TPoint;
begin
result:=Calculate3DPosition(P.X,P.Y,z)
end;
procedure TCanvas3D.Cube(const R: TRect; Z0, Z1: Integer;
DarkSides: Boolean=True);
begin
with R do Cube(Left,Right,Top,Bottom,Z0,Z1,DarkSides);
end;
procedure TCanvas3D.DisableRotation;
begin
end;
procedure TCanvas3D.EnableRotation;
begin
end;
function TCanvas3D.FourPointsFromRect(const R: TRect;
Z: Integer): TFourPoints;
begin
With R do
begin
result[0]:=Calculate3DPosition(TopLeft,Z);
result[1]:=Calculate3DPosition(Right,Top,Z);
result[2]:=Calculate3DPosition(BottomRight,Z);
result[3]:=Calculate3DPosition(Left,Bottom,Z);
end;
end;
procedure TCanvas3D.FrontPlaneBegin;
begin
if IDisabledRotation=0 then
DisableRotation;
Inc(IDisabledRotation);
end;
procedure TCanvas3D.FrontPlaneEnd;
begin
Dec(IDisabledRotation);
if IDisabledRotation=0 then
EnableRotation;
end;
procedure TCanvas3D.LineWithZ(const FromPoint, ToPoint: TPoint;
Z: Integer);
begin
LineWithZ(FromPoint.X,FromPoint.Y,ToPoint.X,ToPoint.Y,Z)
end;
procedure TCanvas3D.MoveTo3D(const P:TPoint3D);
begin
MoveTo3D(P.x,P.y,P.z);
end;
procedure TCanvas3D.LineTo3D(const P:TPoint3D);
begin
LineTo3D(P.x,P.y,P.z);
end;
procedure TCanvas3D.PlaneWithZ(const P: TFourPoints; Z: Integer);
begin
PlaneWithZ(P[0],P[1],P[2],P[3],Z);
end;
Procedure TCanvas3D.Rectangle(Const R:TRect; Z:Integer);
begin
RectangleWithZ(R,Z);
end;
Procedure TCanvas3D.Rectangle(X0,Y0,X1,Y1,Z:Integer);
begin
RectangleWithZ(TeeRect(X0,Y0,X1,Y1),Z);
end;
function TCanvas3D.RectFromRectZ(const R: TRect; Z: Integer): TRect;
var P : TFourPoints;
begin
P:=FourPointsFromRect(R,Z);
result:=RectFromPolygon(P,4);
end;
procedure TCanvas3D.RotatedEllipse(Left, Top, Right, Bottom, Z: Integer;
const Angle: Double);
Var P : TCirclePoints;
Points : TTrianglePoints;
PiStep : Double;
t : Integer;
tmpX : Double;
tmpY : Double;
XCenter : Double;
YCenter : Double;
XRadius : Double;
YRadius : Double;
tmpSin : Extended;
tmpCos : Extended;
tmpSinAngle : Extended;
tmpCosAngle : Extended;
Old : TPenStyle;
begin
XCenter:=(Right+Left)*0.5;
YCenter:=(Bottom+Top)*0.5;
XRadius:=XCenter-Left;
YRadius:=YCenter-Top;
piStep:=2*pi/(NumCirclePoints-1);
SinCos(Angle*TeePiStep,tmpSinAngle,tmpCosAngle);
for t:=0 to NumCirclePoints-1 do
begin
SinCos(t*piStep,tmpSin,tmpCos);
tmpX:=XRadius*tmpSin;
tmpY:=YRadius*tmpCos;
P[t].X:=Round(XCenter+(tmpX*tmpCosAngle+tmpY*tmpSinAngle));
P[t].Y:=Round(YCenter+(-tmpX*tmpSinAngle+tmpY*tmpCosAngle));
end;
if Brush.Style<>bsClear then
begin
Old:=Pen.Style;
Pen.Style:=psClear;
Points[0].X:=Round(XCenter);
Points[0].Y:=Round(YCenter);
Points[1]:=P[0];
Points[2]:=P[1];
PolygonWithZ(Points,Z);
Points[1]:=P[1];
for t:=2 to NumCirclePoints-1 do
begin
Points[2]:=P[t];
PolygonWithZ(Points,Z);
Points[1]:=P[t];
end;
Pen.Style:=Old;
end;
if Pen.Style<>psClear then
Polyline(P,Z);
end;
{$IFDEF CLR}
type PByteArray=IntPtr;
{$ENDIF}
procedure TCanvas3D.StretchDraw(const Rect: TRect; Graphic: TGraphic;
Z: Integer);
{$IFNDEF CLX}
Const BytesPerPixel=3;
{$ENDIF}
var x,y,
tmpW,
tmpH : Integer;
DestW,
DestH : Double;
R : TRect;
Bitmap : TBitmap;
{$IFNDEF CLX}
tmpScan : PByteArray;
Line : PByteArray;
Dif : Integer;
{$IFNDEF CLR}
P : PChar;
{$ENDIF}
{$ELSE}
tmpCanvas : TCanvas;
{$ENDIF}
{$IFNDEF CLX}
{$IFNDEF CLR}
tmpFastBrush : Boolean;
CanvasDC : TTeeCanvasHandle;
{$ENDIF}
{$ENDIF}
IPoints : TFourPoints;
begin
Pen.Style:=psClear;
if Graphic is TBitmap then
begin
Bitmap:=TBitmap(Graphic);
Bitmap.PixelFormat:=TeePixelFormat;
end
else
begin
Bitmap:=TBitmap.Create;
Bitmap.PixelFormat:=TeePixelFormat;
{$IFNDEF CLX}
Bitmap.IgnorePalette:=Graphic.Palette=0; // 7.0
{$ENDIF}
Bitmap.Assign(Graphic);
Bitmap.PixelFormat:=TeePixelFormat;
end;
tmpW:=Bitmap.Width;
tmpH:=Bitmap.Height;
DestH:=(Rect.Bottom-Rect.Top)/tmpH;
DestW:=(Rect.Right-Rect.Left)/tmpW;
{$IFNDEF CLX}
Line:=Bitmap.ScanLine[0];
Dif:=Integer(Bitmap.ScanLine[1])-Integer(Line);
{$ELSE}
tmpCanvas:=Bitmap.Canvas;
{$ENDIF}
{$IFNDEF CLR}
{$IFNDEF CLX}
tmpFastBrush:=Assigned(@TeeSetDCBrushColor);
if tmpFastBrush then
begin
CanvasDC:=Handle;
{$IFDEF TEEWINDOWS}
SelectObject(CanvasDC,GetStockObject(DC_BRUSH));
{$ENDIF}
end
else
CanvasDC:=0;
{$ENDIF}
{$ENDIF}
R.Top:=Rect.Top;
for y:=0 to tmpH-1 do
begin
{$IFNDEF CLX}
tmpScan:=PByteArray(Integer(Line)+Dif*y);
{$ENDIF}
R.Bottom:=Rect.Top+Round(DestH*(y+1));
R.Left:=Rect.Left;
IPoints[0]:=Calculate3DPosition(R.Left,R.Top,Z);
IPoints[3]:=Calculate3DPosition(R.Left,R.Bottom,Z);
for x:=0 to tmpW-1 do
begin
R.Right:=Rect.Left+Round(DestW*(x+1));
IPoints[1]:=Calculate3DPosition(R.Right,R.Top,Z);
IPoints[2]:=Calculate3DPosition(R.Right,R.Bottom,Z);
{$IFDEF CLX}
{$IFDEF D7}
Brush.Color:=tmpCanvas.Pixels[x,y];
{$ELSE}
{$IFDEF MSWINDOWS}
Brush.Color:=Windows.GetPixel(QPainter_handle(tmpCanvas.Handle), X, Y);
{$ELSE}
Brush.Color:=0; // Not implemented.
{$ENDIF}
{$ENDIF}
{$ELSE}
{$IFDEF CLR}
{ TODO : ??? }
{$IFNDEF TEESAFECLR}
//p:=@tmpScan[X*BytesPerPixel];
{$ENDIF}
{$ELSE}
p:=PChar(@tmpScan[X*BytesPerPixel]);
{$ENDIF}
{$IFNDEF TEESAFECLR}
if tmpFastBrush then // 7.0
TeeSetDCBrushColor(CanvasDC,Byte((p+2)^) or (Byte((p+1)^) shl 8) or (Byte((p)^) shl 16))
else
Brush.Color:=Byte((p+2)^) or (Byte((p+1)^) shl 8) or (Byte((p)^) shl 16);
{$ENDIF}
{$ENDIF}
Polygon(IPoints);
R.Left:=R.Right;
IPoints[0]:=IPoints[1];
IPoints[3]:=IPoints[2];
end;
R.Top:=R.Bottom;
end;
{$IFNDEF CLR}
{$IFNDEF CLX}
if tmpFastBrush then Brush.Handle:=0;
{$ENDIF}
{$ENDIF}
if not (Graphic is TBitmap) then
Bitmap.Free;
end;
{ TTeeCanvas3D }
Constructor TTeeCanvas3D.Create;
begin
inherited;
FontZoom:=100;
IZoomText:=True;
FBufferedDisplay:=True;
FDirty:=True;
FTextAlign:=TA_LEFT;
end;
Procedure TTeeCanvas3D.DeleteBitmap;
begin
{$IFDEF CLX}
if Assigned(FBitmap) and QPainter_isActive(FBitmap.Canvas.Handle) then
QPainter_end(FBitmap.Canvas.Handle);
{$ENDIF}
FreeAndNil(FBitmap);
end;
Destructor TTeeCanvas3D.Destroy;
begin
DeleteBitmap;
inherited;
end;
Function TTeeCanvas3D.GetBackMode:TCanvasBackMode;
begin
{$IFDEF CLX}
if QPainter_BackgroundMode(Handle)=BGMode_TransparentMode then
result:=cbmTransparent
else
result:=cbmOpaque;
{$ELSE}
result:=TCanvasBackMode(GetBkMode(FCanvas.Handle));
{$ENDIF}
end;
Procedure TTeeCanvas3D.SetBackMode(Mode:TCanvasBackMode); { Opaque, Transparent }
begin
{$IFDEF CLX}
if Mode<>GetBackMode then
begin
FCanvas.Start;
if Mode=cbmTransparent then QPainter_setBackgroundMode(Handle,BGMode_TransparentMode)
else
if Mode=cbmOpaque then QPainter_setBackGroundMode(Handle,BGMode_OpaqueMode);
FCanvas.Stop;
end;
{$ELSE}
SetBkMode(FCanvas.Handle,Ord(Mode));
{$ENDIF}
end;
Procedure TTeeCanvas3D.SetBackColor(Color:TColor);
{$IFDEF CLX}
Var QC : QColorH;
{$ENDIF}
begin
{$IFDEF CLX}
if Color<>GetBackColor then
begin
QC:=QColor(Color);
FCanvas.Start;
QPainter_setBackgroundColor(Handle,QC);
FCanvas.Stop;
QColor_destroy(QC);
end;
{$ELSE}
SetBkColor(FCanvas.Handle,TColorRef(ColorToRGB(Color)));
{$ENDIF}
end;
function TTeeCanvas3D.GetBackColor:TColor;
begin
{$IFDEF CLX}
result:=QColorColor(QPainter_backgroundColor(Handle));
{$ELSE}
result:=TColor(GetBkColor(FCanvas.Handle));
{$ENDIF}
end;
Procedure TTeeCanvas3D.TextOut(X,Y:Integer; const Text:String);
{$IFNDEF CLX}
var tmpDC : TTeeCanvasHandle;
{$ENDIF}
{$IFDEF CLX}
Procedure InternalTextOut(AX,AY:Integer);
var tmp : Integer;
begin
tmp:=TextAlign;
if tmp>=TA_BOTTOM then
begin
Dec(AY,TextHeight(Text));
Dec(tmp,TA_BOTTOM);
end;
if tmp=TA_RIGHT then
Dec(AX,TextWidth(Text))
else
if tmp=TA_CENTER then
Dec(AX,TextWidth(Text) div 2);
FCanvas.TextOut(AX,AY,Text);
end;
{$ELSE}
Function IsTrueTypeFont:Boolean;
var tmpMet : TTextMetric;
begin
GetTextMetrics(tmpDC,tmpMet);
result:=(tmpMet.tmPitchAndFamily and TMPF_TRUETYPE)=TMPF_TRUETYPE;
end;
{$ENDIF}
Function RectText(tmpX,tmpY:Integer):TRect;
var tmpW : Integer;
tmpH : Integer;
tmp : Integer;
begin
tmpW:=TextWidth(Text);
tmpH:=TextHeight(Text);
tmp:=TextAlign;
if tmp>=TA_BOTTOM then Dec(tmp,TA_BOTTOM);
if tmp=TA_RIGHT then
result:=TeeRect(tmpX-tmpW,tmpY,tmpX,tmpY+tmpH)
else
if tmp=TA_CENTER then
result:=TeeRect(tmpX-(tmpW div 2),tmpY,tmpX+(tmpW div 2),tmpY+tmpH)
else
result:=TeeRect(tmpX,tmpY,tmpX+tmpW,tmpY+tmpH);
end;
{$IFNDEF CLX}
Procedure CreateFontPath;
begin
BeginPath(tmpDC);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.TextOut(tmpDC,X, Y, {$IFNDEF CLR}PChar{$ENDIF}(Text),Length(Text));
EndPath(tmpDC);
end;
{$ENDIF}
Var tmpX : Integer;
tmpY : Integer;
{$IFDEF CLX}
tmpColor : TColor;
{$ELSE}
tmpFontGradient : Boolean;
tmpFontOutLine : Boolean;
{$ENDIF}
tmpBlend : TTeeBlend;
begin
{$IFNDEF CLX}
tmpDC:=FCanvas.Handle;
{$ENDIF}
if Assigned(IFont) and Assigned(IFont.FShadow) then
With IFont.FShadow do
if (HorizSize<>0) or (VertSize<>0) then
begin
if HorizSize<0 then
begin
tmpX:=X;
Dec(X,HorizSize);
end
else tmpX:=X+HorizSize;
if VertSize<0 then
begin
tmpY:=Y;
Dec(Y,VertSize);
end
else tmpY:=Y+VertSize;
if Transparency>0 then
tmpBlend:=BeginBlending(RectText(tmpX,tmpY),Transparency)
else
tmpBlend:=nil;
{$IFNDEF CLX}
SetTextColor(tmpDC, ColorToRGB(IFont.Shadow.Color));
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.TextOut(tmpDC,tmpX, tmpY, {$IFNDEF CLR}PChar{$ENDIF}(Text),Length(Text));
{$ELSE}
tmpColor:=FCanvas.Font.Color;
FCanvas.Font.Color:=ColorToRGB(IFont.Shadow.Color);
InternalTextOut(tmpX,tmpY);
FCanvas.Font.Color:=tmpColor;
{$ENDIF}
if Transparency>0 then
EndBlending(tmpBlend);
end;
{$IFDEF CLX}
FCanvas.Font.Color:=ColorToRGB(FFont.Color);
{$ELSE}
SetTextColor(tmpDC, ColorToRGB(FFont.Color));
{$ENDIF}
{$IFNDEF CLX}
if Assigned(IFont) then // and IsTrueTypeFont then 5.03 (slow)
begin
with IFont do
begin
tmpFontOutLine:=Assigned(FOutline) and (FOutLine.Visible);
tmpFontGradient:=Assigned(FGradient) and (FGradient.Visible);
end;
if tmpFontOutLine or tmpFontGradient then
begin
if tmpFontOutLine then AssignVisiblePen(IFont.FOutLine)
else Pen.Style:=psClear;
Brush.Color:=FFont.Color;
Brush.Style:=bsSolid;
tmpDC:=FCanvas.Handle;
BackMode:=cbmTransparent;
CreateFontPath;
if tmpFontGradient then
begin
if IFont.FGradient.Outline then WidenPath(tmpDC);
SelectClipPath(tmpDC,RGN_AND);
IFont.FGradient.Draw(Self,RectText(x,y));
UnClipRectangle;
if IFont.FGradient.Outline then exit;
// Create path again...
if tmpFontOutLine then
begin
CreateFontPath;
Brush.Style:=bsClear;
end;
end;
if tmpFontOutLine then
if IFont.Color=clNone then StrokePath(tmpDC)
else StrokeAndFillPath(tmpDC);
end
else {$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.TextOut(tmpDC,X, Y, {$IFNDEF CLR}PChar{$ENDIF}(Text),Length(Text));
end
else {$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.TextOut(tmpDC,X, Y, {$IFNDEF CLR}PChar{$ENDIF}(Text),Length(Text));
{$ELSE}
InternalTextOut(x,y);
{$ENDIF}
end;
procedure TTeeCanvas3D.Rectangle(X0,Y0,X1,Y1:Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.Rectangle(FCanvas.Handle,X0,Y0,X1,Y1);
{$ELSE}
FCanvas.Rectangle(X0,Y0,X1,Y1);
{$ENDIF}
end;
procedure TTeeCanvas3D.RoundRect(X1,Y1,X2,Y2,X3,Y3:Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.RoundRect(FCanvas.Handle,X1,Y1,X2,Y2,X3,Y3);
{$ELSE}
FCanvas.RoundRect(X1,Y1,X2,Y2,X3,Y3);
{$ENDIF}
end;
procedure TTeeCanvas3D.SetTextAlign(Align:TCanvasTextAlign);
begin
{$IFDEF CLX}
FTextAlign:=Align;
{$ELSE}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.SetTextAlign(FCanvas.Handle,Ord(Align));
{$ENDIF}
end;
procedure TTeeCanvas3D.MoveTo(X,Y:Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FCanvas.Handle, X, Y, nil);
{$ELSE}
FCanvas.MoveTo(X,Y);
{$ENDIF}
end;
procedure TTeeCanvas3D.LineTo(X,Y:Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FCanvas.Handle, X, Y);
{$ELSE}
FCanvas.LineTo(X,Y);
{$ENDIF}
end;
{ 3D Canvas }
Procedure TTeeCanvas3D.PolygonFour;
begin
{$IFNDEF CLX}
{$IFDEF CLR}
Borland.VCL.Windows.Polygon(FCanvas.Handle, IPoints, 4);
{$ELSE}
Windows.Polygon(FCanvas.Handle, PPoints(@IPoints)^, 4);
{$ENDIF}
{$ELSE}
FCanvas.Polygon(IPoints);
{$ENDIF}
end;
procedure TTeeCanvas3D.PlaneWithZ(P1,P2,P3,P4:TPoint; Z:Integer);
begin
Calc3DTPoint(P1,Z);
Calc3DTPoint(P2,Z);
Calc3DTPoint(P3,Z);
Calc3DTPoint(P4,Z);
IPoints[0]:=P1;
IPoints[1]:=P2;
IPoints[2]:=P3;
IPoints[3]:=P4;
PolygonFour;
end;
Procedure TTeeCanvas3D.Calc3DTPoint(Var P:TPoint; z:Integer);
{$IFDEF CLR}
var x,y : Integer;
{$ENDIF}
begin
{$IFDEF CLR}
x:=P.X;
y:=P.Y;
Calc3DPos(x,y,Z);
P.X:=x;
P.Y:=y;
{$ELSE}
Calc3DPos(P.X,P.Y,Z);
{$ENDIF}
end;
Function TTeeCanvas3D.Calc3DTPoint3D(Const P:TPoint3D):TPoint;
begin
Calc3DPoint(result,P.X,P.Y,P.Z);
end;
Function TTeeCanvas3D.Calculate3DPosition(x,y,z:Integer):TPoint;
begin
Calc3DPos(x,y,z);
result.x:=x;
result.y:=y;
end;
Procedure TTeeCanvas3D.Calc3DPoint( Var P:TPoint; x,y,z:Integer);
begin
Calc3DPos(x,y,z);
P.x:=x;
P.y:=y;
end;
Procedure TTeeCanvas3D.Calculate2DPosition(Var x,y:Integer; z:Integer);
var x1 : Integer;
tmp : Double;
begin
if IZoomFactor<>0 then
begin
tmp:=1.0/IZoomFactor;
if FIsOrthogonal then
begin
x:=Round(((x-FXCenterOffset)*tmp)-(IOrthoX*z))+FXCenter;
y:=Round(((y-FYCenterOffset)*tmp)+(IOrthoY*z))+FYCenter;
end
else
if FIs3D and (tempXX<>0) and (c2c3<>0) then
begin
x1:=x;
z:=z-FZCenter;
x:=Round((((x1-FXCenterOffset)*tmp)-(z*tempXZ)-
(y -FYCenter)*c2s3) / tempXX) + FXCenter;
y:=Round((((y -FYCenterOffset)*tmp)-(z*tempYZ)-
(x1-FXCenter)*tempYX) / c2c3) + FYCenter;
end;
end;
end;
// Floating-point version
Procedure TTeeCanvas3D.Calc3DPoint(Var P:TPoint; x,y:Double; z:Integer);
var tmp : Double;
xx,yy,zz : Double;
begin
if FIsOrthogonal then
begin
P.X:=Round( IZoomFactor*(x-FXCenter+(IOrthoX*z)) )+FXCenterOffset;
P.Y:=Round( IZoomFactor*(y-FYCenter-(IOrthoY*z)) )+FYCenterOffset;
end
else
if FIs3D then
begin
Dec(z,FZCenter);
x:=x-FXCenter;
y:=y-FYCenter;
zz:=z*c2 - x*s2;
xx:=x*c2 + z*s2;
yy:=y*c1 - zz*s1;
if IHasPerspec then
tmp:=IZoomFactor / ( 1+ IZoomPerspec * (zz*c1 + y*s1) )
else
tmp:=IZoomFactor;
P.X:=Round((xx*c3 - yy*s3)*tmp)+FXCenterOffset;
P.Y:=Round((yy*c3 + xx*s3)*tmp)+FYCenterOffset;
end;
end;
// Integer version
Procedure TTeeCanvas3D.Calc3DPos(Var x,y:Integer; z:Integer);
var tmp : Double;
xx,yy,zz : Double;
begin
if FIsOrthogonal then
begin
x:=Round( IZoomFactor*(x-FXCenter+(IOrthoX*z)) )+FXCenterOffset;
y:=Round( IZoomFactor*(y-FYCenter-(IOrthoY*z)) )+FYCenterOffset;
end
else
if FIs3D then
begin
Dec(z,FZCenter);
Dec(x,FXCenter);
Dec(y,FYCenter);
zz:=z*c2 - x*s2;
if IHasPerspec then
tmp:=IZoomFactor / ( 1+ IZoomPerspec * (zz*c1 + y*s1) )
else
tmp:=IZoomFactor;
if IHasTilt then
begin
xx:=x*c2 + z*s2;
yy:=y*c1 - zz*s1;
x:=Round((xx*c3 - yy*s3)*tmp)+FXCenterOffset;
y:=Round((yy*c3 + xx*s3)*tmp)+FYCenterOffset;
end
else
begin
x:=Round((x*c2 + z*s2)*tmp)+FXCenterOffset;
y:=Round((y*c1 - zz*s1)*tmp)+FYCenterOffset;
end;
end;
end;
Function TTeeCanvas3D.GetHandle:TTeeCanvasHandle;
begin
result:=FCanvas.Handle;
end;
procedure TTeeCanvas3D.Cone(Vertical:Boolean; Left,Top,Right,Bottom,
Z0,Z1:Integer; Dark3D:Boolean; ConePercent:Integer);
begin
InternalCylinder(Vertical,Left,Top,Right,Bottom,Z0,Z1,Dark3D,ConePercent);
end;
procedure TTeeCanvas3D.Sphere(x,y,z:Integer; Const Radius:Double);
var tmp : Integer;
begin
tmp:=Round(Radius);
EllipseWithZ(x-tmp,y-tmp,x+tmp,y+tmp,z);
end;
Procedure TTeeCanvas3D.Surface3D( Style:TTeeCanvasSurfaceStyle;
SameBrush:Boolean;
NumXValues,NumZValues:Integer;
CalcPoints:TTeeCanvasCalcPoints );
begin
{ not implemented in GDI mode. (Use TeeOpenGL) }
end;
Procedure TTeeCanvas3D.TextOut3D(x,y,z:Integer; const Text:String);
var {$IFNDEF CLX}
tmpSizeChanged : Boolean;
FDC : HDC;
LogRec : TLogFont;
NewFont : HFont;
OldFont : HFont;
{$ENDIF}
tmp : Integer;
OldSize : Integer;
begin
Calc3DPos(x,y,z);
if IZoomText then
begin
{$IFNDEF CLX}
tmpSizeChanged:=False;
FDC:=0;
OldFont:=0;
{$ENDIF}
if IZoomFactor<>1 then
With FFont do
begin
OldSize:=Size;
tmp:=Math.Max(1,Round(IZoomFactor*OldSize));
if OldSize<>tmp then
begin
{$IFDEF CLX}
FFont.Size:=tmp;
{$ELSE}
FDC:=FCanvas.Handle;
{$IFDEF CLR}
GetObject(FFont.Handle, Marshal.SizeOf(TypeOf(TLogFont)), LogRec);
{$ELSE}
GetObject(FFont.Handle, SizeOf(LogRec), @LogRec);
{$ENDIF}
LogRec.lfHeight:= -MulDiv( tmp,FFont.PixelsPerInch,72);
// Extra weights: LogRec.lfWeight:=FW_THIN;
NewFont:=CreateFontIndirect(LogRec);
OldFont:=SelectObject(FDC,NewFont);
tmpSizeChanged:=True;
{$ENDIF}
end;
end;
TextOut(X,Y,Text);
{$IFNDEF CLX}
if tmpSizeChanged then
DeleteObject(SelectObject(FDC,OldFont));
{$ENDIF}
end
else TextOut(X,Y,Text);
end;
procedure TTeeCanvas3D.MoveTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FCanvas.Handle, X, Y, nil);
{$ELSE}
FCanvas.MoveTo(X,Y);
{$ENDIF}
end;
procedure TTeeCanvas3D.LineTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FCanvas.Handle, X, Y);
{$ELSE}
FCanvas.LineTo(X,Y);
{$ENDIF}
end;
Procedure TTeeCanvas3D.RectangleWithZ(Const Rect:TRect; Z:Integer);
begin
With Rect do
begin
Calc3DPoint(IPoints[0],Left,Top,Z);
Calc3DPoint(IPoints[1],Right,Top,Z);
Calc3DPoint(IPoints[2],Right,Bottom,Z);
Calc3DPoint(IPoints[3],Left,Bottom,Z);
end;
PolygonFour;
end;
Procedure TTeeCanvas3D.DoHorizLine(X0,X1,Y:Integer);
{$IFNDEF CLX}
var FDC : HDC;
{$ENDIF}
begin
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,X0,Y,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,X1,Y);
{$ELSE}
FCanvas.MoveTo(x0,y);
FCanvas.LineTo(x1,y);
{$ENDIF}
end;
Procedure TTeeCanvas3D.DoVertLine(X,Y0,Y1:Integer);
{$IFNDEF CLX}
var FDC : HDC;
{$ENDIF}
begin
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,X,Y0,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,X,Y1);
{$ELSE}
FCanvas.MoveTo(x,y0);
FCanvas.LineTo(x,y1);
{$ENDIF}
end;
{$IFNDEF CLX}
Procedure SetCanvasRegion(DC:TTeeCanvasHandle; Region:HRgn);
begin
if Region<>0 then
begin
WasOldRegion:=GetClipRgn(DC,OldRegion)=1;
ExtSelectClipRgn(DC,Region,RGN_AND);
DeleteObject(Region);
end;
end;
{$ENDIF}
Procedure ClipCanvas(ACanvas:TCanvas; Const Rect:TRect);
var tmpDC : TTeeCanvasHandle;
{$IFNDEF CLX}
P : Array[0..1] of TPoint;
Region : HRgn;
{$ENDIF}
begin
{$IFNDEF CLX}
with Rect do
begin
p[0]:=TopLeft;
p[1]:=BottomRight;
end;
tmpDC:=ACanvas.Handle;
LPToDP(tmpDC,P,2);
Region:=CreateRectRgn(P[0].X,P[0].Y,P[1].X,P[1].Y);
SetCanvasRegion(tmpDC,Region);
{$ELSE}
ACanvas.Start;
tmpDC:=ACanvas.Handle;
QPainter_setClipping(tmpDC,True);
QPainter_setClipRect(tmpDC,@Rect);
{$ENDIF}
end;
procedure TTeeCanvas3D.ClipRectangle(Const Rect:TRect);
begin
ClipCanvas(FCanvas,Rect);
end;
Procedure TTeeCanvas.ClipPolygon(Var Points:Array of TPoint; NumPoints:Integer);
{$IFDEF CLX}
{ From QGraphics.pas }
function PointArrayOf(const Points: array of TPoint; var TempPoints: TPointArray): PPointArray;
var t:Integer;
begin
SetLength(TempPoints, NumPoints);
for t:=0 to NumPoints-1 do TempPoints[t]:=Points[t];
Result := @TempPoints[0];
end;
{$ENDIF}
var {$IFDEF CLX}
Region : QRegionH;
P : TPointArray;
{$ELSE}
Region : HRgn;
{$ENDIF}
tmpDC : TTeeCanvasHandle;
begin
{$IFDEF CLX}
ReferenceCanvas.Start;
tmpDC:=ReferenceCanvas.Handle;
QPainter_setClipping(tmpDC,True);
Region:=QRegion_create(PointArrayOf(Points,P),False);
QPainter_setClipRegion(tmpDC,Region);
QRegion_Destroy(Region);
{$ELSE}
tmpDC:=Handle;
LPToDP(tmpDC,Points,NumPoints);
Region:=CreatePolygonRgn(Points,NumPoints,ALTERNATE);
SetCanvasRegion(tmpDC,Region);
{$ENDIF}
end;
Procedure ClipEllipse(ACanvas:TTeeCanvas; Const Rect:TRect);
begin
ACanvas.ClipEllipse(Rect);
end;
Procedure TTeeCanvas.ClipEllipse(Const Rect:TRect; Inverted:Boolean=False);
var DC : TTeeCanvasHandle;
{$IFNDEF CLX}
R : TRect;
tmpReg : HRgn;
{$ELSE}
tmpRegion : QRegionH;
{$ENDIF}
begin
{$IFNDEF CLX}
DC:=Handle;
R:=Rect;
{$IFNDEF CLR}
LPToDP(DC,R,2);
{$ENDIF}
if Inverted then
begin
tmpReg:=CreateEllipticRgnIndirect(Rect);
ExtSelectClipRgn(Handle,tmpReg,RGN_XOR);
DeleteObject(tmpReg);
end
else SetCanvasRegion(DC,CreateEllipticRgnIndirect(R));
{$ELSE}
ReferenceCanvas.Start;
DC:=Handle;
QPainter_setClipping(DC,True);
tmpRegion:=QRegion_create(@Rect, QRegionRegionType_Ellipse);
QPainter_setClipRegion(DC,tmpRegion);
QRegion_destroy(tmpRegion);
{$ENDIF}
end;
Procedure ClipRoundRectangle(ACanvas:TTeeCanvas; Const Rect:TRect; RoundSize:Integer);
begin
ACanvas.ClipRectangle(Rect,RoundSize);
end;
Procedure TTeeCanvas.ClipRectangle(Const Rect:TRect; RoundSize:Integer);
{$IFNDEF CLX}
var R : TRect;
Region : HRgn;
DC : HDC;
{$ENDIF}
begin
{$IFNDEF CLX}
DC:=Handle;
R:=Rect;
{$IFNDEF CLR}
LPToDP(DC,R,2);
{$ENDIF}
With R do Region:=CreateRoundRectRgn(Left,Top,Right,Bottom,RoundSize,RoundSize);
SetCanvasRegion(DC,Region);
{$ELSE}
ClipRectangle(Rect);
{$ENDIF}
end;
Procedure ClipPolygon(ACanvas:TTeeCanvas; Var Points:Array of TPoint; NumPoints:Integer);
begin
ACanvas.ClipPolygon(Points,NumPoints);
end;
Function RectFromPolygon(Const Points:Array of TPoint; NumPoints:Integer):TRect;
var t : Integer;
begin
result.TopLeft:=Points[0];
result.BottomRight:=result.TopLeft;
for t:=1 to NumPoints-1 do
With Points[t] do
begin
if X<result.Left then result.Left:=X else
if X>result.Right then result.Right:=X;
if Y<result.Top then result.Top:=Y else
if Y>result.Bottom then result.Bottom:=Y;
end;
Inc(result.Right);
Inc(result.Bottom);
end;
Function RectFromTriangle(Const Points:TTrianglePoints):TRect;
begin
result:=RectFromPolygon(Points,3);
end;
// Returns the boundary points of the convex hull of a set of 2D xy points.
// Overwrites the input array.
// Written by Peter Bone : peterbone@hotmail.com
function TTeeCanvas.ConvexHull(var Points : TPointArray) : Boolean;
// sort an array of points by angle
procedure QuickSortAngle(var A: TPointArray; var Angles : Array of Single; iLo, iHi: Integer);
var
Lo, Hi : Integer;
Mid : Single;
TempPoint : TPoint;
TempAngle : Single;
begin
Lo := iLo;
Hi := iHi;
Mid := Angles[(Lo + Hi) div 2];
repeat
while Angles[Lo] < Mid do Inc(Lo);
while Angles[Hi] > Mid do Dec(Hi);
if Lo <= Hi then
begin
// swap points
TempPoint := A[Lo];
A[Lo] := A[Hi];
A[Hi] := TempPoint;
// swap angles
TempAngle := Angles[Lo];
Angles[Lo] := Angles[Hi];
Angles[Hi] := TempAngle;
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
// perform quicksorts on subsections
if Hi > iLo then QuickSortAngle(A, Angles, iLo, Hi);
if Lo < iHi then QuickSortAngle(A, Angles, Lo, iHi);
end;
var
LAngles : Array of Single;
Lindex,
LMinY,
LMaxX,
tmpHigh,
LPivotIndex : integer;
LPivot : TPoint;
LBehind, LInfront : TPoint;
LRightTurn : Boolean;
LVecPoint : {$IFDEF LINUX}TPoint{$ELSE}TPointFloat{$ENDIF};
tmp : Double;
{$IFDEF CLR}
t : Integer;
{$ENDIF}
begin
Result:=True;
if Length(Points) = 3 then Exit // already a convex hull
else
if Length(Points) < 3 then
begin // not enough points
Result := False;
Exit;
end;
// find pivot point, which is known to be on the hull
// point with lowest y - if there are multiple, point with highest x
LMinY := 10000000;
LMaxX := 10000000;
LPivotIndex := 0;
for Lindex := Low(Points) to High(Points) do
if Points[Lindex].Y = LMinY then
begin
if Points[Lindex].X > LMaxX then
begin
LMaxX := Points[Lindex].X;
LPivotIndex := Lindex;
end;
end
else
if Points[Lindex].Y < LMinY then
begin
LMinY := Points[Lindex].Y;
LMaxX := Points[Lindex].X;
LPivotIndex := Lindex;
end;
// put pivot into seperate variable and remove from array
LPivot := Points[LPivotIndex];
Points[LPivotIndex] := Points[High(Points)];
SetLength(Points, High(Points));
// calculate angle to pivot for each point in the array
// quicker to calculate dot product of point with a horizontal comparison vector
SetLength(LAngles, Length(Points));
for Lindex := Low(Points) to High(Points) do
begin
LVecPoint.X := LPivot.X - Points[Lindex].X; // point vector
LVecPoint.Y := LPivot.Y - Points[Lindex].Y;
// reduce to a unit-vector - length 1
tmp:=Hypot(LVecPoint.X, LVecPoint.Y);
if tmp=0 then LAngles[Lindex]:=0
else LAngles[Lindex] := LVecPoint.X / tmp;
end;
// sort the points by angle
QuickSortAngle(Points, LAngles, Low(Points), High(Points));
// step through array to remove points that are not part of the convex hull
Lindex := 1;
Repeat
// assign points behind and infront of current point
if Lindex = 0 then LRightTurn := True
else
begin
LBehind := Points[Lindex-1];
if Lindex = High(Points) then LInfront := LPivot
else LInfront := Points[Lindex + 1];
// work out if we are making a right or left turn using vector product
LRightTurn:= ((LBehind.X-Points[Lindex].X)*(LInfront.Y-Points[Lindex].Y))-
((LInfront.X-Points[Lindex].X)*(LBehind.Y-Points[Lindex].Y)) < 0;
end;
if LRightTurn then Inc(Lindex) // go to next point
else
begin // point is not part of the hull
tmpHigh:=High(Points);
// remove point from convex hull
if Lindex = tmpHigh then
SetLength(Points, tmpHigh)
else
begin
{$IFDEF CLR}
for t:=Lindex to tmpHigh-1 do
Points[t]:=Points[t+1];
{$ELSE}
System.Move(Points[Lindex + 1], Points[Lindex], (tmpHigh - Lindex) * SizeOf(TPoint) );
{$ENDIF}
SetLength(Points, tmpHigh);
end;
Dec(Lindex); // backtrack to previous point
end;
until Lindex = High(Points);
// add pivot back into points array
SetLength(Points, Length(Points) + 1);
Points[High(Points)] := LPivot;
end;
procedure TTeeCanvas3D.ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer);
var tmpR : TRect;
P : TPointArray;
begin
if FIs3D then
begin
SetLength(P,8);
with Rect do
begin
Calc3DPoint(p[0],Left,Bottom,MinZ);
Calc3DPoint(p[1],Left,Bottom,MaxZ);
Calc3DPoint(p[2],Left,Top,MaxZ);
Calc3DPoint(p[3],Right,Top,MaxZ);
Calc3DPoint(p[4],Right,Top,MinZ);
Calc3DPoint(p[5],Right,Bottom,MinZ);
Calc3DPoint(p[6],Left,Top,MinZ);
Calc3DPoint(p[7],Right,Bottom,MaxZ);
end;
ConvexHull(P);
ClipPolygon(P,Length(P));
P:=nil;
end
else
begin
tmpR:=Rect;
Inc(tmpR.Left);
Inc(tmpR.Top);
Dec(tmpR.Bottom);
ClipRectangle(tmpR);
end;
end;
Procedure UnClipCanvas(ACanvas:TCanvas);
begin
{$IFNDEF CLX}
if WasOldRegion then SelectClipRgn(ACanvas.Handle,OldRegion)
else SelectClipRgn(ACanvas.Handle,0);
WasOldRegion:=False;
{$ELSE}
QPainter_setClipping(ACanvas.Handle,False);
ACanvas.Stop;
{$ENDIF}
end;
procedure TTeeCanvas3D.UnClipRectangle;
begin
UnClipCanvas(FCanvas);
end;
Const PerspecFactor=1.0/150.0;
Procedure TTeeCanvas3D.Projection(MaxDepth:Integer; const Bounds,Rect:TRect);
begin
RectCenter(Rect,FXCenter,FYCenter);
Inc(FXCenter,Round(RotationCenter.X));
Inc(FYCenter,Round(RotationCenter.Y));
FZCenter:=Round( (MaxDepth*0.5) + RotationCenter.Z );
FXCenterOffset:=FXCenter;
FYCenterOffset:=FYCenter;
if Assigned(F3DOptions) then
With F3DOptions do
begin
Inc(FXCenterOffset,HorizOffset);
Inc(FYCenterOffset,VertOffset);
CalcPerspective(Rect);
end;
end;
Procedure TTeeCanvas3D.CalcPerspective(const Rect:TRect);
begin
IHasPerspec:=F3DOptions.Perspective>0;
if IHasPerspec then
IZoomPerspec:=IZoomFactor*F3DOptions.Perspective*PerspecFactor/(Rect.Right-Rect.Left);
end;
Procedure TTeeCanvas3D.CalcTrigValues;
Var rx : Double;
ry : Double;
rz : Double;
begin
if not FIsOrthogonal then
begin
if Assigned(F3DOptions) then
With F3DOptions do
begin
rx:=-Elevation;
ry:=-Rotation;
rz:=Tilt;
end
else
begin
rx:=0;
ry:=0;
rz:=0;
end;
IHasPerspec:=False;
IZoomPerspec:=0;
SinCos(rx*TeePiStep,s1,c1);
SinCos(ry*TeePiStep,s2,c2);
IHasTilt:=rz<>0;
SinCos(rz*TeePiStep,s3,c3);
c2s3:=c2*s3;
c2c3:=Math.Max(1E-5,c2*c3);
tempXX:=Math.Max(1E-5, s1*s2*s3 + c1*c3 );
tempYX:=( c3*s1*s2 - c1*s3 );
tempXZ:=( c1*s2*s3 - c3*s1 );
tempYZ:=( c1*c3*s2 + s1*s3 );
end;
end;
Function TTeeCanvas3D.InitWindow( DestCanvas:TCanvas;
A3DOptions:TView3DOptions;
ABackColor:TColor;
Is3D:Boolean;
Const UserRect:TRect):TRect;
var tmpH : Integer;
tmpW : Integer;
tmpCanvas : TCanvas;
tmpSin : Extended;
tmpCos : Extended;
tmpAngle : Extended;
begin
FBounds:=UserRect;
F3DOptions:=A3DOptions;
if Assigned(F3DOptions) then
FontZoom:=F3DOptions.FontZoom;
FIs3D:=Is3D;
FIsOrthogonal:=False;
IZoomFactor:=1;
if FIs3D then
begin
if Assigned(F3DOptions) then
begin
FIsOrthogonal:=F3DOptions.Orthogonal;
if FIsOrthogonal then
begin
tmpAngle:=F3DOptions.OrthoAngle;
if tmpAngle>90 then
begin
IOrthoX:=-1;
tmpAngle:=180-tmpAngle;
end
else IOrthoX:=1;
SinCos(tmpAngle*TeePiStep,tmpSin,tmpCos);
if tmpCos<0.01 then IOrthoY:=1
else IOrthoY:=tmpSin/tmpCos;
end;
IZoomFactor:=0.01*F3DOptions.Zoom;
IZoomText:=F3DOptions.ZoomText;
end;
CalcTrigValues;
end;
if FBufferedDisplay then
begin
RectSize(UserRect,tmpW,tmpH);
if not Assigned(FBitmap) then
begin
FBitmap:=TBitMap.Create;
{$IFNDEF CLX}
FBitmap.IgnorePalette:=True;
{$ENDIF}
end;
FBitmap.Width:=tmpW;
FBitmap.Height:=tmpH;
tmpCanvas:=FBitmap.Canvas;
tmpCanvas.OnChange:=nil;
tmpCanvas.OnChanging:=nil;
SetCanvas(tmpCanvas);
result:=TeeRect(0,0,tmpW,tmpH);
end
else
begin
SetCanvas(DestCanvas);
result:=UserRect;
end;
end;
{.$DEFINE MONITOR_REPAINTS}
{$IFDEF MONITOR_REPAINTS}
var TeeMonitor:Integer=0;
{$ENDIF}
Procedure TTeeCanvas3D.TransferBitmap(ALeft,ATop:Integer; ACanvas:TCanvas);
begin
{$IFNDEF CLX}
{$IFDEF MONITOR_REPAINTS}
Inc(TeeMonitor);
FBitmap.Canvas.TextOut(0,0,IntToStr(TeeMonitor));
{$ENDIF}
{$IFDEF TEEBITMAPSPEED}
if IBitmapCanvas=0 then
begin
IBitmapCanvas:=CreateCompatibleDC(0);
SelectObject(IBitmapCanvas, FBitmap.Handle);
end;
BitBlt( ACanvas.Handle,ALeft,ATop,
FBitmap.Width,
FBitmap.Height,
IBitmapCanvas,0,0,SRCCOPY);
{$ELSE}
BitBlt( ACanvas.Handle,ALeft,ATop,
FBitmap.Width,
FBitmap.Height,
FBitmap.Canvas.Handle,0,0,SRCCOPY);
{$ENDIF}
{$ELSE}
QPainter_drawPixmap(ACanvas.Handle, ALeft, ATop, FBitmap.Handle, 0, 0,
FBitmap.Width, FBitmap.Height);
{$ENDIF}
end;
Function TTeeCanvas3D.ReDrawBitmap:Boolean;
begin
result:=not FDirty;
if result then
TransferBitmap(0,0,FCanvas)
{$IFDEF TEEBITMAPSPEED}
else
begin
DeleteDC(IBitmapCanvas);
IBitmapCanvas:=0;
end;
{$ENDIF}
end;
Procedure TTeeCanvas3D.ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect);
begin
if FBufferedDisplay then
begin
With UserRect do TransferBitmap(Left,Top,DestCanvas);
FDirty:=False;
end;
SetCanvas(DefaultCanvas);
end;
procedure TTeeCanvas3D.StretchDraw(const Rect: TRect; Graphic: TGraphic);
begin
{$IFNDEF CLX}
if Assigned(Graphic) then
{$ENDIF}
FCanvas.StretchDraw(Rect,Graphic);
// TGraphicAccess(Graphic).Draw(FCanvas,Rect);
end;
procedure TTeeCanvas3D.Draw(X, Y: Integer; Graphic: TGraphic);
begin
{$IFNDEF CLX}
if Assigned(Graphic) and (not Graphic.Empty) then
{$ENDIF}
FCanvas.Draw(x,y,Graphic);
// TGraphicAccess(Graphic).Draw(FCanvas,TeeRect(x,y,x+Graphic.Width,y+Graphic.Height));
end;
{$IFDEF LINUX}
Function GetRValue(Color:Integer):Byte;
var QC : QColorH;
begin
QC:=QColor(Color);
try result:=QColor_red(QC); finally QColor_destroy(QC); end;
end;
Function GetGValue(Color:Integer):Byte;
var QC : QColorH;
begin
QC:=QColor(Color);
try result:=QColor_green(QC); finally QColor_destroy(QC); end;
end;
Function GetBValue(Color:Integer):Byte;
var QC : QColorH;
begin
QC:=QColor(Color);
try result:=QColor_blue(QC); finally QColor_destroy(QC); end;
end;
Function QRGB(r,g,b:Integer):QColorH;
begin
result:=QColor_create(r,g,b);
end;
Function RGB(r,g,b:Integer):TColor;
begin
result:=QColorColor(QRGB(r,g,b))
end;
{$ENDIF}
// For gradient balance
Function TeeSigmoid(const Index,Balance,Total:Double):Double;
const Divisor:Double=1/(200/3);
begin
result:=Exp((0.5+(Balance*Divisor))*Ln((1+Index)/(1+Total)));
end;
Procedure TTeeCanvas3D.GradientFill( Const Rect : TRect;
StartColor : TColor;
EndColor : TColor;
Direction : TGradientDirection;
Balance : Integer=50);
Var T0,T1,T2 : Integer;
D0,D1,D2 : Integer;
Range : Integer;
FDC : TTeeCanvasHandle;
{$IFDEF CLX}
tmpBrush : QBrushH;
{$ELSE}
tmpBrush : HBRUSH;
OldColor : TColor;
{$ENDIF}
Function CalcColor(Index:Integer):TColor;
var tmpD : Double;
begin
{$IFDEF CLX}
if Balance=50 then
result:=QColorColor(QColor_create( (T0 + MulDiv(Index,D0,Range)),
(T1 + MulDiv(Index,D1,Range)),
(T2 + MulDiv(Index,D2,Range)) ))
else
begin
tmpD:=TeeSigmoid(Index,Balance,Range);
result:=QColorColor(QColor_create( T0 + Round(tmpD*D0),
T1 + Round(tmpD*D1),
T2 + Round(tmpD*D2) ));
end;
{$ELSE}
if Balance=50 then
result:=(( T0 + ((Index*D0) div Range) ) or
(( T1 + ((Index*D1) div Range) ) shl 8) or
(( T2 + ((Index*D2) div Range) ) shl 16))
else
begin
tmpD:=TeeSigmoid(Index,Balance,Range);
result:=(( T0 + Round(tmpD*D0) ) or
(( T1 + Round(tmpD*D1) ) shl 8) or
(( T2 + Round(tmpD*D2) ) shl 16));
end;
{$ENDIF}
end;
{$IFNDEF CLX}
var tmpFastBrush : Boolean;
{$ENDIF}
procedure CheckFastBrush;
begin
FDC:=FCanvas.Handle;
{$IFNDEF CLX}
tmpFastBrush:=Assigned(@TeeSetDCBrushColor);
if tmpFastBrush then
tmpBrush:=SelectObject(FDC,GetStockObject(DC_BRUSH));
{$ENDIF}
end;
Procedure CalcBrushColor(Index:Integer);
var tmp : {$IFDEF CLX}QColorH{$ELSE}TColor{$ENDIF};
begin
tmp:={$IFDEF CLX}QColor{$ENDIF}(CalcColor(Index));
{$IFDEF CLX}
QBrush_setColor(tmpBrush,tmp);
QColor_destroy(tmp);
{$ELSE}
if tmp<>OldColor then
begin
if tmpFastBrush then
TeeSetDCBrushColor(FDC,tmp)
else
begin
if tmpBrush<>0 then
DeleteObject(SelectObject(FDC,tmpBrush)); // <-- Win API is very slow here !
tmpBrush:=SelectObject(FDC,CreateSolidBrush(tmp));
end;
OldColor:=tmp;
end;
{$ENDIF}
end;
Var tmpRect : TRect;
{$IFDEF CLX}
Procedure PatBlt(AHandle:TTeeCanvasHandle; A,B,C,D,Mode:Integer);
begin
QPainter_fillRect(AHandle, A,B,C,D, tmpBrush);
end;
{$ENDIF}
Procedure RectGradient(Horizontal:Boolean);
var t,
P1,
P2,
P3 : Integer;
Size : Integer;
Steps : Integer;
begin
With tmpRect do
begin
if Horizontal then
begin
P3:=Bottom-Top;
Size:=Right-Left;
end
else
begin
P3:=Right-Left;
Size:=Bottom-Top;
end;
Steps:=Size;
if Steps>256 then Steps:=256;
P1:=0;
{$IFNDEF CLX}
OldColor:=-1;
{$ENDIF}
Range:=Pred(Steps);
if Range>0 then
begin
CheckFastBrush;
for t:=0 to Steps-1 do
Begin
CalcBrushColor(t);
P2:=(t+1)*Size div Steps;
if Horizontal then PatBlt(FDC,Right-P1,Top,P1-P2,P3,PATCOPY)
else PatBlt(FDC,Left,Bottom-P1,P3,P1-P2,PATCOPY);
P1:=P2;
end;
end;
end;
end;
Procedure FromCorner;
var FromTop : Boolean;
SizeX,
SizeY,
tmp1,
tmp2,
P0,
P1 : Integer;
begin
FromTop:=Direction=gdFromTopLeft;
With tmpRect do if FromTop then P1:=Top else P1:=Bottom;
P0:=P1;
RectSize(tmpRect,SizeX,SizeY);
Range:=SizeX+SizeY;
tmp1:=0;
tmp2:=0;
CheckFastBrush;
Repeat
CalcBrushColor(tmp1+tmp2);
PatBlt(FDC,tmpRect.Left+tmp2,P0,1,P1-P0,PATCOPY);
if tmp1<SizeY then
begin
Inc(tmp1);
if FromTop then
begin
PatBlt(FDC,tmpRect.Left,P0,tmp2+1,1,PATCOPY);
if P0<tmpRect.Bottom then Inc(P0)
end
else
begin
PatBlt(FDC,tmpRect.Left,P0-1,tmp2+1,1,PATCOPY);
if P0>tmpRect.Top then Dec(P0);
end;
end;
if tmp2<SizeX then Inc(tmp2);
Until (tmp1>=SizeY) and (tmp2>=SizeX);
end;
Procedure FromCenter;
Const TeeGradientPrecision : Integer = 1; { how many pixels precision, ( 1=best) }
var tmpXCenter,
tmpYCenter,
SizeX,
SizeY,
P0,
P1,
tmpLeft,
tmpTop,
tmp1,
tmp2 : Integer;
begin
RectSize(tmpRect,SizeX,SizeY);
tmpXCenter:=SizeX shr 1;
tmpYCenter:=SizeY shr 1;
tmp1:=0;
tmp2:=0;
Range:=tmpXCenter+tmpYCenter;
CheckFastBrush;
Repeat
CalcBrushColor(tmp1+tmp2);
P0:=SizeY-(2*tmp1);
P1:=SizeX-(2*tmp2);
tmpLeft:=tmpRect.Left+tmp2;
tmpTop:=tmpRect.Top+tmp1;
PatBlt(FDC,tmpLeft,tmpTop,TeeGradientPrecision,P0,PATCOPY);
PatBlt(FDC,tmpRect.Right-tmp2-1,tmpTop,TeeGradientPrecision,P0,PATCOPY);
PatBlt(FDC,tmpLeft,tmpTop,P1,TeeGradientPrecision,PATCOPY);
PatBlt(FDC,tmpLeft,tmpRect.Bottom-tmp1-TeeGradientPrecision,
P1,TeeGradientPrecision,PATCOPY);
if tmp1<tmpYCenter then Inc(tmp1,TeeGradientPrecision);
if tmp2<tmpXCenter then Inc(tmp2,TeeGradientPrecision);
Until (tmp1>=tmpYCenter) and (tmp2>=tmpXCenter);
end;
Procedure DoDrawRadial;
var tmp : TCustomTeeGradient;
begin
tmp:=TCustomTeeGradient.Create(nil);
try
tmp.Direction:=gdRadial;
tmp.StartColor:=StartColor;
tmp.EndColor:=EndColor;
tmp.Draw(Self,tmpRect);
finally
tmp.Free;
end;
end;
procedure DiagonalGradient(Up:Boolean); // 7.0
var tmpFrom,
tmpTo : TPoint;
tmpSize : Integer;
Steps : Integer;
SizeX,
SizeY : Integer;
t : Integer;
tmpPen : TPen;
begin
if Up then tmpFrom:=TeePoint(tmpRect.Left,tmpRect.Bottom)
else tmpFrom:=tmpRect.TopLeft;
tmpTo:=tmpFrom;
RectSize(tmpRect,SizeX,SizeY);
tmpSize:=Max(SizeX,SizeY)+Min(SizeX,SizeY);
Steps:=Pred(tmpSize);
Range:=Min(255,Steps);
tmpPen:=TPen.Create;
try
tmpPen.Assign(Pen);
Pen.Width:=1;
Pen.Style:=psSolid;
Pen.Mode:=pmCopy;
for t:=0 to tmpSize-1 do
begin
Pen.Color:=CalcColor(t*Range div tmpSize);
Line(tmpFrom,tmpTo);
if not Up then
begin
if tmpTo.X<tmpRect.Right then Inc(tmpTo.X)
else
if tmpTo.Y<tmpRect.Bottom then Inc(tmpTo.Y);
if tmpFrom.Y<tmpRect.Bottom then Inc(tmpFrom.Y)
else
if tmpFrom.X<tmpRect.Right then Inc(tmpFrom.X)
end
else
begin
if tmpTo.X<tmpRect.Right then Inc(tmpTo.X)
else
if tmpTo.Y>tmpRect.Top then Dec(tmpTo.Y);
if tmpFrom.Y>tmpRect.Top then Dec(tmpFrom.Y)
else
if tmpFrom.X<tmpRect.Right then Inc(tmpFrom.X)
end;
end;
Pen.Assign(tmpPen);
finally
tmpPen.Free;
end;
end;
{$IFDEF CLR}
var tmpColor : TColor;
{$ENDIF}
begin
tmpRect:=OrientRectangle(Rect);
// deprecated. Use TTeeGradient.Draw method.
if Direction=gdRadial then
begin
DoDrawRadial;
exit;
end;
if (Direction<>gdTopBottom) and (Direction<>gdLeftRight) and
(Direction<>gdDiagonalUp) and (Direction<>gdDiagonalDown) then
{$IFDEF CLR}
begin
tmpColor:=StartColor;
StartColor:=EndColor;
EndColor:=tmpColor;
end;
{$ELSE}
SwapInteger(Integer(StartColor),Integer(EndColor));
{$ENDIF}
StartColor:=ColorToRGB(StartColor);
EndColor:=ColorToRGB(EndColor);
T0:=GetRValue(StartColor);
T1:=GetGValue(StartColor);
T2:=GetBValue(StartColor);
D0:=GetRValue(EndColor)-T0;
D1:=GetGValue(EndColor)-T1;
D2:=GetBValue(EndColor)-T2;
{$IFDEF CLX}
FCanvas.Start;
tmpBrush:=FCanvas.Brush.Handle;
{$ELSE}
tmpBrush:=0;
OldColor:=-1;
{$ENDIF}
Case Direction of
gdLeftRight,
gdRightLeft : RectGradient(True);
gdTopBottom,
gdBottomTop : RectGradient(False);
gdFromTopLeft,
gdFromBottomLeft : FromCorner;
gdFromCenter : FromCenter;
gdDiagonalUp : DiagonalGradient(True); // 7.0
gdDiagonalDown : DiagonalGradient(False);
end;
{$IFDEF CLX}
FCanvas.Stop;
{$ELSE}
if tmpBrush<>0 then DeleteObject(SelectObject(FDC,tmpBrush));
{$ENDIF}
end;
procedure TTeeCanvas3D.EraseBackground(const Rect: TRect);
begin
FillRect(Rect);
end;
procedure TTeeCanvas3D.FillRect(const Rect: TRect);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.FillRect(FCanvas.Handle, Rect, FBrush.Handle);
{$ELSE}
FCanvas.FillRect(Rect);
{$ENDIF}
end;
Function ApplyDark(Color:TColor; HowMuch:Byte):TColor;
Var r : Byte;
g : Byte;
b : Byte;
Begin
Color:=ColorToRGB(Color);
r:=Byte(Color);
g:=Byte(Color shr 8);
b:=Byte(Color shr 16);
if r>HowMuch then Dec(r,HowMuch) else r:=0;
if g>HowMuch then Dec(g,HowMuch) else g:=0;
if b>HowMuch then Dec(b,HowMuch) else b:=0;
result := (r or (g shl 8) or (b shl 16));
end;
Function ApplyBright(Color:TColor; HowMuch:Byte):TColor;
Var r : Byte;
g : Byte;
b : Byte;
Begin
Color:=ColorToRGB(Color);
r:=Byte(Color);
g:=Byte(Color shr 8);
b:=Byte(Color shr 16);
if (r+HowMuch)<256 then Inc(r,HowMuch) else r:=255;
if (g+HowMuch)<256 then Inc(g,HowMuch) else g:=255;
if (b+HowMuch)<256 then Inc(b,HowMuch) else b:=255;
result := (r or (g shl 8) or (b shl 16));
end;
Procedure TTeeCanvas3D.Cube(Left,Right,Top,Bottom,Z0,Z1:Integer; DarkSides:Boolean=True);
Function Culling:Double;
begin
result:=((IPoints[3].x-IPoints[2].x) * (IPoints[1].y-IPoints[2].y)) -
((IPoints[1].x-IPoints[2].x) * (IPoints[3].y-IPoints[2].y));
end;
Var OldColor : TColor;
P0,P1,
P2,P3 : TPoint;
tmp : Double;
Transparent : Boolean;
begin
Calc3DPoint(P0,Left,Top,z0);
Calc3DPoint(P1,Right,Top,z0);
Calc3DPoint(P2,Right,Bottom,z0);
Calc3DPoint(P3,Right,Top,z1);
if FBrush.Style=bsSolid then OldColor:=FBrush.Color
else OldColor:=BackColor;
Transparent:=FBrush.Style=bsClear;
IPoints[0]:=P0;
IPoints[1]:=P1;
IPoints[2]:=P2;
Calc3DPoint(IPoints[3],Left,Bottom,z0);
if Transparent or (Culling>0) then
PolygonFour // front-side
else
begin
Calc3DPoint(IPoints[0],Left,Top,z1);
Calc3DPoint(IPoints[1],Right,Top,z1);
Calc3DPoint(IPoints[2],Right,Bottom,z1);
Calc3DPoint(IPoints[3],Left,Bottom,z1);
PolygonFour // back-side
end;
Calc3DPoint(IPoints[2],Right,Bottom,z1);
IPoints[0]:=P1;
IPoints[1]:=P3;
IPoints[3]:=P2;
if Transparent or (Culling>0) then
begin
if DarkSides then InternalDark(OldColor,DarkerColorQuantity);
PolygonFour; // left-side
end;
IPoints[0]:=P0;
Calc3DPoint(IPoints[1],Left,Top,z1);
Calc3DPoint(IPoints[2],Left,Bottom,z1);
Calc3DPoint(IPoints[3],Left,Bottom,z0);
if Transparent then
tmp:=1
else
tmp:=(IPoints[3].x-IPoints[0].x) * (IPoints[1].y-IPoints[0].y) -
(IPoints[1].x-IPoints[0].x) * (IPoints[3].y-IPoints[0].y);
if tmp>0 then
begin
if DarkSides then InternalDark(OldColor,DarkerColorQuantity);
PolygonFour; // right-side
end;
Calc3DPoint(IPoints[3],Left,Top,z1);
// culling
if Transparent then tmp:=1
else tmp:=(P0.x-P1.x) * (P3.y-P1.y) - (P3.x-P1.x) * (P0.y-P1.y);
if tmp>0 then
begin
IPoints[0]:=P0;
IPoints[1]:=P1;
IPoints[2]:=P3;
if DarkSides then InternalDark(OldColor,DarkColorQuantity);
PolygonFour; // top-side
end;
Calc3DPoint(IPoints[0],Left,Bottom,z0);
Calc3DPoint(IPoints[2],Right,Bottom,z1);
Calc3DPoint(IPoints[1],Left,Bottom,z1);
IPoints[3]:=P2;
if Transparent or (Culling<0) then
begin
if DarkSides then InternalDark(OldColor,DarkColorQuantity);
PolygonFour;
end;
end;
Procedure TTeeCanvas3D.RectangleZ(Left,Top,Bottom,Z0,Z1:Integer);
begin
Calc3DPoint(IPoints[0],Left,Top,Z0);
Calc3DPoint(IPoints[1],Left,Top,Z1);
Calc3DPoint(IPoints[2],Left,Bottom,Z1);
Calc3DPoint(IPoints[3],Left,Bottom,Z0);
PolygonFour;
end;
Procedure TTeeCanvas3D.RectangleY(Left,Top,Right,Z0,Z1:Integer);
begin
Calc3DPoint(IPoints[0],Left,Top,Z0);
Calc3DPoint(IPoints[1],Right,Top,Z0);
Calc3DPoint(IPoints[2],Right,Top,Z1);
Calc3DPoint(IPoints[3],Left,Top,Z1);
PolygonFour;
end;
procedure TTeeCanvas3D.DisableRotation;
begin
FWas3D:=FIs3D;
FIs3D:=False;
end;
procedure TTeeCanvas3D.EnableRotation;
begin
FIs3D:=FWas3D;
end;
Procedure TTeeCanvas3D.Invalidate;
begin
FDirty:=True;
end;
procedure TTeeCanvas3D.RotateLabel3D(x,y,z:Integer; const St:String; RotDegree:Double);
begin
Calc3DPos(x,y,z);
RotateLabel(x,y,St,RotDegree);
end;
procedure TTeeCanvas3D.RotateLabel(x,y:Integer; const St:String; RotDegree:Double);
{$IFNDEF CLX}
var OldFont: HFONT;
NewFont: HFONT;
LogRec : TLOGFONT;
FDC : HDC;
{$ELSE}
var tmpSt : WideString;
tmpW : Integer;
tmpH : Integer;
tmp : Integer;
{$ENDIF}
begin
while RotDegree>360 do RotDegree:=RotDegree-360;
{$IFNDEF CLX}
FBrush.Style := bsClear;
FDC:=FCanvas.Handle;
{$IFDEF CLR}
GetObject(FFont.Handle, Marshal.SizeOf(TypeOf(TLogFont)), LogRec);
{$ELSE}
GetObject(FFont.Handle, SizeOf(LogRec), @LogRec);
{$ENDIF}
LogRec.lfEscapement := Round(RotDegree*10.0);
LogRec.lfOrientation := Round(RotDegree*10.0); { <-- fix, was zero }
LogRec.lfOutPrecision := OUT_TT_ONLY_PRECIS;
if IZoomText then
if IZoomFactor<>1 then
LogRec.lfHeight:= -MulDiv( Math.Max(1,Round(IZoomFactor*FFont.Size)),
FFont.PixelsPerInch, 72);
LogRec.lfQuality:=TeeFontAntiAlias;
NewFont := CreateFontIndirect(LogRec);
OldFont := SelectObject(FDC,NewFont);
TextOut(x,y,St);
DeleteObject(SelectObject(FDC,OldFont));
{$ELSE}
if RotDegree=0 then TextOut(x,y,St)
else
begin
RotDegree:=360-RotDegree;
tmp:=TextAlign;
tmpH:=FCanvas.TextHeight(St);
if tmp>=TA_BOTTOM then
begin
tmpH:=tmpH div 2;
Dec(tmp,TA_BOTTOM);
end;
if tmp=TA_CENTER then
tmpW:=FCanvas.TextWidth(St) div 2
else
if tmp=TA_RIGHT then
tmpW:=FCanvas.TextWidth(St)
else
tmpW:=0;
FCanvas.Start;
QPainter_translate(Handle,x,y);
QPainter_rotate(FCanvas.Handle,RotDegree);
QPainter_translate(Handle,-x-tmpW,-y+tmpH-2); // 2 ?
if IZoomText then
if IZoomFactor<>1 then
FFont.Size:=Math.Max(1,Round(IZoomFactor*FFont.Size));
QPainter_setFont(FCanvas.Handle,FFont.Handle);
tmpSt:=St;
QPainter_drawText(FCanvas.Handle,x,y,PWideString(@tmpSt),-1);
QPainter_resetXForm( FCanvas.Handle ); // 7.0
FCanvas.Stop;
end;
{$ENDIF}
end;
Procedure TTeeCanvas3D.Line(X0,Y0,X1,Y1:Integer);
{$IFNDEF CLX}
var FDC : HDC;
{$ENDIF}
begin
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,X0,Y0,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,X1,Y1);
{$ELSE}
FCanvas.MoveTo(X0,Y0);
FCanvas.LineTo(X1,Y1);
{$ENDIF}
end;
Procedure TTeeCanvas3D.LineWithZ(X0,Y0,X1,Y1,Z:Integer);
{$IFNDEF CLX}
var FDC : HDC;
{$ENDIF}
begin
Calc3DPos(x0,y0,z);
Calc3DPos(x1,y1,z);
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,X0,Y0,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,X1,Y1);
{$ELSE}
Line(X0,Y0,X1,Y1);
{$ENDIF}
end;
Procedure TTeeCanvas3D.Polyline(const Points: {$IFDEF D5}Array of TPoint{$ELSE}TPointArray{$ENDIF});
Begin
{$IFNDEF CLX}
{$IFDEF CLR}
Borland.VCL.Windows.Polyline(FCanvas.Handle, Points, High(Points)+1);
{$ELSE}
Windows.Polyline(FCanvas.Handle, PPoints(@Points)^, High(Points)+1);
{$ENDIF}
{$ELSE}
FCanvas.Polyline(Points);
{$ENDIF}
end;
Procedure TTeeCanvas3D.Polygon(const Points:Array of TPoint);
Begin
{$IFNDEF CLX}
{$IFDEF CLR}
Borland.VCL.Windows.Polygon(FCanvas.Handle, Points, High(Points)+1);
{$ELSE}
Windows.Polygon(FCanvas.Handle, PPoints(@Points)^, High(Points) + 1);
{$ENDIF}
{$ELSE}
FCanvas.Polygon(Points);
{$ENDIF}
end;
procedure TTeeCanvas3D.PolygonWithZ(Points: Array of TPoint; Z:Integer);
var t : Integer;
begin
for t:=0 to Length(Points)-1 do
Calc3DPoint(Points[t],Points[t].X,Points[t].Y,z);
Polygon(Points);
end;
procedure TTeeCanvas3D.Polyline(const Points: Array of TPoint; Z:Integer);
var t : Integer;
L : Integer;
P : Array of TPoint;
begin
L:=Length(Points);
SetLength(P,L);
for t:=0 to L-1 do
P[t]:=Calculate3DPosition(Points[t],z);
{$IFDEF D5}
Polyline(P);
{$ELSE}
// this is due to a D4 bug...
{$IFNDEF CLX}
Windows.Polyline(FCanvas.Handle, PPoints(@Points)^, High(Points) + 1);
{$ELSE}
FCanvas.Polyline(Points);
{$ENDIF}
{$ENDIF}
P:=nil;
end;
procedure TTeeCanvas3D.Ellipse(X1, Y1, X2, Y2: Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.Ellipse(FCanvas.Handle, X1, Y1, X2, Y2);
{$ELSE}
FCanvas.Ellipse(X1,Y1,X2,Y2);
{$ENDIF}
end;
Procedure TTeeCanvas3D.GetCirclePoints(var P:TCirclePoints; X1, Y1, X2, Y2, Z: Integer);
Const PiStep=2.0*Pi*(360.0/(NumCirclePoints-1))/360.0;
var PCenter : TPoint;
XRadius : Integer;
YRadius : Integer;
t : Integer;
tmpSin : Extended;
tmpCos : Extended;
begin
PCenter.X:=(X2+X1) div 2;
PCenter.Y:=(Y2+Y1) div 2;
XRadius:=(X2-X1) div 2;
YRadius:=(Y2-Y1) div 2;
P[0]:=Calculate3DPosition(PCenter.X,Y2,Z);
for t:=1 to NumCirclePoints-1 do
begin
SinCos(t*piStep,tmpSin,tmpCos);
// 6.02, fix for rounding pixel problem:
Calc3DPoint(P[t],PCenter.X+(XRadius*tmpSin),PCenter.Y+(YRadius*tmpCos),Z);
end;
end;
procedure TTeeCanvas3D.EllipseWithZ(X1, Y1, X2, Y2, Z: Integer);
Var P : TCirclePoints;
Points : TTrianglePoints;
PCenter : TPoint;
t : Integer;
Old : TPenStyle;
begin
if FIsOrthogonal then
begin
Calc3DPos(X1,Y1,Z);
Calc3DPos(X2,Y2,Z);
Ellipse(X1,Y1,X2,Y2);
end
else
if FIs3D then
begin
GetCirclePoints(P,X1,Y1,X2,Y2,Z);
if FBrush.Style<>bsClear then
begin
Old:=FPen.Style;
FPen.Style:=psClear;
PCenter.X:=(X2+X1) div 2;
PCenter.Y:=(Y2+Y1) div 2;
Calc3DTPoint(PCenter,Z);
Points[0]:=PCenter;
Points[1]:=P[0];
Points[2]:=P[1];
Polygon(Points);
Points[1]:=P[1];
for t:=2 to NumCirclePoints-1 do
begin
Points[2]:=P[t];
Polygon(Points);
Points[1]:=P[t];
end;
FPen.Style:=Old;
end;
if FPen.Style<>psClear then
begin
{$IFDEF D5}
Polyline(P);
{$ELSE}
// this is due to a D4 bug...
Windows.Polyline(FCanvas.Handle, PPoints(@P)^, High(P) + 1);
{$ENDIF}
end;
end
else Ellipse(X1,Y1,X2+1,Y2+1);
end;
Function TTeeCanvas3D.GetPixel(X, Y: Integer):TColor;
begin
{$IFDEF D7}
result:=FCanvas.Pixels[x,y];
{$ELSE}
{$IFDEF CLX}
{$IFDEF MSWINDOWS}
result:=Windows.GetPixel(QPainter_handle(Handle), X, Y);
{$ELSE}
result:=0; // Not implemented.
{$ENDIF}
{$ELSE}
result:=FCanvas.Pixels[x,y];
{$ENDIF}
{$ENDIF}
end;
procedure TTeeCanvas3D.SetPixel(X, Y: Integer; Value: TColor);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.SetPixel(FCanvas.Handle, X, Y, ColorToRGB(Value));
{$ELSE}
QPainter_drawPoint(Handle,x,y);
{$ENDIF}
end;
procedure TTeeCanvas3D.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.Arc(FCanvas.Handle, X1, Y1, X2, Y2, X3, Y3, X4, Y4);
{$ELSE}
FCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4);
{$ENDIF}
end;
// Donut 2D
procedure TTeeCanvas3D.Donut( XCenter,YCenter,XRadius,YRadius:Integer;
Const StartAngle,EndAngle,HolePercent:Double);
var tmpXRadius,
tmpYRadius : Double;
tmpSin,
tmpCos : Extended;
Procedure CalcPoint(const Angle:Double; var x,y:Integer);
begin
SinCos(Angle,tmpSin,tmpCos);
x:=XCenter+Round(XRadius*tmpCos);
y:=YCenter-Round(YRadius*tmpSin);
end;
Procedure CalcPoint2(const Angle:Double; var x,y:Integer);
begin
SinCos(Angle,tmpSin,tmpCos);
X:=XCenter+Round(tmpXRadius*tmpCos);
Y:=YCenter-Round(tmpYRadius*tmpSin);
end;
{$IFNDEF CLX}
var x3,y3,
x4,y4 : Integer;
tmpDC : TTeeCanvasHandle;
px,py : Integer;
{$ELSE}
Const MaxCircleSteps=128;
var Points : Array[0..2*MaxCircleSteps-1] of TPoint;
t,
CircleSteps,
tmp : Integer;
Step : Double;
tmpAngle : Extended;
{$ENDIF}
begin
tmpXRadius:=HolePercent*XRadius*0.01;
tmpYRadius:=HolePercent*YRadius*0.01;
{$IFNDEF CLX}
CalcPoint(StartAngle,x3,y3);
CalcPoint(EndAngle,x4,y4);
tmpDC:=Handle;
BeginPath(tmpDC);
px:=x3;
py:=y3;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(tmpDC,x3,y3,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.ArcTo(tmpDC,XCenter-XRadius,YCenter-YRadius,XCenter+XRadius,YCenter+YRadius,
x3,y3,x4,y4);
CalcPoint2(StartAngle,x3,y3);
CalcPoint2(EndAngle,x4,y4);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(tmpDC,x4,y4);
if (x4<>x3) or (y4<>y3) then
begin
SetArcDirection(tmpDC,AD_CLOCKWISE);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.ArcTo(tmpDC,XCenter-Round(tmpXRadius),YCenter-Round(tmpYRadius),
XCenter+Round(tmpXRadius),YCenter+Round(tmpYRadius),
x4,y4,x3,y3);
SetArcDirection(tmpDC,AD_COUNTERCLOCKWISE);
end;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(tmpDC,px,py);
EndPath(tmpDC);
StrokeAndFillPath(tmpDC);
{$ELSE}
CircleSteps:=Round(MaxCircleSteps*(EndAngle-StartAngle)/Pi);
if CircleSteps<2 then CircleSteps:=2
else
if CircleSteps>MaxCircleSteps then CircleSteps:=MaxCircleSteps;
Step:=(EndAngle-StartAngle)/Pred(CircleSteps);
tmpAngle:=StartAngle;
for t:=1 to CircleSteps do
begin
SinCos(tmpAngle,tmpSin,tmpCos);
Points[t].X:=XCenter+Round(XRadius*tmpCos);
Points[t].Y:=YCenter-Round(YRadius*tmpSin);
if t=1 then tmp:=0
else tmp:=2*CircleSteps-t+1;
Points[tmp].X:=XCenter+Round(tmpXRadius*tmpCos);
Points[tmp].Y:=YCenter-Round(tmpYRadius*tmpSin);
tmpAngle:=tmpAngle+Step;
end;
Polygon(Slice(Points,2*CircleSteps)); { 5.02 }
{$ENDIF}
end;
procedure TTeeCanvas3D.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
{$IFDEF CLX}
var Theta: Extended;
Theta2: Extended;
{$ENDIF}
begin
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.Pie(FCanvas.Handle, X1, Y1, X2, Y2, X3, Y3, X4, Y4);
{$ELSE}
// bug in CLX, needs this code:
CalcPieAngles(X1,X2,Y1,Y2,X3,Y3,X4,Y4,Theta,Theta2);
FCanvas.Pie(X1, Y1, X2-X1, Y2-Y1, Round(Theta) shl 4, Round(Theta2 - Theta) shl 4);
{$ENDIF}
end;
procedure TCanvas3D.CalcPieAngles(X1,Y1,X2,Y2,X3,Y3,X4,Y4:Integer; var Theta,Theta2:Extended);
const HalfDivPi=180/Pi;
var
Width, Height: Integer;
CenterX, CenterY: Integer;
begin
Width := X2 - X1;
Height := Y2 - Y1;
CenterX := X1 + (Width div 2);
CenterY := Y1 + (Height div 2);
Theta:=ArcTan2(CenterY-Y3, X3 - CenterX);
if Theta<0 then Theta:=2.0*Pi+Theta;
Theta := Theta*HalfDivPi;
Theta2:=ArcTan2(CenterY-Y4, X4 - CenterX);
if Theta2<0 then Theta2:=2.0*Pi+Theta2;
Theta2 :=Theta2*HalfDivPi;
if Theta2=0 then
Theta2:=361;
end;
{$IFDEF CLR}
Function Slice(const A:Array of TPoint; Count:Integer):TPointArray;
begin
SetLength(result,Count);
System.Array.Copy(A,result,Count);
end;
{$ENDIF}
procedure TTeeCanvas3D.Pie3D( XCenter,YCenter,XRadius,YRadius,Z0,Z1:Integer;
Const StartAngle,EndAngle:Double;
DarkSides,DrawSides:Boolean; DonutPercent:Integer=0;
Gradient:TCustomTeeGradient=nil);
Procedure PolygonGradient(var P:Array of TPoint);
var OldBrush : TBrushStyle;
begin
ClipPolygon(P,Length(P));
Gradient.Draw(Self,RectFromPolygon(P,Length(P)));
UnClipRectangle;
if Pen.Style<>psClear then // outline
begin
OldBrush:=Brush.Style;
Brush.Style:=bsClear;
Polygon(P);
Brush.Style:=OldBrush;
end;
end;
Const MaxCircleSteps=96;
var Points : Array[0..2*MaxCircleSteps+1] of TPoint;
Points3D2,
Points3D : Array[1..2*MaxCircleSteps] of TPoint;
Start3D,
End3D,
CircleSteps : Integer;
OldColor : TColor;
Procedure Draw3DPie;
var t,tt : Integer;
{$IFDEF CLR}
tmp : TPointArray;
{$ENDIF}
begin
if DarkSides then InternalDark(OldColor,32);
if (Start3D=1) and (End3D=CircleSteps) then
begin
for t:=1 to CircleSteps do Points3D[t]:=Points[t];
tt:=CircleSteps;
end
else
begin
tt:=0;
for t:=Start3D to End3D do
begin
Inc(tt);
Points3D[tt]:=Points[t];
Points3D[End3D-Start3D+1+tt]:=Points3D[2*CircleSteps-End3D+tt];
end;
end;
{$IFDEF CLR}
tmp:=Slice(Points3D,2*tt);
if Assigned(Gradient) then PolygonGradient(tmp)
else Polygon(tmp);
{$ELSE}
if Assigned(Gradient) then PolygonGradient(Slice(Points3D,2*tt))
else Polygon(Slice(Points3D,2*tt));
{$ENDIF}
end;
var tmpSin,
tmpCos : Extended;
tmpXRadius,
tmpYRadius : Double;
Procedure CalcCenter(Var P:TPoint; const Angle:Double; Z:Integer);
begin
if DonutPercent>0 then
begin
SinCos(Angle,tmpSin,tmpCos);
Calc3DPoint(P,XCenter+(tmpXRadius*tmpCos),YCenter-Round(tmpYRadius*tmpSin),Z);
end
else
Calc3DPoint(P,XCenter,YCenter,Z);
end;
Procedure FinishSide(const Angle:Double);
begin
CalcCenter(IPoints[3],Angle,Z0);
if DarkSides then InternalDark(OldColor,32);
PolygonFour;
end;
Procedure DrawPieTop(NumPoints:Integer);
{$IFDEF CLR}
var tmp : TPointArray;
{$ENDIF}
begin
{$IFDEF CLR}
tmp:=Slice(Points,NumPoints);
if Assigned(Gradient) then PolygonGradient(tmp)
else Polygon(tmp);
{$ELSE}
if Assigned(Gradient) then PolygonGradient(Slice(Points,NumPoints))
else Polygon(Slice(Points,NumPoints))
{$ENDIF}
end;
Var tmpAngle : Extended;
Step : Double;
Started : Boolean;
Ended : Boolean;
t : Integer;
tt : Integer;
tmpX : Double;
tmpY : Double;
begin
CircleSteps:=2+Math.Min(MaxCircleSteps-2,Round(180.0*Abs(EndAngle-StartAngle)/Pi/2.0));
// CircleSteps:=MaxCircleSteps; { improved to draw better rounded }
if DonutPercent>0 then
begin
tmpXRadius:=DonutPercent*XRadius*0.01;
tmpYRadius:=DonutPercent*YRadius*0.01;
end;
CalcCenter(Points[0],StartAngle,Z1);
Step:=(EndAngle-StartAngle)/(CircleSteps-1);
tmpAngle:=StartAngle;
for t:=1 to CircleSteps do
begin
SinCos(tmpAngle,tmpSin,tmpCos);
tmpX:=XCenter+(XRadius*tmpCos); // 6.02, removed "Round"
tmpY:=YCenter-(YRadius*tmpSin); // "" ""
Calc3DPoint(Points[t],tmpX,tmpY,Z1);
Calc3DPoint(Points3D[2*CircleSteps+1-t],tmpX,tmpY,Z0);
tmpAngle:=tmpAngle+Step;
end;
if FBrush.Style=bsSolid then OldColor:=FBrush.Color
else OldColor:=BackColor;
if DonutPercent>0 then
begin
CalcCenter(Points[2*CircleSteps+1],EndAngle,Z1);
Points3D2[1]:=Points[0];
tmpAngle:=EndAngle;
for t:=1 to CircleSteps do
begin
CalcCenter(Points[CircleSteps+t],tmpAngle,Z1);
Points3D2[t]:=Points[CircleSteps+t];
CalcCenter(Points3D2[2*CircleSteps+1-t],tmpAngle,Z0);
tmpAngle:=tmpAngle-Step;
end;
if DarkSides then InternalDark(OldColor,32);
Polygon(Slice(Points3D2,2*CircleSteps)); { 5.02 }
end;
{ side }
if DrawSides then
begin
if Points[CircleSteps].X < FXCenterOffset then
begin
if DonutPercent>0 then IPoints[0]:=Points[2*CircleSteps+1]
else IPoints[0]:=Points[0];
IPoints[1]:=Points[CircleSteps];
IPoints[2]:=Points3D[CircleSteps+1];
FinishSide(EndAngle);
end;
{ side }
if Points[1].X > FXCenterOffset then
begin
IPoints[0]:=Points[0];
IPoints[1]:=Points[1];
IPoints[2]:=Points3D[2*CircleSteps];
FinishSide(StartAngle);
end;
end;
{ 2d pie }
if FBrush.Style=bsSolid then FBrush.Color:=OldColor
else BackColor:=OldColor;
if DonutPercent>0 then DrawPieTop(2*CircleSteps+1)
else DrawPieTop(CircleSteps+1);
{ 3d pie }
Ended:=False;
Start3D:=0;
End3D:=0;
for t:=2 to CircleSteps do
begin
if Points[t].X>Points[t-1].X then
begin
Start3D:=t-1;
Started:=True;
for tt:=t+1 to CircleSteps-1 do
if Points[tt+1].X<Points[tt].X then
begin
End3D:=tt;
Ended:=True;
Break;
end;
if (not Ended) and (Points[CircleSteps].X>=Points[CircleSteps-1].X) then
begin
End3D:=CircleSteps;
Ended:=True;
end;
if Started and Ended then
Draw3DPie;
if End3D<>CircleSteps then
if Points[CircleSteps].X>Points[CircleSteps-1].X then
begin
End3D:=CircleSteps;
tt:=CircleSteps-1;
While (Points[tt].X>Points[tt-1].X) do
begin
Dec(tt);
if tt=1 then break;
end;
if tt>1 then
begin
Start3D:=tt;
Draw3DPie;
end;
end;
break;
end;
end;
end;
procedure TTeeCanvas3D.Plane3D(Const A,B:TPoint; Z0,Z1:Integer);
begin
Calc3DPoint(IPoints[0],A.X,A.Y,Z0);
Calc3DPoint(IPoints[1],B.X,B.Y,Z0);
Calc3DPoint(IPoints[2],B.X,B.Y,Z1);
Calc3DPoint(IPoints[3],A.X,A.Y,Z1);
PolygonFour;
end;
procedure TTeeCanvas3D.InternalCylinder(Vertical:Boolean; Left,Top,Right,Bottom,
Z0,Z1:Integer; Dark3D:Boolean; ConePercent:Integer);
var Radius,
ZRadius,
tmpMid,
tmpMidZ : Integer;
Step:Double;
Procedure CalcPointZ(Index:Integer; var X,Z:Integer);
var tmpSin : Extended;
tmpCos : Extended;
begin
SinCos(Index*Step,tmpSin,tmpCos);
X:=tmpMid+Round(tmpSin*Radius);
Z:=tmpMidZ-Round(tmpCos*ZRadius);
end;
var
tmpSize : Integer;
Poly : Array of TPoint3D;
tmpPoly : Array[1..4] of TPoint;
Procedure CalcPointV(a,b:Integer);
begin
With Poly[a] do
begin
Calc3DPoint(tmpPoly[b],x,y+tmpSize,z);
CalcPointZ(a-4,X,Z);
end;
end;
Procedure CalcPointH(a,b:Integer);
begin
With Poly[a] do
begin
Calc3DPoint(tmpPoly[b],x-tmpSize,y,z);
CalcPointZ(a-5,Y,Z);
end;
end;
Function CoverAtLeft:Boolean;
begin
Calc3DPoint(tmpPoly[1],0,0,0);
Calc3DPoint(tmpPoly[2],0,10,0);
Calc3DPoint(tmpPoly[3],0,10,10);
result:=TeeCull(tmpPoly[1],tmpPoly[2],tmpPoly[3]);
end;
var
OldColor : TColor;
procedure DrawCover;
var tmpPoly2 : Array of TPoint;
t : Integer;
begin
// Cover
SetLength(tmpPoly2,TeeNumCylinderSides);
if (not Vertical) and CoverAtLeft then
for t:=0 to TeeNumCylinderSides-1 do
tmpPoly2[t]:=Calculate3DPosition(Left,Poly[1+t].Y,Poly[1+t].Z)
else
for t:=0 to TeeNumCylinderSides-1 do
tmpPoly2[t]:=Calc3DTPoint3D(Poly[1+t]);
if Dark3D then InternalDark(OldColor,DarkColorQuantity);
Polygon(tmpPoly2);
tmpPoly2:=nil;
end;
Var t : Integer;
NumSide : Integer;
tmp : Integer;
StepColor: Integer;
begin
if ConePercent=0 then ConePercent:=TeeDefaultConePercent;
if FBrush.Style=bsSolid then OldColor:=FBrush.Color
else OldColor:=BackColor;
ZRadius:=(Z1-Z0) div 2;
tmpMidZ:=(Z1+Z0) div 2;
SetLength(Poly,1+TeeNumCylinderSides);
Step:=2.0*Pi/TeeNumCylinderSides;
if Vertical then
begin
Radius:=(Right-Left) div 2;
tmpMid:=(Right+Left) div 2;
tmpSize:=Abs(Bottom-Top);
if Top<Bottom then tmp:=Top
else tmp:=Bottom;
for t:=1 to TeeNumCylinderSides do
begin
Poly[t].Y:=tmp;
CalcPointZ(t-4,Poly[t].X,Poly[t].Z);
end;
end
else
begin
Radius:=(Bottom-Top) div 2;
tmpMid:=(Bottom+Top) div 2;
tmpSize:=Abs(Right-Left);
if Left<Right then tmp:=Right
else tmp:=Left;
for t:=1 to TeeNumCylinderSides do
begin
Poly[t].X:=tmp;
CalcPointZ(t-5,Poly[t].Y,Poly[t].Z);
end;
end;
Radius:=Round(Radius*ConePercent*0.01);
ZRadius:=Round(ZRadius*ConePercent*0.01);
if Vertical then CalcPointV(1,2)
else CalcPointH(1,2);
tmpPoly[1]:=Calc3DTPoint3D(Poly[1]);
NumSide:=0;
StepColor:=256 div (TeeNumCylinderSides * 2);
for t:=2 to TeeNumCylinderSides do
begin
if Vertical then CalcPointV(t,3)
else CalcPointH(t,3);
tmpPoly[4]:=Calc3DTPoint3D(Poly[t]);
if not TeeCull(tmpPoly[1],tmpPoly[2],tmpPoly[3]) then
begin
if Dark3D then
InternalDark(OldColor,StepColor*NumSide);
Polygon(tmpPoly);
end;
tmpPoly[1]:=tmpPoly[4];
tmpPoly[2]:=tmpPoly[3];
Inc(NumSide);
end;
if ConePercent=100 then
begin
if Vertical then CalcPointV(1,3)
else CalcPointH(1,3);
tmpPoly[4]:=Calc3DTPoint3D(Poly[1]);
if not TeeCull(tmpPoly[1],tmpPoly[2],tmpPoly[3]) then
Polygon(tmpPoly);
end;
DrawCover;
Poly:=nil;
end;
procedure TTeeCanvas3D.Cylinder(Vertical:Boolean; Left,Top,Right,Bottom,Z0,Z1:Integer; Dark3D:Boolean);
Begin
InternalCylinder(Vertical,Left,Top,Right,Bottom,Z0,Z1,Dark3D,100);
end;
procedure TTeeCanvas3D.Pyramid(Vertical:Boolean; Left,Top,Right,Bottom,z0,z1:Integer; DarkSides:Boolean);
Var OldColor : TColor;
P0,P1,
P2,P3,
PTop : TPoint;
tmpC : Boolean;
begin
if FBrush.Style=bsSolid then OldColor:=FBrush.Color
else OldColor:=BackColor;
if Vertical then
begin
if Top<>Bottom then
Begin
Calc3DPoint(P0,Left,Bottom,Z0);
Calc3DPoint(P1,Right,Bottom,Z0);
Calc3DPoint(PTop,(Left+Right) div 2,Top,(Z0+Z1) div Integer(2));
Calc3DPoint(P2,Left,Bottom,Z1);
Calc3DPoint(P3,Right,Bottom,Z1);
Polygon([P0,PTop,P1]);
tmpC:=TeeCull(P0,PTop,P2);
if Top<Bottom then tmpC:=not tmpC;
if tmpC then Polygon([ P0,PTop,P2] );
if DarkSides then InternalDark(OldColor,DarkerColorQuantity);
tmpC:=TeeCull(P1,PTop,P3);
if Top>=Bottom then tmpC:=not tmpC;
if tmpC then Polygon([ P1,PTop,P3 ] );
if Top<Bottom then
begin
Calc3DPoint(P2,Left,Bottom,Z1);
if TeeCull(PTop,P2,P3) then Polygon([ PTop,P2,P3 ] );
end;
end;
Calc3DPoint(P0,Left,Bottom,Z0);
Calc3DPoint(P1,Right,Bottom,Z0);
Calc3DPoint(P2,Left,Bottom,Z1);
tmpC:=TeeCull(P0,P1,P2);
if Top>=Bottom then tmpC:=not tmpC;
if tmpC then
begin
if DarkSides then InternalDark(OldColor,DarkColorQuantity);
RectangleY(Left,Bottom,Right,Z0,Z1);
end;
end
else
begin
if Left<>Right then
Begin
Calc3DPoint(P0,Left,Top,Z0);
Calc3DPoint(P1,Left,Bottom,Z0);
Calc3DPoint(PTop,Right,(Top+Bottom) div 2,(Z0+Z1) div 2);
Calc3DPoint(P2,Left,Top,Z1);
Calc3DPoint(P3,Left,Bottom,Z1);
Polygon([P0,PTop,P1]);
tmpC:=TeeCull(P2,PTop,P3);
if Left<Right then tmpC:=not tmpC;
if tmpC then Polygon([ P2,PTop,P3] );
if DarkSides then InternalDark(OldColor,DarkColorQuantity);
tmpC:=TeeCull(P0,PTop,P2);
if Left<Right then tmpC:=not tmpC;
if tmpC then Polygon([ P0,PTop,P2 ] );
tmpC:=TeeCull(P3,PTop,P1);
if Left<Right then tmpC:=not tmpC;
if tmpC then Polygon([ P3,PTop,P1 ] );
end;
Calc3DPoint(P0,Left,Top,Z0);
Calc3DPoint(P1,Left,Bottom,Z0);
Calc3DPoint(P2,Left,Top,Z1);
tmpC:=TeeCull(P0,P1,P2);
if Left>=Right then tmpC:=not tmpC;
if tmpC then
begin
if DarkSides then InternalDark(OldColor,DarkerColorQuantity);
RectangleZ(Left,Top,Bottom,Z0,Z1);
end;
end;
end;
Procedure TTeeCanvas3D.PyramidTrunc(Const R:TRect; StartZ,EndZ:Integer;
TruncX,TruncZ:Integer);
var MidX : Integer;
MidZ : Integer;
Procedure PyramidFrontWall(StartZ,EndZ:Integer);
var P : TFourPoints;
P0,P1,P2:TPoint;
begin
P[0].X:=MidX-TruncX;
P[0].Y:=R.Top;
P[1].X:=MidX+TruncX;
P[1].Y:=R.Top;
P[2].X:=R.Right;
P[2].Y:=R.Bottom;
P[3].X:=R.Left;
P[3].Y:=R.Bottom;
P0:=Calculate3DPosition(P[0],StartZ);
P1:=Calculate3DPosition(P[1],StartZ);
P2:=Calculate3DPosition(P[2],EndZ);
if EndZ>StartZ then // 7.0
begin
if not TeeCull(P0,P1,P2) then
PlaneFour3D(P,StartZ,EndZ);
end
else
if TeeCull(P0,P1,P2) then
PlaneFour3D(P,StartZ,EndZ);
end;
Procedure PyramidSideWall(HorizPos1,HorizPos2:Integer; IsLeft:Boolean);
var tmp : Boolean;
begin
IPoints[0]:=Calculate3DPosition(HorizPos2,R.Top,MidZ-TruncZ);
IPoints[1]:=Calculate3DPosition(HorizPos2,R.Top,MidZ+TruncZ);
IPoints[2]:=Calculate3DPosition(HorizPos1,R.Bottom,EndZ);
IPoints[3]:=Calculate3DPosition(HorizPos1,R.Bottom,StartZ);
tmp:=TeeCull(IPoints[3], IPoints[2], IPoints[1]);
if IsLeft then
begin
if tmp then PolygonFour;
end
else
if not tmp then PolygonFour;
end;
Procedure BottomCover;
begin
RectangleY(R.Left,R.Bottom,R.Right,StartZ,EndZ)
end;
Procedure TopCover;
begin
if TruncX<>0 then
RectangleY(MidX-TruncX,R.Top,MidX+TruncX,MidZ-TruncZ,MidZ+TruncZ);
end;
begin
MidX:=(R.Left+R.Right) div 2;
MidZ:=(StartZ+EndZ) div 2;
if R.Bottom>R.Top then BottomCover else TopCover;
PyramidFrontWall(MidZ+TruncZ,EndZ);
PyramidSideWall(R.Left,MidX-TruncX,True);
PyramidFrontWall(MidZ-TruncZ,StartZ);
PyramidSideWall(R.Right,MidX+TruncX,False);
if R.Bottom>R.Top then TopCover else BottomCover;
end;
procedure TTeeCanvas3D.PlaneFour3D(Var Points:TFourPoints; Z0,Z1:Integer);
{$IFDEF TEEPLANEFLOAT}
{$IFNDEF CLR}
var tmpX: Double;
{$ENDIF}
{$ENDIF}
begin
IPoints:=Points;
{$IFDEF CLR}
Calc3DTPoint(IPoints[0],Z0);
Calc3DTPoint(IPoints[1],Z0);
Calc3DTPoint(IPoints[2],Z1);
Calc3DTPoint(IPoints[3],Z1);
{$ELSE}
{$IFDEF TEEPLANEFLOAT}
tmpX:=Points[0].X;
Calc3DPoint(IPoints[0],tmpX,Points[0].Y,Z0);
tmpX:=Points[1].X;
Calc3DPoint(IPoints[1],tmpX,Points[1].Y,Z0);
tmpX:=Points[2].X;
Calc3DPoint(IPoints[2],tmpX,Points[2].Y,Z1);
tmpX:=Points[3].X;
Calc3DPoint(IPoints[3],tmpX,Points[3].Y,Z1);
{$ELSE}
Calc3DPos(IPoints[0].X,IPoints[0].Y,Z0);
Calc3DPos(IPoints[1].X,IPoints[1].Y,Z0);
Calc3DPos(IPoints[2].X,IPoints[2].Y,Z1);
Calc3DPos(IPoints[3].X,IPoints[3].Y,Z1);
{$ENDIF}
{$ENDIF}
PolygonFour;
end;
Function TTeeCanvas3D.GetPixel3D(X,Y,Z: Integer):TColor;
begin
Calc3DPos(X,Y,Z);
result:=GetPixel(x,y);
end;
procedure TTeeCanvas3D.SetPixel3D(X,Y,Z:Integer; Value: TColor);
{$IFNDEF CLX}
var FDC : HDC;
{$ENDIF}
begin
Calc3DPos(X,Y,Z);
if FPen.Width=1 then SetPixel(X,Y,Value)
else
begin { simulate a big dot pixel }
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,X,Y,nil);
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,X,Y);
{$ELSE}
Pixels[X,Y]:=Value;
{$ENDIF}
end;
end;
Function TTeeCanvas3D.GetSupports3DText:Boolean;
begin
result:=False;
end;
Function TTeeCanvas3D.GetSupportsFullRotation:Boolean;
begin
result:=False;
end;
Function TTeeCanvas3D.GetTextAlign:TCanvasTextAlign;
begin
{$IFNDEF CLX}
result:={$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.GetTextAlign(FCanvas.Handle);
{$ELSE}
result:=FTextAlign;
{$ENDIF}
end;
Function TTeeCanvas3D.GetUseBuffer:Boolean;
begin
result:=FBufferedDisplay;
end;
Procedure TTeeCanvas3D.SetUseBuffer(Value:Boolean);
begin
if FBufferedDisplay<>Value then
begin
FBufferedDisplay:=Value;
if (not FBufferedDisplay) and Assigned(FBitmap) then
begin
DeleteBitmap;
FDirty:=True;
end
else
if FBufferedDisplay and Assigned(FBitmap) then
SetCanvas(FBitmap.Canvas);
end;
end;
Function TTeeCanvas3D.GetMonochrome:Boolean;
begin
result:=FMonochrome;
end;
Procedure TTeeCanvas3D.SetMonochrome(Value:Boolean);
begin
if FMonochrome<>Value then
begin
FMonochrome:=Value;
FDirty:=True;
if Assigned(F3DOptions) then F3DOptions.Repaint;
end;
end;
Procedure TTeeCanvas3D.HorizLine3D(Left,Right,Y,Z:Integer);
var {$IFNDEF CLX}
FDC : HDC;
{$ENDIF}
tmpY : Integer;
begin
tmpY:=Y;
Calc3DPos(Left,tmpY,Z);
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,Left,tmpY,nil);
{$ELSE}
FCanvas.MoveTo(Left,tmpY);
{$ENDIF}
tmpY:=Y;
Calc3DPos(Right,tmpY,Z);
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,Right,tmpY);
{$ELSE}
FCanvas.LineTo(Right,tmpY);
{$ENDIF}
end;
Procedure TTeeCanvas3D.VertLine3D(X,Top,Bottom,Z:Integer);
var {$IFNDEF CLX}
FDC : HDC;
{$ENDIF}
tmpX : Integer;
begin
tmpX:=X;
Calc3DPos(tmpX,Top,Z);
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,tmpX,Top,nil);
{$ELSE}
FCanvas.MoveTo(tmpX,Top);
{$ENDIF}
tmpX:=X;
Calc3DPos(tmpX,Bottom,Z);
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,tmpX,Bottom);
{$ELSE}
FCanvas.LineTo(tmpX,Bottom);
{$ENDIF}
end;
Procedure TTeeCanvas3D.ZLine3D(X,Y,Z0,Z1:Integer);
var {$IFNDEF CLX}
FDC : HDC;
{$ENDIF}
tmpX : Integer;
tmpY : Integer;
begin
tmpX:=X;
tmpY:=Y;
Calc3DPos(tmpX,tmpY,Z0);
{$IFNDEF CLX}
FDC:=FCanvas.Handle;
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.MoveToEx(FDC,tmpX,tmpY,nil);
{$ELSE}
FCanvas.MoveTo(tmpX,tmpY);
{$ENDIF}
tmpX:=X;
tmpY:=Y;
Calc3DPos(tmpX,tmpY,Z1);
{$IFNDEF CLX}
{$IFDEF CLR}Borland.VCL.{$ENDIF}Windows.LineTo(FDC,tmpX,tmpY);
{$ELSE}
FCanvas.LineTo(tmpX,tmpY);
{$ENDIF}
end;
procedure TTeeCanvas3D.Triangle3D( Const Points:TTrianglePoints3D;
Const Colors:TTriangleColors3D);
var P : TTrianglePoints;
begin
P[0]:=Calc3DTPoint3D(Points[0]);
P[1]:=Calc3DTPoint3D(Points[1]);
P[2]:=Calc3DTPoint3D(Points[2]);
if Brush.Style<>bsClear then Brush.Color:=Colors[0];
Polygon(P);
end;
procedure TTeeCanvas3D.TriangleWithZ(Const P1,P2,P3:TPoint; Z:Integer);
var Points : TTrianglePoints;
begin
Calc3DPoint(Points[0],P1.X,P1.Y,Z);
Calc3DPoint(Points[1],P2.X,P2.Y,Z);
Calc3DPoint(Points[2],P3.X,P3.Y,Z);
Polygon(Points);
end;
Procedure TTeeCanvas3D.Arrow( Filled:Boolean;
Const FromPoint,ToPoint:TPoint;
ArrowWidth,ArrowHeight,Z:Integer);
Var x : Double;
y : Double;
SinA : Double;
CosA : Double;
Function CalcArrowPoint:TPoint;
Begin
result.X:=Round( x*CosA + y*SinA);
result.Y:=Round(-x*SinA + y*CosA);
Calc3DTPoint(result,Z);
end;
Var tmpHoriz : Integer;
tmpVert : Integer;
dx : Integer;
dy : Integer;
tmpHoriz4 : Double;
xb : Double;
yb : Double;
l : Double;
{ These are the Arrows points coordinates }
To3D,pc,pd,pe,pf,pg,ph:TPoint;
(* pc
|\
ph pf| \
|------------ \ ToPoint
From |------------ /
pg pe| /
|/
pd
*)
begin
dx:=ToPoint.x-FromPoint.x;
dy:=FromPoint.y-ToPoint.y;
l:=TeeDistance(dx,dy);
if l>0 then { if at least one pixel... }
Begin
tmpHoriz:=ArrowWidth;
tmpVert :=Math.Min(Round(l),ArrowHeight);
SinA:= dy / l;
CosA:= dx / l;
xb:= ToPoint.x*CosA - ToPoint.y*SinA;
yb:= ToPoint.x*SinA + ToPoint.y*CosA;
x := xb - tmpVert;
y := yb - tmpHoriz*0.5;
pc:=CalcArrowPoint;
y := yb + tmpHoriz*0.5;
pd:=CalcArrowPoint;
if Filled then
Begin
tmpHoriz4:=tmpHoriz*0.25;
y := yb - tmpHoriz4;
pe:=CalcArrowPoint;
y := yb + tmpHoriz4;
pf:=CalcArrowPoint;
x := FromPoint.x*cosa - FromPoint.y*sina;
y := yb - tmpHoriz4;
pg:=CalcArrowPoint;
y := yb + tmpHoriz4;
ph:=CalcArrowPoint;
To3D:=ToPoint;
Calc3DTPoint(To3D,Z);
Polygon([ ph,pg,pe,pc,To3D,pd,pf ]);
end
else
begin
MoveTo3D(FromPoint.x,FromPoint.y,z);
LineTo3D(ToPoint.x,ToPoint.y,z);
LineTo3D(pd.x,pd.y,z);
MoveTo3D(ToPoint.x,ToPoint.y,z);
LineTo3D(pc.x,pc.y,z);
end;
end;
end;
{ TTeeShadow }
Constructor TTeeShadow.Create(AOnChange:TNotifyEvent);
begin
inherited Create;
FSmooth:=True;
IOnChange:=AOnChange;
FColor:=clSilver;
DefaultColor:=FColor;
end;
Procedure TTeeShadow.Assign(Source:TPersistent);
begin
if Source is TTeeShadow then
With TTeeShadow(Source) do
begin
Self.FColor :=Color;
Self.FHorizSize :=HorizSize;
Self.FSmooth :=Smooth;
Self.FTransparency :=Transparency;
Self.FVertSize :=VertSize;
end
else inherited;
end;
procedure TTeeShadow.Changed;
begin
if Assigned(IOnChange) then IOnChange(Self);
end;
Procedure TTeeShadow.SetIntegerProperty(Var Variable:Integer; Const Value:Integer);
begin
if Variable<>Value then
begin
Variable:=Value;
Changed;
end;
end;
Procedure TTeeShadow.SetColor(Value:TColor);
begin
if FColor<>Value then
begin
FColor:=Value;
Changed;
end;
end;
Procedure TTeeShadow.SetHorizSize(Value:Integer);
begin
SetIntegerProperty(FHorizSize,Value);
end;
Procedure TTeeShadow.SetVertSize(Value:Integer);
begin
SetIntegerProperty(FVertSize,Value);
end;
function TTeeShadow.GetSize: Integer;
begin
result:=Math.Max(HorizSize,VertSize)
end;
procedure TTeeShadow.SetSize(const Value: Integer);
begin
HorizSize:=Value;
VertSize:=Value;
end;
procedure TTeeShadow.SetSmooth(const Value: Boolean);
begin
if FSmooth<>Value then
begin
FSmooth:=Value;
Changed;
end;
end;
procedure TTeeShadow.SetTransparency(Value: TTeeTransparency);
begin
if FTransparency<>Value then
begin
FTransparency:=Value;
Changed;
end;
end;
Function TTeeShadow.PrepareCanvas(ACanvas:TCanvas3D; const R:TRect;
Z:Integer=0):Boolean;
begin
result:=(Color<>clNone) and ((HorizSize<>0) or (VertSize<>0));
if result then
begin
With ACanvas do
begin
Brush.Color:=Self.Color;
Brush.Style:=bsSolid;
Pen.Style:=psClear;
end;
if Transparency>0 then
IBlend:=ACanvas.BeginBlending(ACanvas.RectFromRectZ(TeeRect(R.Left+HorizSize,
R.Top+VertSize,R.Right+HorizSize,R.Bottom+VertSize),Z),
Transparency);
end;
end;
procedure TTeeShadow.FinishBlending(ACanvas:TTeeCanvas);
begin
if Transparency>0 then
ACanvas.EndBlending(IBlend);
end;
procedure TTeeShadow.Draw(ACanvas: TCanvas3D; const Rect: TRect);
begin
Draw(ACanvas,Rect,0);
end;
procedure TTeeShadow.Draw(ACanvas:TCanvas3D; Const Rect:TRect; Z:Integer);
var tmpDelta : Integer;
tmpRGB : TRGBTriple;
Procedure CalcDelta(ASize:Integer);
begin
with tmpRGB do
tmpDelta:=Round((255-((rgbtBlue+rgbtGreen+rgbtRed)/3.0))/ASize);
end;
var t : Integer;
Is3D : Boolean;
begin
Is3D:=ACanvas.IDisabledRotation=0;
if PrepareCanvas(ACanvas,Rect,Z) then
begin
With Rect do
begin
if Smooth and (Size>1) then
begin
tmpRGB:=RGBValue(ColorToRGB(Color));
ACanvas.Pen.Style:=psSolid;
if VertSize<>0 then
begin
ACanvas.Pen.Color:=Color;
CalcDelta(VertSize);
for t:=1 to VertSize do
begin
if Is3D then
ACanvas.HorizLine3D(Left+HorizSize,Right+HorizSize-VertSize+t-1,Bottom+t-1,Z)
else
ACanvas.DoHorizLine(Left+HorizSize,Right+HorizSize-VertSize+t-1,Bottom+t-1);
ACanvas.Pen.Color:=ApplyBright(ACanvas.Pen.Color,tmpDelta);
end;
end;
if HorizSize<>0 then
begin
ACanvas.Pen.Color:=Color;
CalcDelta(HorizSize);
for t:=1 to HorizSize do
begin
if Is3D then
begin
ACanvas.VertLine3D(Right+t-1,Top+VertSize,Bottom+VertSize-HorizSize+t-1,Z);
ACanvas.Pixels3D[Right+t-2,Bottom+VertSize-HorizSize+t-2,Z]:=ACanvas.Pen.Color;
end
else
begin
ACanvas.DoVertLine(Right+t-1,Top+VertSize,Bottom+VertSize-HorizSize+t-1);
ACanvas.Pixels[Right+t-2,Bottom+VertSize-HorizSize+t-2]:=ACanvas.Pen.Color;
end;
ACanvas.Pen.Color:=ApplyBright(ACanvas.Pen.Color,tmpDelta);
end;
end;
end
else
begin
if Is3D then
begin
ACanvas.Rectangle(Left+HorizSize,Bottom,Right+HorizSize,Bottom+VertSize,Z);
ACanvas.Rectangle(Right,Top+VertSize,Right+HorizSize,Bottom+VertSize,Z);
end
else
begin
ACanvas.Rectangle(Left+HorizSize,Bottom,Right+HorizSize,Bottom+VertSize);
ACanvas.Rectangle(Right,Top+VertSize,Right+HorizSize,Bottom+VertSize);
end;
end;
end;
FinishBlending(ACanvas);
end;
end;
procedure TTeeShadow.DrawEllipse(ACanvas: TCanvas3D; const Rect: TRect;
Z:Integer=0);
var tmpR : TRect;
begin
if PrepareCanvas(ACanvas,Rect,Z) then
begin
if Smooth then // 7.0
begin
with Rect do
tmpR:=ACanvas.CalcRect3D(TeeRect(Left+HorizSize,Top+VertSize,
Right+HorizSize,Bottom+VertSize),Z);
ACanvas.ClipEllipse(tmpR);
with TTeeGradient.Create(nil) do
try
EndColor:=ApplyBright(Self.Color,32);
StartColor:=ApplyDark(Self.Color,128);
DrawRadial(ACanvas,tmpR);
finally
Free;
end;
ACanvas.UnClipRectangle;
end
else
With Rect do
ACanvas.EllipseWithZ(Left+HorizSize,Top+VertSize,
Right+HorizSize,Bottom+VertSize,Z);
FinishBlending(ACanvas);
end;
end;
function TTeeShadow.IsColorStored: Boolean;
begin
result:=FColor<>DefaultColor;
end;
function TTeeShadow.IsHorizStored: Boolean;
begin
result:=FHorizSize<>DefaultSize;
end;
function TTeeShadow.IsVertStored: Boolean;
begin
result:=FVertSize<>DefaultSize;
end;
{ TCustomTeeGradient }
Constructor TCustomTeeGradient.Create(ChangedEvent:TNotifyEvent);
Begin
inherited Create;
IChanged :=ChangedEvent;
FDirection :=gdTopBottom;
FStartColor :=clWhite;
FEndColor :=clYellow;
FMidColor :=clNone;
FBalance :=50;
End;
Procedure TCustomTeeGradient.UseMiddleColor;
begin
if not IHasMiddle then
begin
IHasMiddle:=True;
DoChanged;
end;
end;
Function TCustomTeeGradient.GetMidColor:TColor;
begin
if IHasMiddle then result:=FMidColor
else result:=clNone;
end;
Procedure TCustomTeeGradient.DoChanged;
begin
if Assigned(IChanged) then IChanged(Self);
end;
Procedure TCustomTeeGradient.SetVisible(Value:Boolean);
Begin
if FVisible<>Value then
begin
FVisible:=Value;
DoChanged;
end;
End;
Procedure TCustomTeeGradient.SetBalance(Value:Integer);
begin
SetIntegerProperty(FBalance,Value);
end;
Procedure TCustomTeeGradient.SetDirection(Value:TGradientDirection);
Begin
if FDirection<>Value then
Begin
FDirection:=Value;
DoChanged;
end;
End;
Procedure TCustomTeeGradient.SetIntegerProperty(Var Variable:Integer; Value:Integer);
begin
if Variable<>Value then
begin
Variable:=Value;
DoChanged;
end;
end;
Procedure TCustomTeeGradient.SetColorProperty(var Variable:TColor; const Value:TColor);
begin
if Variable<>Value then
begin
Variable:=Value;
DoChanged;
end;
end;
Procedure TCustomTeeGradient.SetStartColor(Value:TColor);
Begin
SetColorProperty(FStartColor,Value);
End;
Procedure TCustomTeeGradient.SetEndColor(Value:TColor);
Begin
SetColorProperty(FEndColor,Value);
End;
Procedure TCustomTeeGradient.SetMidColor(Value:TColor);
Begin
if IHasMiddle then { 5.02 }
begin
if Value=clNone then
begin
IHasMiddle:=False;
DoChanged;
end
else
SetColorProperty(FMidColor,Value);
end
else
if Value<>clNone then
begin
IHasMiddle:=True;
FMidColor:=Value;
DoChanged;
end;
End;
Procedure TCustomTeeGradient.Assign(Source:TPersistent);
Begin
if Source is TCustomTeeGradient then
With TCustomTeeGradient(Source) do
Begin
Self.FBalance :=FBalance;
Self.FDirection :=FDirection;
Self.FEndColor :=FEndColor;
Self.FMidColor :=FMidColor;
Self.FRadialX :=FRadialX;
Self.FRadialY :=FRadialY;
Self.FStartColor:=FStartColor;
Self.FVisible :=FVisible;
Self.IHasMiddle :=IHasMiddle;
end
else inherited;
end;
Procedure TCustomTeeGradient.DrawRadial(Canvas:TTeeCanvas; Rect:TRect);
var tmpRect : TRect;
Procedure DoRadialGradient;
var Step,
SizeX,
SizeY,
t,
e0,e1,e2 : Integer;
xc,yc,
InvStep,
tmpD,
tmpX,
tmpY,
sx,
sy : Double;
dr,
dg,
db : Double;
OldBrushColor : TColor;
OldPenStyle : TPenStyle;
{$IFNDEF CLX}
{$IFNDEF CLR}
IsFastBrush : Boolean;
tmpDc : TTeeCanvasHandle;
{$ENDIF}
{$ENDIF}
begin
RectSize(tmpRect,SizeX,SizeY);
Step:=Math.Min(255,Math.Max(SizeX,SizeY));
InvStep:=1/Step;
sx:=0.5*SizeX*InvStep;
sy:=0.5*SizeY*InvStep;
e0:=GetRValue(StartColor);
e1:=GetGValue(StartColor);
e2:=GetBValue(StartColor);
if Balance=50 then
begin
dr:=(GetRValue(EndColor)-e0)*InvStep;
dg:=(GetGValue(EndColor)-e1)*InvStep;
db:=(GetBValue(EndColor)-e2)*InvStep;
end
else
begin
dr:=(GetRValue(EndColor)-e0);
dg:=(GetGValue(EndColor)-e1);
db:=(GetBValue(EndColor)-e2);
end;
OldPenStyle:=Canvas.Pen.Style;
Canvas.Pen.Style:=psClear;
OldBrushColor:=Canvas.Brush.Color;
try
Canvas.Brush.Color:=EndColor;
Canvas.FillRect(tmpRect);
if ((SizeX mod 2)=1) or ((SizeY mod 2)=1) then Dec(Step);
xc:=1+RadialX+((tmpRect.Left+tmpRect.Right)*0.5);
yc:=1+RadialY+((tmpRect.Top+tmpRect.Bottom)*0.5);
{$IFNDEF CLR}
{$IFNDEF CLX}
IsFastBrush:=Assigned(@TeeSetDCBrushColor);
if IsFastBrush then
begin
tmpDC:=Canvas.Handle;
SelectObject(tmpDC,GetStockObject(DC_BRUSH));
end
else
tmpDC:=0;
{$ENDIF}
{$ENDIF}
for t:=Step downto 0 do
begin
if Balance=50 then
{$IFNDEF CLR}
{$IFNDEF CLX}
if IsFastBrush then
TeeSetDCBrushColor(tmpDC,RGB(e0+Round(dr*t),e1+Round(dg*t),e2+Round(db*t)))
else
{$ENDIF}
{$ENDIF}
Canvas.Brush.Color:=RGB(e0+Round(dr*t),e1+Round(dg*t),e2+Round(db*t))
else
begin
tmpD:=TeeSigmoid(t,Balance,Step);
{$IFNDEF CLR}
{$IFNDEF CLX}
if IsFastBrush then
TeeSetDCBrushColor(tmpDC,(( e0 + Round(tmpD*dr) ) or
(( e1 + Round(tmpD*dg) ) shl 8) or
(( e2 + Round(tmpD*db) ) shl 16)))
else
{$ENDIF}
{$ENDIF}
Canvas.Brush.Color:=(( e0 + Round(tmpD*dr) ) or
(( e1 + Round(tmpD*dg) ) shl 8) or
(( e2 + Round(tmpD*db) ) shl 16));
end;
tmpX:=t*sx;
tmpY:=t*sy;
Canvas.Ellipse(Round(xc-tmpX),Round(yc-tmpY),Round(xc+tmpX),Round(yc+tmpY));
end;
finally
Canvas.Brush.Color:=OldBrushColor;
Canvas.Pen.Style:=OldPenStyle;
end;
end;
begin
tmpRect:=OrientRectangle(Rect);
{$IFDEF CLX}
Canvas.FCanvas.Start;
{$ELSE}
Canvas.ClipRectangle(tmpRect);
{$ENDIF}
DoRadialGradient;
{$IFDEF CLX}
Canvas.FCanvas.Stop;
{$ELSE}
Canvas.UnClipRectangle;
{$ENDIF}
end;
procedure TCustomTeeGradient.Draw(Canvas:TCanvas3D; var P:TPointArray; Z:Integer; Is3D:Boolean); // 7.0
var P2 : TPointArray;
t : Integer;
begin
if Is3D then
begin
SetLength(P2,Length(P));
try
for t:=0 to Length(P)-1 do
P2[t]:=Canvas.Calculate3DPosition(P[t],Z);
Canvas.ClipPolygon(P2,Length(P));
finally
P2:=nil;
end;
Draw(Canvas,Canvas.CalcRect3D(PolygonBounds(P),Z));
end
else
begin
Canvas.ClipPolygon(P,Length(P));
Draw(Canvas,PolygonBounds(P));
end;
Canvas.UnClipRectangle;
end;
Procedure TCustomTeeGradient.Draw( Canvas:TTeeCanvas; Const Rect:TRect;
RoundRectSize:Integer=0);
var R : TRect;
Procedure DoVert(C0,C1,C2,C3:TColor);
begin
R.Bottom:=(Rect.Bottom+Rect.Top) div 2;
Canvas.GradientFill(R,C0,C1,Direction);
R.Top:=R.Bottom;
R.Bottom:=Rect.Bottom;
Canvas.GradientFill(R,C2,C3,Direction);
end;
Procedure DoHoriz(C0,C1,C2,C3:TColor);
begin
R.Right:=(Rect.Left+Rect.Right) div 2;
Canvas.GradientFill(R,C0,C1,Direction);
R.Left:=R.Right;
R.Right:=Rect.Right;
Canvas.GradientFill(R,C2,C3,Direction);
end;
Function TryGrayColor(Const AColor:TColor):TColor;
var tmpRGB : TRGBTriple;
tmp : Byte;
begin
if Canvas.Monochrome then
begin
tmpRGB:=RGBValue(ColorToRGB(AColor));
with tmpRGB do
tmp:=(rgbtBlue+rgbtGreen+rgbtRed) div 3;
result:=RGB(tmp,tmp,tmp);
end
else result:=AColor;
end;
var tmpMid : TColor;
tmpStart : TColor;
tmpEnd : TColor;
begin
tmpMid:=TryGrayColor(MidColor);
tmpStart:=TryGrayColor(StartColor);
tmpEnd:=TryGrayColor(EndColor);
if RoundRectSize>0 then
Canvas.ClipRectangle(Rect,RoundRectSize);
if Direction=gdRadial then DrawRadial(Canvas,Rect)
else
if IHasMiddle and (Direction<>gdDiagonalUp) and (Direction<>gdDiagonalDown) then
begin
R:=Rect;
Case Direction of
gdTopBottom: DoVert(tmpMid,tmpEnd,tmpStart,tmpMid);
gdBottomTop: DoVert(tmpStart,tmpMid,tmpMid,tmpEnd);
gdLeftRight: DoHoriz(tmpMid,tmpEnd,tmpStart,tmpMid);
gdRightLeft: DoHoriz(tmpStart,tmpMid,tmpMid,tmpEnd);
else
Canvas.GradientFill(Rect,tmpStart,tmpEnd,Direction)
end;
end
else
Canvas.GradientFill(Rect,tmpStart,tmpEnd,Direction,Balance);
if RoundRectSize>0 then Canvas.UnClipRectangle;
end;
procedure TCustomTeeGradient.SetRadialX(const Value: Integer);
begin
SetIntegerProperty(FRadialX,Value);
end;
procedure TCustomTeeGradient.SetRadialY(const Value: Integer);
begin
SetIntegerProperty(FRadialY,Value);
end;
procedure TCustomTeeGradient.Draw(Canvas: TTeeCanvas; var P: TFourPoints);
begin
Canvas.ClipPolygon(P,4);
Draw(Canvas,RectFromPolygon(P,4));
Canvas.UnClipRectangle;
end;
Procedure TCustomTeeGradient.Draw(Canvas:TCanvas3D; var P:TFourPoints; Z:Integer);
var P2 : TFourPoints;
begin
P2[0]:=Canvas.Calculate3DPosition(P[0],Z);
P2[1]:=Canvas.Calculate3DPosition(P[1],Z);
P2[2]:=Canvas.Calculate3DPosition(P[2],Z);
P2[3]:=Canvas.Calculate3DPosition(P[3],Z);
Draw(Canvas,P2);
end;
{ TTeeFont }
Constructor TTeeFont.Create(ChangedEvent:TNotifyEvent);
begin
inherited Create;
Color:=clBlack;
IDefColor:=clBlack;
{$IFNDEF CLX}
if CharSet<>DEFAULT_CHARSET then
CharSet:=DEFAULT_CHARSET;
{$ENDIF}
Name:=GetDefaultFontName;
if Size<>GetDefaultFontSize then // 6.01
Size:=GetDefaultFontSize;
OnChange:=ChangedEvent; { at the create end... 5.02 }
end;
Destructor TTeeFont.Destroy;
begin
FOutLine.Free;
FShadow.Free;
FGradient.Free;
{ 5.01 removed, ICanvas might be corrupt in some circumstances }
{ if Assigned(ICanvas) and (ICanvas.IFont=Self) then ICanvas.IFont:=nil; }
inherited;
end;
Procedure TTeeFont.Assign(Source:TPersistent);
begin
if Source is TTeeFont then
With TTeeFont(Source) do
begin
Self.Gradient :=FGradient;
Self.FInterCharSize:=FInterCharSize;
Self.OutLine :=FOutLine;
Self.Shadow :=FShadow;
end;
inherited;
end;
Procedure TTeeFont.SetInterCharSize(Value:Integer);
begin
if Value<>FInterCharSize then
begin
FInterCharSize:=Value;
if Assigned(OnChange) then OnChange(Self);
end;
end;
function TTeeFont.GetOutLine: TChartHiddenPen;
begin
if not Assigned(FOutLine) then
FOutLine:=TChartHiddenPen.Create(OnChange);
result:=FOutLine;
end;
Procedure TTeeFont.SetOutLine(Value:TChartHiddenPen);
begin
if Assigned(Value) then OutLine.Assign(Value)
else FreeAndNil(FOutLine);
end;
Function TTeeFont.GetShadow:TTeeShadow;
begin
if not Assigned(FShadow) then
FShadow:=TTeeShadow.Create(OnChange);
result:=FShadow;
end;
Procedure TTeeFont.SetShadow(Value:TTeeShadow);
begin
if Assigned(Value) then Shadow.Assign(Value)
else FreeAndNil(FShadow);
end;
function TTeeFont.IsHeightStored: Boolean;
begin
result:=Size<>GetDefaultFontSize;
end;
function TTeeFont.IsNameStored: Boolean;
begin
result:=Name<>GetDefaultFontName;
end;
function TTeeFont.IsStyleStored: Boolean;
begin
result:=Style<>IDefStyle;
end;
Function TTeeFont.IsColorStored:Boolean;
begin
result:=Color<>IDefColor;
end;
function TTeeFont.GetGradient: TTeeFontGradient;
begin
if not Assigned(FGradient) then
FGradient:=TTeeFontGradient.Create(OnChange);
result:=FGradient;
end;
procedure TTeeFont.SetGradient(const Value: TTeeFontGradient);
begin
if Assigned(Value) then Gradient.Assign(Value)
else FreeAndNil(FGradient);
end;
{ Util functions }
Procedure SwapDouble(Var a,b:Double);
var tmp : Double;
begin
tmp:=a; a:=b; b:=tmp;
end;
Procedure SwapInteger(Var a,b:Integer);
var tmp : Integer;
Begin
tmp:=a; a:=b; b:=tmp;
end;
{$IFDEF TEEVCL}
{ TTeeButton }
Procedure TTeebutton.DrawSymbol(ACanvas:TTeeCanvas); // virtual; abstract;
begin
end;
{$IFNDEF CLX}
procedure TTeeButton.WMPaint(var Message: TWMPaint);
begin
ControlState:=ControlState+[csCustomPaint];
inherited;
ControlState:=ControlState-[csCustomPaint];
end;
procedure TTeeButton.CMTextChanged(var Message: TMessage); // 7.0
begin
inherited;
Invalidate;
end;
procedure TTeeButton.PaintWindow(DC: HDC);
var tmp : TTeeCanvas;
begin
inherited;
if Assigned(Instance) then
begin
tmp:=TTeeCanvas3D.Create;
with tmp do
try
ReferenceCanvas:=TCanvas.Create;
try
ReferenceCanvas.Handle:=DC;
DrawSymbol(tmp);
finally
ReferenceCanvas.Free;
end;
finally
Free;
end;
end;
end;
procedure TTeeButton.CMEnabledChanged(var Message: TMessage);
begin
inherited;
Repaint;
end;
{$ELSE}
procedure TTeeButton.Painting(Sender: QObjectH; EventRegion: QRegionH);
var tmp : TTeeCanvas3D;
begin
inherited;
if Assigned(Instance) then
begin
tmp:=TTeeCanvas3D.Create;
with tmp do
try
ReferenceCanvas:=TQtCanvas.Create;
try
ReferenceCanvas.Handle:=Handle;
{$IFNDEF LINUX} // Kylix bug
DrawSymbol(tmp);
{$ENDIF}
finally
ReferenceCanvas.Free;
end;
finally
Free;
end;
end;
end;
{$ENDIF}
procedure TTeeButton.LinkProperty(AInstance: TObject;
const PropName: String);
begin
Instance:=AInstance;
if Assigned(Instance) then
begin
if PropName='' then
Info:=nil
else
Info:=GetPropInfo(Instance{$IFNDEF D5}.ClassInfo{$ENDIF},PropName);
Invalidate; // 5.02
end;
end;
{$ENDIF}
{$IFNDEF D5}
procedure FreeAndNil(var Obj);
var P : TObject;
begin
P:=TObject(Obj);
TObject(Obj):=nil;
P.Free;
end;
{$ENDIF}
{$IFNDEF TEEVCL}
procedure FreeAndNil(var Obj);
var P : TObject;
begin
P:=TObject(Obj);
TObject(Obj):=nil;
P.Free;
end;
type
Exception=class(TObject)
private
FMessage: string;
public
Constructor Create(S:String);
end;
EConvertError=class(Exception);
Constructor Exception.Create(S:String);
begin
FMessage:=S;
end;
function StrToInt(const S: string): Integer;
var E: Integer;
begin
Val(S, Result, E);
if E <> 0 then
raise EConvertError.Create('Invalid integer: '+S);
end;
function ColorToRGB(Color: TColor): Longint;
begin
if Color < 0 then
Result := GetSysColor(Color and $000000FF) else
Result := Color;
end;
{$IFNDEF LINUX}
function SafeLoadLibrary(const Filename: string; ErrorMode: UINT = SEM_NOOPENFILEERRORBOX): HMODULE;
var
OldMode: UINT;
FPUControlWord: Word;
begin
OldMode := SetErrorMode(ErrorMode);
try
asm
FNSTCW FPUControlWord
end;
try
Result := LoadLibrary(PChar(Filename));
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
finally
SetErrorMode(OldMode);
end;
end;
{$ELSE}
function SafeLoadLibrary(const FileName: string; Dummy: LongWord): HMODULE;
var
FPUControlWord: Word;
begin
asm
FNSTCW FPUControlWord
end;
try
Result := LoadLibrary(PChar(Filename));
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
var
{ Win32 platform identifier. This will be one of the following values:
VER_PLATFORM_WIN32s
VER_PLATFORM_WIN32_WINDOWS
VER_PLATFORM_WIN32_NT
See WINDOWS.PAS for the numerical values. }
Win32Platform: Integer = 0;
{ Win32 OS version information -
see TOSVersionInfo.dwMajorVersion/dwMinorVersion/dwBuildNumber }
Win32MajorVersion: Integer = 0;
Win32MinorVersion: Integer = 0;
Win32BuildNumber: Integer = 0;
procedure InitPlatformId;
var
OSVersionInfo: TOSVersionInfo;
begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then
with OSVersionInfo do
begin
Win32Platform := dwPlatformId;
Win32MajorVersion := dwMajorVersion;
Win32MinorVersion := dwMinorVersion;
if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then
Win32BuildNumber := dwBuildNumber and $FFFF
else
Win32BuildNumber := dwBuildNumber;
//Win32CSDVersion := szCSDVersion;
end;
end;
{$ENDIF}
{$ENDIF}
Procedure TeeDefaultFont;
Begin
GetDefaultFontSize:=StrToInt(TeeMsg_DefaultFontSize);
{$IFNDEF CLR}
{$IFNDEF CLX}
{$IFDEF TEEVCL}
if (GetDefaultFontSize=8) and (SysLocale.PriLangID=LANG_JAPANESE) then
GetDefaultFontSize:=-MulDiv(DefFontData.Height,72,Screen.PixelsPerInch);
{$ENDIF}
{$ENDIF}
{$ENDIF}
GetDefaultFontName:=TeeMsg_DefaultFontName;
{$IFNDEF CLR}
{$IFNDEF CLX}
{$IFDEF TEEVCL}
if (GetDefaultFontName='Arial') and (SysLocale.PriLangID=LANG_JAPANESE) then { <-- do not translate }
GetDefaultFontName:=DefFontData.Name;
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
{$IFNDEF LINUX}
type
AlphaBlendType=function(DC: HDC; p2, p3, p4, p5: Integer;
DC6: HDC; p7, p8, p9, p10: Integer;
p11: TBlendFunction): BOOL; stdcall;
{$ENDIF}
var
CanUseWinAlphaBlend : Boolean=False;
{$IFNDEF LINUX}
AlphaBlendProc : AlphaBlendType=nil;
{$ENDIF}
{$IFNDEF CLR}
{$IFDEF TEEVCL}
type
TRGBTripleArray=packed array[0..0] of TRGBTriple;
{$ENDIF}
procedure TeeBlendBitmaps(Const Percent: Double; ABitmap,BBitmap:TBitmap; BOrigin:TPoint);
Const BytesPerPixel={$IFDEF CLX}4{$ELSE}3{$ENDIF};
{$IFNDEF D5}
type PColor = ^TColor;
{$ENDIF}
var tmpW : Integer;
tmpH : Integer;
tmpX : Integer;
tmpY : Integer;
{$IFDEF CLX}
tmpScanA : ^TRGBTripleArray;
tmpScanB : ^TRGBTripleArray;
{$ELSE}
BlendFunc: BLENDFUNCTION;
tmpScanA : PByteArray;
tmpScanB : PByteArray;
Line0A : PByteArray;
Line0B : PByteArray;
DifA : Integer;
DifB : Integer;
{$ENDIF}
tmpXB3 : Integer;
p : PChar;
pc : PChar;
Percent1 : Integer;
tmpBBitmap : TBitmap;
begin
ABitmap.PixelFormat:=TeePixelFormat;
BBitmap.PixelFormat:=TeePixelFormat;
if BOrigin.Y<0 then BOrigin.Y:=0;
if BOrigin.X<0 then BOrigin.X:=0;
tmpW:=Math.Min(ABitmap.Width,BBitmap.Width-BOrigin.X);
tmpH:=Math.Min(ABitmap.Height,BBitmap.Height-BOrigin.Y);
if (tmpW>0) and (tmpH>0) then // 7.0 fix
begin
{$IFNDEF CLX}
if CanUseWinAlphaBlend then
begin
// Alphablend fails in Win98
BlendFunc.BlendOp:=AC_SRC_OVER;
BlendFunc.BlendFlags:=0;
BlendFunc.SourceConstantAlpha:=255-Round(Percent*2.55);
BlendFunc.AlphaFormat:=0;
AlphaBlendProc(BBitmap.Canvas.Handle, BOrigin.X, BOrigin.Y, tmpW, tmpH,
ABitmap.Canvas.Handle,0,0,tmpW,tmpH, BlendFunc);
Exit;
end;
{$ENDIF}
{$IFNDEF LINUX}
tmpBBitmap:=BBitmap;
{$ELSE}
tmpBBitmap:=TBitmap.Create;
tmpBBitmap.Width:=BBitmap.Width;
tmpBBitmap.Height:=BBitmap.Height;
QPixmap_setOptimization( BBitmap.Handle, QPixmapOptimization_BestOptim );
QPixmap_setOptimization( tmpBBitmap.Handle, QPixmapOptimization_BestOptim );
BitBlt( tmpBBitmap.Handle, 0, 0, BBitmap.Handle, 0, 0,
BBitmap.Width, BBitmap.Height, RasterOp_CopyROP, true );
{$ENDIF}
Percent1:=100-Round(Percent);
{$IFNDEF CLX}
Line0A:=ABitmap.ScanLine[0];
Line0B:=tmpBBitmap.ScanLine[BOrigin.Y];
if tmpH>1 then // 7.0 fix
begin
DifA:=Integer(ABitmap.ScanLine[1])-Integer(Line0A);
DifB:=Integer(tmpBBitmap.ScanLine[BOrigin.Y+1])-Integer(Line0B);
end
else
begin
DifA:=0;
DifB:=0;
end;
{$ENDIF}
for tmpY:=0 to tmpH-1 do
begin
{$IFNDEF CLX}
// faster version
tmpScanA:=PByteArray(Integer(Line0A)+DifA*tmpY);
tmpScanB:=PByteArray(Integer(Line0B)+DifB*tmpY);
{$ELSE}
// slower (safer?) version
tmpScanA:=ABitmap.ScanLine[tmpY];
tmpScanB:=tmpBBitmap.ScanLine[tmpY+BOrigin.Y];
{$ENDIF}
for tmpX:=0 to tmpW-1 do
begin
tmpXB3:=(tmpX+BOrigin.X){$IFNDEF CLX}*BytesPerPixel{$ENDIF};
pc:=PChar(@tmpScanB[tmpXB3]);
if PColor(pc)^=$FFFFFF then // Already white color
{$IFDEF CLX}
tmpScanB[tmpXB3].rgbtBlue:=$FF-1;
{$ELSE}
tmpScanB[tmpXB3+2]:=$FF-1;
{$ENDIF}
{$IFDEF CLX}
p:=@tmpScanA[tmpX];
{$ELSE}
p:=PChar(@tmpScanA[tmpX*BytesPerPixel]);
{$ENDIF}
PByte(pc)^:=Byte(pc^)+((Percent1*(Byte(p^)-Byte(pc^))) div 100);
Inc(pc);
PByte(pc)^:=Byte(pc^)+((Percent1*(Byte((p+1)^)-Byte(pc^))) div 100);
Inc(pc);
PByte(pc)^:=Byte(pc^)+((Percent1*(Byte((p+2)^)-Byte(pc^))) div 100);
end;
end;
{$IFDEF LINUX}
BitBlt( BBitmap.Handle, 0, 0,
tmpBBitmap.Handle, 0, 0, BBitmap.Width, BBitmap.Height, RasterOp_CopyROP, true );
FreeAndNil(tmpBBitmap);
{$ENDIF}
end;
end;
{$ENDIF}
{ TTeeBlend }
Constructor TTeeBlend.Create(ACanvas: TTeeCanvas; const R: TRect);
begin
inherited Create;
FCanvas:=ACanvas;
SetRectangle(R);
end;
Destructor TTeeBlend.Destroy;
begin
FBitmap.Free;
inherited;
end;
Procedure TTeeBlend.SetRectangle(Const R:TRect);
var tmp : TCanvas;
tmpW : Integer;
tmpH : Integer;
begin
FRect:=OrientRectangle(R);
with FRect do
begin
if Left<0 then Left:=0;
if Top<0 then Top:=0;
if Right<0 then Right:=0;
if Bottom<0 then Bottom:=0;
if Right-Left<1 then Right:=Left+1; // 7.0 fix
if Bottom-Top<1 then Bottom:=Top+1;
if Right>FCanvas.Bounds.Right then
Right:=FCanvas.Bounds.Right;
if Bottom>FCanvas.Bounds.Bottom then
Bottom:=FCanvas.Bounds.Bottom;
tmpW:=(Right-Left);
tmpH:=(Bottom-Top);
end;
IValidSize:=(tmpW>0) and (tmpH>0);
if IValidSize then
begin
FreeAndNil(FBitmap); // speed optimization
if not Assigned(FBitmap) then
begin
FBitmap:=TBitmap.Create;
With FBitmap do
begin
{$IFNDEF CLX}
IgnorePalette:=True;
{$ENDIF}
PixelFormat:=TeePixelFormat;
end;
end;
FBitmap.Width:=tmpW;
FBitmap.Height:=tmpH;
if (FCanvas is TTeeCanvas3D) and Assigned((FCanvas as TTeeCanvas3D).Bitmap) then
tmp:=(FCanvas as TTeeCanvas3D).Bitmap.Canvas
else
tmp:=FCanvas.ReferenceCanvas;
FBitmap.Canvas.CopyRect( TeeRect(0,0,tmpW,tmpH), tmp, FRect );
end;
end;
procedure TTeeBlend.DoBlend(Transparency: TTeeTransparency);
{$IFDEF CLR}
begin
end;
{$ELSE}
var tmp : TBitmap;
tmpNew : Boolean;
tmpPoint : TPoint;
{$IFNDEF CLX}
tmpAlign : TCanvasTextAlign;
{$ENDIF}
begin
if not FCanvas.Metafiling then // 7.0
if IValidSize then
begin
tmp:=TTeeCanvas3D(FCanvas).Bitmap;
tmpNew:=not Assigned(tmp);
if tmpNew then
begin
tmp:=TBitmap.Create;
{$IFNDEF CLX}
tmp.IgnorePalette:=True;
{$ENDIF}
tmp.Width:=FRect.Right-FRect.Left;
tmp.Height:=FRect.Bottom-FRect.Top;
{ 5.03 fixed. (Blend inverted rect params) }
tmp.Canvas.CopyRect(TeeRect(0,0,tmp.Width,tmp.Height),FCanvas.ReferenceCanvas,FRect);
tmpPoint:=TeePoint(0,0);
end
else tmpPoint:=FRect.TopLeft;
{$IFDEF CLX}
FCanvas.ReferenceCanvas.Stop;
{$ELSE}
tmpAlign:=FCanvas.TextAlign;
{$ENDIF}
TeeBlendBitmaps(100-Transparency,FBitmap,tmp,tmpPoint);
{$IFNDEF CLX}
if FCanvas.TextAlign<>tmpAlign then
begin
if Assigned(FCanvas.IFont) then
FCanvas.AssignFont(FCanvas.IFont);
FCanvas.TextAlign:=tmpAlign;
end;
{$ENDIF}
if tmpNew then
begin
FCanvas.Draw(FRect.Left,FRect.Top,tmp);
tmp.Free;
end;
end;
end;
{$ENDIF}
{$IFDEF CLX}
{ TUpDown }
Constructor TUpDown.Create(AOwner:TComponent);
begin
inherited;
Height:=22;
end;
procedure TUpDown.Change(AValue: Integer);
begin
inherited;
if (not IChangingText) and
Assigned(FAssociate) and
(not (csDesigning in FAssociate.ComponentState)) and
(FAssociate is TCustomEdit) then
begin
DoChangeEdit;
if Assigned(OldChanged) then OldChanged(FAssociate);
end;
end;
procedure TUpDown.ChangedEdit(Sender: TObject);
begin
if not IChangingText then
begin
if TCustomEdit(Sender).Text='' then
Value:=Min
else
begin
IChangingText:=True;
Value:=StrToIntDef(TCustomEdit(Sender).Text,Value);
IChangingText:=False;
end;
end;
if Assigned(OldChanged) then OldChanged(FAssociate);
end;
function TUpDown.GetPosition: Integer;
begin
result:=Value;
end;
type TCustomEditAccess=class(TCustomEdit);
procedure TUpDown.Loaded;
begin
inherited;
Height:=23;
Width:=18;
GetOldChanged;
end;
Procedure TUpDown.GetOldChanged;
begin
if Assigned(FAssociate) and
(FAssociate is TCustomEdit) and
(not (csDesigning in FAssociate.ComponentState)) then
begin
ChangedEdit(TCustomEdit(FAssociate));
if @OldChanged=nil then
begin
OldChanged:=TCustomEditAccess(FAssociate).OnChange;
TCustomEditAccess(FAssociate).OnChange:=ChangedEdit;
end;
end;
end;
procedure TUpDown.SetAssociate(const AValue: TComponent);
begin
if Assigned(FAssociate) and
(FAssociate is TCustomEdit) and
(not (csDesigning in FAssociate.ComponentState)) and
(not Assigned(AValue)) then
TCustomEditAccess(FAssociate).OnChange:=OldChanged;
FAssociate:=AValue;
// GetOldChanged;
end;
procedure TUpDown.SetPosition(const AValue: Integer);
begin
Value:=AValue;
if Assigned(Associate) and (Associate is TCustomEdit) then
DoChangeEdit;
end;
Procedure TUpDown.DoChangeEdit;
begin
IChangingText:=True;
try
TCustomEdit(Associate).Text:=IntToStr(Value);
finally
IChangingText:=False;
end;
end;
{$ENDIF}
{ This procedure will convert all pixels in ABitmap to
levels of gray }
Procedure TeeGrayScale(ABitmap:TBitmap; Inverted:Boolean; AMethod:Integer);
{$IFDEF CLR}
begin
end;
{$ELSE}
Var RGB : ^TRGBTripleArray;
x : Integer;
y : Integer;
tmp : Integer;
begin
if Assigned(ABitmap) then
With ABitmap do
begin
PixelFormat:=TeePixelFormat;
for y:=Height-1 downto 0 do
begin
RGB:=ScanLine[y];
for x:=0 to Width-1 do
{$R-}
With RGB[x] do
begin
if AMethod=0 then
tmp:=(rgbtBlue+rgbtGreen+rgbtRed) div 3
else
tmp:=Round( (0.30*rgbtRed) +
(0.59*rgbtGreen) +
(0.11*rgbtBlue));
// tmp:=(11*rgbtRed+16*rgbtGreen+5*rgbtBlue) div 32 // faster ?
if Inverted then tmp:=255-tmp;
rgbtBlue:=tmp;
rgbtGreen:=tmp;
rgbtRed:=tmp;
end;
end;
{$IFNDEF CLX}
PixelFormat:=pfDevice; { for non-24bit color displays }
{$ENDIF}
end;
end;
{$ENDIF}
{$IFDEF TEEVCL}
{ EditColor }
Function EditColor(AOwner:TComponent; AColor:TColor):TColor;
Begin
With TColorDialog.Create(AOwner) do
try
Color:=AColor;
if not Assigned(TeeCustomEditColors) then
TeeCustomEditColors:=TStringList.Create
else
CustomColors:=TeeCustomEditColors;
if Execute then
begin
TeeCustomEditColors.Assign(CustomColors);
result:=Color;
end
else result:=AColor;
finally
Free;
end;
end;
{ Show the TColorDialog, return True if color changed }
Function EditColorDialog(AOwner:TComponent; var AColor:TColor):Boolean;
var tmpNew : TColor;
begin
tmpNew:=EditColor(AOwner,AColor);
result:=tmpNew<>AColor;
if result then AColor:=tmpNew;
end;
{ TButtonColor }
procedure TButtonColor.Click;
var tmp : TColor;
begin
if Assigned(Instance) then
begin
tmp:=GetTeeColor;
if EditColorDialog(Self,tmp) then
begin
SetOrdProp(Instance,Info,tmp);
Repaint;
inherited;
end;
end
else inherited;
end;
Function TButtonColor.GetTeeColor:TColor;
begin
if Assigned(GetColorProc) then
result:=GetColorProc
else
if Assigned(Info) then result:=ColorToRGB(GetOrdProp(Instance,Info)) { 5.03 }
else result:=clNone;
end;
procedure TButtonColor.SetTeeColor(Const Value:TColor); // 7.0
begin
if Assigned(Info) then SetOrdProp(Instance,Info,Value);
end;
procedure TButtonColor.DrawSymbol(ACanvas:TTeeCanvas);
Const tmpWidth={$IFDEF CLX}15{$ELSE}19{$ENDIF};
var tmp : Integer;
begin
With ACanvas do
begin
Brush.Color:=GetTeeColor;
if Brush.Color<>clNone then
begin
if not Enabled then Pen.Style:=psClear;
tmp:=Height div 4;
Rectangle(Width-tmpWidth,Height-3*tmp,Width-6,Height-tmp);
end;
end;
end;
{ TComboFlat }
constructor TComboFlat.Create(AOwner: TComponent);
begin
inherited;
Height:=21;
ItemHeight:=13;
Style:=csDropDownList;
end;
{$IFNDEF D6}
procedure TComboFlat.AddItem(Item: String; AObject: TObject);
begin
Items.AddObject(Item, AObject);
end;
{$ENDIF}
{$IFNDEF CLX}
procedure TComboFlat.WMPaint(var Message: TWMPaint);
var R: TRect;
begin
inherited;
if (not Inside) and (not Focused) then
begin
with TControlCanvas.Create do
try
Control:=Self;
Pen.Color:=clBtnFace;
Brush.Style:=bsClear;
R:=ClientRect;
{$IFNDEF D5}
with R do Rectangle(Left,Top,Right,Bottom);
{$ELSE}
Rectangle(R);
{$ENDIF}
InflateRect(R,-1,-1);
{$IFNDEF D5}
with R do Rectangle(Left,Top,Right,Bottom);
{$ELSE}
Rectangle(R);
{$ENDIF}
R.Left:=R.Right-GetSystemMetrics(SM_CXSIZE)-2;
Inc(R.Top);
Dec(R.Bottom);
Pen.Color:=clWindow;
{$IFNDEF D5}
with R do Rectangle(Left,Top,Right,Bottom);
{$ELSE}
Rectangle(R);
{$ENDIF}
MoveTo(R.Right-2,R.Top);
LineTo(R.Right-2,R.Bottom);
finally
Free;
end;
end;
end;
procedure TComboFlat.CMMouseEnter(var Message: TMessage);
begin
inherited;
Inside:=True;
Repaint;
end;
procedure TComboFlat.CMMouseLeave(var Message: TMessage);
begin
inherited;
Inside:=False;
Repaint;
end;
{$IFNDEF CLR}
procedure TComboFlat.CMFocusChanged(var Message: TCMFocusChanged);
begin
inherited;
Inside:=False;
Repaint;
end;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{ TTeeFontGradient }
procedure TTeeFontGradient.SetOutline(const Value: Boolean);
begin
SetBooleanProperty(FOutline,Value);
end;
Procedure TTeeFontGradient.SetBooleanProperty( Var Variable:Boolean;
Const Value:Boolean);
begin
if Variable<>Value then
begin
Variable:=Value;
DoChanged;
end;
end;
{ TWhitePen }
constructor TWhitePen.Create(OnChangeEvent: TNotifyEvent);
begin
inherited;
Color:=clWhite;
end;
// Returns point "ATo" minus ADist pixels from AFrom point.
Function PointAtDistance(AFrom,ATo:TPoint; ADist:Integer):TPoint;
var tmpSin : Extended;
tmpCos : Extended;
begin
result:=ATo;
if ATo.X<>AFrom.X then
begin
SinCos({$IFDEF CLR}Borland.VCL.{$ENDIF}Math.ArcTan2((ATo.Y-AFrom.Y),(ATo.X-AFrom.X)),tmpSin,tmpCos);
Dec(result.X,Round(ADist*tmpCos));
Dec(result.Y,Round(ADist*tmpSin));
end
else
begin
if ATo.Y<AFrom.Y then Inc(result.Y,ADist)
else Dec(result.Y,ADist);
end;
end;
Function TeeDistance(const x,y:Double):Double; // 7.0 changed to "double"
begin
result:=Sqrt(Sqr(x)+Sqr(y));
end;
{$IFNDEF CLR}
// Anders Melander Resample.pas
// www.melander.dk anders@aztech.dk
// Modified and optimized for speed.
type
TFilterValue=Single;
// Type of a filter for use with Stretch()
TFilterProc=function(Value: TFilterValue): TFilterValue;
// Contributor for a pixel
TContributor=packed record
Pixel : Integer; // Source pixel
Weight : Integer; // TFilterValue Pixel weight
end;
TContributorList = array[0..0] of TContributor;
PContributorList = ^TContributorList;
// List of source pixels contributing to a destination pixel
TCList = packed record
n : Integer;
p : PContributorList;
end;
PCList = ^TCList;
TCListList=array of TCList;
// Physical bitmap pixel
TColorRGB = packed record
r, g, b : Byte;
{$IFDEF CLX}
a : Byte;
{$ENDIF}
end;
PColorRGB = ^TColorRGB;
// Physical bitmap scanline (row)
TRGBList = packed array[0..0] of TColorRGB;
PRGBList = ^TRGBList;
{$DEFINE USE_SCANLINE}
procedure SmoothStretch(Src, Dst: TBitmap; filter: TFilterProc; const fwidth: TFilterValue); overload;
{$IFNDEF USE_SCANLINE}
function Color2RGB(Color: TColor): TColorRGB;
begin
{$IFDEF CLX}
result.a :=0;
{$ENDIF}
Result.r := Color AND $000000FF;
Result.g := (Color AND $0000FF00) SHR 8;
Result.b := (Color AND $00FF0000) SHR 16;
end;
function RGB2Color(Color: TColorRGB): TColor;
begin
Result := Color.r OR (Color.g SHL 8) OR (Color.b SHL 16);
end;
{$ENDIF}
var
xscale,
yscale : TFilterValue; // Zoom scale factors
Work : TBitmap;
contrib : TCListList;
SrcWidth,
SrcHeight,
DstWidth,
DstHeight : integer;
tmpWidth : Integer;
procedure CalcHorizSubSampling;
var i : Integer;
j : Integer;
k : Integer;
TwoSrcWidthMinusOne : Integer;
weight : Integer;
fscale,
center : TFilterValue;
width : TFilterValue;
left,
right : integer; // Filter calculation variables
begin
fscale := 1.0 / xscale;
width := fwidth * fscale;
tmpWidth:=Trunc(width * 2.0 + 1);
TwoSrcWidthMinusOne:=SrcWidth+ SrcWidth - 1;
for i := 0 to DstWidth-1 do
begin
contrib[i].n := 0;
GetMem(contrib[i].p, tmpWidth * sizeof(TContributor));
center := i * fscale; // = i / xscale
// Original code:
// left := ceil(center - width);
// right := floor(center + width);
left := Floor(center - width);
right := Ceil(center + width);
for j := left to right do
begin
weight := Round(1000.0*filter((center - j) * xscale) * xscale);
if weight = 0 then Continue;
k := contrib[i].n;
Inc(contrib[i].n);
if (j < 0) then
contrib[i].p^[k].pixel := -j
else if (j >= SrcWidth) then
contrib[i].p^[k].pixel := TwoSrcWidthMinusOne - j
else
contrib[i].p^[k].pixel := j;
contrib[i].p^[k].weight := weight;
end;
end;
end;
procedure CalcHorizSuperSampling;
var i : Integer;
j : Integer;
k : Integer;
TwoSrcWidthMinusOne : Integer;
weight : Integer;
center : TFilterValue;
left,
right : integer; // Filter calculation variables
begin
tmpWidth:=Trunc(fwidth * 2.0 + 1);
TwoSrcWidthMinusOne:=SrcWidth + SrcWidth - 1;
for i := 0 to DstWidth-1 do
begin
contrib[i].n := 0;
GetMem(contrib[i].p, tmpWidth * sizeof(TContributor));
center := i / xscale;
// Original code:
// left := ceil(center - fwidth);
// right := floor(center + fwidth);
left := floor(center - fwidth);
right := ceil(center + fwidth);
for j := left to right do
begin
weight := Round(1000.0*filter(center - j));
if weight = 0 then Continue;
k := contrib[i].n;
Inc(contrib[i].n);
if (j < 0) then
contrib[i].p^[k].pixel := -j
else if (j >= SrcWidth) then
contrib[i].p^[k].pixel := TwoSrcWidthMinusOne - j
else
contrib[i].p^[k].pixel := j;
contrib[i].p^[k].weight := weight;
end;
end;
end;
procedure FilterHorizontally;
var k : Integer;
i : Integer;
j : Integer;
rgbr,
rgbg,
rgbb : Integer;
{$IFDEF USE_SCANLINE}
SourceLine : PRGBList;
DestPixel : PColorRGB;
{$ENDIF}
begin
for k := 0 to SrcHeight-1 do
begin
{$IFDEF USE_SCANLINE}
SourceLine := Src.ScanLine[k];
DestPixel := Work.ScanLine[k];
{$ENDIF}
for i := 0 to DstWidth-1 do
with contrib[i] do
begin
rgbr := 0;
rgbg := 0;
rgbb := 0;
for j := 0 to n-1 do
with p^[j] do
begin
{$IFDEF USE_SCANLINE}
with SourceLine^[pixel] do
{$ELSE}
with Color2RGB(Src.Canvas.Pixels[pixel, k]) do
{$ENDIF}
begin
Inc(rgbr, r * weight);
Inc(rgbg, g * weight);
Inc(rgbb, b * weight);
end;
end;
if (rgbr > 255000) then
DestPixel^.r := 255
else if (rgbr < 0) then
DestPixel^.r := 0
else
DestPixel^.r := rgbr div 1000; //Round(rgbr);
if (rgbg > 255000) then
DestPixel^.g := 255
else if (rgbg < 0) then
DestPixel^.g := 0
else
DestPixel^.g := rgbg div 1000; //Round(rgbg);
if (rgbb > 255000) then
DestPixel^.b := 255
else if (rgbb < 0) then
DestPixel^.b := 0
else
DestPixel^.b := rgbb div 1000; //Round(rgbb);
{$IFDEF USE_SCANLINE}
Inc(DestPixel);
{$ELSE}
Work.Canvas.Pixels[i, k] := RGB2Color(color);
{$ENDIF}
end;
end;
end;
procedure CalcVerticalSubSampling;
var i : Integer;
j : Integer;
k : Integer;
TwoSrcHeightMinusOne : Integer;
weight : Integer;
fscale,
center : TFilterValue;
width : TFilterValue;
left,
right : integer; // Filter calculation variables
begin
fscale := 1.0 / yscale;
width := fwidth * fscale; // = fwidth / yscale
tmpWidth:=Trunc(width * 2.0 + 1);
TwoSrcHeightMinusOne:=SrcHeight + SrcHeight - 1;
for i := 0 to DstHeight-1 do
begin
contrib[i].n := 0;
GetMem(contrib[i].p, tmpWidth * sizeof(TContributor));
center := i * fscale;
// Original code:
// left := ceil(center - width);
// right := floor(center + width);
left := floor(center - width);
right := ceil(center + width);
for j := left to right do
begin
weight := Round(1000.0*filter((center - j) * yscale) * yscale);
if weight = 0 then Continue;
k := contrib[i].n;
Inc(contrib[i].n);
if (j < 0) then
contrib[i].p^[k].pixel := -j
else if (j >= SrcHeight) then
contrib[i].p^[k].pixel := TwoSrcHeightMinusOne - j
else
contrib[i].p^[k].pixel := j;
contrib[i].p^[k].weight := weight;
end;
end
end;
procedure CalcVerticalSuperSampling;
var i : Integer;
j : Integer;
k : Integer;
TwoSrcHeightMinusOne : Integer;
weight : Integer; // TFilterValue;
center : TFilterValue;
left,
right : integer; // Filter calculation variables
begin
tmpWidth:=Trunc(fwidth * 2.0 + 1);
TwoSrcHeightMinusOne:=SrcHeight + SrcHeight - 1;
for i := 0 to DstHeight-1 do
begin
contrib[i].n := 0;
GetMem(contrib[i].p, tmpWidth * sizeof(TContributor));
center := i / yscale;
// Original code:
// left := ceil(center - fwidth);
// right := floor(center + fwidth);
left := floor(center - fwidth);
right := ceil(center + fwidth);
for j := left to right do
begin
weight := Round(1000.0*filter(center - j));
if weight = 0 then Continue;
k := contrib[i].n;
Inc(contrib[i].n);
if (j < 0) then
contrib[i].p^[k].pixel := -j
else if (j >= SrcHeight) then
contrib[i].p^[k].pixel := TwoSrcHeightMinusOne - j
else
contrib[i].p^[k].pixel := j;
contrib[i].p^[k].weight := weight;
end;
end;
end;
procedure FilterVertically;
var k : Integer;
i : Integer;
j : Integer;
DestDelta : integer;
Delta : Integer;
rgbr,
rgbg,
rgbb : Integer; // TFilterValue;
{$IFDEF USE_SCANLINE}
SourceLine : PRGBList;
DestLine : PRGBList;
DestPixel : PColorRGB;
{$ENDIF}
begin
{$IFDEF USE_SCANLINE}
SourceLine := Work.ScanLine[0];
Delta := Integer(Work.ScanLine[1]) - Integer(SourceLine);
DestLine := Dst.ScanLine[0];
DestDelta := Integer(Dst.ScanLine[1]) - Integer(DestLine);
{$ENDIF}
for k := 0 to DstWidth-1 do
begin
{$IFDEF USE_SCANLINE}
DestPixel := pointer(DestLine);
{$ENDIF}
for i := 0 to DstHeight-1 do
with contrib[i] do
begin
rgbr := 0;
rgbg := 0;
rgbb := 0;
for j := 0 to n-1 do
with p^[j] do
begin
{$IFDEF USE_SCANLINE}
with PColorRGB(Integer(SourceLine)+pixel*Delta)^ do
{$ELSE}
with Color2RGB(Work.Canvas.Pixels[k, pixel]) do
{$ENDIF}
begin
Inc(rgbr, r * weight);
Inc(rgbg, g * weight);
Inc(rgbb, b * weight);
end;
end;
if (rgbr > 255000) then
DestPixel^.r := 255
else if (rgbr < 0) then
DestPixel^.r := 0
else
DestPixel^.r := rgbr div 1000; //Round(rgbr);
if (rgbg > 255000) then
DestPixel^.g := 255
else if (rgbg < 0) then
DestPixel^.g := 0
else
DestPixel^.g := rgbg div 1000; // Round(rgbg);
if (rgbb > 255000) then
DestPixel^.b := 255
else if (rgbb < 0) then
DestPixel^.b := 0
else
DestPixel^.b := rgbb div 1000; // Round(rgbb);
{$IFDEF USE_SCANLINE}
Inc(Integer(DestPixel), DestDelta);
{$ELSE}
Dst.Canvas.Pixels[k, i] := RGB2Color(color);
{$ENDIF}
end;
{$IFDEF USE_SCANLINE}
Inc(SourceLine);
Inc(DestLine);
{$ENDIF}
end;
end;
var i : Integer;
begin
if (not Assigned(Dst)) or (not Assigned(Src)) then Exit;
DstWidth := Dst.Width;
DstHeight := Dst.Height;
SrcWidth := Src.Width;
SrcHeight := Src.Height;
if (SrcWidth < 1) or (SrcHeight < 1) then
raise Exception.Create('SmoothStretch: Source bitmap too small');
if (DstWidth < 1) or (DstHeight < 1) then
raise Exception.Create('SmoothStretch: Destination bitmap too small');
// Create intermediate image to hold horizontal zoom
Work := TBitmap.Create;
try
{$IFDEF USE_SCANLINE}
Src.PixelFormat := TeePixelFormat;
Dst.PixelFormat := Src.PixelFormat;
Work.PixelFormat := Src.PixelFormat;
{$ENDIF}
Work.Height := SrcHeight;
Work.Width := DstWidth;
// xscale := DstWidth / SrcWidth;
// yscale := DstHeight / SrcHeight;
// Improvement suggested by David Ullrich:
if (SrcWidth = 1) then
xscale:= DstWidth / SrcWidth
else
xscale:= (DstWidth - 1) / (SrcWidth - 1);
if (SrcHeight = 1) then
yscale:= DstHeight / SrcHeight
else
yscale:= (DstHeight - 1) / (SrcHeight - 1);
// This implementation only works on 24-bit images because it uses
// TBitmap.Scanline
// --------------------------------------------
// Pre-calculate filter contributions for a row
// -----------------------------------------------
SetLength(contrib,DstWidth);
// Horizontal sub-sampling
// Scales from bigger to smaller width
if xscale < 1 then
CalcHorizSubSampling
else
// Horizontal super-sampling
// Scales from smaller to bigger width
CalcHorizSuperSampling;
// ----------------------------------------------------
// Apply filter to sample horizontally from Src to Work
// ----------------------------------------------------
FilterHorizontally;
// Free the memory allocated for horizontal filter weights
for i := 0 to DstWidth-1 do
FreeMem(contrib[i].p);
// contrib:=nil;
// -----------------------------------------------
// Pre-calculate filter contributions for a column
// -----------------------------------------------
SetLength(contrib,DstHeight);
// Vertical sub-sampling
// Scales from bigger to smaller height
if yscale < 1 then
CalcVerticalSubSampling
else
// Vertical super-sampling
// Scales from smaller to bigger height
CalcVerticalSuperSampling;
// --------------------------------------------------
// Apply filter to sample vertically from Work to Dst
// --------------------------------------------------
FilterVertically;
// Free the memory allocated for vertical filter weights
for i := 0 to DstHeight-1 do
FreeMem(contrib[i].p);
contrib:=nil;
finally
Work.Free;
end;
end;
// Lanczos3 filter
function Lanczos3Filter(Value: TFilterValue): TFilterValue;
function SinC(const Value: TFilterValue): TFilterValue;
begin
Result := Sin(Value) / Value
end;
const PiDiv3 = Pi/3.0;
begin
if Value < 0 then
Value := -Value
else
if Value=0 then
begin
result:=1;
exit;
end;
if Value < 3 then
result:=SinC(Value*Pi) * SinC(Value*PiDiv3)
else
result:=0;
end;
function TriangleFilter(Value: TFilterValue): TFilterValue;
begin
if (Value < 0.0) then
Value := -Value;
if (Value < 1.0) then
Result := 1.0 - Value
else
Result := 0.0;
end;
{$ENDIF}
procedure SmoothStretch(Src, Dst: TBitmap); overload;
begin
SmoothStretch(Src,Dst,ssBestQuality);
end;
procedure SmoothStretch(Src, Dst: TBitmap; Option:TSmoothStretchOption); overload;
{$IFDEF CLR}
var g: System.Drawing.Graphics;
i: System.Drawing.Image;
r: System.Drawing.Rectangle;
n: Integer;
begin
if not Src.Empty then
begin
n:=Integer(Src.Handle); // prevent longword-->integer overflow
i:=System.Drawing.Image.FromHBitmap(IntPtr(n));
n:=Integer(Dst.Canvas.Handle); // prevent longword-->integer overflow
g:=System.Drawing.Graphics.FromHdc(IntPtr(n));
r:=System.Drawing.Rectangle.FromLTRB(0,0,Dst.Width,Dst.Height);
g.InterpolationMode:=InterpolationMode.High;
g.DrawImage(i,r);
g.Free;
i.Free;
end;
end;
{$ELSE}
begin
if Option=ssBestQuality then
SmoothStretch(Src,Dst,Lanczos3Filter,3) // Slower but big quality.
else
SmoothStretch(Src,Dst,TriangleFilter,1); // Faster, but not big quality.
end;
{$ENDIF}
{$IFNDEF CLX}
{$IFNDEF CLR}
var TeeMSIMG32:THandle=0; // 7
Function CheckWinAlphaBlend:Boolean;
begin
TeeMSIMG32:=TeeLoadLibrary('msimg32.dll');
if TeeMSIMG32<>0 then
@AlphaBlendProc:=GetProcAddress(TeeMSIMG32,'AlphaBlend')
else
@AlphaBlendProc:=nil;
result:=@AlphaBlendProc<>nil;
end;
var TeeGDI32:THandle=0; // 5.03
Procedure TryLoadSetDC; // 7.0
begin
TeeGDI32:=TeeLoadLibrary('gdi32.dll');
if TeeGDI32<>0 then
begin
@TeeSetDCBrushColor:=GetProcAddress(TeeGDI32,'SetDCBrushColor');
@TeeSetDCPenColor:=GetProcAddress(TeeGDI32,'SetDCPenColor');
end
else
begin
TeeSetDCBrushColor:=nil;
TeeSetDCPenColor:=nil;
end;
end;
{$ENDIF}
{$ENDIF}
{$IFNDEF LINUX}
Function TeeLoadLibrary(Const FileName:String):HInst;
{$IFNDEF D5}
var OldError: Integer;
{$ENDIF}
begin
{$IFNDEF D5}
OldError:=SetErrorMode(SEM_NOOPENFILEERRORBOX);
try
{$ENDIF}
result:={$IFDEF D5}SafeLoadLibrary{$ELSE}LoadLibrary{$ENDIF}({$IFNDEF D5}PChar{$ENDIF}(FileName));
{$IFNDEF D5}
finally
SetErrorMode(OldError);
end;
{$ENDIF}
end;
// Free Library, but do not free library in Windows 95 (lock bug)
Procedure TeeFreeLibrary(hLibModule: HMODULE);
begin
if (Win32Platform=VER_PLATFORM_WIN32_WINDOWS) and
(Win32MinorVersion=0) then
else
FreeLibrary(hLibModule);
end;
{$ENDIF}
{$IFNDEF TEEVCL}
Procedure TPersistent.Assign(Source:TPersistent);
begin
raise Exception.Create('Cannot assign TPersistent');
end;
procedure TGraphicObject.Changed;
begin
end;
function TCanvas.GetPixel(X, Y: Integer): TColor;
begin
result:=0;
end;
procedure TCanvas.SetPixel(X, Y: Integer; Value: TColor);
begin
end;
procedure TCanvas.CopyRect(const Dest: TRect; Canvas: TCanvas; const Source: TRect);
begin
end;
function TCanvas.TextExtent(const Text: string): TSize;
begin
result.cx:=0;
result.cy:=0;
end;
procedure TCanvas.Draw(X, Y: Integer; Graphic: TGraphic);
begin
end;
procedure TCanvas.StretchDraw(const Rect: TRect; Graphic: TGraphic);
begin
end;
Constructor TCustomPanel.Create(AOwner: TComponent);
begin
end;
procedure TCustomPanel.AssignTo(Dest: TPersistent);
begin
end;
procedure TCustomPanel.CreateParams(var Params: TCreateParams);
begin
end;
Procedure TCustomPanel.DefineProperties(Filer:TFiler);
begin
end;
{$ENDIF}
procedure CreateEmptyRegion;
begin
{$IFNDEF CLX}
OldRegion:=CreateRectRgn(0,0,0,0);
{$ELSE}
// OldRegion:=QRegion_create(0,0,0,0,QRegionRegionType_Rectangle);
{$ENDIF}
end;
procedure DeleteEmptyRegion;
begin
{$IFDEF CLX}
// if Assigned(OldRegion) then QRegion_destroy(OldRegion);
{$ELSE}
if OldRegion>0 then DeleteObject(OldRegion);
{$ENDIF}
end;
initialization
{$IFNDEF TEEVCL}
InitPlatformId;
{$ENDIF}
{$IFNDEF CLX}
IsWindowsNT:=Win32Platform=VER_PLATFORM_WIN32_NT; // Alphablend fails in Win98
{$IFNDEF CLR}
CanUseWinAlphaBlend:=IsWindowsNT and CheckWinAlphaBlend;
{$ENDIF}
{$ENDIF}
CreateEmptyRegion;
TeeDefaultFont;
{$IFDEF TEEVCL}
{$IFDEF D6}
{$IFNDEF CLR}
ActivateClassGroup(TControl);
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$IFNDEF CLX}
{$IFNDEF CLR}
TryLoadSetDC;
{$ENDIF}
{$ENDIF}
finalization
{$IFNDEF CLR}
{$IFNDEF CLX}
if TeeGDI32<>0 then
TeeFreeLibrary(TeeGDI32);
if TeeMSIMG32<>0 then
TeeFreeLibrary(TeeMSIMG32);
{$ENDIF}
{$ENDIF}
DeleteEmptyRegion;
TeeCustomEditColors.Free;
end.
|
unit BrickCamp.Model.IProduct;
interface
uses
Spring;
type
IProduct = interface(IInterface)
['{C2DA14B4-A905-4665-85AE-5BE3A25B5C42}']
function GetId: Integer;
function GetName: string;
function GetDescription: string;
function GetPrice: Extended;
procedure SetName(const Value: string);
procedure SetDescription(const Value: string);
procedure SetPrice(const Value: Extended);
end;
implementation
end.
|
unit SQLQuery;
interface
type
TSQLQueries = class(TObject)
private
FReadingIndex: Integer;
FWritingIndex: Integer;
FActualCount: Integer;
FModified: Boolean;
FSQLQueriesArray: array of string;
procedure ReadQueries;
procedure SaveQueries;
procedure ReadSettings;
procedure SaveSettings;
function ExistsTheSame(const Value: AnsiString): Boolean;
function GetBeginOfList: Boolean;
function GetEndOfList: Boolean;
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
function NextQuery: AnsiString;
function PrevQuery: AnsiString;
procedure Add(const Value: AnsiString);
property BeginOfList: Boolean read GetBeginOfList;
property EndOfList: Boolean read GetEndOfList;
property Count: Integer read FActualCount;
property ItemIndex: Integer read FReadingIndex;
end;
implementation
uses
Forms, SysUtils, ForestConsts, ForestTypes, IniFiles;
//---------------------------------------------------------------------------
{ TSQLQueries }
procedure TSQLQueries.Add(const Value: AnsiString);
begin
if Trim(Value) = '' then
Exit;
if ExistsTheSame(Value) then
Exit;
if FActualCount < MaxQueriesCount then
begin
Inc(FActualCount);
SetLength(FSQLQueriesArray, FActualCount);
end;
if FWritingIndex < FActualCount - 1 then
Inc(FWritingIndex)
else
FWritingIndex := 0;
try
FSQLQueriesArray[FWritingIndex] := Value;
FModified := True;
except
raise Exception.Create(Format(E_WRITE_QUERY, [MaxQueriesCount, FActualCount, FWritingIndex, FReadingIndex]));
end;
end;
//---------------------------------------------------------------------------
constructor TSQLQueries.Create(AOwner: TObject);
begin
FModified := False;
ReadSettings();
ReadQueries();
end;
//---------------------------------------------------------------------------
destructor TSQLQueries.Destroy;
begin
if FModified then
SaveQueries();
SaveSettings();
inherited;
end;
//---------------------------------------------------------------------------
function TSQLQueries.ExistsTheSame(const Value: AnsiString): Boolean;
var
I: Integer;
S: AnsiString;
begin
Result := False;
S := AnsiUpperCase(Value);
for I := 0 to Length(FSQLQueriesArray) - 1 do
begin
Result := S = AnsiUpperCase(FSQLQueriesArray[I]);
if Result then
Break;
end;
end;
//---------------------------------------------------------------------------
function TSQLQueries.GetBeginOfList: Boolean;
begin
Result := FReadingIndex = 0;
end;
//---------------------------------------------------------------------------
function TSQLQueries.GetEndOfList: Boolean;
begin
Result := (FReadingIndex = FActualCount - 1) or (FActualCount = 0);
end;
//---------------------------------------------------------------------------
function TSQLQueries.NextQuery: AnsiString;
begin
if not EndOfList then
try
Result := FSQLQueriesArray[FReadingIndex + 1];
Inc(FReadingIndex);
except
raise Exception.Create(Format(E_READ_QUERY, [MaxQueriesCount, FActualCount, FWritingIndex, FReadingIndex]));
end;
end;
//---------------------------------------------------------------------------
function TSQLQueries.PrevQuery: AnsiString;
begin
if not BeginOfList then
try
Result := FSQLQueriesArray[FReadingIndex - 1];
Dec(FReadingIndex);
except
raise Exception.Create(Format(E_READ_QUERY, [MaxQueriesCount, FActualCount, FWritingIndex, FReadingIndex]));
end;
end;
//---------------------------------------------------------------------------
procedure TSQLQueries.ReadQueries;
var
QueryFile: file of TSQLQuery;
Query: TSQLQuery;
begin
if not FileExists(S_QUERY_FILE_NAME) then
Exit;
Assign(QueryFile, S_QUERY_FILE_NAME);
Reset(QueryFile);
try
while not Eof(QueryFile) do
begin
Read(QueryFile, Query);
Add(Query.QueryText);
end;
finally
CloseFile(QueryFile);
end;
end;
//---------------------------------------------------------------------------
procedure TSQLQueries.ReadSettings;
begin
if not FileExists(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME)
then
Exit;
with TIniFile.Create(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME) do
try
FReadingIndex := ReadInteger(S_INI_QUERIES, S_READING_INDEX, 0);
FWritingIndex := ReadInteger(S_INI_QUERIES, S_WRITING_INDEX, 0);
MaxQueriesCount := ReadInteger(S_INI_QUERIES, S_MAX_QUERIES_COUNT, 50);
finally
Free();
end;
end;
//---------------------------------------------------------------------------
procedure TSQLQueries.SaveQueries;
var
QueryFile: file of TSQLQuery;
Query: TSQLQuery;
I: Integer;
begin
Assign(QueryFile, S_QUERY_FILE_NAME);
Rewrite(QueryFile);
try
for I := 0 to (Length(FSQLQueriesArray) - 1) do
begin
Query.QueryIndex := I;
Query.QueryText := FSQLQueriesArray[I];
Write(QueryFile, Query);
end;
finally
CloseFile(QueryFile);
end;
end;
//---------------------------------------------------------------------------
procedure TSQLQueries.SaveSettings;
begin
with TIniFile.Create(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME) do
try
WriteInteger(S_INI_QUERIES, S_READING_INDEX, FReadingIndex);
WriteInteger(S_INI_QUERIES, S_WRITING_INDEX, FWritingIndex);
WriteInteger(S_INI_QUERIES, S_MAX_QUERIES_COUNT, MaxQueriesCount);
finally
Free();
end;
end;
end.
|
unit BrickCamp.Repositories.TQuestion;
interface
uses
System.JSON,
Spring.Container.Injection,
Spring.Container.Common,
BrickCamp.IDB,
BrickCamp.Model.TQuestion,
BrickCamp.Repositories.IQuestion;
type
TQuestionRepository = class(TInterfacedObject, IQuestionRepository)
protected
[Inject]
FDb: IBrickCampDb;
public
function GetOne(const Id: Integer): TQuestion;
function GetList: TJSONArray;
procedure Insert(const Question: TQuestion);
procedure Update(const Question: TQuestion);
procedure Delete(const Id: Integer);
function GetListByProductId(const ProductId: Integer): TJSONArray;
end;
implementation
uses
Spring.Collections,
Spring.Persistence.Criteria.Interfaces,
Spring.Persistence.Criteria.Properties,
MARS.Core.Utils;
{ TQuestionRepository }
procedure TQuestionRepository.Delete(const Id: Integer);
var
Question: TQuestion;
begin
Question := FDb.GetSession.FindOne<TQuestion>(Id);
if Assigned(Question) then
FDb.GetSession.Delete(Question);
end;
function TQuestionRepository.GetList: TJSONArray;
var
LList: IList<TQuestion>;
LItem: TQuestion;
begin
LList := FDb.GetSession.FindAll<TQuestion>;
result := TJSONArray.Create;
for LItem in LList do
Result.Add(ObjectToJson(LItem));
end;
function TQuestionRepository.GetListByProductId(const ProductId: Integer): TJSONArray;
var
ProductIdCriteria: Prop;
LList: IList<TQuestion>;
LItem: TQuestion;
begin
ProductIdCriteria := Prop.Create('PRODUCT_ID');
LList := FDb.GetSession.FindWhere<TQuestion>(ProductIdCriteria = ProductId);
result := TJSONArray.Create;
for LItem in LList do
Result.Add(ObjectToJson(LItem));
end;
function TQuestionRepository.GetOne(const Id: Integer): TQuestion;
begin
result := FDb.GetSession.FindOne<TQuestion>(Id);
end;
procedure TQuestionRepository.Insert(const Question: TQuestion);
begin
FDb.GetSession.Insert(Question);
end;
procedure TQuestionRepository.Update(const Question: TQuestion);
begin
FDb.GetSession.Update(Question);
end;
end.
|
program linearListObj;
const maxlen=100;
type
mylist = object
private
data : array[1..maxlen] of char;
last : 0..maxlen;
public
constructor init(l: integer);
function length() : integer;
procedure printlist();
procedure insert(x:char;p:integer);
function locate(x:char):integer;
procedure empty();
function get(i:integer):char;
end;
var
l,l1 : mylist;
p: integer;
x:char;
constructor mylist.init(l: integer);
var
i:integer;
begin
randomize;
if (l<= 0) then begin
last:=0;
exit;
end;
if (l>maxlen) then l:= maxlen;
for i:=1 to l do
begin
data[i]:=chr(65+round(random(26)));
inc(last);
end;
end;
function mylist.length() : integer;
begin
length := last;
end;
procedure mylist.printlist();
var
i:integer;
begin
for i:=1 to last do write(data[i]);
writeln;
end;
procedure mylist.insert(x:char;p:integer);
var
i:integer;
begin
if (p<= 1) then p:= 1;
if (p>last) then p:= last+1;
for i:=last+1 downto p do
data[i+1]:=data[i];
data[p]:=x;
last:=last+1;
end;
function mylist.locate(x:char):integer;
var
i:integer;
begin
for i:=1 to last do begin
if(data[i]=x) then begin
exit(i);
end;
end;
exit(0);
end;
procedure mylist.empty();
begin
last := 0;
end;
function mylist.get(i:integer):char;
begin
if ((i< 1) or(i>last) ) then exit(chr(0));
exit(data[i]);
end;
operator +(A:mylist; B:mylist) C:mylist;
var
i:integer;
begin
C.init(0);
for i:=1 to A.last do begin
C.insert(A.data[i],C.length+1);
end;
for i:=1 to B.last do begin
C.insert(B.data[i],C.length+1);
end;
end;
operator *(A:mylist; B:mylist) C:mylist;
var
i:integer;
begin
C.init(0);
for i:=1 to A.last do begin
if(C.locate(A.data[i])=0) then C.insert(A.data[i],C.length+1);
end;
for i:=1 to B.last do begin
if(C.locate(B.data[i])=0) then C.insert(B.data[i],C.length+1);
end;
end;
begin
l.init(10);
l.printlist();
writeln('输入一个字符和整数如:c 4,将字符c插如到第四个字符:');
readln(x,p);
l.insert(x,p);
l.printlist();
writeln('再生成个线性表:');
l1.init(10);
l1.printlist();
writeln('合并两个线性表:');
l:=l*l1;
l.printlist();
writeln('不去重复项合并两个线性表:');
l:=l+l1;
for p:=1 to l.length() do write(l.get(p));
writeln;
end.
|
{ ****************************************************************************** }
{ * FFMPEG video Writer by qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit FFMPEG_Writer;
{$INCLUDE zDefine.inc}
interface
uses SysUtils, CoreClasses, PascalStrings, UnicodeMixedLib, MemoryStream64, MemoryRaster, DoStatusIO, FFMPEG;
type
TFFMPEG_Writer = class(TCoreClassObject)
protected
VideoCodec: PAVCodec;
VideoCodecCtx: PAVCodecContext;
AVPacket_Ptr: PAVPacket;
Frame, FrameRGB: PAVFrame;
SWS_CTX: PSwsContext;
FOutput: TCoreClassStream;
FAutoFreeOutput: Boolean;
FPixelFormat: TAVPixelFormat;
FLastWidth, FLastHeight: Integer;
FEncodeNum: Integer;
function InternalOpenCodec(const codec: PAVCodec; const Width, Height, PSF, gop, bFrame, quantizerMin, quantizerMax: Integer; const Bitrate: Int64): Boolean;
public
constructor Create(output_: TCoreClassStream);
destructor Destroy; override;
class procedure PrintEncodec();
function OpenCodec(const codec_name: U_String; const Width, Height, PSF, gop, bFrame: Integer; const Bitrate: Int64): Boolean; overload;
function OpenCodec(const codec_id: TAVCodecID; const Width, Height, PSF, gop, bFrame: Integer; const Bitrate: Int64): Boolean; overload;
function OpenH264Codec(const Width, Height, PSF: Integer; const Bitrate: Int64): Boolean; overload;
function OpenH264Codec(const codec_name: U_String; const Width, Height, PSF: Integer; const Bitrate: Int64): Boolean; overload;
// default quantizerMin=2, quantizerMax=31
function OpenJPEGCodec(const Width, Height, quantizerMin, quantizerMax: Integer): Boolean; overload;
function OpenJPEGCodec(const Width, Height: Integer): Boolean; overload;
procedure CloseCodec;
function EncodeRaster(raster: TMemoryRaster; var Updated: Integer): Boolean; overload;
function EncodeRaster(raster: TMemoryRaster): Boolean; overload;
procedure Flush;
property EncodeNum: Integer read FEncodeNum;
function Size: Int64;
function LockOutput: TCoreClassStream;
procedure UnLockOutoput;
property AutoFreeOutput: Boolean read FAutoFreeOutput write FAutoFreeOutput;
property PixelFormat: TAVPixelFormat read FPixelFormat write FPixelFormat;
property LastWidth: Integer read FLastWidth;
property LastHeight: Integer read FLastHeight;
end;
implementation
function TFFMPEG_Writer.InternalOpenCodec(const codec: PAVCodec; const Width, Height, PSF, gop, bFrame, quantizerMin, quantizerMax: Integer; const Bitrate: Int64): Boolean;
var
r: Integer;
begin
Result := False;
VideoCodec := codec;
if not Assigned(VideoCodec) then
begin
DoStatus('not found Codec.');
exit;
end;
VideoCodecCtx := avcodec_alloc_context3(VideoCodec);
if not Assigned(VideoCodecCtx) then
begin
DoStatus('Could not allocate video codec context');
exit;
end;
AVPacket_Ptr := av_packet_alloc();
VideoCodecCtx^.bit_rate := Bitrate;
VideoCodecCtx^.Width := Width - (Width mod 2);
VideoCodecCtx^.Height := Height - (Height mod 2);
VideoCodecCtx^.time_base.num := 1;
VideoCodecCtx^.time_base.den := PSF;
VideoCodecCtx^.framerate.num := PSF;
VideoCodecCtx^.framerate.den := 1;
VideoCodecCtx^.gop_size := gop;
VideoCodecCtx^.max_b_frames := bFrame;
VideoCodecCtx^.pix_fmt := FPixelFormat;
VideoCodecCtx^.qmin := quantizerMin;
VideoCodecCtx^.qmax := quantizerMax;
r := avcodec_open2(VideoCodecCtx, VideoCodec, nil);
if r < 0 then
begin
DoStatus('Could not open codec: %s', [av_err2str(r)]);
exit;
end;
// alloc frame
Frame := av_frame_alloc();
FrameRGB := av_frame_alloc();
if (FrameRGB = nil) or (Frame = nil) then
begin
DoStatus('Could not allocate AVFrame structure');
exit;
end;
Frame^.format := Ord(VideoCodecCtx^.pix_fmt);
Frame^.Width := VideoCodecCtx^.Width;
Frame^.Height := VideoCodecCtx^.Height;
Frame^.pts := 0;
// alignment
r := av_frame_get_buffer(Frame, 32);
if r < 0 then
begin
DoStatus('Could not allocate the video frame data');
exit;
end;
FrameRGB^.format := Ord(AV_PIX_FMT_RGB32);
FrameRGB^.Width := Frame^.Width;
FrameRGB^.Height := Frame^.Height;
SWS_CTX := sws_getContext(
FrameRGB^.Width,
FrameRGB^.Height,
AV_PIX_FMT_RGB32,
Frame^.Width,
Frame^.Height,
FPixelFormat,
SWS_BILINEAR,
nil,
nil,
nil);
FLastWidth := Width;
FLastHeight := Height;
FEncodeNum := 0;
Result := True;
end;
constructor TFFMPEG_Writer.Create(output_: TCoreClassStream);
begin
inherited Create;
VideoCodecCtx := nil;
VideoCodec := nil;
AVPacket_Ptr := nil;
Frame := nil;
FrameRGB := nil;
SWS_CTX := nil;
FOutput := output_;
FAutoFreeOutput := False;
FPixelFormat := AV_PIX_FMT_YUV420P;
FLastWidth := 0;
FLastHeight := 0;
FEncodeNum := 0;
end;
destructor TFFMPEG_Writer.Destroy;
begin
CloseCodec;
if FAutoFreeOutput then
DisposeObject(FOutput);
inherited Destroy;
end;
class procedure TFFMPEG_Writer.PrintEncodec;
var
codec: PAVCodec;
begin
codec := av_codec_next(nil);
while codec <> nil do
begin
if av_codec_is_encoder(codec) = 1 then
DoStatus('ID[%d] Name[%s] %s', [Integer(codec^.id), string(codec^.name), string(codec^.long_name)]);
codec := av_codec_next(codec);
end;
end;
function TFFMPEG_Writer.OpenCodec(const codec_name: U_String; const Width, Height, PSF, gop, bFrame: Integer; const Bitrate: Int64): Boolean;
var
tmp: Pointer;
begin
FPixelFormat := AV_PIX_FMT_YUV420P;
tmp := codec_name.BuildPlatformPChar();
Result := InternalOpenCodec(avcodec_find_encoder_by_name(tmp), Width, Height, PSF, gop, bFrame, 2, 31, Bitrate);
U_String.FreePlatformPChar(tmp);
end;
function TFFMPEG_Writer.OpenCodec(const codec_id: TAVCodecID; const Width, Height, PSF, gop, bFrame: Integer; const Bitrate: Int64): Boolean;
begin
FPixelFormat := AV_PIX_FMT_YUV420P;
Result := InternalOpenCodec(avcodec_find_encoder(codec_id), Width, Height, PSF, gop, bFrame, 2, 31, Bitrate);
end;
function TFFMPEG_Writer.OpenH264Codec(const Width, Height, PSF: Integer; const Bitrate: Int64): Boolean;
begin
Result := OpenCodec(AV_CODEC_ID_H264, Width, Height, PSF, PSF div 2, 1, Bitrate);
end;
function TFFMPEG_Writer.OpenH264Codec(const codec_name: U_String; const Width, Height, PSF: Integer; const Bitrate: Int64): Boolean;
begin
Result := OpenCodec(codec_name, Width, Height, PSF, PSF div 2, 1, Bitrate);
end;
function TFFMPEG_Writer.OpenJPEGCodec(const Width, Height, quantizerMin, quantizerMax: Integer): Boolean;
begin
FPixelFormat := AV_PIX_FMT_YUVJ420P;
Result := InternalOpenCodec(avcodec_find_encoder(AV_CODEC_ID_MJPEG), Width, Height, 25, 1, 0, quantizerMin, quantizerMax, 1024 * 1024);
end;
function TFFMPEG_Writer.OpenJPEGCodec(const Width, Height: Integer): Boolean;
begin
Result := OpenJPEGCodec(Width, Height, 2, 31);
end;
procedure TFFMPEG_Writer.CloseCodec;
begin
if VideoCodecCtx <> nil then
avcodec_free_context(@VideoCodecCtx);
if Frame <> nil then
av_frame_free(@Frame);
if AVPacket_Ptr <> nil then
av_packet_free(@AVPacket_Ptr);
if SWS_CTX <> nil then
sws_freeContext(SWS_CTX);
if FrameRGB <> nil then
av_frame_free(@FrameRGB);
VideoCodecCtx := nil;
VideoCodec := nil;
AVPacket_Ptr := nil;
Frame := nil;
FrameRGB := nil;
SWS_CTX := nil;
end;
function TFFMPEG_Writer.EncodeRaster(raster: TMemoryRaster; var Updated: Integer): Boolean;
var
r: Integer;
begin
Result := False;
if FrameRGB = nil then
exit;
if raster = nil then
exit;
if SWS_CTX = nil then
exit;
if Frame = nil then
exit;
if VideoCodecCtx = nil then
exit;
if AVPacket_Ptr = nil then
exit;
LockObject(FOutput);
try
// FrameRGB
FrameRGB^.data[0] := @raster.Bits^[0];
FrameRGB^.Width := Frame^.Width;
FrameRGB^.Height := Frame^.Height;
FrameRGB^.linesize[0] := Frame^.Width * 4;
// transform BGRA to YV420
sws_scale(
SWS_CTX,
@FrameRGB^.data,
@FrameRGB^.linesize,
0,
Frame^.Height,
@Frame^.data,
@Frame^.linesize);
(* make sure the frame data is writable *)
r := av_frame_make_writable(Frame);
if r < 0 then
begin
DoStatus('av_frame_make_writable failed!');
exit;
end;
r := avcodec_send_frame(VideoCodecCtx, Frame);
if r < 0 then
begin
DoStatus('Error sending a frame for encoding');
exit;
end;
// seek stream to end
FOutput.Position := FOutput.Size;
while r >= 0 do
begin
r := avcodec_receive_packet(VideoCodecCtx, AVPacket_Ptr);
if (r = AVERROR_EAGAIN) or (r = AVERROR_EOF) then
Break;
if r < 0 then
begin
DoStatus('Error during encoding');
exit;
end;
FOutput.Write(AVPacket_Ptr^.data^, AVPacket_Ptr^.Size);
inc(Updated);
av_packet_unref(AVPacket_Ptr);
end;
Result := True;
AtomInc(Frame^.pts);
finally
AtomInc(FEncodeNum);
UnLockObject(FOutput);
end;
end;
function TFFMPEG_Writer.EncodeRaster(raster: TMemoryRaster): Boolean;
var
Updated: Integer;
begin
Updated := 0;
Result := EncodeRaster(raster, Updated);
end;
procedure TFFMPEG_Writer.Flush;
var
r: Integer;
begin
LockObject(FOutput);
try
(*
avcodec_send_frame(VideoCodecCtx, here It can be NULL), in which case it is considered a flush packet.
This signals the end of the stream. If the encoder still has packets buffered,
it will return them after this call.
Once flushing mode has been entered, additional flush packets are ignored, and sending frames will return AVERROR_EOF.
*)
r := avcodec_send_frame(VideoCodecCtx, nil);
if r < 0 then
begin
DoStatus('Error sending eof frame');
exit;
end;
// seek stream to end
FOutput.Position := FOutput.Size;
while r >= 0 do
begin
r := avcodec_receive_packet(VideoCodecCtx, AVPacket_Ptr);
if (r = AVERROR_EAGAIN) or (r = AVERROR_EOF) then
Break;
if r < 0 then
begin
DoStatus('Error during encoding');
Break;
end;
FOutput.Write(AVPacket_Ptr^.data^, AVPacket_Ptr^.Size);
av_packet_unref(AVPacket_Ptr);
end;
finally
UnLockObject(FOutput);
end;
end;
function TFFMPEG_Writer.Size: Int64;
begin
Result := LockOutput().Size;
UnLockOutoput();
end;
function TFFMPEG_Writer.LockOutput: TCoreClassStream;
begin
LockObject(FOutput);
Result := FOutput;
end;
procedure TFFMPEG_Writer.UnLockOutoput;
begin
UnLockObject(FOutput);
end;
end.
|
unit UL.Classes;
interface
uses
System.Classes,
VCL.Controls;
type
TUExtAlign = (
ualNone, ualTop, ualLeft, ualRight, ualBottom,
ualTopCenter, ualLeftCenter, ualRightCenter, ualBottomCenter,
ualCenter, ualClient);
TULayout = class(TPersistent)
private
FAAlign: TAlign;
FAWidth: Integer;
FAHeight: Integer;
FBAlign: TAlign;
FBWidth: Integer;
FBHeight: Integer;
published
property AAlign: TAlign read FAAlign write FAAlign;
property AWidth: Integer read FAWidth write FAWidth;
property AHeight: Integer read FAHeight write FAHeight;
property BAlign: TAlign read FBAlign write FBAlign;
property BWidth: Integer read FBWidth write FBWidth;
property BHeight: Integer read FBHeight write FBHeight;
procedure Assign(Source: TPersistent); override;
end;
implementation
{ TULayout }
procedure TULayout.Assign(Source: TPersistent);
begin
if Source is TULayout then
begin
FAAlign := (Source as TULayout).AAlign;
FAWidth := (Source as TULayout).AWidth;
FAHeight := (Source as TULayout).AHeight;
FBAlign := (Source as TULayout).BAlign;
FBWidth := (Source as TULayout).BWidth;
FBHeight := (Source as TULayout).BHeight;
end
else
inherited;
end;
end.
|
unit NtUtils.Processes.Snapshots;
interface
uses
Ntapi.ntexapi, NtUtils.Exceptions, DelphiUtils.Arrays;
type
TSystemThreadInformation = Ntapi.ntexapi.TSystemThreadInformation;
TProcessEntry = record
ImageName: String;
Process: TSystemProcessInformationFixed;
Threads: TArray<TSystemThreadInformation>;
end;
PProcessEntry = ^TProcessEntry;
// Snapshot active processes on the system
function NtxEnumerateProcesses(out Processes: TArray<TProcessEntry>):
TNtxStatus;
procedure NtxFilterProcessessByImage(var Processes: TArray<TProcessEntry>;
ImageName: String; Action: TFilterAction = ftKeep);
// Find a process in the snapshot by PID
function NtxFindProcessById(Processes: TArray<TProcessEntry>;
PID: NativeUInt): PProcessEntry;
// A parent checker to use with TArrayHelper.BuildTree<TProcessEntry>
function IsParentProcess(const Parent, Child: TProcessEntry): Boolean;
// Enumerate processes and build a process tree
function NtxEnumerateProcessesEx(out ProcessTree:
TArray<TTreeNode<TProcessEntry>>): TNtxStatus;
// TODO: NtxEnumerateProcessesOfSession
implementation
uses
Ntapi.ntstatus, Ntapi.ntdef;
function NtxEnumerateProcesses(out Processes: TArray<TProcessEntry>):
TNtxStatus;
var
BufferSize, ReturnLength: Cardinal;
Buffer, pProcess: PSystemProcessInformation;
Count, i, j: Integer;
begin
Result.Location := 'NtQuerySystemInformation';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(SystemProcessInformation);
Result.LastCall.InfoClassType := TypeInfo(TSystemInformationClass);
// - x86: 184 bytes per process + 64 bytes per thread + ImageName
// - x64: 256 bytes per process + 80 bytes per thread + ImageName
//
// On my system it's usually about 150 processes with 1.5k threads, so it's
// about 200 KB of data.
// We don't want to use a huge initial buffer since system spends
// more time probing it rather than enumerating the processes.
BufferSize := 384 * 1024;
repeat
Buffer := AllocMem(BufferSize);
ReturnLength := 0;
Result.Status := NtQuerySystemInformation(SystemProcessInformation,
Buffer, BufferSize, @ReturnLength);
if not Result.IsSuccess then
FreeMem(Buffer);
until not NtxExpandBuffer(Result, BufferSize, ReturnLength);
if not Result.IsSuccess then
Exit;
// Count processes
Count := 0;
pProcess := Buffer;
repeat
Inc(Count);
if pProcess.Process.NextEntryOffset = 0 then
Break
else
pProcess := Offset(pProcess, pProcess.Process.NextEntryOffset);
until False;
SetLength(Processes, Count);
// Iterate through processes
j := 0;
pProcess := Buffer;
repeat
// Save process information
Processes[j].Process := pProcess.Process;
Processes[j].ImageName := pProcess.Process.ImageName.ToString;
Processes[j].Process.ImageName.Buffer := PWideChar(Processes[j].ImageName);
if pProcess.Process.ProcessId = 0 then
Processes[j].ImageName := 'System Idle Process';
// Save each thread information
SetLength(Processes[j].Threads, pProcess.Process.NumberOfThreads);
for i := 0 to High(Processes[j].Threads) do
Processes[j].Threads[i] := pProcess.Threads{$R-}[i]{$R+};
// Proceed to the next process
if pProcess.Process.NextEntryOffset = 0 then
Break
else
pProcess := Offset(pProcess, pProcess.Process.NextEntryOffset);
Inc(j);
until False;
FreeMem(Buffer);
end;
function FilterByImage(const ProcessEntry: TProcessEntry;
Parameter: NativeUInt): Boolean;
begin
Result := (ProcessEntry.ImageName = PWideChar(Parameter));
end;
procedure NtxFilterProcessessByImage(var Processes: TArray<TProcessEntry>;
ImageName: String; Action: TFilterAction);
begin
TArrayHelper.Filter<TProcessEntry>(Processes, FilterByImage,
NativeUInt(PWideChar(ImageName)), Action);
end;
function NtxFindProcessById(Processes: TArray<TProcessEntry>;
PID: NativeUInt): PProcessEntry;
var
i: Integer;
begin
for i := 0 to High(Processes) do
if Processes[i].Process.ProcessId = PID then
Exit(@Processes[i]);
Result := nil;
end;
function IsParentProcess(const Parent, Child: TProcessEntry): Boolean;
begin
// Note: since PIDs can be reused we need to ensure
// that parents were created earlier than childer.
Result := (Child.Process.InheritedFromProcessId = Parent.Process.ProcessId)
and (Child.Process.CreateTime.QuadPart > Parent.Process.CreateTime.QuadPart)
end;
function NtxEnumerateProcessesEx(out ProcessTree:
TArray<TTreeNode<TProcessEntry>>): TNtxStatus;
var
Processes: TArray<TProcessEntry>;
begin
Result := NtxEnumerateProcesses(Processes);
if Result.IsSuccess then
ProcessTree := TArrayHelper.BuildTree<TProcessEntry>(Processes,
IsParentProcess);
end;
end.
|
{*******************************************************}
{ }
{ Landerson Gomes }
{ }
{* Class Helper para Classes TDataSet *}
{ }
{*******************************************************}
unit ULGTDataSetHelper;
interface
uses
Data.DB, System.JSON, REST.Json, System.NetEncoding;
Type
TDataSetHelper = class Helper for TDataSet
public
function DataSetToJSON(const ARegistroAtual: Boolean = False) : TJSonArray;
procedure SaveToJSON(aFileName : string);
end;
implementation
uses
System.Classes;
{ TDataSetHelper }
function TDataSetHelper.DataSetToJSON(const ARegistroAtual: Boolean = False): TJSonArray;
var
lRow : integer;
lJO : TJSONObject;
StreamIn : TStream;
StreamOut : TStringStream;
procedure Executar;
var
lCol : integer;
begin
for lCol := 0 to FieldCount - 1 do
begin
if Fields[lCol].IsNull then
lJO.AddPair(Fields[lCol].FieldName, 'null')
else
begin
if Fields[lCol].IsBlob then
begin
StreamIn := CreateBlobStream(Fields[lCol], bmRead);
StreamOut := TStringStream.Create;
TNetEncoding.Base64.Encode(StreamIn, StreamOut);
StreamOut.Position := 0;
lJO.AddPair(Fields[lCol].DisplayName, StreamOut.DataString);
end
else
begin
if Fields[lCol].DataType in [ftCurrency, ftFloat, ftInteger, ftSmallint, ftSingle ] then
lJO.AddPair(Fields[lCol].FieldName,
TJSONNumber.Create(Fields[lcol].Value))
else
lJO.AddPair(fields[lcol].FieldName, fields[lcol].Value);
end;
end;
end;
end;
begin
Result := TJSONArray.Create;
if ARegistroAtual then
begin
lJO := TJSONObject.Create;
Executar;
Result.AddElement(lJO);
end
else
begin
First;
for lRow := 0 to Pred(RecordCount) do
begin
(*
lJO := TJSONObject.Create;
for lCol := 0 to FieldCount - 1 do
begin
if Fields[lCol].IsNull then
lJO.AddPair(Fields[lCol].FieldName, 'null')
else
begin
if Fields[lCol].IsBlob then
begin
StreamIn := CreateBlobStream(Fields[lCol], bmRead);
StreamOut := TStringStream.Create;
TNetEncoding.Base64.Encode(StreamIn, StreamOut);
StreamOut.Position := 0;
lJO.AddPair(Fields[lCol].DisplayName, StreamOut.DataString);
end
else
begin
if Fields[lCol].DataType in [ftCurrency, ftFloat, ftInteger, ftSmallint, ftSingle ] then
lJO.AddPair(Fields[lCol].FieldName,
TJSONNumber.Create(Fields[lcol].Value))
else
lJO.AddPair(fields[lcol].FieldName, fields[lcol].Value);
end;
end;
end;
*)
lJO := TJSONObject.Create;
Executar;
Result.AddElement(lJO);
Next;
end;
end;
end;
procedure TDataSetHelper.SaveToJSON(aFileName: string);
var
S : TStringList;
begin
S := TStringList.Create;
S.Clear;
S.Add(TJSON.Format(DataSetToJSON));
S.SaveToFile(aFileName);
end;
end.
|
unit TestFindReplace;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestFindReplace, released Sept 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{ test the find-replace feature }
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess;
type
TTestFindReplace = class(TBaseTestProcess)
private
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNoAction;
procedure TestProc;
procedure TestVar;
procedure TestType;
end;
implementation
uses
SysUtils,
JcfRegistrySettings, JcfSettings, TestConstants, FindReplace;
procedure TTestFindReplace.Setup;
var
lsSettingsFileName: string;
begin
inherited;
if not GetRegSettings.HasRead then
GetRegSettings.ReadAll;
{ use clarify test settings }
lsSettingsFileName := GetTestSettingsFileName;
Check(FileExists(lsSettingsFileName), 'Settings file ' + lsSettingsFileName +
' not found');
GetRegSettings.FormatConfigFileName := lsSettingsFileName;
JcfFormatSettings; // create and read
JcfFormatSettings.Obfuscate.Enabled := False;
JcfFormatSettings.Replace.Enabled := True;
JcfFormatSettings.Replace.Words.Clear;
JcfFormatSettings.Replace.Words.Add('Foo;Bar');
JcfFormatSettings.Replace.SplitWords
end;
procedure TTestFindReplace.TearDown;
begin
JcfFormatSettings.Replace.Enabled := False;
JcfFormatSettings.Replace.Words.Clear;
end;
procedure TTestFindReplace.TestNoAction;
const
IN_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
begin
TestProcessResult(TFindReplace, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestFindReplace.TestProc;
const
IN_UNIT_TEXT = UNIT_HEADER + ' procedure Foo; begin end; ' + UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' procedure Bar; begin end; ' + UNIT_FOOTER;
begin
TestProcessResult(TFindReplace, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestFindReplace.TestVar;
const
IN_UNIT_TEXT = UNIT_HEADER + ' procedure Foo2; var Foo: integer; begin end; ' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' procedure Foo2; var Bar: integer; begin end; ' +
UNIT_FOOTER;
begin
TestProcessResult(TFindReplace, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestFindReplace.TestType;
const
IN_UNIT_TEXT = UNIT_HEADER + ' procedure Foo2; var a: Foo; begin end; ' + UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' procedure Foo2; var a: Bar; begin end; ' + UNIT_FOOTER;
begin
TestProcessResult(TFindReplace, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestFindReplace.Suite);
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
//GLS
GLCrossPlatform, GLBaseClasses, GLScene, GLVectorGeometry,
GLWin32Viewer, GLParticles, GLCadencer, GLObjects, GLCoordinates, GLBehaviours;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
Panel1: TPanel;
Timer1: TTimer;
GLCadencer1: TGLCadencer;
GLScene1: TGLScene;
GLParticles1: TGLParticles;
DummyCube1: TGLDummyCube;
Sprite1: TGLSprite;
GLCamera1: TGLCamera;
procedure Timer1Timer(Sender: TObject);
procedure GLDummyCube1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure GLParticles1ActivateParticle(Sender: TObject;
particle: TGLBaseSceneObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
mx, my : Integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.GLParticles1ActivateParticle(Sender: TObject;
particle: TGLBaseSceneObject);
var
r, alpha, cr, sr : Single;
begin
with particle do begin
alpha:=Random*2*PI;
r:=2*Random;
SinCosine(alpha, r*r, sr, cr);
Children[0].Position.SetPoint(sr, 3*r-3, cr);
GetOrCreateInertia(particle).TurnSpeed:=Random(30);
TGLCustomSceneObject(particle).TagFloat:=GLCadencer1.CurrentTime;
end;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if Shift<>[] then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
end;
end;
procedure TForm1.GLDummyCube1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
with TGLCustomSceneObject(Sender) do begin
if newTime-TagFloat>3 then
GLParticles1.KillParticle(TGLCustomSceneObject(Sender));
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Panel1.Caption:=Format('%d particles, %.1f FPS',
[GLParticles1.Count, GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLParticles1.CreateParticle;
end;
end.
|
(* RLE: MM, 2020-04-06 *)
(* ------ *)
(* Program to encode or decode txt Files *)
(* ========================================================================= *)
PROGRAM RLE;
CONST ENDLINE_SYMBOL = '$';
PROCEDURE CheckIOError(message: STRING);
VAR error: INTEGER;
BEGIN (* CheckIOError *)
error := IOResult;
IF (error <> 0) THEN BEGIN
WriteLn('ERROR: ', message, '(Code: ', error, ')');
HALT;
END; (* IF *)
END; (* CheckIOError *)
FUNCTION ToString(i: INTEGER): STRING;
VAR s: STRING;
BEGIN (* ToString *)
Str(i, s);
ToString := s;
END; (* ToString *)
FUNCTION ToInt(s: STRING): INTEGER;
VAR i: INTEGER;
BEGIN (* ToInt *)
Val(s, i);
ToInt := i;
END; (* ToInt *)
PROCEDURE CompressText(VAR s: STRING);
VAR i, count: INTEGER;
newS: STRING;
currChar: CHAR;
BEGIN (* CompressText *)
currChar := s[1];
newS := '';
count := 1;
FOR i := 1 TO Length(s) DO BEGIN
IF (s[i] = currChar) THEN BEGIN
IF (i <> 1) THEN
Inc(count);
END ELSE BEGIN
IF (count > 2) THEN BEGIN
newS := newS + s[i - 1] + ToString(count);
currChar := s[i];
count := 1;
END ELSE IF (count = 2) THEN BEGIN
newS := newS + s[i - 1] + s[i - 1];
currChar := s[i];
count := 1;
END ELSE BEGIN
newS := newS + s[i - 1];
currChar := s[i];
count := 1;
END; (* IF *)
END; (* IF *)
END; (* FOR *)
s := newS + ENDLINE_SYMBOL;
END; (* CompressText *)
PROCEDURE DecompressText(VAR s: STRING);
VAR i, j: INTEGER;
newS, count: STRING;
BEGIN (* DecompressText *)
newS := '';
i := 1;
WHILE (s[i] <> ENDLINE_SYMBOL) DO BEGIN
IF (s[i + 1] in ['0'..'9']) THEN BEGIN
IF (s[i + 2] in ['0'..'9']) THEN
count := Copy(s, i + 1, 2)
ELSE
count := Copy(s, i + 1, 1);
FOR j := 1 TO ToInt(count) DO BEGIN
newS := newS + s[i];
END; (* FOR *)
IF (ToInt(count) > 9) THEN
i := i + 3
ELSE
i := i + 2;
END ELSE BEGIN
newS := newS + s[i];
Inc(i);
END; (* IF *)
END; (* WHILE *)
s := newS + ENDLINE_SYMBOL;
END; (* DecompressText *)
PROCEDURE TransformText(VAR s: STRING; compressMode: BOOLEAN);
BEGIN (* TransformText *)
IF (compressMode) THEN BEGIN
CompressText(s);
END ELSE BEGIN
DecompressText(s);
END; (* IF *)
END; (* TransformText *)
VAR
compressMode: BOOLEAN;
stdOutput: TEXT;
inputFileName, outputFileName: STRING;
line: STRING;
hasOutput: BOOLEAN;
BEGIN (* RLE *)
stdOutput := output;
compressMode := TRUE;
hasOutput := TRUE;
IF (ParamCount = 0) THEN BEGIN
WriteLn('ERROR: No input file defined');
WriteLn('Usage: RLE.exe [-c | -d] <input.txt> [<output.txt>]');
HALT;
END ELSE IF (ParamCount = 1) THEN BEGIN
IF ((ParamStr(1) = '-c') OR (ParamStr(1) = '-d')) THEN BEGIN
WriteLn('ERROR: No Input File defined');
WriteLn('Usage: RLE.exe [-c | -d] <input.txt> [<output.txt>]');
HALT;
END ELSE BEGIN
inputFileName := ParamStr(1);
Assign(input, inputFileName);
{$I-}
Reset(input);
CheckIOError('Cannot open input file');
{$I+}
END; (* IF *)
END ELSE IF (ParamCount = 2) THEN BEGIN
IF ((ParamStr(1) = '-c') OR (ParamStr(1) = '-d')) THEN BEGIN
compressMode := (ParamStr(1) = '-c');
inputFileName := ParamStr(2);
Assign(input, inputFileName);
{$I-}
Reset(input);
CheckIOError('Cannot open input file');
{$I+}
END ELSE BEGIN
inputFileName := ParamStr(1);
Assign(input, inputFileName);
{$I-}
Reset(input);
CheckIOError('Cannot open input file');
{$I+}
outputFileName := ParamStr(2);
Assign(output, outputFileName);
{$I-}
Rewrite(output);
CheckIOError('Cannot write to output file.');
hasOutput := TRUE;
{$I+}
END; (* IF *)
END ELSE IF (ParamCount = 3) THEN BEGIN
compressMode := (ParamStr(1) = '-c');
inputFileName := ParamStr(2);
Assign(input, inputFileName);
{$I-}
Reset(input);
CheckIOError('Cannot open input file');
{$I+}
outputFileName := ParamStr(3);
Assign(output, outputFileName);
{$I-}
Rewrite(output);
CheckIOError('Cannot write to output file.');
hasOutput := TRUE;
{$I+}
END ELSE BEGIN
WriteLn('ERROR: Unknown number of parameters.');
WriteLn('Usage: RLE.exe [-c | -d] <input.txt> [<output.txt>]');
HALT;
END; (* IF *)
REPEAT
ReadLn(input, line);
IF (line[Length(line)] <> ENDLINE_SYMBOL) THEN BEGIN
WriteLn('Invalid End of Line Symbol. Expected "$"');
HALT;
END; (* IF *)
TransformText(line, compressMode);
WriteLn(output, line);
UNTIL (Eof(input)); (* REPEAT *)
Close(input);
IF (hasOutput) THEN BEGIN
Close(output);
END; (* IF *)
output := stdOutput;
WriteLn('Done!');
END. (* RLE *) |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.IOUtils;
interface
// File Locations in Internal memory. (Accessible only to the program.
// Not accessible to anyone without rooting the Android system.)
// Files written here are deleted when uninstalling the application.)
function GetFilesDir: string;
function GetCacheDir: string;
function GetLibraryPath: string;
// File Locations in External memory. (Accessible only to the program, but easily
// readable mounting the external storage as a drive in a computer.
// Files written here are deleted when uninstalling the application.)
function GetExternalFilesDir: string;
function GetExternalCacheDir: string;
function GetExternalPicturesDir: string;
function GetExternalCameraDir: string;
/// <summary>Get documents from external storage</summary>
function GetExternalDocumentsDir: string;
function GetExternalDownloadsDir: string;
function GetExternalMoviesDir: string;
function GetExternalMusicDir: string;
function GetExternalAlarmsDir: string;
function GetExternalRingtonesDir: string;
// File Locations in External memory. (Accessible to all programs, easily
// readable mounting the external storage as a drive in a computer.
// Files written here are preserved when uninstalling the application.)
function GetSharedFilesDir: string;
function GetSharedPicturesDir: string;
function GetSharedCameraDir: string;
/// <summary>Get Shared documents from external storage</summary>
function GetSharedDocumentsDir: string;
function GetSharedDownloadsDir: string;
function GetSharedMoviesDir: string;
function GetSharedMusicDir: string;
function GetSharedAlarmsDir: string;
function GetSharedRingtonesDir: string;
implementation
uses
Androidapi.Jni,
Androidapi.NativeActivity;
const
sDocuments = 'Documents'; { do not translate }
cPathDelimiter = '/'; { do not translate }
procedure RemoveLastFolder(var APath: string);
var
I: Integer;
begin
for I := High(APath) downto 0 do
begin
if APath[I] = cPathDelimiter then
Break;
end;
SetLength(APath, I);
end;
function GetJniPath(MethodName, Signature: MarshaledAString): string;
var
PEnv: PJniEnv;
ContextClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
GetPathMethod: JNIMethodID;
StrPathObject: JNIObject;
FileObject: JNIObject;
begin
Result := '';
PJavaVM(System.JavaMachine)^.AttachCurrentThread(System.JavaMachine, @PEnv, nil);
ContextClass := PEnv^.GetObjectClass(PEnv, System.JavaContext);
GetMethod := PEnv^.GetMethodID(PEnv, ContextClass, MethodName, Signature);
FileObject := PEnv^.CallObjectMethodA(PEnv, System.JavaContext, GetMethod, PJNIValue(ArgsToJNIValues([nil])));
if FileObject <> nil then
begin
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
GetPathMethod := PEnv^.GetMethodID(PEnv, FileClass, 'getPath', '()Ljava/lang/String;');
StrPathObject := PEnv^.CallObjectMethodA(PEnv, FileObject, GetPathMethod, PJNIValue(ArgsToJNIValues([])));
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
end;
PEnv^.DeleteLocalRef(PEnv, ContextClass);
end;
{
public static String constants related to common directories.
DIRECTORY_ALARMS Standard directory in which to place any audio files that should be in the list of alarms that the user can select (not as regular music).
DIRECTORY_DCIM The traditional location for pictures and videos when mounting the device as a camera.
DIRECTORY_DOCUMENTS Standard directory in which to place documents that have been created by the user.
DIRECTORY_DOWNLOADS Standard directory in which to place files that have been downloaded by the user.
DIRECTORY_MOVIES Standard directory in which to place movies that are available to the user.
DIRECTORY_MUSIC Standard directory in which to place any audio files that should be in the regular list of music for the user.
DIRECTORY_NOTIFICATIONS Standard directory in which to place any audio files that should be in the list of notifications that the user can select (not as regular music).
DIRECTORY_PICTURES Standard directory in which to place pictures that are available to the user.
DIRECTORY_PODCASTS Standard directory in which to place any audio files that should be in the list of podcasts that the user can select (not as regular music).
DIRECTORY_RINGTONES Standard directory in which to place any audio files that should be in the list of ringtones that the user can select (not as regular music).
}
type
TCustomPathType = (cpNONE, cpALARMS, cpDCIM, cpDOCUMENTS, cpDOWNLOADS, cpMOVIES, cpMUSIC, cpNOTIFICATIONS, cpPICTURES,
cpPODCASTS, cpRINGTONES);
const
StrPathType: array [TCustomPathType] of MarshaledAString = ('', 'DIRECTORY_ALARMS', 'DIRECTORY_DCIM', 'DIRECTORY_DOCUMENTS',
'DIRECTORY_DOWNLOADS', 'DIRECTORY_MOVIES', 'DIRECTORY_MUSIC', 'DIRECTORY_NOTIFICATIONS', 'DIRECTORY_PICTURES',
'DIRECTORY_PODCASTS', 'DIRECTORY_RINGTONES'
); { do not translate }
function GetJniCustomPath(MethodName, Signature: MarshaledAString; PathType:TCustomPathType; IsStatic: Boolean = False): string;
var
PEnv: PJniEnv;
ContextClass, EnvironmentClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
GetPathMethod: JNIMethodID;
StrPathObject: JNIObject;
CustomPathObject: JNIObject;
FileObject: JNIObject;
PathFieldID: JNIFieldID;
begin
Result := '';
PJavaVM(System.JavaMachine)^.AttachCurrentThread(System.JavaMachine, @PEnv, nil);
ContextClass := PEnv^.GetObjectClass(PEnv, System.JavaContext);
EnvironmentClass := PEnv^.FindClass(PEnv, 'android/os/Environment');
if PathType = cpNONE then
PathFieldID := nil
else
begin
PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, StrPathType[PathType], 'Ljava/lang/String;');
// Swallow any exception that occurred under JNI if GetStaticFieldID failed to find the Field and returned nil.
if PEnv^.ExceptionCheck(PEnv) = 1 then
PEnv^.ExceptionClear(PEnv);
end;
// If the PathType cannot be obtained from the system return a blank path. That way we can try an alternate one.
if not ((PathFieldID = nil) and (PathType <> cpNONE)) then
begin
if PathFieldID = nil then
CustomPathObject := nil
else
CustomPathObject := PEnv^.GetStaticObjectField(PEnv, EnvironmentClass, PathFieldID);
if IsStatic then
begin
GetMethod := PEnv^.GetStaticMethodID(PEnv, EnvironmentClass, MethodName, Signature);
FileObject := PEnv^.CallStaticObjectMethodA(PEnv, EnvironmentClass, GetMethod, PJNIValue(ArgsToJNIValues([CustomPathObject])));
end
else begin
GetMethod := PEnv^.GetMethodID(PEnv, ContextClass, MethodName, Signature);
FileObject := PEnv^.CallObjectMethodA(PEnv, System.JavaContext, GetMethod, PJNIValue(ArgsToJNIValues([CustomPathObject])));
end;
if FileObject <> nil then
begin
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
GetPathMethod := PEnv^.GetMethodID(PEnv, FileClass, 'getPath', '()Ljava/lang/String;');
StrPathObject := PEnv^.CallObjectMethodA(PEnv, FileObject, GetPathMethod, PJNIValue(ArgsToJNIValues([])));
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
end;
if CustomPathObject <> nil then
PEnv^.DeleteLocalRef(PEnv, CustomPathObject);
end;
PEnv^.DeleteLocalRef(PEnv, EnvironmentClass);
PEnv^.DeleteLocalRef(PEnv, ContextClass);
end;
function GetLibraryPath: string;
var
PEnv: PJniEnv;
ContextClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
PropertyID: JNIFieldID;
StrPathObject: JNIObject;
FileObject: JNIObject;
begin
Result := '';
PJavaVM(System.JavaMachine)^.AttachCurrentThread(System.JavaMachine, @PEnv, nil);
ContextClass := PEnv^.GetObjectClass(PEnv, System.JavaContext);
GetMethod := PEnv^.GetMethodID(PEnv, ContextClass, 'getApplicationInfo', '()Landroid/content/pm/ApplicationInfo;');
FileObject := PEnv^.CallObjectMethodA(PEnv, System.JavaContext, GetMethod, PJNIValue(ArgsToJNIValues([nil])));
if FileObject <> nil then
begin
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
PropertyID := PEnv^.GetFieldID(PEnv, FileClass, 'nativeLibraryDir', 'Ljava/lang/String;');
StrPathObject := PEnv^.GetObjectField(PEnv, FileObject, PropertyID);
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
end;
PEnv^.DeleteLocalRef(PEnv, ContextClass);
end;
function GetFilesDir: string;
begin
{ Retrieving it via JNI, ensures that the retrieved path exists.
The folder is created if it does not exist. This way we can avoid the problem
that if we do it via NativeActivity we can have problems trying to write to
the folder if we do not do a previous ForceDirectories.
}
Result := GetJniPath('getFilesDir', '()Ljava/io/File;');
end;
function GetExternalFilesDir: string;
begin
{ Retrieving it via JNI, ensures that the retrieved path exists.
The folder is created if it does not exist. This way we can avoid the problem
that if we do it via NativeActivity we can have problems trying to write to
the folder if we do not do a previous ForceDirectories.
}
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpNONE);
end;
function GetCacheDir: string;
begin
Result := GetJniPath('getCacheDir', '()Ljava/io/File;');
end;
function GetExternalCacheDir: string;
begin
Result := GetJniPath('getExternalCacheDir', '()Ljava/io/File;');
end;
function GetExternalPicturesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpPICTURES);
end;
function GetExternalCameraDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpDCIM);
end;
function GetExternalDocumentsDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpDOCUMENTS);
if Result = '' then
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpNONE) + cPathDelimiter + sDocuments;
end;
function GetExternalDownloadsDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS);
end;
function GetExternalMoviesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpMOVIES);
end;
function GetExternalMusicDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpMUSIC);
end;
function GetExternalAlarmsDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpALARMS);
end;
function GetExternalRingtonesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpRINGTONES);
end;
// Shared Folders functions.
function GetSharedFilesDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS, True);
RemoveLastFolder(Result);
end;
function GetSharedPicturesDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpPICTURES, True);
end;
function GetSharedCameraDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDCIM, True);
end;
function GetSharedDocumentsDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOCUMENTS, True);
if Result = '' then
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS, True);
RemoveLastFolder(Result);
Result := Result + cPathDelimiter + sDocuments;
end;
end;
function GetSharedDownloadsDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS, True);
end;
function GetSharedMoviesDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpMOVIES, True);
end;
function GetSharedMusicDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpMUSIC, True);
end;
function GetSharedAlarmsDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpALARMS, True);
end;
function GetSharedRingtonesDir: string;
begin
Result := GetJniCustomPath('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpRINGTONES, True);
end;
end.
|
// **************************************************************************************************
// Delphi Aio Library.
// Unit Aio
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 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
//
//
// The Original Code is Aio.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit Aio;
interface
uses Classes, Greenlets, Gevent, Hub, SysUtils, sock, RegularExpressions,
SyncObjs, IdGlobal,
{$IFDEF MSWINDOWS}
Winapi.Windows
{$ELSE}
{$ENDIF};
const
CR = #$0d;
LF = #$0a;
CRLF = CR + LF;
type
IAioProvider = interface
['{2E14A16F-BDF8-4116-88A6-41C18591D444}']
function GetFd: THandle;
// io operations
// if Size > 0 -> Will return control when all bytes will be transmitted
// if Size < 0 -> Will return control when the operation is completed partially
// if Size = 0 -> Will return data buffer length of driver
function Read(Buf: Pointer; Size: Integer): LongWord;
function Write(Buf: Pointer; Size: Integer): LongWord;
// stream interfaces
function AsStream: TStream;
function AsFile(Size: LongWord): TStream;
// extended interfaces
// strings
function GetEncoding: TEncoding;
procedure SetEncoding(Value: TEncoding);
function GetEOL: string; // end of line ex: LF or CRLF
procedure SetEOL(const Value: string);
function ReadLn: string; overload; // raise AEOF in end of stream
function ReadLn(out S: string): Boolean; overload;
function ReadLns: TGenerator<string>; overload;
function ReadLns(const EOLs: array of string): TGenerator<string>; overload;
function ReadRegEx(const RegEx: TRegEx; out S: string): Boolean; overload;
function ReadRegEx(const Pattern: string; out S: string): Boolean; overload;
function ReadRegEx(const RegEx: TRegEx): TGenerator<string>; overload;
function ReadRegEx(const Pattern: string): TGenerator<string>; overload;
function ReadString(Enc: TEncoding; out Buf: string; const EOL: string = CRLF): Boolean;
procedure WriteLn(const S: string = ''); overload;
procedure WriteLn(const S: array of string); overload;
function WriteString(Enc: TEncoding; const Buf: string; const EOL: string = CRLF): Boolean;
// others
function ReadBytes(out Buf: TBytes): Boolean; overload;
function ReadBytes(out Buf: TIdBytes): Boolean; overload;
function ReadByte(out Buf: Byte): Boolean;
function ReadInteger(out Buf: Integer): Boolean;
function ReadSmallInt(out Buf: SmallInt): Boolean;
function ReadSingle(out Buf: Single): Boolean;
function ReadDouble(out Buf: Double): Boolean;
function WriteBytes(const Bytes: TBytes): Boolean;
function WriteByte(const Value: Byte): Boolean;
function WriteInteger(const Value: Integer): Boolean;
function WriteSmallInt(const Value: SmallInt): Boolean;
function WriteSingle(const Value: Single): Boolean;
function WriteDouble(const Value: Double): Boolean;
end;
IAioFile = interface(IAioProvider)
['{94C6A1A6-790D-4993-8C47-25B11E9994EC}']
function GetPosition: Int64;
procedure SetPosition(const Value: Int64);
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
end;
TAddress = record
IP: string;
Port: Integer;
function ToString: string;
constructor Create(const IP: string; Port: Integer);
end;
IAioTcpSocket = interface(IAioProvider)
['{AB418388-935A-4D8E-B772-E7C47760BAC5}']
procedure Bind(const Address: string; Port: Integer);
procedure Listen;
function Accept: IAioTcpSocket;
function Connect(const Address: string; Port: Integer; Timeout: LongWord): Boolean;
procedure Disconnect;
function OnConnect: TGevent;
function OnDisconnect: TGevent;
function LocalAddress: TAddress;
function RemoteAddress: TAddress;
end;
IAioUdpSocket = interface(IAioProvider)
['{58614476-06E6-4C46-BAE5-CF69D129FD93}']
procedure Bind(const Address: string; Port: Integer);
function GetRemoteAddress: TAddress;
procedure SetRemoteAddress(const Value: TAddress);
end;
TComState = (
evBreak, evCTS, evDSR, evERR, evRING, evRLSD, evRXCHAR,
evRXFLAG, evTXEMPTY
);
TEventMask = set of TComState;
IAioComPort = interface(IAioProvider)
['{DC8E2309-EE04-4D49-AB83-36ED2D5FD7D3}']
function EventMask: TEventMask;
function OnState: TGevent;
end;
IAioNamedPipe = interface(IAioProvider)
['{3E60B4DE-3EEA-425C-8902-4A16DA187F28}']
// server-side
procedure MakeServer(BufSize: Longword=4096);
function WaitConnection(Timeout: LongWord = INFINITE): Boolean;
// client-side
procedure Open;
// not remove data from read buffer
function Peek: TBytes;
end;
IAioConsoleApplication = interface
['{061B7959-057F-447F-9086-26FC6D93F26F}']
// encodings
function GetEncoding: TEncoding;
procedure SetEncoding(Value: TEncoding);
function GetEOL: string;
procedure SetEOL(const Value: string);
// in-out
function StdIn: IAioProvider;
function StdOut: IAioProvider;
function StdError: IAioProvider;
// process-specific
function ProcessId: LongWord;
function OnTerminate: TGevent;
function GetExitCode(const Block: Boolean = True): Integer;
procedure Terminate(ExitCode: Integer = 0);
end;
IAioConsole = interface
['{6D99A321-A851-4FA6-9E19-649F085ADCD1}']
function StdIn: IAioProvider;
function StdOut: IAioProvider;
function StdError: IAioProvider;
end;
IAioSoundCard = interface(IAioProvider)
['{E16E70D3-7052-431C-BD94-38B462D2B72F}']
end;
function MakeAioFile(const FileName: string; Mode: Word): IAioFile;
function MakeAioTcpSocket: IAioTcpSocket; overload;
function MakeAioUdpSocket: IAioUdpSocket;
function MakeAioComPort(const FileName: string): IAioComPort;
function MakeAioNamedPipe(const Name: string): IAioNamedPipe;
function MakeAioConsoleApp(const Cmd: string; const Args: array of const;
const WorkDir: string = ''): IAioConsoleApplication;
function MakeAioConsole: IAioConsole;
function MakeAioSoundCard(SampPerFreq: LongWord; Channels: LongWord = 1;
BitsPerSamp: LongWord = 16): IAioSoundCard;
implementation
uses Math, MMSystem, AioImpl;
function MakeAioFile(const FileName: string; Mode: Word): IAioFile;
var
Impl: TAioFile;
begin
Impl := TAioFile.Create(FileName, Mode);
Result := Impl;
end;
function MakeAioTcpSocket: IAioTcpSocket;
var
Impl: TAioTCPSocket;
begin
Impl := TAioTCPSocket.Create;
Result := Impl;
end;
function MakeAioUdpSocket: IAioUdpSocket;
var
Impl: TAioUDPSocket;
begin
Impl := TAioUDPSocket.Create;
Result := Impl;
end;
function MakeAioComPort(const FileName: string): IAioComPort;
var
Impl: TAioComPort;
begin
Impl := TAioComPort.Create(FileName);
Result := Impl;
end;
function MakeAioNamedPipe(const Name: string): IAioNamedPipe;
var
Impl: TAioNamedPipe;
begin
Impl := TAioNamedPipe.Create(Name);
Result := Impl;
end;
function MakeAioConsoleApp(const Cmd: string; const Args: array of const;
const WorkDir: string = ''): IAioConsoleApplication;
var
Impl: TAioConsoleApplication;
begin
Impl := TAioConsoleApplication.Create(Cmd, Args, WorkDir);
Result := Impl;
end;
function MakeAioConsole: IAioConsole;
var
Impl: TAioConsole;
begin
Impl := TAioConsole.Create;
Result := Impl;
end;
function MakeAioSoundCard(SampPerFreq: LongWord; Channels: LongWord = 1;
BitsPerSamp: LongWord = 16): IAioSoundCard;
var
Impl: TAioSoundCard;
begin
Impl := TAioSoundCard.Create(SampPerFreq, Channels, BitsPerSamp);
Result := Impl;
end;
{ TAddress }
constructor TAddress.Create(const IP: string; Port: Integer);
begin
Self.IP := IP;
Self.Port := Port;
end;
function TAddress.ToString: string;
begin
Result := Format('%s:%d', [IP, Port])
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 13 O(N2) Dfs Algorithm
}
program
ConnectedComponents;
const
MaxN = 100;
var
N : Integer;
A : array [1 .. MaxN, 1 .. MaxN] of Integer;
M : array [1 .. MaxN] of Boolean;
I, J : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, A[I, J]); A[J, I] := A[I, J];
end;
Readln(F);
end;
Close(F);
Assign(F, 'output.txt');
ReWrite(F);
end;
procedure DFS (V : Integer);
var
I : Integer;
begin
M[V] := True;
Write(F, V, ' ');
for I := 1 to N do
if (A[V, I] = 1) and not M[I] then
DFS(I);
end;
procedure DfdAlg;
begin
J := 0;
for I := 1 to N do
if not M[I] then
begin
Inc(J);
DFS(I);
Writeln(F);
end;
ReWrite(F);
Writeln(F, J);
FillChar(M, SizeOf(M), 0);
for I := 1 to N do
if not M[I] then
begin
DFS(I);
Writeln(F);
end;
end;
begin
ReadInput;
DfdAlg;
Close(F);
end. |
/// <summary>
/// TStreamOp is based on TStreamOp form PascalCoin Core by Alfred Molina
/// </summary>
unit PascalCoin.StreamOp;
interface
uses PascalCoin.Wallet.Interfaces, PascalCoin.Utils.Interfaces, System.Classes,
System.SysUtils;
type
TStreamOp = Class(TInterfacedObject, IStreamOp)
public
function ReadRawBytes(Stream: TStream; var Value: TRawBytes): Integer;
function WriteRawBytes(Stream: TStream; const Value: TRawBytes)
: Integer; overload;
function ReadString(Stream: TStream; var Value: String): Integer;
function WriteAccountKey(Stream: TStream; const Value: IPublicKey): Integer;
function ReadAccountKey(Stream: TStream; var Value: IPublicKey): Integer;
function SaveStreamToRawBytes(Stream: TStream): TRawBytes;
procedure LoadStreamFromRawBytes(Stream: TStream; const raw: TRawBytes);
End;
implementation
{ TStreamOp }
uses PascalCoin.Helpers;
procedure TStreamOp.LoadStreamFromRawBytes(Stream: TStream;
const raw: TRawBytes);
begin
Stream.WriteBuffer(raw[Low(raw)], Length(raw));
end;
function TStreamOp.ReadAccountKey(Stream: TStream;
var Value: IPublicKey): Integer;
begin
end;
function TStreamOp.ReadRawBytes(Stream: TStream; var Value: TRawBytes): Integer;
Var
w: Word;
begin
if Stream.Size - Stream.Position < 2 then
begin
SetLength(Value, 0);
Result := -1;
Exit;
end;
Stream.Read(w, 2);
if Stream.Size - Stream.Position < w then
begin
Stream.Position := Stream.Position - 2; // Go back!
SetLength(Value, 0);
Result := -1;
Exit;
end;
SetLength(Value, w);
if (w > 0) then
begin
Stream.ReadBuffer(Value[Low(Value)], w);
end;
Result := w + 2;
end;
function TStreamOp.ReadString(Stream: TStream; var Value: String): Integer;
var
raw: TRawBytes;
begin
Result := ReadRawBytes(Stream, raw);
Value := raw.ToString;
end;
function TStreamOp.SaveStreamToRawBytes(Stream: TStream): TRawBytes;
begin
SetLength(Result, Stream.Size);
Stream.Position := 0;
Stream.ReadBuffer(Result[Low(Result)], Stream.Size);
end;
function TStreamOp.WriteAccountKey(Stream: TStream;
const Value: IPublicKey): Integer;
begin
end;
function TStreamOp.WriteRawBytes(Stream: TStream;
const Value: TRawBytes): Integer;
Var
w: Word;
begin
if (Length(Value) > (256 * 256)) then
begin
raise Exception.Create('Invalid stream size! ' + Inttostr(Length(Value)));
end;
w := Length(Value);
Stream.Write(w, 2);
if (w > 0) then
Stream.WriteBuffer(Value[Low(Value)], Length(Value));
Result := w + 2;
end;
end.
|
{ Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. }
function CPackGetCustomInstallationMessage(Param: String): String;
begin
Result := SetupMessage(msgCustomInstallation);
end;
{ Downloaded components }
#ifdef CPackDownloadCount
const
NO_PROGRESS_BOX = 4;
RESPOND_YES_TO_ALL = 16;
var
CPackDownloadPage: TDownloadWizardPage;
CPackShell: Variant;
<event('InitializeWizard')>
procedure CPackInitializeWizard();
begin
CPackDownloadPage := CreateDownloadPage(SetupMessage(msgWizardPreparing), SetupMessage(msgPreparingDesc), nil);
CPackShell := CreateOleObject('Shell.Application');
end;
<event('NextButtonClick')>
function CPackNextButtonClick(CurPageID: Integer): Boolean;
begin
if CurPageID = wpReady then
begin
CPackDownloadPage.Clear;
CPackDownloadPage.Show;
#sub AddDownload
if WizardIsComponentSelected('{#CPackDownloadComponents[i]}') then
#emit "CPackDownloadPage.Add('" + CPackDownloadUrls[i] + "', '" + CPackDownloadArchives[i] + ".zip', '" + CPackDownloadHashes[i] + "');"
#endsub
#define i
#for {i = 0; i < CPackDownloadCount; i++} AddDownload
#undef i
try
try
CPackDownloadPage.Download;
Result := True;
except
if not CPackDownloadPage.AbortedByUser then
SuppressibleMsgBox(AddPeriod(GetExceptionMessage), mbCriticalError, MB_OK, IDOK);
Result := False;
end;
finally
CPackDownloadPage.Hide;
end;
end else
Result := True;
end;
procedure CPackExtractFile(ArchiveName, FileName: String);
var
ZipFileName: String;
ZipFile: Variant;
Item: Variant;
TargetFolderName: String;
TargetFolder: Variant;
begin
TargetFolderName := RemoveBackslashUnlessRoot(ExpandConstant('{tmp}\' + ArchiveName + '\' + ExtractFileDir(FileName)));
ZipFileName := ExpandConstant('{tmp}\' + ArchiveName + '.zip');
if not DirExists(TargetFolderName) then
if not ForceDirectories(TargetFolderName) then
RaiseException(Format('Target path "%s" cannot be created', [TargetFolderName]));
ZipFile := CPackShell.NameSpace(ZipFileName);
if VarIsClear(ZipFile) then
RaiseException(Format('Cannot open ZIP file "%s" or does not exist', [ZipFileName]));
Item := ZipFile.ParseName(FileName);
if VarIsClear(Item) then
RaiseException(Format('Cannot find "%s" in "%s" ZIP file', [FileName, ZipFileName]));
TargetFolder := CPackShell.NameSpace(TargetFolderName);
if VarIsClear(TargetFolder) then
RaiseException(Format('Target path "%s" does not exist', [TargetFolderName]));
TargetFolder.CopyHere(Item, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;
#endif
|
unit BaseTestProcess;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is BaseTestProcess, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ delphi }
Classes,
{ dunit }
TestFrameWork,
{ local }
JcfStringUtils,
BaseVisitor,
Converter, ConvertTypes;
type
TBaseTestProcess = class(TTestCase)
private
fcConvert: TConverter;
fcMessages: TStringList;
procedure OnStatusMessage(const psUnit, psMessage: string;
const peMessageType: TStatusMessageType;
const piY, piX: integer);
protected
procedure TestNoWarnings(const psUnit: string);
procedure TestWarnings(const psUnit: string; const psWarningMatch: string); overload;
procedure TestWarnings(const psUnit: string;
const psWarningMatches: array of string); overload;
procedure TestWarnings(const psUnit: string; const piMatchCount: integer;
const psWarningMatches: array of string); overload;
procedure TestProcessResult(processType: TTreeNodeVisitorType;
const psIn, psOut: string);
procedure TestFormatResult(const psIn, psOut: string);
procedure TestFormatPartResult(const psIn, psOut: string; const piStart, piEnd: integer);
protected
procedure SetUp; override;
procedure TearDown; override;
published
end;
const
INTERFACE_HEADER = 'unit Test;' + NativeLineBreak +
'interface' + NativeLineBreak;
UNIT_HEADER = INTERFACE_HEADER +
'implementation' + NativeLineBreak;
UNIT_FOOTER = NativeLineBreak + 'end.';
SPACED_INTERFACE_HEADER = 'unit Test;' + NativeLineBreak + NativeLineBreak +
'interface' + NativeLineBreak + NativeLineBreak;
SPACED_UNIT_HEADER = SPACED_INTERFACE_HEADER +
'implementation' + NativeLineBreak;
implementation
uses
{ delphi }
SysUtils, Dialogs,
{ local }
TestConstants;
procedure TBaseTestProcess.Setup;
begin
inherited;
fcConvert := TConverter.Create;
fcMessages := TStringList.Create;
fcConvert.OnStatusMessage := OnStatusMessage;
InitTestSettings;
end;
procedure TBaseTestProcess.TearDown;
begin
FreeAndNil(fcConvert);
FreeAndNil(fcMessages);
end;
procedure TBaseTestProcess.TestWarnings(const psUnit, psWarningMatch: string);
begin
TestWarnings(psUnit, 1, [psWarningMatch]);
end;
procedure TBaseTestProcess.TestWarnings(const psUnit: string;
const psWarningMatches: array of string);
var
liCount: integer;
begin
liCount := High(psWarningMatches) - Low(psWarningMatches) + 1;
TestWarnings(psUnit, liCount, psWarningMatches);
end;
procedure TBaseTestProcess.TestWarnings(const psUnit: string;
const piMatchCount: integer; const psWarningMatches: array of string);
var
lbFound: boolean;
liLoop: integer;
begin
fcMessages.Clear;
fcConvert.InputCode := psUnit;
fcConvert.Convert;
// convert should work
//CheckEquals(False, fcConvert.ConvertError, fcConvert.ConvertErrorMessage);
// with messages
CheckEquals(piMatchCount, fcMessages.Count, 'Wrong number of messages ' + fcMessages.text);
for liLoop := Low(psWarningMatches) to High(psWarningMatches) do
begin
// containing certain text
lbFound := (StrIPos(psWarningMatches[liLoop], fcMessages.Text) > 0);
Check(lbFound, psWarningMatches[liLoop] + ' was not found in output ' +
fcMessages.Text);
end;
fcConvert.Clear;
end;
procedure TBaseTestProcess.TestNoWarnings(const psUnit: string);
begin
TestWarnings(psUnit, 0, []);
end;
function MarkReturns(const ps: string): string;
begin
Result := ps;
StrReplace(Result, NativeLineBreak, '-q' + NativeLineBreak, [rfReplaceAll]);
end;
function DiffText(const ps1, ps2: WideString): string;
var
psDiff1, psDiff2: string;
liStartDif: integer;
lsBeforeDif: string;
begin
liStartDif := 0;
psDiff1 := ps1;
psDiff2 := ps2;
// strip same chars on start
while (length(psDiff1) > 0) and (length(psDiff2) > 0) and (psDiff1[1] = psDiff2[1]) do
begin
psDiff1 := StrRestOf(psDiff1, 2);
psDiff2 := StrRestOf(psDiff2, 2);
inc(liStartDif);
end;
while (length(psDiff1) > 0) and (length(psDiff2) > 0) and
(psDiff1[length(psDiff1)] = psDiff2[length(psDiff2)]) do
begin
psDiff1 := StrChopRight(psDiff1, 1);
psDiff2 := StrChopRight(psDiff2, 1);
end;
lsBeforeDif := StrLeft(ps1, liStartDif);
Result := psDiff1 + '<->' + psDiff2 +
NativeLineBreak + 'at char ' + IntToStr(liStartDif) + NativeLineBreak +
' After: ' + NativeLineBreak +
lsBeforeDif + '-q';
end;
procedure TBaseTestProcess.TestProcessResult(processType: TTreeNodeVisitorType;
const psIn, psOut: string);
begin
// run just this process
fcConvert.SingleProcess := processType;
try
TestFormatResult(psIn, psOut);
finally
fcConvert.SingleProcess := nil;
end;
end;
procedure TBaseTestProcess.TestFormatResult(const psIn, psOut: string);
var
lsOut: string;
begin
fcMessages.Clear;
fcConvert.InputCode := psIn;
fcConvert.Convert;
if fcConvert.ConvertError then
lsOut := 'Convert error'
else
lsOut := fcConvert.OutputCode;
{ an extra return is attached from using a stringlist
if it wasn't there already
this is not ideal for TestTextAfterUnitEnd
but better than a trim
}
if (StrRight(lsOut, 2) = NativeLineBreak) then
begin
lsOut := StrChopRight(lsOut, 2);
end;
//(*
// debug
if (lsOut <> psOut) then
begin
ShowMessage(string(MarkReturns(lsOut)) +
NativeLineBreak + NativeLineBreak + '-- should have been --' +
NativeLineBreak + NativeLineBreak +
string(MarkReturns(psOut)));
ShowMessage(DiffText(lsOut, psOut));
// debug temp - use external diff tool(WinMerge) to compare them
//StringToFile('c:\t1.out', lsOut);
//StringToFile('c:\t2.out', psOut);
end;
//*)
CheckEquals(Length(psOut), Length(lsOut), 'Results length mismatch');
CheckEquals(psOut, lsOut, 'Bad result text');
end;
procedure TBaseTestProcess.TestFormatPartResult(const psIn, psOut: string; const piStart, piEnd: integer);
var
lsOut: string;
begin
fcMessages.Clear;
fcConvert.InputCode := psIn;
fcConvert.ConvertPart(piStart, piEnd);
lsOut := fcConvert.OutputCode;
{ an extra return is attached from using a stringlist
if it wasn't there already
this is not ideal for TestTextAfterUnitEnd
but better than a trim
}
if (StrRight(lsOut, 2) = NativeLineBreak) then
begin
lsOut := StrChopRight(lsOut, 2);
end;
{ }
// debug
if (lsOut <> psOut) then
begin
ShowMessage(string(MarkReturns(lsOut)) +
NativeLineBreak + NativeLineBreak + '-- should have been --' +
NativeLineBreak + NativeLineBreak +
string(MarkReturns(psOut)));
ShowMessage(DiffText(lsOut, psOut));
end;
{ }
CheckEquals(Length(psOut), Length(lsOut), 'Results length mismatch');
CheckEquals(psOut, lsOut, 'Bad result text');
end;
procedure TBaseTestProcess.OnStatusMessage(const psUnit, psMessage: string;
const peMessageType: TStatusMessageType;
const piY, piX: integer);
begin
fcMessages.Add(psMessage);
end;
end.
|
unit untEasyWorkFlowDiagramShadow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Variants, Dialogs, ExtCtrls, StdCtrls, ComCtrls, atDiagram;
type
TfrmEasyWorkFlowDiagramShadow = class(TForm)
UpDown1: TUpDown;
UpDown2: TUpDown;
PaintBox1: TPaintBox;
Label1: TLabel;
Panel1: TPanel;
ColorDialog1: TColorDialog;
Button1: TButton;
Button2: TButton;
PaintBox2: TPaintBox;
procedure Panel1Click(Sender: TObject);
procedure UpDown1ChangingEx(Sender: TObject; var AllowChange: Boolean;
NewValue: Smallint; Direction: TUpDownDirection);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure UpDown2ChangingEx(Sender: TObject; var AllowChange: Boolean;
NewValue: Smallint; Direction: TUpDownDirection);
procedure PaintBox1Paint(Sender: TObject);
procedure PaintBox2Paint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Shad: TBlockShadow;
function EditShadow(AShadow: TBlockShadow): Boolean;
end;
var
frmEasyWorkFlowDiagramShadow: TfrmEasyWorkFlowDiagramShadow;
implementation
{$R *.dfm}
function TfrmEasyWorkFlowDiagramShadow.EditShadow(AShadow: TBlockShadow): Boolean;
begin
Result := False;
shad.Assign(AShadow);
UpDown1.Position := shad.VOffset;
UpDown2.Position := shad.HOffset;
if shad.Visible then
panel1.Color := shad.Color
else
panel1.Color := clGray;
if (ShowModal = mrOk) then
begin
AShadow.Assign(shad);
Result := true;
end;
end;
procedure TfrmEasyWorkFlowDiagramShadow.Panel1Click(Sender: TObject);
begin
ColorDialog1.Color := Panel1.Color;
if Colordialog1.Execute then
begin
panel1.Color := ColorDialog1.Color;
shad.Color := ColorDialog1.Color;
PaintBox1.Invalidate;
end;
end;
procedure TfrmEasyWorkFlowDiagramShadow.UpDown1ChangingEx(Sender: TObject;
var AllowChange: Boolean; NewValue: Smallint;
Direction: TUpDownDirection);
begin
shad.VOffset := NewValue;
PaintBox1.Invalidate;
end;
procedure TfrmEasyWorkFlowDiagramShadow.FormCreate(Sender: TObject);
begin
shad := TBlockShadow.Create(nil);
end;
procedure TfrmEasyWorkFlowDiagramShadow.FormDestroy(Sender: TObject);
begin
shad.Free;
end;
procedure TfrmEasyWorkFlowDiagramShadow.UpDown2ChangingEx(Sender: TObject;
var AllowChange: Boolean; NewValue: Smallint;
Direction: TUpDownDirection);
begin
shad.HOffset := NewValue;
PaintBox1.Invalidate;
end;
procedure TfrmEasyWorkFlowDiagramShadow.PaintBox1Paint(Sender: TObject);
var
r: Trect;
begin
with PaintBox1.Canvas do
begin
Pen.Color := clSilver;
Pen.Width := 1;
Brush.Style := bsClear;
r := PaintBox1.ClientRect;
InflateRect(r,-1,-1);
Rectangle(r.Left,r.Top,r.Right, r.Bottom);
inflaterect(r,-15,-15);
Brush.Color := shad.Color;
Pen.Color := shad.Color;
OffsetRect(r,shad.HOffset, shad.VOffset);
Rectangle(r.Left,r.Top,r.Right, r.Bottom);
OffsetRect(r,-shad.HOffset, -shad.VOffset);
Pen.Color := clSilver;
Brush.Color := clWhite;
Rectangle(r.Left,r.Top,r.Right, r.Bottom);
end;
end;
procedure TfrmEasyWorkFlowDiagramShadow.PaintBox2Paint(Sender: TObject);
begin
paintbox2.Canvas.Brush.Color := panel1.Color;
paintbox2.Canvas.Pen.Color := panel1.Color;
PaintBox2.Canvas.FillRect(paintbox2.clientrect);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий тестовые данные }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.SpeedTest;
interface
uses Windows, SysUtils, Classes, SyncObjs,uBaseClasses,
MediaServer.Stream.Source,
MediaProcessing.Definitions;
type
//Класс, выполняющий непосредственно получение данных (видеопотока) из камеры
TMediaServerSourceSpeedTest = class (TMediaServerSource)
private
FEmitThread : TThreadObjectVar<TThread>;
procedure OnFrameReceived(aMediaType: TMediaType;
aData: pointer; aDataSize:cardinal;
const aFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal);
protected
function GetStreamType(aMediaType: TMediaType): TStreamType; override;
public
constructor Create; overload;
destructor Destroy; override;
procedure DoOpen(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
//property Framer: TStreamFramer read FFramer;
end;
implementation
uses Math,Forms,MediaServer.Workspace,uTrace,MediaStream.FramerFactory,ThreadNames;
type
TSpeedTestThread = class (TThread)
private
FOwner: TMediaServerSourceSpeedTest;
FOpenLock: TCriticalSection;
function StreamInfo: TBytes;
//function StreamType: TStreamType;
protected
procedure Execute; override;
public
constructor Create(aOwner: TMediaServerSourceSpeedTest);
destructor Destroy; override;
end;
{ TSpeedTestThread }
constructor TSpeedTestThread.Create(aOwner: TMediaServerSourceSpeedTest);
begin
FOwner:=aOwner;
FOpenLock:=TCriticalSection.Create;
inherited Create(false);
end;
destructor TSpeedTestThread.Destroy;
begin
inherited;
FreeAndNil(FOpenLock);
end;
function TSpeedTestThread.StreamInfo: TBytes;
begin
FOpenLock.Enter;
try
result:=nil;
finally
FOpenLock.Leave;
end;
end;
procedure TSpeedTestThread.Execute;
var
gDummyData : TBytes;
gDummyFormat : TMediaStreamDataHeader;
begin
SetCurrentThreadName('Source: '+ClassName);
SetLength(gDummyData,1024*100); //100 КБайт
gDummyFormat.Clear;
gDummyFormat.biStreamType:=stBinary;
Include(gDummyFormat.biFrameFlags,ffKeyFrame);
while not Terminated do
begin
try
FOwner.OnFrameReceived(mtVideo,gDummyData,Length(gDummyData),gDummyFormat,nil,0);
sleep(1);
except
on E:Exception do
;
end;
end;
end;
{ TMediaServerSourceSpeedTest }
constructor TMediaServerSourceSpeedTest.Create();
begin
Create(-1);
FEmitThread:=TThreadObjectVar<TThread>.Create;
//UsePrebuffer:=false;
end;
destructor TMediaServerSourceSpeedTest.Destroy;
begin
inherited;
FreeAndNil(FEmitThread);
end;
function TMediaServerSourceSpeedTest.DeviceType: string;
begin
result:='Virtual';
end;
function TMediaServerSourceSpeedTest.Name: string;
begin
result:='Speed Test';
end;
procedure TMediaServerSourceSpeedTest.OnFrameReceived(aMediaType: TMediaType;
aData: pointer; aDataSize:cardinal;
const aFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal);
begin
DoDataReceived(aFormat, aData,aDataSize, aInfo,aInfoSize);
end;
procedure TMediaServerSourceSpeedTest.DoOpen(aSync: boolean);
begin
if Opened then
exit;
Close;
FEmitThread.Value:=TSpeedTestThread.Create(self);
if Assigned(OnConnectionOk) then
OnConnectionOk(self);
end;
procedure TMediaServerSourceSpeedTest.DoClose;
begin
FEmitThread.FreeValue;
end;
function TMediaServerSourceSpeedTest.GetStreamType(aMediaType: TMediaType): TStreamType;
begin
result:=stBinary;
end;
function TMediaServerSourceSpeedTest.ConnectionString: string;
begin
result:='';
end;
function TMediaServerSourceSpeedTest.Opened: Boolean;
begin
result:=FEmitThread.Value<>nil;
end;
function TMediaServerSourceSpeedTest.StreamInfo: TBytes;
begin
FEmitThread.Lock;
try
CheckConnected;
result:=TSpeedTestThread(FEmitThread.Value).StreamInfo;
finally
FEmitThread.Unlock;
end;
end;
function TMediaServerSourceSpeedTest.PtzSupported: boolean;
begin
result:=false;
end;
procedure TMediaServerSourceSpeedTest.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
end;
end.
|
unit CAM_Base;
(*************************************************************************
DESCRIPTION : Camellia Encryption basic routines
REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18/D25S, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : about 4.5 KB static data
DISPLAY MODE : ---
REFERENCES : [1] K. Aoki et al, "Specification of Camellia - a 128-bit Block Cipher", V2.0, 2001
http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/01espec.pdf
[2] RFC 3713, "A Description of the Camellia Encryption Algorithm"
http://tools.ietf.org/html/rfc3713
[3] Camellia C reference code
http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/camellia.c.gz
REMARKS :- NTT has published NTT's open source codes of Camellia, but users
of this unit should read my legal.txt and NTT's Intellectual
Property Information: http://info.isl.ntt.co.jp/crypt/eng/info/chiteki.html
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 15.06.08 W.Ehrhardt Initial BP7 CAM_Init
0.11 15.06.08 we CAM_Encrypt for Keysize=128
0.12 16.06.08 we All key sizes, CAM_Decrypt, other compilers
0.13 16.06.08 we Feistel code from Spec C.2.6, some local types
0.14 17.06.08 we References and remarks
0.15 17.06.08 we Improved Feistel
0.16 21.06.08 we Fill word in ctx for align 8
0.17 26.07.08 we Removed BASM16 in Feistel
0.18 28.08.08 we 32 bit code / sboxes
0.19 28.08.08 we separate sections for 16 and 32 bit code
0.20 28.08.08 we BIT16: FLlayer with LRot_1
0.21 29.08.08 we BIT32/Cam_Decrypt: Fix final Xorblock and endian conversion
0.22 29.08.08 we Keep only 32 bit sboxes
0.23 29.08.08 we FLlayer_E/D procedures for 16/32 bit
0.24 29.08.08 we SwapHalf with TWA4
0.25 03.09.08 we BIT32: use bswap via conditional define
0.26 03.09.08 we Index/shift arrays [4..], no code for r=0 in rotblock
0.27 21.05.09 we Error codes for CCM mode and EAX all-in-one functions
0.28 28.07.10 we CAM_Err_CTR_SeekOffset, CAM_Err_Invalid_16Bit_Length
0.29 22.07.12 we 64-bit compatibility
0.30 25.12.12 we {$J+} if needed
0.31 08.11.17 we RB for CPUARM, CAM_Err_GCM errors
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i std.inc}
interface
const
CAM_Err_Invalid_Key_Size = -1; {Key size in bits not 128, 192, or 256}
CAM_Err_Invalid_Length = -3; {No full block for cipher stealing}
CAM_Err_Data_After_Short_Block = -4; {Short block must be last}
CAM_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
CAM_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
CAM_Err_EAX_Inv_Text_Length = -7; {More than 64K text length in EAX all-in-one for 16 Bit}
CAM_Err_EAX_Inv_TAG_Length = -8; {EAX all-in-one tag length not 0..16}
CAM_Err_EAX_Verify_Tag = -9; {EAX all-in-one tag does not compare}
CAM_Err_CCM_Hdr_length = -10; {CCM header length >= $FF00}
CAM_Err_CCM_Nonce_length = -11; {CCM nonce length < 7 or > 13}
CAM_Err_CCM_Tag_length = -12; {CCM tag length not in [4,6,8,19,12,14,16]}
CAM_Err_CCM_Verify_Tag = -13; {Computed CCM tag does not compare}
CAM_Err_CCM_Text_length = -14; {16 bit plain/cipher text length to large}
CAM_Err_CTR_SeekOffset = -15; {Negative offset in CAM_CTR_Seek}
CAM_Err_GCM_Verify_Tag = -17; {GCM all-in-one tag does not compare}
CAM_Err_GCM_Auth_After_Final = -18; {Auth after final or multiple finals}
CAM_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TCAMBlock = packed array[0..15] of byte; {128 bit block}
TCAMRndKey = packed array[0..16] of TCAMBlock; {Round key schedule}
PCAMBlock = ^TCAMBlock;
type
TCAMIncProc = procedure(var CTR: TCAMBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TCAMContext = packed record
IV : TCAMBlock; {IV or CTR }
buf : TCAMBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
KeyBits: word; {Bit size of key }
Fill : word; {Fill for Align 8 }
IncProc: TCAMIncProc; {Increment proc CTR-Mode}
EK : TCAMRndKey; {Extended round key }
end;
const
CAMBLKSIZE = sizeof(TCAMBlock); {Camellia block size in bytes}
{$ifdef CONST}
function CAM_Init(const Key; KeyBits: word; var ctx: TCAMContext): integer;
{-Camellia context/round key initialization}
{$ifdef DLL} stdcall; {$endif}
procedure CAM_Encrypt(var ctx: TCAMContext; const BI: TCAMBlock; var BO: TCAMBlock);
{-encrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure CAM_Decrypt(var ctx: TCAMContext; const BI: TCAMBlock; var BO: TCAMBlock);
{-decrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure CAM_XorBlock(const B1, B2: TCAMBlock; var B3: TCAMBlock);
{-xor two blocks, result in third}
{$ifdef DLL} stdcall; {$endif}
{$else}
function CAM_Init(var Key; KeyBits: word; var ctx: TCAMContext): integer;
{-Camellia context/round key initialization}
procedure CAM_Encrypt(var ctx: TCAMContext; var BI: TCAMBlock; var BO: TCAMBlock);
{-encrypt one block (in ECB mode)}
procedure CAM_Decrypt(var ctx: TCAMContext; var BI: TCAMBlock; var BO: TCAMBlock);
{-decrypt one block (in ECB mode)}
procedure CAM_XorBlock(var B1, B2: TCAMBlock; var B3: TCAMBlock);
{-xor two blocks, result in third}
{$endif}
procedure CAM_Reset(var ctx: TCAMContext);
{-Clears ctx fields bLen and Flag}
{$ifdef DLL} stdcall; {$endif}
procedure CAM_SetFastInit(value: boolean);
{-set FastInit variable}
{$ifdef DLL} stdcall; {$endif}
function CAM_GetFastInit: boolean;
{-Returns FastInit variable}
{$ifdef DLL} stdcall; {$endif}
implementation
{$ifdef D4Plus}
var
{$else}
{$ifdef J_OPT} {$J+} {$endif}
const
{$endif}
FastInit : boolean = true; {Clear only necessary context data at init}
{IV and buf remain uninitialized}
{common 16/32 bit helper types}
type
TWA2 = packed array[0..1] of longint; {64 bit block as two longints}
TWA4 = packed array[0..3] of longint; {Block as array of longint}
TWA8 = packed array[0..7] of longint; {Block as array of longint}
TE32 = packed array[0..67] of longint; {Rndkey as array of longints}
TRK4 = packed array[0..16] of TWA4; {Round key helper type}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9+ errors!}
{$endif}
const
sb1110: array[0..255] of longint = (
$70707000,$82828200,$2c2c2c00,$ececec00,$b3b3b300,$27272700,$c0c0c000,$e5e5e500,
$e4e4e400,$85858500,$57575700,$35353500,$eaeaea00,$0c0c0c00,$aeaeae00,$41414100,
$23232300,$efefef00,$6b6b6b00,$93939300,$45454500,$19191900,$a5a5a500,$21212100,
$ededed00,$0e0e0e00,$4f4f4f00,$4e4e4e00,$1d1d1d00,$65656500,$92929200,$bdbdbd00,
$86868600,$b8b8b800,$afafaf00,$8f8f8f00,$7c7c7c00,$ebebeb00,$1f1f1f00,$cecece00,
$3e3e3e00,$30303000,$dcdcdc00,$5f5f5f00,$5e5e5e00,$c5c5c500,$0b0b0b00,$1a1a1a00,
$a6a6a600,$e1e1e100,$39393900,$cacaca00,$d5d5d500,$47474700,$5d5d5d00,$3d3d3d00,
$d9d9d900,$01010100,$5a5a5a00,$d6d6d600,$51515100,$56565600,$6c6c6c00,$4d4d4d00,
$8b8b8b00,$0d0d0d00,$9a9a9a00,$66666600,$fbfbfb00,$cccccc00,$b0b0b000,$2d2d2d00,
$74747400,$12121200,$2b2b2b00,$20202000,$f0f0f000,$b1b1b100,$84848400,$99999900,
$dfdfdf00,$4c4c4c00,$cbcbcb00,$c2c2c200,$34343400,$7e7e7e00,$76767600,$05050500,
$6d6d6d00,$b7b7b700,$a9a9a900,$31313100,$d1d1d100,$17171700,$04040400,$d7d7d700,
$14141400,$58585800,$3a3a3a00,$61616100,$dedede00,$1b1b1b00,$11111100,$1c1c1c00,
$32323200,$0f0f0f00,$9c9c9c00,$16161600,$53535300,$18181800,$f2f2f200,$22222200,
$fefefe00,$44444400,$cfcfcf00,$b2b2b200,$c3c3c300,$b5b5b500,$7a7a7a00,$91919100,
$24242400,$08080800,$e8e8e800,$a8a8a800,$60606000,$fcfcfc00,$69696900,$50505000,
$aaaaaa00,$d0d0d000,$a0a0a000,$7d7d7d00,$a1a1a100,$89898900,$62626200,$97979700,
$54545400,$5b5b5b00,$1e1e1e00,$95959500,$e0e0e000,$ffffff00,$64646400,$d2d2d200,
$10101000,$c4c4c400,$00000000,$48484800,$a3a3a300,$f7f7f700,$75757500,$dbdbdb00,
$8a8a8a00,$03030300,$e6e6e600,$dadada00,$09090900,$3f3f3f00,$dddddd00,$94949400,
$87878700,$5c5c5c00,$83838300,$02020200,$cdcdcd00,$4a4a4a00,$90909000,$33333300,
$73737300,$67676700,$f6f6f600,$f3f3f300,$9d9d9d00,$7f7f7f00,$bfbfbf00,$e2e2e200,
$52525200,$9b9b9b00,$d8d8d800,$26262600,$c8c8c800,$37373700,$c6c6c600,$3b3b3b00,
$81818100,$96969600,$6f6f6f00,$4b4b4b00,$13131300,$bebebe00,$63636300,$2e2e2e00,
$e9e9e900,$79797900,$a7a7a700,$8c8c8c00,$9f9f9f00,$6e6e6e00,$bcbcbc00,$8e8e8e00,
$29292900,$f5f5f500,$f9f9f900,$b6b6b600,$2f2f2f00,$fdfdfd00,$b4b4b400,$59595900,
$78787800,$98989800,$06060600,$6a6a6a00,$e7e7e700,$46464600,$71717100,$bababa00,
$d4d4d400,$25252500,$ababab00,$42424200,$88888800,$a2a2a200,$8d8d8d00,$fafafa00,
$72727200,$07070700,$b9b9b900,$55555500,$f8f8f800,$eeeeee00,$acacac00,$0a0a0a00,
$36363600,$49494900,$2a2a2a00,$68686800,$3c3c3c00,$38383800,$f1f1f100,$a4a4a400,
$40404000,$28282800,$d3d3d300,$7b7b7b00,$bbbbbb00,$c9c9c900,$43434300,$c1c1c100,
$15151500,$e3e3e300,$adadad00,$f4f4f400,$77777700,$c7c7c700,$80808000,$9e9e9e00);
sb0222: array[0..255] of longint = (
$00e0e0e0,$00050505,$00585858,$00d9d9d9,$00676767,$004e4e4e,$00818181,$00cbcbcb,
$00c9c9c9,$000b0b0b,$00aeaeae,$006a6a6a,$00d5d5d5,$00181818,$005d5d5d,$00828282,
$00464646,$00dfdfdf,$00d6d6d6,$00272727,$008a8a8a,$00323232,$004b4b4b,$00424242,
$00dbdbdb,$001c1c1c,$009e9e9e,$009c9c9c,$003a3a3a,$00cacaca,$00252525,$007b7b7b,
$000d0d0d,$00717171,$005f5f5f,$001f1f1f,$00f8f8f8,$00d7d7d7,$003e3e3e,$009d9d9d,
$007c7c7c,$00606060,$00b9b9b9,$00bebebe,$00bcbcbc,$008b8b8b,$00161616,$00343434,
$004d4d4d,$00c3c3c3,$00727272,$00959595,$00ababab,$008e8e8e,$00bababa,$007a7a7a,
$00b3b3b3,$00020202,$00b4b4b4,$00adadad,$00a2a2a2,$00acacac,$00d8d8d8,$009a9a9a,
$00171717,$001a1a1a,$00353535,$00cccccc,$00f7f7f7,$00999999,$00616161,$005a5a5a,
$00e8e8e8,$00242424,$00565656,$00404040,$00e1e1e1,$00636363,$00090909,$00333333,
$00bfbfbf,$00989898,$00979797,$00858585,$00686868,$00fcfcfc,$00ececec,$000a0a0a,
$00dadada,$006f6f6f,$00535353,$00626262,$00a3a3a3,$002e2e2e,$00080808,$00afafaf,
$00282828,$00b0b0b0,$00747474,$00c2c2c2,$00bdbdbd,$00363636,$00222222,$00383838,
$00646464,$001e1e1e,$00393939,$002c2c2c,$00a6a6a6,$00303030,$00e5e5e5,$00444444,
$00fdfdfd,$00888888,$009f9f9f,$00656565,$00878787,$006b6b6b,$00f4f4f4,$00232323,
$00484848,$00101010,$00d1d1d1,$00515151,$00c0c0c0,$00f9f9f9,$00d2d2d2,$00a0a0a0,
$00555555,$00a1a1a1,$00414141,$00fafafa,$00434343,$00131313,$00c4c4c4,$002f2f2f,
$00a8a8a8,$00b6b6b6,$003c3c3c,$002b2b2b,$00c1c1c1,$00ffffff,$00c8c8c8,$00a5a5a5,
$00202020,$00898989,$00000000,$00909090,$00474747,$00efefef,$00eaeaea,$00b7b7b7,
$00151515,$00060606,$00cdcdcd,$00b5b5b5,$00121212,$007e7e7e,$00bbbbbb,$00292929,
$000f0f0f,$00b8b8b8,$00070707,$00040404,$009b9b9b,$00949494,$00212121,$00666666,
$00e6e6e6,$00cecece,$00ededed,$00e7e7e7,$003b3b3b,$00fefefe,$007f7f7f,$00c5c5c5,
$00a4a4a4,$00373737,$00b1b1b1,$004c4c4c,$00919191,$006e6e6e,$008d8d8d,$00767676,
$00030303,$002d2d2d,$00dedede,$00969696,$00262626,$007d7d7d,$00c6c6c6,$005c5c5c,
$00d3d3d3,$00f2f2f2,$004f4f4f,$00191919,$003f3f3f,$00dcdcdc,$00797979,$001d1d1d,
$00525252,$00ebebeb,$00f3f3f3,$006d6d6d,$005e5e5e,$00fbfbfb,$00696969,$00b2b2b2,
$00f0f0f0,$00313131,$000c0c0c,$00d4d4d4,$00cfcfcf,$008c8c8c,$00e2e2e2,$00757575,
$00a9a9a9,$004a4a4a,$00575757,$00848484,$00111111,$00454545,$001b1b1b,$00f5f5f5,
$00e4e4e4,$000e0e0e,$00737373,$00aaaaaa,$00f1f1f1,$00dddddd,$00595959,$00141414,
$006c6c6c,$00929292,$00545454,$00d0d0d0,$00787878,$00707070,$00e3e3e3,$00494949,
$00808080,$00505050,$00a7a7a7,$00f6f6f6,$00777777,$00939393,$00868686,$00838383,
$002a2a2a,$00c7c7c7,$005b5b5b,$00e9e9e9,$00eeeeee,$008f8f8f,$00010101,$003d3d3d);
sb3033: array[0..255] of longint = (
$38003838,$41004141,$16001616,$76007676,$d900d9d9,$93009393,$60006060,$f200f2f2,
$72007272,$c200c2c2,$ab00abab,$9a009a9a,$75007575,$06000606,$57005757,$a000a0a0,
$91009191,$f700f7f7,$b500b5b5,$c900c9c9,$a200a2a2,$8c008c8c,$d200d2d2,$90009090,
$f600f6f6,$07000707,$a700a7a7,$27002727,$8e008e8e,$b200b2b2,$49004949,$de00dede,
$43004343,$5c005c5c,$d700d7d7,$c700c7c7,$3e003e3e,$f500f5f5,$8f008f8f,$67006767,
$1f001f1f,$18001818,$6e006e6e,$af00afaf,$2f002f2f,$e200e2e2,$85008585,$0d000d0d,
$53005353,$f000f0f0,$9c009c9c,$65006565,$ea00eaea,$a300a3a3,$ae00aeae,$9e009e9e,
$ec00ecec,$80008080,$2d002d2d,$6b006b6b,$a800a8a8,$2b002b2b,$36003636,$a600a6a6,
$c500c5c5,$86008686,$4d004d4d,$33003333,$fd00fdfd,$66006666,$58005858,$96009696,
$3a003a3a,$09000909,$95009595,$10001010,$78007878,$d800d8d8,$42004242,$cc00cccc,
$ef00efef,$26002626,$e500e5e5,$61006161,$1a001a1a,$3f003f3f,$3b003b3b,$82008282,
$b600b6b6,$db00dbdb,$d400d4d4,$98009898,$e800e8e8,$8b008b8b,$02000202,$eb00ebeb,
$0a000a0a,$2c002c2c,$1d001d1d,$b000b0b0,$6f006f6f,$8d008d8d,$88008888,$0e000e0e,
$19001919,$87008787,$4e004e4e,$0b000b0b,$a900a9a9,$0c000c0c,$79007979,$11001111,
$7f007f7f,$22002222,$e700e7e7,$59005959,$e100e1e1,$da00dada,$3d003d3d,$c800c8c8,
$12001212,$04000404,$74007474,$54005454,$30003030,$7e007e7e,$b400b4b4,$28002828,
$55005555,$68006868,$50005050,$be00bebe,$d000d0d0,$c400c4c4,$31003131,$cb00cbcb,
$2a002a2a,$ad00adad,$0f000f0f,$ca00caca,$70007070,$ff00ffff,$32003232,$69006969,
$08000808,$62006262,$00000000,$24002424,$d100d1d1,$fb00fbfb,$ba00baba,$ed00eded,
$45004545,$81008181,$73007373,$6d006d6d,$84008484,$9f009f9f,$ee00eeee,$4a004a4a,
$c300c3c3,$2e002e2e,$c100c1c1,$01000101,$e600e6e6,$25002525,$48004848,$99009999,
$b900b9b9,$b300b3b3,$7b007b7b,$f900f9f9,$ce00cece,$bf00bfbf,$df00dfdf,$71007171,
$29002929,$cd00cdcd,$6c006c6c,$13001313,$64006464,$9b009b9b,$63006363,$9d009d9d,
$c000c0c0,$4b004b4b,$b700b7b7,$a500a5a5,$89008989,$5f005f5f,$b100b1b1,$17001717,
$f400f4f4,$bc00bcbc,$d300d3d3,$46004646,$cf00cfcf,$37003737,$5e005e5e,$47004747,
$94009494,$fa00fafa,$fc00fcfc,$5b005b5b,$97009797,$fe00fefe,$5a005a5a,$ac00acac,
$3c003c3c,$4c004c4c,$03000303,$35003535,$f300f3f3,$23002323,$b800b8b8,$5d005d5d,
$6a006a6a,$92009292,$d500d5d5,$21002121,$44004444,$51005151,$c600c6c6,$7d007d7d,
$39003939,$83008383,$dc00dcdc,$aa00aaaa,$7c007c7c,$77007777,$56005656,$05000505,
$1b001b1b,$a400a4a4,$15001515,$34003434,$1e001e1e,$1c001c1c,$f800f8f8,$52005252,
$20002020,$14001414,$e900e9e9,$bd00bdbd,$dd00dddd,$e400e4e4,$a100a1a1,$e000e0e0,
$8a008a8a,$f100f1f1,$d600d6d6,$7a007a7a,$bb00bbbb,$e300e3e3,$40004040,$4f004f4f);
sb4404: array[0..255] of longint = (
$70700070,$2c2c002c,$b3b300b3,$c0c000c0,$e4e400e4,$57570057,$eaea00ea,$aeae00ae,
$23230023,$6b6b006b,$45450045,$a5a500a5,$eded00ed,$4f4f004f,$1d1d001d,$92920092,
$86860086,$afaf00af,$7c7c007c,$1f1f001f,$3e3e003e,$dcdc00dc,$5e5e005e,$0b0b000b,
$a6a600a6,$39390039,$d5d500d5,$5d5d005d,$d9d900d9,$5a5a005a,$51510051,$6c6c006c,
$8b8b008b,$9a9a009a,$fbfb00fb,$b0b000b0,$74740074,$2b2b002b,$f0f000f0,$84840084,
$dfdf00df,$cbcb00cb,$34340034,$76760076,$6d6d006d,$a9a900a9,$d1d100d1,$04040004,
$14140014,$3a3a003a,$dede00de,$11110011,$32320032,$9c9c009c,$53530053,$f2f200f2,
$fefe00fe,$cfcf00cf,$c3c300c3,$7a7a007a,$24240024,$e8e800e8,$60600060,$69690069,
$aaaa00aa,$a0a000a0,$a1a100a1,$62620062,$54540054,$1e1e001e,$e0e000e0,$64640064,
$10100010,$00000000,$a3a300a3,$75750075,$8a8a008a,$e6e600e6,$09090009,$dddd00dd,
$87870087,$83830083,$cdcd00cd,$90900090,$73730073,$f6f600f6,$9d9d009d,$bfbf00bf,
$52520052,$d8d800d8,$c8c800c8,$c6c600c6,$81810081,$6f6f006f,$13130013,$63630063,
$e9e900e9,$a7a700a7,$9f9f009f,$bcbc00bc,$29290029,$f9f900f9,$2f2f002f,$b4b400b4,
$78780078,$06060006,$e7e700e7,$71710071,$d4d400d4,$abab00ab,$88880088,$8d8d008d,
$72720072,$b9b900b9,$f8f800f8,$acac00ac,$36360036,$2a2a002a,$3c3c003c,$f1f100f1,
$40400040,$d3d300d3,$bbbb00bb,$43430043,$15150015,$adad00ad,$77770077,$80800080,
$82820082,$ecec00ec,$27270027,$e5e500e5,$85850085,$35350035,$0c0c000c,$41410041,
$efef00ef,$93930093,$19190019,$21210021,$0e0e000e,$4e4e004e,$65650065,$bdbd00bd,
$b8b800b8,$8f8f008f,$ebeb00eb,$cece00ce,$30300030,$5f5f005f,$c5c500c5,$1a1a001a,
$e1e100e1,$caca00ca,$47470047,$3d3d003d,$01010001,$d6d600d6,$56560056,$4d4d004d,
$0d0d000d,$66660066,$cccc00cc,$2d2d002d,$12120012,$20200020,$b1b100b1,$99990099,
$4c4c004c,$c2c200c2,$7e7e007e,$05050005,$b7b700b7,$31310031,$17170017,$d7d700d7,
$58580058,$61610061,$1b1b001b,$1c1c001c,$0f0f000f,$16160016,$18180018,$22220022,
$44440044,$b2b200b2,$b5b500b5,$91910091,$08080008,$a8a800a8,$fcfc00fc,$50500050,
$d0d000d0,$7d7d007d,$89890089,$97970097,$5b5b005b,$95950095,$ffff00ff,$d2d200d2,
$c4c400c4,$48480048,$f7f700f7,$dbdb00db,$03030003,$dada00da,$3f3f003f,$94940094,
$5c5c005c,$02020002,$4a4a004a,$33330033,$67670067,$f3f300f3,$7f7f007f,$e2e200e2,
$9b9b009b,$26260026,$37370037,$3b3b003b,$96960096,$4b4b004b,$bebe00be,$2e2e002e,
$79790079,$8c8c008c,$6e6e006e,$8e8e008e,$f5f500f5,$b6b600b6,$fdfd00fd,$59590059,
$98980098,$6a6a006a,$46460046,$baba00ba,$25250025,$42420042,$a2a200a2,$fafa00fa,
$07070007,$55550055,$eeee00ee,$0a0a000a,$49490049,$68680068,$38380038,$a4a400a4,
$28280028,$7b7b007b,$c9c900c9,$c1c100c1,$e3e300e3,$f4f400f4,$c7c700c7,$9e9e009e);
const
SIGMA: array[0..2] of TWA4 = (($a09e667f, $3bcc908b, $b67ae858, $4caa73b2),
($c6ef372f, $e94f82be, $54ff53a5, $f1d36f1c),
($10e527fa, $de682d1d, $b05688c2, $b3e6c1fd));
const
KIDX1: array[4..25] of integer = (0,0,8,8,8,8,0,0,8,0,8,8,
0,0,0,0,8,8,0,0,8,8);
KIDX2: array[4..33] of integer = (4,4,8,8,4,4,12,12,0,0,8,8,0,0,4,4,
12,12,0,0,8,8,4,4,8,8,0,0,12,12);
KSFT1: array[4..25] of integer = (15,79,15,79,30,94,45,109,45,124,60,124,
77,13,94,30,94,30,111,47,111,47);
KSFT2: array[4..33] of integer = (15,79,15,79,30,94,30,94,45,109,45,
109,60,124,60,124,60,124,77,13,77,
13,94,30,94,30,111,47,111,47);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
{$ifndef BIT16}
{32/64-bit code}
{$ifdef BIT64}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{$ifdef CPUARM}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler; {&frame-}
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{$endif}
{$endif}
{$else} {16-bit}
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{$endif}
{$ifdef BASM16}
{---------------------------------------------------------------------------}
procedure CAM_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TCAMBlock; var B3: TCAMBlock);
{-xor two blocks, result in third}
begin
asm
mov di,ds
lds si,[B1]
db $66; mov ax,[si]
db $66; mov bx,[si+4]
db $66; mov cx,[si+8]
db $66; mov dx,[si+12]
lds si,[B2]
db $66; xor ax,[si]
db $66; xor bx,[si+4]
db $66; xor cx,[si+8]
db $66; xor dx,[si+12]
lds si,[B3]
db $66; mov [si],ax
db $66; mov [si+4],bx
db $66; mov [si+8],cx
db $66; mov [si+12],dx
mov ds,di
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure CAM_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TCAMBlock; var B3: TCAMBlock);
{-xor two blocks, result in third}
var
a1: TWA4 absolute B1;
a2: TWA4 absolute B2;
a3: TWA4 absolute B3;
begin
a3[0] := a1[0] xor a2[0];
a3[1] := a1[1] xor a2[1];
a3[2] := a1[2] xor a2[2];
a3[3] := a1[3] xor a2[3];
end;
{$endif BASM16}
{$ifndef BIT16}
{---------------------------------------------------------------------------}
{----------------------- 32/64 bit specific code --------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
procedure Feistel2E(var x: TWA4; const k: TWA4);
{-Camellia double Feistel F function for encryption and key setup}
var
D,U,s1,s2: longint;
begin
s1 := x[0] xor k[0];
U := sb4404[s1 and $FF] xor sb3033[(s1 shr 8) and $FF] xor sb0222[(s1 shr 16) and $FF] xor sb1110[s1 shr 24];
s2 := x[1] xor k[1];
D := sb1110[s2 and $FF] xor sb4404[(s2 shr 8) and $FF] xor sb3033[(s2 shr 16) and $FF] xor sb0222[s2 shr 24];
x[2] := x[2] xor (D xor U);
x[3] := x[3] xor (D xor U) xor ((U shr 8) or (U shl 24));
s1 := x[2] xor k[2];
U := sb4404[s1 and $FF] xor sb3033[(s1 shr 8) and $FF] xor sb0222[(s1 shr 16) and $FF] xor sb1110[s1 shr 24];
s2 := x[3] xor k[3];
D := sb1110[s2 and $FF] xor sb4404[(s2 shr 8) and $FF] xor sb3033[(s2 shr 16) and $FF] xor sb0222[s2 shr 24];
x[0] := x[0] xor (D xor U);
x[1] := x[1] xor (D xor U) xor ((U shr 8) or (U shl 24));
end;
{---------------------------------------------------------------------------}
procedure Feistel2D(var x: TWA4; const k: TWA4);
{-Camellia double Feistel F function for decryption}
var
D,U,s1,s2: longint;
begin
s1 := x[0] xor k[2];
U := sb4404[s1 and $FF] xor sb3033[(s1 shr 8) and $FF] xor sb0222[(s1 shr 16) and $FF] xor sb1110[s1 shr 24];
s2 := x[1] xor k[3];
D := sb1110[s2 and $FF] xor sb4404[(s2 shr 8) and $FF] xor sb3033[(s2 shr 16) and $FF] xor sb0222[s2 shr 24];
x[2] := x[2] xor (D xor U);
x[3] := x[3] xor (D xor U) xor ((U shr 8) or (U shl 24));
s1 := x[2] xor k[0];
U := sb4404[s1 and $FF] xor sb3033[(s1 shr 8) and $FF] xor sb0222[(s1 shr 16) and $FF] xor sb1110[s1 shr 24];
s2 := x[3] xor k[1];
D := sb1110[s2 and $FF] xor sb4404[(s2 shr 8) and $FF] xor sb3033[(s2 shr 16) and $FF] xor sb0222[s2 shr 24];
x[0] := x[0] xor (D xor U);
x[1] := x[1] xor (D xor U) xor ((U shr 8) or (U shl 24));
end;
{---------------------------------------------------------------------------}
procedure FLlayer_E(var x: TWA4; const k: TWA4);
{-FL/FLINV transformation for encryption}
var
t: longint;
begin
t := x[0] and k[0];
x[1] := x[1] xor ((t shl 1) or (t shr 31));
x[0] := x[0] xor (x[1] or k[1]);
x[2] := x[2] xor (x[3] or k[3]);
t := x[2] and k[2];
x[3] := x[3] xor ((t shl 1) or (t shr 31));
end;
{---------------------------------------------------------------------------}
procedure FLlayer_D(var x: TWA4; const k: TWA4);
{-FL/FLINV transformation for decryption}
var
t: longint;
begin
t := x[0] and k[2];
x[1] := x[1] xor ((t shl 1) or (t shr 31));
x[0] := x[0] xor (x[1] or k[3]);
x[2] := x[2] xor (x[3] or k[1]);
t := x[2] and k[0];
x[3] := x[3] xor ((t shl 1) or (t shr 31));
end;
{$else}
{---------------------------------------------------------------------------}
{----------------------- 16 bit specific code ----------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function LRot_1(x: longint): longint;
{-Rotate left 1}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$2B/$C9/ {sub cx,cx}
$D1/$D0/ {rcl ax,1 }
$D1/$D2/ {rcl dx,1 }
$13/$C1); {adc ax,cx}
{---------------------------------------------------------------------------}
function RRot_8(x: longint): longint;
{-Rotate right 8}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$88/$C1/ {mov cl,al}
$88/$E0/ {mov al,ah}
$88/$D4/ {mov ah,dl}
$88/$F2/ {mov dl,dh}
$88/$CE); {mov dh,cl}
{---------------------------------------------------------------------------}
procedure Feistel2E(var x: TWA4; {$ifdef CONST} const {$else} var {$endif} k: TWA4);
{-Camellia double Feistel F function for encryption and key setup}
var
D,U,SL: longint;
s: array[0..3] of byte absolute SL;
begin
SL := x[0] xor k[0];
U := sb4404[s[0]] xor sb3033[s[1]] xor sb0222[s[2]] xor sb1110[s[3]];
SL := x[1] xor k[1];
D := U xor sb1110[s[0]] xor sb4404[s[1]] xor sb3033[s[2]] xor sb0222[s[3]];
x[2]:= x[2] xor D;
x[3]:= x[3] xor D xor RRot_8(U);
SL := x[2] xor k[2];
U := sb4404[s[0]] xor sb3033[s[1]] xor sb0222[s[2]] xor sb1110[s[3]];
SL := x[3] xor k[3];
D := U xor sb1110[s[0]] xor sb4404[s[1]] xor sb3033[s[2]] xor sb0222[s[3]];
x[0]:= x[0] xor D;
x[1]:= x[1] xor D xor RRot_8(U);
end;
{---------------------------------------------------------------------------}
procedure Feistel2D(var x: TWA4; {$ifdef CONST} const {$else} var {$endif} k: TWA4);
{-Camellia double Feistel F function for decryption}
var
D,U,SL: longint;
s: array[0..3] of byte absolute SL;
begin
SL := x[0] xor k[2];
U := sb4404[s[0]] xor sb3033[s[1]] xor sb0222[s[2]] xor sb1110[s[3]];
SL := x[1] xor k[3];
D := U xor sb1110[s[0]] xor sb4404[s[1]] xor sb3033[s[2]] xor sb0222[s[3]];
x[2]:= x[2] xor D;
x[3]:= x[3] xor D xor RRot_8(U);
SL := x[2] xor k[0];
U := sb4404[s[0]] xor sb3033[s[1]] xor sb0222[s[2]] xor sb1110[s[3]];
SL := x[3] xor k[1];
D := U xor sb1110[s[0]] xor sb4404[s[1]] xor sb3033[s[2]] xor sb0222[s[3]];
x[0]:= x[0] xor D;
x[1]:= x[1] xor D xor RRot_8(U);
end;
{---------------------------------------------------------------------------}
procedure FLlayer_E(var x: TWA4; {$ifdef CONST} const {$else} var {$endif} k: TWA4);
{-FL/FLINV transformation for encryption}
begin
x[1] := x[1] xor LRot_1(x[0] and k[0]);
x[0] := x[0] xor (x[1] or k[1]);
x[2] := x[2] xor (x[3] or k[3]);
x[3] := x[3] xor LRot_1(x[2] and k[2]);
end;
{---------------------------------------------------------------------------}
procedure FLlayer_D(var x: TWA4; {$ifdef CONST} const {$else} var {$endif} k: TWA4);
{-FL/FLINV transformation for decryption}
begin
x[1] := x[1] xor LRot_1(x[0] and k[2]);
x[0] := x[0] xor (x[1] or k[3]);
x[2] := x[2] xor (x[3] or k[1]);
x[3] := x[3] xor LRot_1(x[2] and k[0]);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure RotBlock({$ifdef CONST} const {$else} var {$endif} xx; n: integer; var yy);
{-Returns 64 bits of rotated 128 bit block}
var
r: integer;
x: TWA4 absolute xx;
y: TWA2 absolute yy;
begin
r := n and 31;
n := n shr 5;
{$ifdef debug}
{$ifdef HAS_ASSERT}
assert(r<>0);
{$endif}
{$endif}
y[0] := (x[n and 3] shl r) xor (x[(n+1) and 3] shr (32-r));
y[1] := (x[(n+1) and 3 ] shl r) xor (x[(n+2) and 3] shr (32-r));
end;
{---------------------------------------------------------------------------}
procedure SwapHalf(var x: TWA4);
{-Swap the two 64 bit halfs of a 128 bit block}
var
t: longint;
begin
t := x[0]; x[0] := x[2]; x[2] := t;
t := x[1]; x[1] := x[3]; x[3] := t;
end;
{---------------------------------------------------------------------------}
procedure CAM_SetFastInit(value: boolean);
{-set FastInit variable}
begin
FastInit := value;
end;
{---------------------------------------------------------------------------}
function CAM_GetFastInit: boolean;
{-Returns FastInit variable}
begin
CAM_GetFastInit := FastInit;
end;
{---------------------------------------------------------------------------}
procedure CAM_Reset(var ctx: TCAMContext);
{-Clears ctx fields bLen and Flag}
begin
with ctx do begin
bLen :=0;
Flag :=0;
end;
end;
{---------------------------------------------------------------------------}
function CAM_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBits: word; var ctx: TCAMContext): integer;
{-Camellia context/round key initialization}
var
i,j: integer;
t: array[0..15] of longint;
type
TW44 = packed array[0..3] of TWA4;
TBL4 = packed array[0..3] of TCAMBlock;
begin
if (KeyBits<>128) and (KeyBits<>192) and (KeyBits<>256) then begin
CAM_Init := CAM_Err_Invalid_Key_Size;
exit;
end;
CAM_Init := 0;
if FastInit then begin
{Clear only the necessary context data at init. IV and buf}
{remain uninitialized, other fields are initialized below.}
CAM_Reset(ctx);
{$ifdef CONST}
ctx.IncProc := nil;
{$else}
{TP5-6 do not like IncProc := nil;}
fillchar(ctx.IncProc, sizeof(ctx.IncProc), 0);
{$endif}
end
else fillchar(ctx, sizeof(ctx), 0);
ctx.KeyBits := KeyBits;
t[0] := RB(TWA8(key)[0]);
t[1] := RB(TWA8(key)[1]);
t[2] := RB(TWA8(key)[2]);
t[3] := RB(TWA8(key)[3]);
case KeyBits of
128: begin
t[4] := 0;
t[5] := 0;
t[6] := 0;
t[7] := 0;
end;
192: begin
t[4] := RB(TWA8(key)[4]);
t[5] := RB(TWA8(key)[5]);
t[6] := not t[4];
t[7] := not t[5];
end;
256: begin
t[4] := RB(TWA8(key)[4]);
t[5] := RB(TWA8(key)[5]);
t[6] := RB(TWA8(key)[6]);
t[7] := RB(TWA8(key)[7]);
end;
end;
CAM_XorBlock(TBL4(t)[0], TBL4(t)[1], TBL4(t)[2]);
Feistel2E(TW44(t)[2], SIGMA[0]);
CAM_XorBlock(TBL4(t)[2], TBL4(t)[0], TBL4(t)[2]);
Feistel2E(TW44(t)[2], SIGMA[1]);
if KeyBits=128 then begin
move(t[0], ctx.EK[0], 16);
move(t[8], ctx.EK[1], 16);
for i:=2 to 12 do begin
j := i+i;
RotBlock(t[KIDX1[j]], KSFT1[j], TE32(ctx.EK)[4*i]);
inc(j);
RotBlock(t[KIDX1[j]], KSFT1[j], TE32(ctx.EK)[4*i+2]);
end;
end
else begin
CAM_XorBlock(TBL4(t)[2], TBL4(t)[1], TBL4(t)[3]);
Feistel2E(TW44(t)[3], SIGMA[2]);
move(t[0], ctx.EK[0], 16);
move(t[12], ctx.EK[1], 16);
for i:=2 to 16 do begin
j := i+i;
RotBlock(t[KIDX2[j]], KSFT2[j], TE32(ctx.EK)[4*i]);
inc(j);
RotBlock(t[KIDX2[j]], KSFT2[j], TE32(ctx.EK)[4*i+2]);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure CAM_Encrypt(var ctx: TCAMContext; {$ifdef CONST} const {$else} var {$endif} BI: TCAMBlock; var BO: TCAMBlock);
{-encrypt one block (in ECB mode)}
var
B4: TWA4 absolute BO;
begin
B4[0] := RB(TWA4(BI)[0]) xor TE32(ctx.EK)[0];
B4[1] := RB(TWA4(BI)[1]) xor TE32(ctx.EK)[1];
B4[2] := RB(TWA4(BI)[2]) xor TE32(ctx.EK)[2];
B4[3] := RB(TWA4(BI)[3]) xor TE32(ctx.EK)[3];
Feistel2E(B4, TRK4(ctx.EK)[1]);
Feistel2E(B4, TRK4(ctx.EK)[2]);
Feistel2E(B4, TRK4(ctx.EK)[3]);
FLlayer_E(B4, TRK4(ctx.EK)[4]);
Feistel2E(B4, TRK4(ctx.EK)[5]);
Feistel2E(B4, TRK4(ctx.EK)[6]);
Feistel2E(B4, TRK4(ctx.EK)[7]);
FLlayer_E(B4, TRK4(ctx.EK)[8]);
Feistel2E(B4, TRK4(ctx.EK)[9]);
Feistel2E(B4, TRK4(ctx.EK)[10]);
Feistel2E(B4, TRK4(ctx.EK)[11]);
if ctx.KeyBits=128 then begin
SwapHalf(B4);
CAM_XorBlock(BO, ctx.EK[12], BO);
end
else begin
FLlayer_E(B4, TRK4(ctx.EK)[12]);
Feistel2E(B4, TRK4(ctx.EK)[13]);
Feistel2E(B4, TRK4(ctx.EK)[14]);
Feistel2E(B4, TRK4(ctx.EK)[15]);
SwapHalf(B4);
CAM_XorBlock(BO, ctx.EK[16], BO);
end;
B4[0] := RB(B4[0]);
B4[1] := RB(B4[1]);
B4[2] := RB(B4[2]);
B4[3] := RB(B4[3]);
end;
{---------------------------------------------------------------------------}
procedure CAM_Decrypt(var ctx: TCAMContext; {$ifdef CONST} const {$else} var {$endif} BI: TCAMBlock; var BO: TCAMBlock);
{-encrypt one block (in ECB mode)}
var
B4: TWA4 absolute BO;
begin
B4[0] := RB(TWA4(BI)[0]);
B4[1] := RB(TWA4(BI)[1]);
B4[2] := RB(TWA4(BI)[2]);
B4[3] := RB(TWA4(BI)[3]);
if ctx.KeyBits=128 then CAM_XorBlock(BO, ctx.EK[12], BO)
else begin
CAM_XorBlock(BO, ctx.EK[16], BO);
Feistel2D(B4, TRK4(ctx.EK)[15]);
Feistel2D(B4, TRK4(ctx.EK)[14]);
Feistel2D(B4, TRK4(ctx.EK)[13]);
FLlayer_D(B4, TRK4(ctx.EK)[12]);
end;
Feistel2D(B4, TRK4(ctx.EK)[11]);
Feistel2D(B4, TRK4(ctx.EK)[10]);
Feistel2D(B4, TRK4(ctx.EK)[9]);
FLlayer_D(B4, TRK4(ctx.EK)[8]);
Feistel2D(B4, TRK4(ctx.EK)[7]);
Feistel2D(B4, TRK4(ctx.EK)[6]);
Feistel2D(B4, TRK4(ctx.EK)[5]);
FLlayer_D(B4, TRK4(ctx.EK)[4]);
Feistel2D(B4, TRK4(ctx.EK)[3]);
Feistel2D(B4, TRK4(ctx.EK)[2]);
Feistel2D(B4, TRK4(ctx.EK)[1]);
SwapHalf(B4);
B4[0] := RB(B4[0] xor TE32(ctx.EK)[0]);
B4[1] := RB(B4[1] xor TE32(ctx.EK)[1]);
B4[2] := RB(B4[2] xor TE32(ctx.EK)[2]);
B4[3] := RB(B4[3] xor TE32(ctx.EK)[3]);
end;
end.
|
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
interface
uses
Printers, // Unit containing the Printer command
SysUtils, Graphics, Windows,
Forms, Dialogs, Classes, Controls, StdCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm} // Include form definitions
// A subroutine used to display a print-cancel dialog
procedure CancelDialog;
begin
// Display the cancel print dialog
Dialogs.MessageDlg('Press cancel to abort printing',mtCustom,[mbCancel],0);
// Now that the user has pressed cancel, we abort the printing
if Printer.Printing then
begin
Printer.Abort;
ShowMessage('Printing aborted');
end;
// End this thread
endThread(0);
end;
// The main form On Create routine - our main program
procedure TForm1.FormCreate(Sender: TObject);
const
TOTAL_PAGES = 4; // How many pages to print
var
printDialog : TPrintDialog;
cancelThreadId : Integer;
threadId : LongWord;
page, startPage, endPage : Integer;
begin
// Create a printer selection dialog
printDialog := TPrintDialog.Create(Form1);
// Set up print dialog options
printDialog.MinPage := 1; // First allowed page number
printDialog.MaxPage := TOTAL_PAGES; // Highest allowed page number
printDialog.ToPage := TOTAL_PAGES; // 1 to ToPage page range allowed
printDialog.Options := [poPageNums]; // Allow page range selection
// if the user has selected a printer (or default), then print!
if printDialog.Execute then
begin
// Start a cancel print dilaog as a separate thread!
cancelThreadId := beginThread(nil,
0,
Addr(CancelDialog),
nil,
0,
threadId);
// Use the Printer function to get access to the global TPrinter object.
// Set to landscape orientation
Printer.Orientation := poLandscape;
// Set the printjob title - as it it appears in the print job manager
Printer.Title := 'Test print for Delphi';
// Set the number of copies to print each page
// This is crude - it doies not take Collation into account
Printer.Copies := printDialog.Copies;
// Start printing
Printer.BeginDoc;
// Has the user selected a page range?
if printDialog.PrintRange = prPageNums then
begin
startPage := printDialog.FromPage;
endPage := printDialog.ToPage;
end
else // All pages
begin
startPage := 1;
endPage := TOTAL_PAGES;
end;
// Set up the start page number
page := startPage;
// Keep printing whilst all OK
while (not Printer.Aborted) and Printer.Printing do
begin
// Show a message saying we are starting a page
ShowMessagePos('Starting to print page '+IntToStr(page),300,300);
// Set up a medium sized font
Printer.Canvas.Font.Size := 10;
// Allow Windows to keep processing messages
Application.ProcessMessages;
// Write out the page number
Printer.Canvas.Font.Color := clBlue;
Printer.Canvas.TextOut(40, 20, 'Page number = '+IntToStr(page));
// Underline this page number
Printer.Canvas.MoveTo(40,80);
Printer.Canvas.LineTo(Printer.PageWidth-20,80);
// Write out the page size
Printer.Canvas.Font.Color := clRed;
Printer.Canvas.TextOut(40, 100, 'Page width = '+
IntToStr(Printer.PageWidth));
Printer.Canvas.TextOut(40, 180, 'Page height = '+
IntToStr(Printer.PageHeight));
// Increment the page number
Inc(page);
// Now start a new page - if not the last
if (page <= endPage) and (not Printer.Aborted)
then Printer.NewPage;
end;
// Finish printing
Printer.EndDoc;
end;
end;
end.
{
procedure TForm1.Button1Click(Sender: TObject);
const
TOTAL_PAGES = 4; // How many pages to print
var
printDialog : TPrintDialog;
page, startPage, endPage : Integer;
begin
//1. Usando a caixa de diálogo da impressora
{Aqui, criamos um objeto de diálogo de impressão, configuramos algumas opções e, em seguida, o exibimos. O método Execute retorna true
se o usuário clicar em OK em vez de cancelar. Em seguida, imprimimos o documento. O usuário pode selecionar, por meio dessas opções,
se deseja imprimir todas as 4 páginas ou um intervalo dessas páginas, conforme visto em uma parte da caixa de diálogo mostrada abaixo:}
// Create a printer selection dialog
{ printDialog := TPrintDialog.Create(Form1);
// Set up print dialog options
printDialog.MinPage := 1; // First allowed page number
printDialog.MaxPage := TOTAL_PAGES; // Highest allowed page number
printDialog.ToPage := TOTAL_PAGES; // 1 to ToPage page range allowed
printDialog.Options := [poPageNums]; // Allow page range selection
//2. Começando a imprimir
{O objeto Impressora está permanentemente disponível para o seu código (você deve usar a unidade Impressoras para obter acesso aos seus
métodos e campos). Com esse objetivo, a impressão ocorre de maneira ordenada.}
// if the user has selected a printer (or default), then print!
{ if printDialog.Execute then
begin
//... Your print statements
//O seguinte snippet de código define algumas novas variáveis: var page, startPage, endPage : Integer;
//E agora definimos essas variáveis ??na caixa de diálogo de impressão:
// Has the user selected a page range?
if printDialog.PrintRange = prPageNums then
begin
startPage := printDialog.FromPage;
endPage := printDialog.ToPage;
end
else // All pages
begin
startPage := 1;
endPage := TOTAL_PAGES;
end;
// Set up the start page number
page := startPage;
//O valor prPageNums é um valor TPrintRange e é um dos valores que PrintRange pode ter. Se definido, significa que o usuário
// selecionou um intervalo de páginas. Os FromPage e ToPage valores irá então ser definido para os valores especificados pelo
//utilizador.
// Use the Printer function to get access to the global TPrinter object.
// Set to landscape orientation
Printer.Orientation := poLandscape;
// Set the printjob title - as it it appears in the print job manager
Printer.Title := 'Test print for Delphi';
// Set the number of copies to print each page
// This is crude - it doies not take Collation into account
Printer.Copies := printDialog.Copies;
// Start printing
Printer.BeginDoc;
{Isso inicia um trabalho de impressão, com um layout de página em paisagem, um título e o número de cópias especificado pelo usuário.
Observe que estamos ignorando o agrupamento - sempre imprimimos todas as cópias da página 1 antes da página 2, etc.}
{ while (not Printer.Aborted) and Printer.Printing do
begin
// Show a message saying we are starting a page
ShowMessagePos('Starting to print page '+IntToStr(page),300,300);
// Set up a medium sized font
Printer.Canvas.Font.Size := 10;
// Allow Windows to keep processing messages
Application.ProcessMessages;
// Write out the page number
Printer.Canvas.Font.Color := clBlue;
Printer.Canvas.TextOut(40, 20, 'Page number = '+IntToStr(page));
// Underline this page number
Printer.Canvas.MoveTo(40,80);
Printer.Canvas.LineTo(Printer.PageWidth-20,80);
// Write out the page size
Printer.Canvas.Font.Color := clRed;
Printer.Canvas.TextOut(40, 100, 'Page width = '+ IntToStr(Printer.PageWidth));
Printer.Canvas.TextOut(40, 180, 'Page height = '+ IntToStr(Printer.PageHeight));
// Increment the page number
Inc(page);
// Now start a new page - if not the last
if (page <= endPage) and (not Printer.Aborted) then Printer.NewPage;
end;
// Finish printing
Printer.EndDoc;
end;
//
end;
end.
|
unit IdWhoIsServer;
interface
uses
Classes,
IdGlobal,
IdTCPServer;
type
TGetEvent = procedure(AThread: TIdPeerThread; ALookup: string) of object;
TIdWhoIsServer = class(TIdTCPserver)
protected
FOnCommandLookup: TGetEvent;
function DoExecute(AThread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
property OnCommandLookup: TGetEvent read FOnCommandLookup write
FOnCommandLookup;
property DefaultPort default IdPORT_WHOIS;
end;
implementation
constructor TIdWhoIsServer.Create(AOwner: TComponent);
begin
inherited;
DefaultPort := IdPORT_WHOIS;
end;
function TIdWhoIsServer.DoExecute(AThread: TIdPeerThread): boolean;
var
Response: string;
begin
result := true;
with AThread.Connection do
begin
while Connected do
begin
Response := ReadLn;
if Connected then
begin
if Assigned(OnCommandLookup) then
begin
OnCommandLookup(AThread, Response);
end;
end;
end;
Disconnect;
end;
end;
end.
|
unit Test02.DaylightTimeZone;
interface
uses
DUnitX.TestFramework;
{$M+}
type
[TestFixture]
Test02DaylightTimeZone = class(TObject)
published
[Test]
procedure CheckWebSiteStructure_TimeAndDate;
[Test]
[TestCase(' - USA Atlanta - 2021', 'usa/atlanta,2021,true')]
[TestCase(' - India Bangalore - 1998', 'india/bangalore,1998,false')]
procedure IsDaylightSavingTime(const aArea: string; const aYear: word;
const aIsDST: boolean);
[Test]
[TestCase(' - USA Atlanta - 1999', 'usa/atlanta,1999,1999-04-04 02:00')]
[TestCase(' - Poland Warsaw - 2015', 'poland/warsaw,2015,2015-03-29 02:00')]
[TestCase(' - USA Atlanta - 2021', 'usa/atlanta,2021,2021-03-14 02:00')]
procedure Test_GetDaylightStartDate(const aArea: string; const aYear: word;
const aExpectedTime: string);
[Test]
[TestCase(' - USA Atlanta - 1999', 'usa/atlanta,1999,1999-10-31 02:00')]
[TestCase(' - Poland Warsaw - 2015', 'poland/warsaw,2015,2015-10-25 03:00')]
[TestCase(' - USA Atlanta - 2021', 'usa/atlanta,2021,2021-11-07 02:00')]
procedure Test_GetDaylightEndDate(const aArea: string; const aYear: word;
const aExpectedTime: string);
[Test]
procedure Test_Performance();
end;
implementation
uses
System.SysUtils,
System.DateUtils,
Code02.HttpGet,
Code02.Clarc1984.DaylightTimeZone,
Code02.Jacek.DaylightTimeZone,
Code02.Ongakw.DaylightTimeZone,
Code02.pslomski.DaylightTimeZone;
type
TCh02Participants = (
cpJacekLaskowski, // jaclas - Jacek Laskowski
cpLukaszKotynski, // Clarc1984 - Łukasz Kotyński
cpPiotrSlomski, // pslomski - Piotr Słomski
cpOngakw); // ???
var
CurrentParticipants: TCh02Participants = cpPiotrSlomski;
function IsDaylightSaving(const area: string; year: Word): boolean;
begin
Result:=False;
case CurrentParticipants of
cpJacekLaskowski:
Result := Code02.Jacek.DaylightTimeZone.IsDaylightSaving(area, year);
cpLukaszKotynski:
Result := Code02.Clarc1984.DaylightTimeZone.IsDaylightSaving(area, year);
cpPiotrSlomski:
Result := Code02.pslomski.DaylightTimeZone.IsDaylightSaving(area, year);
cpOngakw:
Result := Code02.Ongakw.DaylightTimeZone.IsDaylightSaving(area, year);
end;
end;
function GetDaylightStart(const area: string; year: Word): TDateTime;
begin
Result:=0;
case CurrentParticipants of
cpJacekLaskowski:
Result := Code02.Jacek.DaylightTimeZone.GetDaylightStart(area, year);
cpLukaszKotynski:
Result := Code02.Clarc1984.DaylightTimeZone.GetDaylightStart(area, year);
cpPiotrSlomski:
Result := Code02.pslomski.DaylightTimeZone.GetDaylightStart(area, year);
cpOngakw:
Result := Code02.Ongakw.DaylightTimeZone.GetDaylightStart(area, year);
end;
end;
function GetDaylightEnd(const area: string; year: Word): TDateTime;
begin
Result:=0;
case CurrentParticipants of
cpJacekLaskowski:
Result := Code02.Jacek.DaylightTimeZone.GetDaylightEnd(area, year);
cpLukaszKotynski:
Result := Code02.Clarc1984.DaylightTimeZone.GetDaylightEnd(area, year);
cpPiotrSlomski:
Result := Code02.pslomski.DaylightTimeZone.GetDaylightEnd(area, year);
cpOngakw:
Result := Code02.Ongakw.DaylightTimeZone.GetDaylightEnd(area, year);
end;
end;
procedure Test02DaylightTimeZone.CheckWebSiteStructure_TimeAndDate;
var
aHtmlPageContent: string;
isContains: Boolean;
begin
aHtmlPageContent := TMyHttpGet.GetWebsiteContent
('https://www.timeanddate.com/time/change/poland/warsaw?year=1998');
isContains := aHtmlPageContent.Contains('<p>25 Oct 2020, 03:00</p>');
Assert.IsTrue(isContains,
'Unsupported timeanddate web page structure. Parser requires update');
end;
procedure Test02DaylightTimeZone.IsDaylightSavingTime(const aArea: string;
const aYear: word; const aIsDST: boolean);
begin
Assert.AreEqual(aIsDST, IsDaylightSaving(aArea, aYear));
end;
procedure Test02DaylightTimeZone.Test_GetDaylightStartDate(const aArea: string;
const aYear: word; const aExpectedTime: string);
var
dt: TDateTime;
actual: string;
begin
TMyHttpGet.CounterHttpCalls := 0;
dt := GetDaylightStart(aArea, aYear);
actual := FormatDateTime('yyyy-mm-dd hh:mm', dt);
Assert.AreEqual(aExpectedTime, actual);
end;
procedure Test02DaylightTimeZone.Test_GetDaylightEndDate(const aArea: string;
const aYear: word; const aExpectedTime: string);
var
dt: TDateTime;
actual: string;
begin
TMyHttpGet.CounterHttpCalls := 0;
dt := GetDaylightEnd(aArea, aYear);
actual := FormatDateTime('yyyy-mm-dd hh:mm', dt);
Assert.AreEqual(aExpectedTime, actual);
end;
procedure Test02DaylightTimeZone.Test_Performance;
var
area: string;
year: Integer;
begin
TMyHttpGet.CounterHttpCalls := 0;
area := 'usa/atlanta';
year := 1995;
IsDaylightSaving(area, year);
GetDaylightStart(area, year);
GetDaylightEnd(area, year);
GetDaylightStart(area, year);
Assert.AreEqual(1, TMyHttpGet.CounterHttpCalls);
end;
initialization
TDUnitX.RegisterTestFixture(Test02DaylightTimeZone);
end.
|
// **************************************************************************************************
// Delphi Aio Library.
// Unit GarbageCollector
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 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
//
//
// The Original Code is GarbageCollector.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit GarbageCollector;
interface
uses {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
PasMP;
type
IGCPointer<T> = interface
function GetValue: T;
function GetRefCount: Integer;
end;
IGCObject = IGCPointer<TObject>;
TGarbageCollector = class
private
type
TLocalRefs = class(TInterfacedObject, IGCObject)
strict private
FContainer: TGarbageCollector;
FGlobalRef: IGCObject;
FValue: TObject;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
property Container: TGarbageCollector read FContainer write FContainer;
public
constructor Create(Container: TGarbageCollector; GlobalRef: IGCObject);
function GetValue: TObject;
function GetRefCount: Integer;
property GlobalRef: IGCObject read FGlobalRef;
end;
var
{$IFDEF DCC}
FStorage: TDictionary<TObject, TLocalRefs>;
{$ELSE}
FStorage: TFPGMap<TObject, TLocalRefs>;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
function IsExists(A: TObject): Boolean;
function SetValue(A: TObject): IGCObject;
procedure Clear;
class function ExistsInGlobal(A: TObject): Boolean; static;
end;
TFinalizer<T> = record
public
class procedure Fin(var A: T); static;
end;
TGCPointerImpl<T> = class(TInterfacedObject, IGCPointer<T>)
strict private
FValue: T;
FIsObject: Boolean;
FObject: TObject;
FDynArr: Pointer;
FIsDynArr: Boolean;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Value: T); overload;
destructor Destroy; override;
function GetValue: T;
function GetRefCount: Integer;
end;
var
GlobalGC: TPasMPHashTable<Pointer, IGCObject>;
GlobalGCActive: Boolean;
{$IFDEF DEBUG}
GCCounter: Integer;
{$ENDIF}
implementation
uses TypInfo;
{ TGarbageCollector }
procedure TGarbageCollector.Clear;
var
LocalRefs: TLocalRefs;
begin
for LocalRefs in FStorage.Values do
LocalRefs.Container := nil;
FStorage.Clear;
end;
constructor TGarbageCollector.Create;
begin
{$IFDEF DCC}
FStorage := TDictionary<TObject, TLocalRefs>.Create
{$ELSE}
FStorage := TFPGMap<TObject, TLocalRefs>.Create;
{$ENDIF}
end;
destructor TGarbageCollector.Destroy;
begin
Clear;
FStorage.Free;
inherited;
end;
class function TGarbageCollector.ExistsInGlobal(A: TObject): Boolean;
var
Smart: IGCObject;
begin
Result := GlobalGC.GetKeyValue(A, Smart)
end;
function TGarbageCollector.IsExists(A: TObject): Boolean;
{$IFDEF FPC}
var
Index: Integer;
{$ENDIF}
begin
{$IFDEF DCC}
Result := FStorage.ContainsKey(A)
{$ELSE}
Result := FStorage.Find(Key, Index);
{$ENDIF}
end;
function TGarbageCollector.SetValue(A: TObject): IGCObject;
var
GlobalRef: IGCObject;
LocalRefs: TLocalRefs;
begin
if A = nil then
Exit(nil);
if IsExists(A) then
Result := FStorage[A]
else if GlobalGC.GetKeyValue(A, GlobalRef) then begin
LocalRefs := TLocalRefs.Create(Self, GlobalRef);
Result := LocalRefs;
FStorage.Add(A, LocalRefs)
end
else begin
GlobalRef := TGCPointerImpl<TObject>.Create(A);
{$IFDEF DEBUG}
Assert(GlobalGC.SetKeyValue(A, GlobalRef));
{$ELSE}
GlobalGC.SetKeyValue(A, GlobalRef);
{$ENDIF}
LocalRefs := TLocalRefs.Create(Self, GlobalRef);
Result := LocalRefs;
FStorage.Add(A, LocalRefs)
end
end;
class procedure TFinalizer<T>.Fin(var A: T);
var
ti: PTypeInfo;
ObjValuePtr: PObject;
begin
ti := TypeInfo(T);
if (ti.Kind = tkClass) then begin
ObjValuePtr := @A;
if Assigned(ObjValuePtr) then
ObjValuePtr.Free;
end
end;
{ TGCPointerImpl<T> }
constructor TGCPointerImpl<T>.Create(Value: T);
var
ti: PTypeInfo;
ObjValuePtr: PObject;
DynArrPtr: Pointer;
begin
FValue := Value;
ti := TypeInfo(T);
if (ti.Kind = tkClass) then begin
ObjValuePtr := @Value;
FObject := ObjValuePtr^;
FIsObject := True;
end
else if ti.Kind = tkDynArray then begin
FDynArr := @Value;
FIsDynArr := True;
end;
end;
destructor TGCPointerImpl<T>.Destroy;
begin
TFinalizer<T>.Fin(FValue);
inherited;
end;
function TGCPointerImpl<T>.GetRefCount: Integer;
begin
Result := FRefCount
end;
function TGCPointerImpl<T>.GetValue: T;
begin
Result := FValue
end;
function TGCPointerImpl<T>._AddRef: Integer;
var
Ref: IGCObject;
begin
Result := inherited _AddRef;
if FIsObject and (Result = 1) then begin
{$IFDEF DEBUG}
Assert(not GlobalGC.GetKeyValue(FObject, Ref));
{$ENDIF}
Ref := TGCPointerImpl<TObject>(Self);
GlobalGC.SetKeyValue(FObject, Ref)
end;
{$IFDEF DEBUG}
AtomicIncrement(GCCounter);
{$ENDIF}
end;
function TGCPointerImpl<T>._Release: Integer;
begin
Result := inherited _Release;
if FIsObject and (Result = 1) then begin
if GlobalGCActive then begin
{$IFDEF DEBUG}
Assert(GlobalGC.DeleteKey(FObject));
{$ELSE}
GlobalGC.DeleteKey(FObject)
{$ENDIF}
end;
end;
{$IFDEF DEBUG}
AtomicDecrement(GCCounter);
{$ENDIF}
end;
{ TGarbageCollector.TLocalRefs }
constructor TGarbageCollector.TLocalRefs.Create(Container: TGarbageCollector;
GlobalRef: IGCObject);
begin
FContainer := Container;
FGlobalRef := GlobalRef;
FValue := GlobalRef.GetValue;
end;
function TGarbageCollector.TLocalRefs.GetRefCount: Integer;
begin
Result := FRefCount
end;
function TGarbageCollector.TLocalRefs.GetValue: TObject;
begin
Result := FGlobalRef.GetValue
end;
function TGarbageCollector.TLocalRefs._AddRef: Integer;
begin
Result := inherited _AddRef;
end;
function TGarbageCollector.TLocalRefs._Release: Integer;
begin
Result := inherited _Release;
if Result = 0 then begin
if Assigned(FContainer) then
if FContainer.FStorage.ContainsKey(FValue) then
FContainer.FStorage.Remove(FValue);
end;
end;
initialization
GlobalGC := TPasMPHashTable<Pointer, IGCObject>.Create;
GlobalGCActive := True;
finalization
GlobalGCActive := False;
GlobalGC.Free
end.
|
(*************************************************************************
Cephes Math Library Release 2.8: June, 2000
Copyright by Stephen L. Moshier
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from C to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
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 (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit airyf;
interface
uses Math, Sysutils, Ap;
procedure Airy(x : AlglibFloat;
var Ai : AlglibFloat;
var Aip : AlglibFloat;
var Bi : AlglibFloat;
var Bip : AlglibFloat);
implementation
(*************************************************************************
Airy function
Solution of the differential equation
y"(x) = xy.
The function returns the two independent solutions Ai, Bi
and their first derivatives Ai'(x), Bi'(x).
Evaluation is by power series summation for small x,
by rational minimax approximations for large x.
ACCURACY:
Error criterion is absolute when function <= 1, relative
when function > 1, except * denotes relative error criterion.
For large negative x, the absolute error increases as x^1.5.
For large positive x, the relative error increases as x^1.5.
Arithmetic domain function # trials peak rms
IEEE -10, 0 Ai 10000 1.6e-15 2.7e-16
IEEE 0, 10 Ai 10000 2.3e-14* 1.8e-15*
IEEE -10, 0 Ai' 10000 4.6e-15 7.6e-16
IEEE 0, 10 Ai' 10000 1.8e-14* 1.5e-15*
IEEE -10, 10 Bi 30000 4.2e-15 5.3e-16
IEEE -10, 10 Bi' 30000 4.9e-15 7.3e-16
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
*************************************************************************)
procedure Airy(x : AlglibFloat;
var Ai : AlglibFloat;
var Aip : AlglibFloat;
var Bi : AlglibFloat;
var Bip : AlglibFloat);
var
z : AlglibFloat;
zz : AlglibFloat;
t : AlglibFloat;
f : AlglibFloat;
g : AlglibFloat;
uf : AlglibFloat;
ug : AlglibFloat;
k : AlglibFloat;
zeta : AlglibFloat;
theta : AlglibFloat;
domflg : AlglibInteger;
c1 : AlglibFloat;
c2 : AlglibFloat;
sqrt3 : AlglibFloat;
sqpii : AlglibFloat;
AFN : AlglibFloat;
AFD : AlglibFloat;
AGN : AlglibFloat;
AGD : AlglibFloat;
APFN : AlglibFloat;
APFD : AlglibFloat;
APGN : AlglibFloat;
APGD : AlglibFloat;
AN : AlglibFloat;
AD : AlglibFloat;
APN : AlglibFloat;
APD : AlglibFloat;
BN16 : AlglibFloat;
BD16 : AlglibFloat;
BPPN : AlglibFloat;
BPPD : AlglibFloat;
begin
sqpii := 5.64189583547756286948E-1;
c1 := 0.35502805388781723926;
c2 := 0.258819403792806798405;
sqrt3 := 1.732050807568877293527;
domflg := 0;
if AP_FP_Greater(x,25.77) then
begin
ai := 0;
aip := 0;
bi := MaxRealNumber;
bip := MaxRealNumber;
Exit;
end;
if AP_FP_Less(x,-2.09) then
begin
domflg := 15;
t := sqrt(-x);
zeta := -2.0*x*t/3.0;
t := sqrt(t);
k := sqpii/t;
z := 1.0/zeta;
zz := z*z;
AFN := -1.31696323418331795333E-1;
AFN := AFN*zz-6.26456544431912369773E-1;
AFN := AFN*zz-6.93158036036933542233E-1;
AFN := AFN*zz-2.79779981545119124951E-1;
AFN := AFN*zz-4.91900132609500318020E-2;
AFN := AFN*zz-4.06265923594885404393E-3;
AFN := AFN*zz-1.59276496239262096340E-4;
AFN := AFN*zz-2.77649108155232920844E-6;
AFN := AFN*zz-1.67787698489114633780E-8;
AFD := 1.00000000000000000000E0;
AFD := AFD*zz+1.33560420706553243746E1;
AFD := AFD*zz+3.26825032795224613948E1;
AFD := AFD*zz+2.67367040941499554804E1;
AFD := AFD*zz+9.18707402907259625840E0;
AFD := AFD*zz+1.47529146771666414581E0;
AFD := AFD*zz+1.15687173795188044134E-1;
AFD := AFD*zz+4.40291641615211203805E-3;
AFD := AFD*zz+7.54720348287414296618E-5;
AFD := AFD*zz+4.51850092970580378464E-7;
uf := 1.0+zz*AFN/AFD;
AGN := 1.97339932091685679179E-2;
AGN := AGN*zz+3.91103029615688277255E-1;
AGN := AGN*zz+1.06579897599595591108E0;
AGN := AGN*zz+9.39169229816650230044E-1;
AGN := AGN*zz+3.51465656105547619242E-1;
AGN := AGN*zz+6.33888919628925490927E-2;
AGN := AGN*zz+5.85804113048388458567E-3;
AGN := AGN*zz+2.82851600836737019778E-4;
AGN := AGN*zz+6.98793669997260967291E-6;
AGN := AGN*zz+8.11789239554389293311E-8;
AGN := AGN*zz+3.41551784765923618484E-10;
AGD := 1.00000000000000000000E0;
AGD := AGD*zz+9.30892908077441974853E0;
AGD := AGD*zz+1.98352928718312140417E1;
AGD := AGD*zz+1.55646628932864612953E1;
AGD := AGD*zz+5.47686069422975497931E0;
AGD := AGD*zz+9.54293611618961883998E-1;
AGD := AGD*zz+8.64580826352392193095E-2;
AGD := AGD*zz+4.12656523824222607191E-3;
AGD := AGD*zz+1.01259085116509135510E-4;
AGD := AGD*zz+1.17166733214413521882E-6;
AGD := AGD*zz+4.91834570062930015649E-9;
ug := z*AGN/AGD;
theta := zeta+0.25*PI;
f := sin(theta);
g := cos(theta);
ai := k*(f*uf-g*ug);
bi := k*(g*uf+f*ug);
APFN := 1.85365624022535566142E-1;
APFN := APFN*zz+8.86712188052584095637E-1;
APFN := APFN*zz+9.87391981747398547272E-1;
APFN := APFN*zz+4.01241082318003734092E-1;
APFN := APFN*zz+7.10304926289631174579E-2;
APFN := APFN*zz+5.90618657995661810071E-3;
APFN := APFN*zz+2.33051409401776799569E-4;
APFN := APFN*zz+4.08718778289035454598E-6;
APFN := APFN*zz+2.48379932900442457853E-8;
APFD := 1.00000000000000000000E0;
APFD := APFD*zz+1.47345854687502542552E1;
APFD := APFD*zz+3.75423933435489594466E1;
APFD := APFD*zz+3.14657751203046424330E1;
APFD := APFD*zz+1.09969125207298778536E1;
APFD := APFD*zz+1.78885054766999417817E0;
APFD := APFD*zz+1.41733275753662636873E-1;
APFD := APFD*zz+5.44066067017226003627E-3;
APFD := APFD*zz+9.39421290654511171663E-5;
APFD := APFD*zz+5.65978713036027009243E-7;
uf := 1.0+zz*APFN/APFD;
APGN := -3.55615429033082288335E-2;
APGN := APGN*zz-6.37311518129435504426E-1;
APGN := APGN*zz-1.70856738884312371053E0;
APGN := APGN*zz-1.50221872117316635393E0;
APGN := APGN*zz-5.63606665822102676611E-1;
APGN := APGN*zz-1.02101031120216891789E-1;
APGN := APGN*zz-9.48396695961445269093E-3;
APGN := APGN*zz-4.60325307486780994357E-4;
APGN := APGN*zz-1.14300836484517375919E-5;
APGN := APGN*zz-1.33415518685547420648E-7;
APGN := APGN*zz-5.63803833958893494476E-10;
APGD := 1.00000000000000000000E0;
APGD := APGD*zz+9.85865801696130355144E0;
APGD := APGD*zz+2.16401867356585941885E1;
APGD := APGD*zz+1.73130776389749389525E1;
APGD := APGD*zz+6.17872175280828766327E0;
APGD := APGD*zz+1.08848694396321495475E0;
APGD := APGD*zz+9.95005543440888479402E-2;
APGD := APGD*zz+4.78468199683886610842E-3;
APGD := APGD*zz+1.18159633322838625562E-4;
APGD := APGD*zz+1.37480673554219441465E-6;
APGD := APGD*zz+5.79912514929147598821E-9;
ug := z*APGN/APGD;
k := sqpii*t;
aip := -k*(g*uf+f*ug);
bip := k*(f*uf-g*ug);
Exit;
end;
if AP_FP_Greater_Eq(x,2.09) then
begin
domflg := 5;
t := sqrt(x);
zeta := 2.0*x*t/3.0;
g := exp(zeta);
t := sqrt(t);
k := 2.0*t*g;
z := 1.0/zeta;
AN := 3.46538101525629032477E-1;
AN := AN*z+1.20075952739645805542E1;
AN := AN*z+7.62796053615234516538E1;
AN := AN*z+1.68089224934630576269E2;
AN := AN*z+1.59756391350164413639E2;
AN := AN*z+7.05360906840444183113E1;
AN := AN*z+1.40264691163389668864E1;
AN := AN*z+9.99999999999999995305E-1;
AD := 5.67594532638770212846E-1;
AD := AD*z+1.47562562584847203173E1;
AD := AD*z+8.45138970141474626562E1;
AD := AD*z+1.77318088145400459522E2;
AD := AD*z+1.64234692871529701831E2;
AD := AD*z+7.14778400825575695274E1;
AD := AD*z+1.40959135607834029598E1;
AD := AD*z+1.00000000000000000470E0;
f := AN/AD;
ai := sqpii*f/k;
k := -0.5*sqpii*t/g;
APN := 6.13759184814035759225E-1;
APN := APN*z+1.47454670787755323881E1;
APN := APN*z+8.20584123476060982430E1;
APN := APN*z+1.71184781360976385540E2;
APN := APN*z+1.59317847137141783523E2;
APN := APN*z+6.99778599330103016170E1;
APN := APN*z+1.39470856980481566958E1;
APN := APN*z+1.00000000000000000550E0;
APD := 3.34203677749736953049E-1;
APD := APD*z+1.11810297306158156705E1;
APD := APD*z+7.11727352147859965283E1;
APD := APD*z+1.58778084372838313640E2;
APD := APD*z+1.53206427475809220834E2;
APD := APD*z+6.86752304592780337944E1;
APD := APD*z+1.38498634758259442477E1;
APD := APD*z+9.99999999999999994502E-1;
f := APN/APD;
aip := f*k;
if AP_FP_Greater(x,8.3203353) then
begin
BN16 := -2.53240795869364152689E-1;
BN16 := BN16*z+5.75285167332467384228E-1;
BN16 := BN16*z-3.29907036873225371650E-1;
BN16 := BN16*z+6.44404068948199951727E-2;
BN16 := BN16*z-3.82519546641336734394E-3;
BD16 := 1.00000000000000000000E0;
BD16 := BD16*z-7.15685095054035237902E0;
BD16 := BD16*z+1.06039580715664694291E1;
BD16 := BD16*z-5.23246636471251500874E0;
BD16 := BD16*z+9.57395864378383833152E-1;
BD16 := BD16*z-5.50828147163549611107E-2;
f := z*BN16/BD16;
k := sqpii*g;
bi := k*(1.0+f)/t;
BPPN := 4.65461162774651610328E-1;
BPPN := BPPN*z-1.08992173800493920734E0;
BPPN := BPPN*z+6.38800117371827987759E-1;
BPPN := BPPN*z-1.26844349553102907034E-1;
BPPN := BPPN*z+7.62487844342109852105E-3;
BPPD := 1.00000000000000000000E0;
BPPD := BPPD*z-8.70622787633159124240E0;
BPPD := BPPD*z+1.38993162704553213172E1;
BPPD := BPPD*z-7.14116144616431159572E0;
BPPD := BPPD*z+1.34008595960680518666E0;
BPPD := BPPD*z-7.84273211323341930448E-2;
f := z*BPPN/BPPD;
bip := k*t*(1.0+f);
Exit;
end;
end;
f := 1.0;
g := x;
t := 1.0;
uf := 1.0;
ug := x;
k := 1.0;
z := x*x*x;
while AP_FP_Greater(t,MachineEpsilon) do
begin
uf := uf*z;
k := k+1.0;
uf := uf/k;
ug := ug*z;
k := k+1.0;
ug := ug/k;
uf := uf/k;
f := f+uf;
k := k+1.0;
ug := ug/k;
g := g+ug;
t := AbsReal(uf/f);
end;
uf := c1*f;
ug := c2*g;
if domflg mod 2=0 then
begin
ai := uf-ug;
end;
if domflg div 2 mod 2=0 then
begin
bi := sqrt3*(uf+ug);
end;
k := 4.0;
uf := x*x/2.0;
ug := z/3.0;
f := uf;
g := 1.0+ug;
uf := uf/3.0;
t := 1.0;
while AP_FP_Greater(t,MachineEpsilon) do
begin
uf := uf*z;
ug := ug/k;
k := k+1.0;
ug := ug*z;
uf := uf/k;
f := f+uf;
k := k+1.0;
ug := ug/k;
uf := uf/k;
g := g+ug;
k := k+1.0;
t := AbsReal(ug/g);
end;
uf := c1*f;
ug := c2*g;
if domflg div 4 mod 2=0 then
begin
aip := uf-ug;
end;
if domflg div 8 mod 2=0 then
begin
bip := sqrt3*(uf+ug);
end;
end;
end. |
{ *********************************************************************** }
{ }
{ Delphi Runtime Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
{*******************************************************}
{ Standard conversions types }
{*******************************************************}
{ ***************************************************************************
Physical, Fluidic, Thermal, and Temporal conversion units
The metric units and prefixes in this unit follow the various
SI/NIST standards (http://physics.nist.gov/cuu/Units/index.html and
http://www.bipm.fr/enus/3_SI). We have decided to use the Deca instead
of Deka to represent 10 of something.
Great conversion sites
http://www.ex.ac.uk/cimt/dictunit/dictunit.htm !! GREAT SITE !!
http://www.unc.edu/~rowlett/units/index.html !! GREAT SITE !!
http://www.omnis.demon.co.uk/indexfrm.htm !! GREAT SITE !!
http://www.sciencemadesimple.com/conversions.html
http://www.numberexchange.net/Convert/Weight.html
http://students.washington.edu/kyle/temp.html
http://www.convertit.com
***************************************************************************
References:
[1] NIST: Mendenhall Order of 1893
[2] http://ds.dial.pipex.com/nib/metric.htm
[3] http://www.omnis.demon.co.uk/conversn/oldenguk.htm
[4] NIST (http://physics.nist.gov/cuu/Units/outside.html)
[5] NIST (http://physics.nist.gov/cuu/Units/meter.html)
[6] Accepted best guess, but nobody really knows
[7] http://www.ex.ac.uk/cimt/dictunit/dictunit.htm
}
unit StdConvs;
interface
uses
SysUtils, ConvUtils;
var
{ ************************************************************************* }
{ Distance Conversion Units }
{ basic unit of measurement is meters }
cbDistance: TConvFamily;
duMicromicrons: TConvType;
duAngstroms: TConvType;
duMillimicrons: TConvType;
duMicrons: TConvType;
duMillimeters: TConvType;
duCentimeters: TConvType;
duDecimeters: TConvType;
duMeters: TConvType;
duDecameters: TConvType;
duHectometers: TConvType;
duKilometers: TConvType;
duMegameters: TConvType;
duGigameters: TConvType;
duInches: TConvType;
duFeet: TConvType;
duYards: TConvType;
duMiles: TConvType;
duNauticalMiles: TConvType;
duAstronomicalUnits: TConvType;
duLightYears: TConvType;
duParsecs: TConvType;
duCubits: TConvType;
duFathoms: TConvType;
duFurlongs: TConvType;
duHands: TConvType;
duPaces: TConvType;
duRods: TConvType;
duChains: TConvType;
duLinks: TConvType;
duPicas: TConvType;
duPoints: TConvType;
{ ************************************************************************* }
{ Area Conversion Units }
{ basic unit of measurement is square meters }
cbArea: TConvFamily;
auSquareMillimeters: TConvType;
auSquareCentimeters: TConvType;
auSquareDecimeters: TConvType;
auSquareMeters: TConvType;
auSquareDecameters: TConvType;
auSquareHectometers: TConvType;
auSquareKilometers: TConvType;
auSquareInches: TConvType;
auSquareFeet: TConvType;
auSquareYards: TConvType;
auSquareMiles: TConvType;
auAcres: TConvType;
auCentares: TConvType;
auAres: TConvType;
auHectares: TConvType;
auSquareRods: TConvType;
{ ************************************************************************* }
{ Volume Conversion Units }
{ basic unit of measurement is cubic meters }
cbVolume: TConvFamily;
vuCubicMillimeters: TConvType;
vuCubicCentimeters: TConvType;
vuCubicDecimeters: TConvType;
vuCubicMeters: TConvType;
vuCubicDecameters: TConvType;
vuCubicHectometers: TConvType;
vuCubicKilometers: TConvType;
vuCubicInches: TConvType;
vuCubicFeet: TConvType;
vuCubicYards: TConvType;
vuCubicMiles: TConvType;
vuMilliLiters: TConvType;
vuCentiLiters: TConvType;
vuDeciLiters: TConvType;
vuLiters: TConvType;
vuDecaLiters: TConvType;
vuHectoLiters: TConvType;
vuKiloLiters: TConvType;
vuAcreFeet: TConvType;
vuAcreInches: TConvType;
vuCords: TConvType;
vuCordFeet: TConvType;
vuDecisteres: TConvType;
vuSteres: TConvType;
vuDecasteres: TConvType;
vuFluidGallons: TConvType; { American Fluid Units }
vuFluidQuarts: TConvType;
vuFluidPints: TConvType;
vuFluidCups: TConvType;
vuFluidGills: TConvType;
vuFluidOunces: TConvType;
vuFluidTablespoons: TConvType;
vuFluidTeaspoons: TConvType;
vuDryGallons: TConvType; { American Dry Units }
vuDryQuarts: TConvType;
vuDryPints: TConvType;
vuDryPecks: TConvType;
vuDryBuckets: TConvType;
vuDryBushels: TConvType;
vuUKGallons: TConvType; { English Imperial Fluid/Dry Units }
vuUKPottles: TConvType;
vuUKQuarts: TConvType;
vuUKPints: TConvType;
vuUKGills: TConvType;
vuUKOunces: TConvType;
vuUKPecks: TConvType;
vuUKBuckets: TConvType;
vuUKBushels: TConvType;
{ ************************************************************************* }
{ Mass Conversion Units }
{ basic unit of measurement is grams }
cbMass: TConvFamily;
muNanograms: TConvType;
muMicrograms: TConvType;
muMilligrams: TConvType;
muCentigrams: TConvType;
muDecigrams: TConvType;
muGrams: TConvType;
muDecagrams: TConvType;
muHectograms: TConvType;
muKilograms: TConvType;
muMetricTons: TConvType;
muDrams: TConvType; // Avoirdupois Units
muGrains: TConvType;
muLongTons: TConvType;
muTons: TConvType;
muOunces: TConvType;
muPounds: TConvType;
muStones: TConvType;
{ ************************************************************************* }
{ Temperature Conversion Units }
{ basic unit of measurement is celsius }
cbTemperature: TConvFamily;
tuCelsius: TConvType;
tuKelvin: TConvType;
tuFahrenheit: TConvType;
tuRankine: TConvType;
tuReaumur: TConvType;
{ ************************************************************************* }
{ Time Conversion Units }
{ basic unit of measurement is days (which is also the same as TDateTime) }
cbTime: TConvFamily;
tuMilliSeconds: TConvType;
tuSeconds: TConvType;
tuMinutes: TConvType;
tuHours: TConvType;
tuDays: TConvType;
tuWeeks: TConvType;
tuFortnights: TConvType;
tuMonths: TConvType;
tuYears: TConvType;
tuDecades: TConvType;
tuCenturies: TConvType;
tuMillennia: TConvType;
tuDateTime: TConvType;
tuJulianDate: TConvType;
tuModifiedJulianDate: TConvType;
{ Constants (and their derivatives) used in this unit }
const
MetersPerInch = 0.0254; // [1]
MetersPerFoot = MetersPerInch * 12;
MetersPerYard = MetersPerFoot * 3;
MetersPerMile = MetersPerFoot * 5280;
MetersPerNauticalMiles = 1852;
MetersPerAstronomicalUnit = 1.49598E11; // [4]
MetersPerLightSecond = 2.99792458E8; // [5]
MetersPerLightYear = MetersPerLightSecond * 31556925.9747; // [7]
MetersPerParsec = MetersPerAstronomicalUnit * 206264.806247096; // 60 * 60 * (180 / Pi)
MetersPerCubit = 0.4572; // [6][7]
MetersPerFathom = MetersPerFoot * 6;
MetersPerFurlong = MetersPerYard * 220;
MetersPerHand = MetersPerInch * 4;
MetersPerPace = MetersPerInch * 30;
MetersPerRod = MetersPerFoot * 16.5;
MetersPerChain = MetersPerRod * 4;
MetersPerLink = MetersPerChain / 100;
MetersPerPoint = MetersPerInch * 0.013837; // [7]
MetersPerPica = MetersPerPoint * 12;
SquareMetersPerSquareInch = MetersPerInch * MetersPerInch;
SquareMetersPerSquareFoot = MetersPerFoot * MetersPerFoot;
SquareMetersPerSquareYard = MetersPerYard * MetersPerYard;
SquareMetersPerSquareMile = MetersPerMile * MetersPerMile;
SquareMetersPerAcre = SquareMetersPerSquareYard * 4840;
SquareMetersPerSquareRod = MetersPerRod * MetersPerRod;
CubicMetersPerCubicInch = MetersPerInch * MetersPerInch * MetersPerInch;
CubicMetersPerCubicFoot = MetersPerFoot * MetersPerFoot * MetersPerFoot;
CubicMetersPerCubicYard = MetersPerYard * MetersPerYard * MetersPerYard;
CubicMetersPerCubicMile = MetersPerMile * MetersPerMile * MetersPerMile;
CubicMetersPerAcreFoot = SquareMetersPerAcre * MetersPerFoot;
CubicMetersPerAcreInch = SquareMetersPerAcre * MetersPerInch;
CubicMetersPerCord = CubicMetersPerCubicFoot * 128;
CubicMetersPerCordFoot = CubicMetersPerCubicFoot * 16;
CubicMetersPerUSFluidGallon = CubicMetersPerCubicInch * 231; // [2][3][7]
CubicMetersPerUSFluidQuart = CubicMetersPerUSFluidGallon / 4;
CubicMetersPerUSFluidPint = CubicMetersPerUSFluidQuart / 2;
CubicMetersPerUSFluidCup = CubicMetersPerUSFluidPint / 2;
CubicMetersPerUSFluidGill = CubicMetersPerUSFluidCup / 2;
CubicMetersPerUSFluidOunce = CubicMetersPerUSFluidCup / 8;
CubicMetersPerUSFluidTablespoon = CubicMetersPerUSFluidOunce / 2;
CubicMetersPerUSFluidTeaspoon = CubicMetersPerUSFluidOunce / 6;
CubicMetersPerUSDryGallon = CubicMetersPerCubicInch * 268.8025; // [7]
CubicMetersPerUSDryQuart = CubicMetersPerUSDryGallon / 4;
CubicMetersPerUSDryPint = CubicMetersPerUSDryQuart / 2;
CubicMetersPerUSDryPeck = CubicMetersPerUSDryGallon * 2;
CubicMetersPerUSDryBucket = CubicMetersPerUSDryPeck * 2;
CubicMetersPerUSDryBushel = CubicMetersPerUSDryBucket * 2;
CubicMetersPerUKGallon = 0.00454609; // [2][7]
CubicMetersPerUKPottle = CubicMetersPerUKGallon / 2;
CubicMetersPerUKQuart = CubicMetersPerUKPottle / 2;
CubicMetersPerUKPint = CubicMetersPerUKQuart / 2;
CubicMetersPerUKGill = CubicMetersPerUKPint / 4;
CubicMetersPerUKOunce = CubicMetersPerUKPint / 20;
CubicMetersPerUKPeck = CubicMetersPerUKGallon * 2;
CubicMetersPerUKBucket = CubicMetersPerUKPeck * 2;
CubicMetersPerUKBushel = CubicMetersPerUKBucket * 2;
GramsPerPound = 453.59237; // [1][7]
GramsPerDrams = GramsPerPound / 256;
GramsPerGrains = GramsPerPound / 7000;
GramsPerTons = GramsPerPound * 2000;
GramsPerLongTons = GramsPerPound * 2240;
GramsPerOunces = GramsPerPound / 16;
{ various strings used in this unit }
resourcestring
{ ************************************************************************* }
{ Distance's family type }
SDistanceDescription = 'Distance';
{ Distance's various conversion types }
SMicromicronsDescription = 'Micromicrons';
SAngstromsDescription = 'Angstroms';
SMillimicronsDescription = 'Millimicrons';
SMicronsDescription = 'Microns';
SMillimetersDescription = 'Millimeters';
SCentimetersDescription = 'Centimeters';
SDecimetersDescription = 'Decimeters';
SMetersDescription = 'Meters';
SDecametersDescription = 'Decameters';
SHectometersDescription = 'Hectometers';
SKilometersDescription = 'Kilometers';
SMegametersDescription = 'Megameters';
SGigametersDescription = 'Gigameters';
SInchesDescription = 'Inches';
SFeetDescription = 'Feet';
SYardsDescription = 'Yards';
SMilesDescription = 'Miles';
SNauticalMilesDescription = 'NauticalMiles';
SAstronomicalUnitsDescription = 'AstronomicalUnits';
SLightYearsDescription = 'LightYears';
SParsecsDescription = 'Parsecs';
SCubitsDescription = 'Cubits';
SFathomsDescription = 'Fathoms';
SFurlongsDescription = 'Furlongs';
SHandsDescription = 'Hands';
SPacesDescription = 'Paces';
SRodsDescription = 'Rods';
SChainsDescription = 'Chains';
SLinksDescription = 'Links';
SPicasDescription = 'Picas';
SPointsDescription = 'Points';
{ ************************************************************************* }
{ Area's family type }
SAreaDescription = 'Area';
{ Area's various conversion types }
SSquareMillimetersDescription = 'SquareMillimeters';
SSquareCentimetersDescription = 'SquareCentimeters';
SSquareDecimetersDescription = 'SquareDecimeters';
SSquareMetersDescription = 'SquareMeters';
SSquareDecametersDescription = 'SquareDecameters';
SSquareHectometersDescription = 'SquareHectometers';
SSquareKilometersDescription = 'SquareKilometers';
SSquareInchesDescription = 'SquareInches';
SSquareFeetDescription = 'SquareFeet';
SSquareYardsDescription = 'SquareYards';
SSquareMilesDescription = 'SquareMiles';
SAcresDescription = 'Acres';
SCentaresDescription = 'Centares';
SAresDescription = 'Ares';
SHectaresDescription = 'Hectares';
SSquareRodsDescription = 'SquareRods';
{ ************************************************************************* }
{ Volume's family type }
SVolumeDescription = 'Volume';
{ Volume's various conversion types }
SCubicMillimetersDescription = 'CubicMillimeters';
SCubicCentimetersDescription = 'CubicCentimeters';
SCubicDecimetersDescription = 'CubicDecimeters';
SCubicMetersDescription = 'CubicMeters';
SCubicDecametersDescription = 'CubicDecameters';
SCubicHectometersDescription = 'CubicHectometers';
SCubicKilometersDescription = 'CubicKilometers';
SCubicInchesDescription = 'CubicInches';
SCubicFeetDescription = 'CubicFeet';
SCubicYardsDescription = 'CubicYards';
SCubicMilesDescription = 'CubicMiles';
SMilliLitersDescription = 'MilliLiters';
SCentiLitersDescription = 'CentiLiters';
SDeciLitersDescription = 'DeciLiters';
SLitersDescription = 'Liters';
SDecaLitersDescription = 'DecaLiters';
SHectoLitersDescription = 'HectoLiters';
SKiloLitersDescription = 'KiloLiters';
SAcreFeetDescription = 'AcreFeet';
SAcreInchesDescription = 'AcreInches';
SCordsDescription = 'Cords';
SCordFeetDescription = 'CordFeet';
SDecisteresDescription = 'Decisteres';
SSteresDescription = 'Steres';
SDecasteresDescription = 'Decasteres';
{ American Fluid Units }
SFluidGallonsDescription = 'FluidGallons';
SFluidQuartsDescription = 'FluidQuarts';
SFluidPintsDescription = 'FluidPints';
SFluidCupsDescription = 'FluidCups';
SFluidGillsDescription = 'FluidGills';
SFluidOuncesDescription = 'FluidOunces';
SFluidTablespoonsDescription = 'FluidTablespoons';
SFluidTeaspoonsDescription = 'FluidTeaspoons';
{ American Dry Units }
SDryGallonsDescription = 'DryGallons';
SDryQuartsDescription = 'DryQuarts';
SDryPintsDescription = 'DryPints';
SDryPecksDescription = 'DryPecks';
SDryBucketsDescription = 'DryBuckets';
SDryBushelsDescription = 'DryBushels';
{ English Imperial Fluid/Dry Units }
SUKGallonsDescription = 'UKGallons';
SUKPottlesDescription = 'UKPottle';
SUKQuartsDescription = 'UKQuarts';
SUKPintsDescription = 'UKPints';
SUKGillsDescription = 'UKGill';
SUKOuncesDescription = 'UKOunces';
SUKPecksDescription = 'UKPecks';
SUKBucketsDescription = 'UKBuckets';
SUKBushelsDescription = 'UKBushels';
{ ************************************************************************* }
{ Mass's family type }
SMassDescription = 'Mass';
{ Mass's various conversion types }
SNanogramsDescription = 'Nanograms';
SMicrogramsDescription = 'Micrograms';
SMilligramsDescription = 'Milligrams';
SCentigramsDescription = 'Centigrams';
SDecigramsDescription = 'Decigrams';
SGramsDescription = 'Grams';
SDecagramsDescription = 'Decagrams';
SHectogramsDescription = 'Hectograms';
SKilogramsDescription = 'Kilograms';
SMetricTonsDescription = 'MetricTons';
SDramsDescription = 'Drams';
SGrainsDescription = 'Grains';
STonsDescription = 'Tons';
SLongTonsDescription = 'LongTons';
SOuncesDescription = 'Ounces';
SPoundsDescription = 'Pounds';
{ ************************************************************************* }
{ Temperature's family type }
STemperatureDescription = 'Temperature';
{ Temperature's various conversion types }
SCelsiusDescription = 'Celsius';
SKelvinDescription = 'Kelvin';
SFahrenheitDescription = 'Fahrenheit';
SRankineDescription = 'Rankine';
SReaumurDescription = 'Reaumur';
{ ************************************************************************* }
{ Time's family type }
STimeDescription = 'Time';
{ Time's various conversion types }
SMilliSecondsDescription = 'MilliSeconds';
SSecondsDescription = 'Seconds';
SMinutesDescription = 'Minutes';
SHoursDescription = 'Hours';
SDaysDescription = 'Days';
SWeeksDescription = 'Weeks';
SFortnightsDescription = 'Fortnights';
SMonthsDescription = 'Months';
SYearsDescription = 'Years';
SDecadesDescription = 'Decades';
SCenturiesDescription = 'Centuries';
SMillenniaDescription = 'Millennia';
SDateTimeDescription = 'DateTime';
SJulianDateDescription = 'JulianDate';
SModifiedJulianDateDescription = 'ModifiedJulianDate';
{ simple temperature conversion }
function FahrenheitToCelsius(const AValue: Double): Double;
function CelsiusToFahrenheit(const AValue: Double): Double;
implementation
uses
DateUtils;
function FahrenheitToCelsius(const AValue: Double): Double;
begin
Result := ((AValue - 32) * 5) / 9;
end;
function CelsiusToFahrenheit(const AValue: Double): Double;
begin
Result := ((AValue * 9) / 5) + 32;
end;
function KelvinToCelsius(const AValue: Double): Double;
begin
Result := AValue - 273.15;
end;
function CelsiusToKelvin(const AValue: Double): Double;
begin
Result := AValue + 273.15;
end;
function RankineToCelsius(const AValue: Double): Double;
begin
Result := FahrenheitToCelsius(AValue - 459.67);
end;
function CelsiusToRankine(const AValue: Double): Double;
begin
Result := CelsiusToFahrenheit(AValue) + 459.67;
end;
function ReaumurToCelsius(const AValue: Double): Double;
begin
Result := ((CelsiusToFahrenheit(AValue) - 32) * 4) / 9;
end;
function CelsiusToReaumur(const AValue: Double): Double;
begin
Result := FahrenheitToCelsius(((AValue * 9) / 4) + 32);
end;
function ConvDateTimeToJulianDate(const AValue: Double): Double;
begin
Result := DateTimeToJulianDate(AValue);
end;
function ConvJulianDateToDateTime(const AValue: Double): Double;
begin
Result := JulianDateToDateTime(AValue);
end;
function ConvDateTimeToModifiedJulianDate(const AValue: Double): Double;
begin
Result := DateTimeToModifiedJulianDate(AValue);
end;
function ConvModifiedJulianDateToDateTime(const AValue: Double): Double;
begin
Result := ModifiedJulianDateToDateTime(AValue);
end;
initialization
{ ************************************************************************* }
{ Distance's family type }
cbDistance := RegisterConversionFamily(SDistanceDescription);
{ Distance's various conversion types }
duMicromicrons := RegisterConversionType(cbDistance, SMicromicronsDescription, 1E-12);
duAngstroms := RegisterConversionType(cbDistance, SAngstromsDescription, 1E-10);
duMillimicrons := RegisterConversionType(cbDistance, SMillimicronsDescription, 1E-9);
duMicrons := RegisterConversionType(cbDistance, SMicronsDescription, 1E-6);
duMillimeters := RegisterConversionType(cbDistance, SMillimetersDescription, 0.001);
duCentimeters := RegisterConversionType(cbDistance, SCentimetersDescription, 0.01);
duDecimeters := RegisterConversionType(cbDistance, SDecimetersDescription, 0.1);
duMeters := RegisterConversionType(cbDistance, SMetersDescription, 1);
duDecameters := RegisterConversionType(cbDistance, SDecametersDescription, 10);
duHectometers := RegisterConversionType(cbDistance, SHectometersDescription, 100);
duKilometers := RegisterConversionType(cbDistance, SKilometersDescription, 1000);
duMegameters := RegisterConversionType(cbDistance, SMegametersDescription, 1E+6);
duGigameters := RegisterConversionType(cbDistance, SGigametersDescription, 1E+9);
duInches := RegisterConversionType(cbDistance, SInchesDescription, MetersPerInch);
duFeet := RegisterConversionType(cbDistance, SFeetDescription, MetersPerFoot);
duYards := RegisterConversionType(cbDistance, SYardsDescription, MetersPerYard);
duMiles := RegisterConversionType(cbDistance, SMilesDescription, MetersPerMile);
duNauticalMiles := RegisterConversionType(cbDistance, SNauticalMilesDescription, MetersPerNauticalMiles);
duAstronomicalUnits := RegisterConversionType(cbDistance, SAstronomicalUnitsDescription, MetersPerAstronomicalUnit);
duLightYears := RegisterConversionType(cbDistance, SLightYearsDescription, MetersPerLightYear);
duParsecs := RegisterConversionType(cbDistance, SParsecsDescription, MetersPerParsec);
duCubits := RegisterConversionType(cbDistance, SCubitsDescription, MetersPerCubit);
duFathoms := RegisterConversionType(cbDistance, SFathomsDescription, MetersPerFathom);
duFurlongs := RegisterConversionType(cbDistance, SFurlongsDescription, MetersPerFurlong);
duHands := RegisterConversionType(cbDistance, SHandsDescription, MetersPerHand);
duPaces := RegisterConversionType(cbDistance, SPacesDescription, MetersPerPace);
duRods := RegisterConversionType(cbDistance, SRodsDescription, MetersPerRod);
duChains := RegisterConversionType(cbDistance, SChainsDescription, MetersPerChain);
duLinks := RegisterConversionType(cbDistance, SLinksDescription, MetersPerLink);
duPicas := RegisterConversionType(cbDistance, SPicasDescription, MetersPerPica);
duPoints := RegisterConversionType(cbDistance, SPointsDescription, MetersPerPoint);
{ ************************************************************************* }
{ Area's family type }
cbArea := RegisterConversionFamily(SAreaDescription);
{ Area's various conversion types }
auSquareMillimeters := RegisterConversionType(cbArea, SSquareMillimetersDescription, 1E-6);
auSquareCentimeters := RegisterConversionType(cbArea, SSquareCentimetersDescription, 0.0001);
auSquareDecimeters := RegisterConversionType(cbArea, SSquareDecimetersDescription, 0.01);
auSquareMeters := RegisterConversionType(cbArea, SSquareMetersDescription, 1);
auSquareDecameters := RegisterConversionType(cbArea, SSquareDecametersDescription, 100);
auSquareHectometers := RegisterConversionType(cbArea, SSquareHectometersDescription, 10000);
auSquareKilometers := RegisterConversionType(cbArea, SSquareKilometersDescription, 1E+6);
auSquareInches := RegisterConversionType(cbArea, SSquareInchesDescription, SquareMetersPerSquareInch);
auSquareFeet := RegisterConversionType(cbArea, SSquareFeetDescription, SquareMetersPerSquareFoot);
auSquareYards := RegisterConversionType(cbArea, SSquareYardsDescription, SquareMetersPerSquareYard);
auSquareMiles := RegisterConversionType(cbArea, SSquareMilesDescription, SquareMetersPerSquareMile);
auAcres := RegisterConversionType(cbArea, SAcresDescription, SquareMetersPerAcre);
auCentares := RegisterConversionType(cbArea, SCentaresDescription, 1);
auAres := RegisterConversionType(cbArea, SAresDescription, 100);
auHectares := RegisterConversionType(cbArea, SHectaresDescription, 10000);
auSquareRods := RegisterConversionType(cbArea, SSquareRodsDescription, SquareMetersPerSquareRod);
{ ************************************************************************* }
{ Volume's family type }
cbVolume := RegisterConversionFamily(SVolumeDescription);
{ Volume's various conversion types }
vuCubicMillimeters := RegisterConversionType(cbVolume, SCubicMillimetersDescription, 1E-9);
vuCubicCentimeters := RegisterConversionType(cbVolume, SCubicCentimetersDescription, 1E-6);
vuCubicDecimeters := RegisterConversionType(cbVolume, SCubicDecimetersDescription, 0.001);
vuCubicMeters := RegisterConversionType(cbVolume, SCubicMetersDescription, 1);
vuCubicDecameters := RegisterConversionType(cbVolume, SCubicDecametersDescription, 1000);
vuCubicHectometers := RegisterConversionType(cbVolume, SCubicHectometersDescription, 1E+6);
vuCubicKilometers := RegisterConversionType(cbVolume, SCubicKilometersDescription, 1E+9);
vuCubicInches := RegisterConversionType(cbVolume, SCubicInchesDescription, CubicMetersPerCubicInch);
vuCubicFeet := RegisterConversionType(cbVolume, SCubicFeetDescription, CubicMetersPerCubicFoot);
vuCubicYards := RegisterConversionType(cbVolume, SCubicYardsDescription, CubicMetersPerCubicYard);
vuCubicMiles := RegisterConversionType(cbVolume, SCubicMilesDescription, CubicMetersPerCubicMile);
vuMilliLiters := RegisterConversionType(cbVolume, SMilliLitersDescription, 1E-6);
vuCentiLiters := RegisterConversionType(cbVolume, SCentiLitersDescription, 1E-5);
vuDeciLiters := RegisterConversionType(cbVolume, SDeciLitersDescription, 1E-4);
vuLiters := RegisterConversionType(cbVolume, SLitersDescription, 0.001);
vuDecaLiters := RegisterConversionType(cbVolume, SDecaLitersDescription, 0.01);
vuHectoLiters := RegisterConversionType(cbVolume, SHectoLitersDescription, 0.1);
vuKiloLiters := RegisterConversionType(cbVolume, SKiloLitersDescription, 1);
vuAcreFeet := RegisterConversionType(cbVolume, SAcreFeetDescription, CubicMetersPerAcreFoot);
vuAcreInches := RegisterConversionType(cbVolume, SAcreInchesDescription, CubicMetersPerAcreInch);
vuCords := RegisterConversionType(cbVolume, SCordsDescription, CubicMetersPerCord);
vuCordFeet := RegisterConversionType(cbVolume, SCordFeetDescription, CubicMetersPerCordFoot);
vuDecisteres := RegisterConversionType(cbVolume, SDecisteresDescription, 0.1);
vuSteres := RegisterConversionType(cbVolume, SSteresDescription, 1);
vuDecasteres := RegisterConversionType(cbVolume, SDecasteresDescription, 10);
{ American Fluid Units }
vuFluidGallons := RegisterConversionType(cbVolume, SFluidGallonsDescription, CubicMetersPerUSFluidGallon);
vuFluidQuarts := RegisterConversionType(cbVolume, SFluidQuartsDescription, CubicMetersPerUSFluidQuart);
vuFluidPints := RegisterConversionType(cbVolume, SFluidPintsDescription, CubicMetersPerUSFluidPint);
vuFluidCups := RegisterConversionType(cbVolume, SFluidCupsDescription, CubicMetersPerUSFluidCup);
vuFluidGills := RegisterConversionType(cbVolume, SFluidGillsDescription, CubicMetersPerUSFluidGill);
vuFluidOunces := RegisterConversionType(cbVolume, SFluidOuncesDescription, CubicMetersPerUSFluidOunce);
vuFluidTablespoons := RegisterConversionType(cbVolume, SFluidTablespoonsDescription, CubicMetersPerUSFluidTablespoon);
vuFluidTeaspoons := RegisterConversionType(cbVolume, SFluidTeaspoonsDescription, CubicMetersPerUSFluidTeaspoon);
{ American Dry Units }
vuDryGallons := RegisterConversionType(cbVolume, SDryGallonsDescription, CubicMetersPerUSDryGallon);
vuDryQuarts := RegisterConversionType(cbVolume, SDryQuartsDescription, CubicMetersPerUSDryQuart);
vuDryPints := RegisterConversionType(cbVolume, SDryPintsDescription, CubicMetersPerUSDryPint);
vuDryPecks := RegisterConversionType(cbVolume, SDryPecksDescription, CubicMetersPerUSDryPeck);
vuDryBuckets := RegisterConversionType(cbVolume, SDryBucketsDescription, CubicMetersPerUSDryBucket);
vuDryBushels := RegisterConversionType(cbVolume, SDryBushelsDescription, CubicMetersPerUSDryBushel);
{ English Imperial Fluid/Dry Units }
vuUKGallons := RegisterConversionType(cbVolume, SUKGallonsDescription, CubicMetersPerUKGallon);
vuUKPottles := RegisterConversionType(cbVolume, SUKPottlesDescription, CubicMetersPerUKPottle);
vuUKQuarts := RegisterConversionType(cbVolume, SUKQuartsDescription, CubicMetersPerUKQuart);
vuUKPints := RegisterConversionType(cbVolume, SUKPintsDescription, CubicMetersPerUKPint);
vuUKGills := RegisterConversionType(cbVolume, SUKGillsDescription, CubicMetersPerUKGill);
vuUKOunces := RegisterConversionType(cbVolume, SUKOuncesDescription, CubicMetersPerUKOunce);
vuUKPecks := RegisterConversionType(cbVolume, SUKPecksDescription, CubicMetersPerUKPeck);
vuUKBuckets := RegisterConversionType(cbVolume, SUKBucketsDescription, CubicMetersPerUKBucket);
vuUKBushels := RegisterConversionType(cbVolume, SUKBushelsDescription, CubicMetersPerUKBushel);
{ ************************************************************************* }
{ Mass's family type }
cbMass := RegisterConversionFamily(SMassDescription);
{ Mass's various conversion types }
muNanograms := RegisterConversionType(cbMass, SNanogramsDescription, 1E-9);
muMicrograms := RegisterConversionType(cbMass, SMicrogramsDescription, 1E-6);
muMilligrams := RegisterConversionType(cbMass, SMilligramsDescription, 0.001);
muCentigrams := RegisterConversionType(cbMass, SCentigramsDescription, 0.01);
muDecigrams := RegisterConversionType(cbMass, SDecigramsDescription, 0.1);
muGrams := RegisterConversionType(cbMass, SGramsDescription, 1);
muDecagrams := RegisterConversionType(cbMass, SDecagramsDescription, 10);
muHectograms := RegisterConversionType(cbMass, SHectogramsDescription, 100);
muKilograms := RegisterConversionType(cbMass, SKilogramsDescription, 1000);
muMetricTons := RegisterConversionType(cbMass, SMetricTonsDescription, 1E+6);
muDrams := RegisterConversionType(cbMass, SDramsDescription, GramsPerDrams);
muGrains := RegisterConversionType(cbMass, SGrainsDescription, GramsPerGrains);
muTons := RegisterConversionType(cbMass, STonsDescription, GramsPerTons);
muLongTons := RegisterConversionType(cbMass, SLongTonsDescription, GramsPerLongTons);
muOunces := RegisterConversionType(cbMass, SOuncesDescription, GramsPerOunces);
muPounds := RegisterConversionType(cbMass, SPoundsDescription, GramsPerPound);
{ ************************************************************************* }
{ Temperature's family type }
cbTemperature := RegisterConversionFamily(STemperatureDescription);
{ Temperature's various conversion types }
tuCelsius := RegisterConversionType(cbTemperature, SCelsiusDescription, 1);
tuKelvin := RegisterConversionType(cbTemperature, SKelvinDescription,
KelvinToCelsius, CelsiusToKelvin);
tuFahrenheit := RegisterConversionType(cbTemperature, SFahrenheitDescription,
FahrenheitToCelsius, CelsiusToFahrenheit);
tuRankine := RegisterConversionType(cbTemperature, SRankineDescription,
RankineToCelsius, CelsiusToRankine);
tuReaumur := RegisterConversionType(cbTemperature, SReaumurDescription,
ReaumurToCelsius, CelsiusToReaumur);
{ ************************************************************************* }
{ Time's family type }
cbTime := RegisterConversionFamily(STimeDescription);
{ Time's various conversion types }
tuMilliSeconds := RegisterConversionType(cbTime, SMilliSecondsDescription, 1 / MSecsPerDay);
tuSeconds := RegisterConversionType(cbTime, SSecondsDescription, 1 / SecsPerDay);
tuMinutes := RegisterConversionType(cbTime, SMinutesDescription, 1 / MinsPerDay);
tuHours := RegisterConversionType(cbTime, SHoursDescription, 1 / HoursPerDay);
tuDays := RegisterConversionType(cbTime, SDaysDescription, 1);
tuWeeks := RegisterConversionType(cbTime, SWeeksDescription, DaysPerWeek);
tuFortnights := RegisterConversionType(cbTime, SFortnightsDescription, WeeksPerFortnight * DaysPerWeek);
tuMonths := RegisterConversionType(cbTime, SMonthsDescription, ApproxDaysPerMonth);
tuYears := RegisterConversionType(cbTime, SYearsDescription, ApproxDaysPerYear);
tuDecades := RegisterConversionType(cbTime, SDecadesDescription, ApproxDaysPerYear * YearsPerDecade);
tuCenturies := RegisterConversionType(cbTime, SCenturiesDescription, ApproxDaysPerYear * YearsPerCentury);
tuMillennia := RegisterConversionType(cbTime, SMillenniaDescription, ApproxDaysPerYear * YearsPerMillennium);
tuDateTime := RegisterConversionType(cbTime, SDateTimeDescription, 1);
tuJulianDate := RegisterConversionType(cbTime, SJulianDateDescription,
ConvJulianDateToDateTime, ConvDateTimeToJulianDate);
tuModifiedJulianDate := RegisterConversionType(cbTime, SModifiedJulianDateDescription,
ConvModifiedJulianDateToDateTime, ConvDateTimeToModifiedJulianDate);
finalization
{ Unregister all the conversion types we are responsible for }
UnregisterConversionFamily(cbDistance);
UnregisterConversionFamily(cbArea);
UnregisterConversionFamily(cbVolume);
UnregisterConversionFamily(cbMass);
UnregisterConversionFamily(cbTemperature);
UnregisterConversionFamily(cbTime);
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Menus, StdCtrls;
const
crMaletUp : integer = 5;
crMaletDown : integer = 6;
MissedPoints : integer = -2;
HitPoints : integer = 5;
MissedCritter : integer = -1;
CritterSize : integer = 72;
TimerId : integer = 1;
type
THole = record
Time : integer;
Dead : boolean;
end;
TSwatForm = class(TForm)
MainMenu1: TMainMenu;
Gamr1: TMenuItem;
New1: TMenuItem;
Options1: TMenuItem;
Stop1: TMenuItem;
Pause1: TMenuItem;
About1: TMenuItem;
Timer1: TTimer;
GameOverImage: TImage;
Image1: TImage;
TimeLabel: TLabel;
MissLabel: TLabel;
HitsLabel: TLabel;
EscapedLabel: TLabel;
ScoreLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure New1Click(Sender: TObject);
procedure Options1Click(Sender: TObject);
procedure Stop1Click(Sender: TObject);
procedure Pause1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
private
{ Private declarations }
Score : integer;
Hits, Miss, Escaped : integer;
IsGameOver, IsPause : Boolean;
Live : TBitmap;
Dead : TBitmap;
HoleInfo : array[0..4] of THole;
Holes : array[0..4] of TPoint;
procedure WriteScore;
public
{ Public declarations }
LiveTime, Frequence, GameTime : integer;
end;
var
SwatForm: TSwatForm;
implementation
uses options, about;
{$R *.dfm}
{$R extrares.res}
procedure TSwatForm.FormCreate(Sender: TObject);
begin
Holes[0] := Point( 10, 10 );
Holes[1] := Point( 200, 10 );
Holes[2] := Point( 100, 100 );
Holes[3] := Point( 10, 200 );
Holes[4] := Point( 200, 200 );
Screen.Cursors[crMaletUp] := LoadCursor(HInstance, 'Malet');
Screen.Cursors[crMaletDown] := LoadCursor(HInstance, 'MaletDown');
Screen.Cursor := TCursor(crMaletUp);
randomize;
Live := TBitmap.Create;
Live.LoadFromResourceName(HInstance, 'Live');
Dead := TBitmap.Create;
Dead.LoadFromResourceName(HInstance, 'Dead');
IsGameOver := true;
IsPause := false;
LiveTime := 10;
Frequence := 20;
GameTime := 150; // fifteen seconds
Application.OnMinimize := Pause1Click;
Application.OnRestore := Pause1Click;
end;
procedure TSwatForm.Timer1Timer(Sender: TObject);
var
i : integer;
begin
Timer1.Tag := Timer1.Tag + 1;
i := random(Frequence);
if (i < 5) then
begin
if (HoleInfo[i].Time = 0) then
begin
HoleInfo[i].Time := Timer1.Tag + LiveTime;
HoleInfo[i].Dead := false;
Canvas.Draw(Holes[i].x, Holes[i].y, Live);
end;
end;
for i := 0 to 4 do
begin
if ( (Timer1.Tag > HoleInfo[i].Time ) and ( HoleInfo[i].Time <> 0 ) ) then
begin
HoleInfo[i].Time := 0;
if not(HoleInfo[i].Dead) then
begin
inc( Score, MissedCritter );
inc( Escaped );
end;
Canvas.FillRect(Rect(Holes[i].x, Holes[i].y, Holes[i].x + Dead.Width, Holes[i].y + Dead.Height));
end;
end;
WriteScore;
if (Timer1.Tag >= GameTime) then
Stop1Click(self);
end;
procedure TSwatForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
i : integer;
hit : boolean;
begin
Screen.Cursor := TCursor(crMaletDown);
if (IsGameOver or IsPause) then
exit;
hit := false;
for i := 0 to 4 do
if ( (not HoleInfo[i].Dead) and (HoleInfo[i].Time <> 0) ) then
if (X > Holes[i].x ) and ( X < (Holes[i].x + Live.Width) ) and
( Y > Holes[i].y ) and ( Y < (Holes[i].y + Live.Height)) then
begin
inc( Score, HitPoints );
HoleInfo[i].Dead := true;
HoleInfo[i].Time := Timer1.Tag + 2 * LiveTime;
inc( Hits );
hit := true;
Canvas.Draw(Holes[i].x, Holes[i].y, Dead);
end;
if not(hit) then
begin
inc ( Score, MissedPoints );
inc( Miss );
end;
WriteScore;
end;
procedure TSwatForm.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Screen.Cursor := TCursor(crMaletUp);
end;
procedure TSwatForm.New1Click(Sender: TObject);
begin
Timer1.Enabled := true;
Timer1.Tag := 0;
Score := 0;
Hits := 0;
Miss := 0;
Escaped := 0;
if (IsPause)
then begin
IsPause := false;
Pause1.Caption := '&Pause';
end;
GameOverImage.Visible := false;
IsGameOver := false;
FillChar(HoleInfo, sizeof(HoleInfo), 0);
New1.Enabled := false;
Options1.Enabled := false;
Stop1.Enabled := true;
end;
procedure TSwatForm.Options1Click(Sender: TObject);
begin
OptionsDlg.ShowModal;
end;
procedure TSwatForm.Stop1Click(Sender: TObject);
var
i : integer;
begin
Timer1.Enabled := false;
IsPause := false;
GameOverImage.Visible := true;
IsGameOver := true;
Timer1.Tag := GameTime;
New1.Enabled := true;
Options1.Enabled := true;
Stop1.Enabled := false;
for i := 0 to 4 do
if (HoleInfo[i].Time <> 0) then
Canvas.FillRect(Rect(Holes[i].x, Holes[i].y, Holes[i].x + Dead.Width,
Holes[i].y + Dead.Height));
end;
procedure TSwatForm.Pause1Click(Sender: TObject);
begin
if (IsGameOver) then
exit;
if (IsPause) then
begin
IsPause := false;
Pause1.Caption := '&Pause';
Stop1.Enabled := true;
Timer1.Enabled := true;
end
else
begin
IsPause := true;
Pause1.Caption := '&Continue';
Stop1.Enabled := false;
Timer1.Enabled := false;
end;
end;
procedure TSwatForm.About1Click(Sender: TObject);
begin
AboutBox.ShowModal;
end;
procedure TSwatForm.WriteScore;
begin
TimeLabel.Caption := IntToStr(GameTime - Timer1.Tag);
HitsLabel.Caption := IntToStr(Hits);
MissLabel.Caption := IntToStr(Miss);
EscapedLabel.Caption := IntToStr(Escaped);
ScoreLabel.Caption := IntToStr(Score);
end;
end.
|
unit oCoverSheet;
{
================================================================================
*
* Application: CPRS - Coversheet controller object
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Primary (Singleton) Coversheet Controller
*
* Notes:
*
================================================================================
}
interface
uses
Dialogs,
System.Classes,
System.SysUtils,
System.Generics.Collections,
System.Types,
System.StrUtils,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Graphics,
iGridPanelIntf,
iCoverSheetIntf;
type
TCoverSheet = class(TInterfacedObject, ICoverSheet, ICPRS508, ICPRSTab)
private
fUniqueID: string;
fIPAddress: string;
fParamList: ICoverSheetParamList;
fControls: TObjectList<TControl>;
fCoverSheetRows: array of IGridPanelDisplay;
fFontSize: integer;
fScreenReaderActive: boolean;
fGridSettings: ICoverSheetGrid;
{ External event pointers }
fOnRefreshCWAD: TNotifyEvent;
fOnRefreshReminders: TNotifyEvent;
{ External RefreshCWAD event support }
function getOnRefreshCWAD: TNotifyEvent;
procedure setOnRefreshCWAD(const aValue: TNotifyEvent);
procedure fRefreshCWAD(Sender: TObject);
{ External RefreshReminders event support }
function getOnRefreshReminders: TNotifyEvent;
procedure setOnRefreshReminders(const aValue: TNotifyEvent);
procedure fRefreshReminders(Sender: TObject);
function getParams: ICoverSheetParamList;
function getUniqueID: string;
function getIPAddress: string;
function getIsFinishedLoading: boolean;
function getPanelCount: integer;
protected
{ ICPRS508 }
procedure OnFocusFirstControl(Sender: TObject); virtual;
procedure OnSetFontSize(Sender: TObject; aNewSize: integer); virtual;
procedure OnSetScreenReaderStatus(Sender: TObject; aActive: boolean); virtual;
{ ICPRSTab }
procedure OnClearPtData(Sender: TObject); virtual;
procedure OnDisplayPage(Sender: TObject; aCallingContext: integer); virtual;
procedure OnLoaded(Sender: TObject); virtual;
{ ICoverSheet }
procedure OnDisplay(Sender: TObject; aGridPanel: TGridPanel); virtual; final;
procedure OnExpandAllPanels(Sender: TObject); virtual; final;
procedure OnInitCoverSheet(Sender: TObject); virtual; final;
procedure OnRefreshPanel(Sender: TObject; aPanelID: integer); virtual; final;
procedure OnSwitchToPatient(Sender: TObject; aDFN: string); virtual;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
oCoverSheetGrid,
oCoverSheetParam_CPRS,
oCoverSheetParam_CPRS_ActiveMeds,
oCoverSheetParam_CPRS_Allergies,
oCoverSheetParam_CPRS_Appts,
oCoverSheetParam_CPRS_Immunizations,
oCoverSheetParam_CPRS_Labs,
oCoverSheetParam_CPRS_Postings,
oCoverSheetParam_CPRS_ProblemList,
oCoverSheetParam_CPRS_Reminders,
oCoverSheetParam_CPRS_Vitals,
oCoverSheetParam_CPRS_WH,
oCoverSheetParam_WidgetClock,
oCoverSheetParam_Web,
oCoverSheetParamList,
ORFn,
ORNet;
{ TCoverSheet }
constructor TCoverSheet.Create;
begin
inherited Create;
TCoverSheetParamList.Create.GetInterface(ICoverSheetParamList, fParamList);
fControls := TObjectList<TControl>.Create;
fControls.OwnsObjects := False;
fUniqueID := NewGUID;
fIPAddress := DottedIPStr;
fOnRefreshCWAD := fRefreshCWAD;
fFontSize := 8;
fScreenReaderActive := False;
SetLength(fCoverSheetRows, 0);
TCoverSheetGrid.Create.GetInterface(ICoverSheetGrid, fGridSettings);
end;
destructor TCoverSheet.Destroy;
begin
fParamList := nil;
fControls.Clear;
FreeAndNil(fControls);
inherited;
end;
procedure TCoverSheet.OnClearPtData(Sender: TObject);
var
aControl: TControl;
aCPRSTab: ICPRSTab;
begin
for aControl in fControls do
if Supports(aControl, ICPRSTab, aCPRSTab) then
aCPRSTab.OnClearPtData(Sender);
end;
procedure TCoverSheet.OnDisplayPage(Sender: TObject; aCallingContext: integer);
begin
//
end;
procedure TCoverSheet.OnLoaded(Sender: TObject);
begin
//
end;
procedure TCoverSheet.OnDisplay(Sender: TObject; aGridPanel: TGridPanel);
var
aParam: ICoverSheetParam;
aDisplayPanel: ICoverSheetDisplayPanel;
aGridPanelFrame: IGridPanelFrame;
aCPRS508: ICPRS508;
aControl: TControl;
aIndex: integer;
aGridPanelRow: TGridPanel;
aCol: integer;
aRow: integer;
begin
try
fGridSettings.PanelCount := fParamList.Count;
aGridPanel.Visible := False;
aGridPanel.Align := alNone;
{ NOTE: Actual controls are free'd aGridPanel.ControlCollection.Clear }
fControls.Clear;
aGridPanel.ControlCollection.Clear;
aGridPanel.RowCollection.Clear;
aGridPanel.ColumnCollection.Clear;
{ Make sure we have ONLY 1 column }
aGridPanel.ColumnCollection.Add;
{ Make sure we have enough rows }
while aGridPanel.RowCollection.Count < fGridSettings.RowCount do
aGridPanel.RowCollection.Add;
{ Build the rows as plain TGridPanels but store their interfaces in fCoverSheetRows }
SetLength(fCoverSheetRows, aGridPanel.RowCollection.Count);
for aIndex := 0 to aGridPanel.RowCollection.Count - 1 do
begin
{ Get new TGridPanel for the row in aIndex }
NewGridPanel(aGridPanel, 1, 1, aGridPanelRow);
aGridPanelRow.Name := Format('%s_Row_%d', [aGridPanelRow.ClassName, aIndex]);
aGridPanelRow.Parent := aGridPanel;
{ Add this TGridPanel the main Grid at Col 0, Row aIndex }
aGridPanel.ControlCollection.AddControl(aGridPanelRow, 0, aIndex);
{ Create new IGridPanelDisplay for this TGridPanel Row and place it in fCoverSheetRows }
NewGridPanelDisplay(aGridPanelRow, fCoverSheetRows[aIndex]);
end;
{ Finally, we can start building and placing the frames into the fCoverSheetRows[] panels }
for aIndex := 0 to fParamList.Count - 1 do
begin
aParam := fParamList.ParamByIndex[aIndex];
aParam.DisplayRow := fGridSettings.PanelRow[aIndex];
aParam.DisplayColumn := fGridSettings.PanelColumn[aIndex];
aControl := aParam.NewCoverSheetControl(aGridPanel);
fControls.Add(aControl);
{ Set up the frame as an IGridPanelFrame }
if aControl.GetInterface(IGridPanelFrame, aGridPanelFrame) then
begin
aGridPanelFrame.Title := aParam.Title;
aGridPanelFrame.AllowCollapse := gpcColumn;
aGridPanelFrame.AllowRefresh := True;
end;
{ Assign the parameter to the frame }
if Supports(aControl, ICoverSheetDisplayPanel, aDisplayPanel) then
aDisplayPanel.Params := aParam;
{ Hook up the 508 'stuff' }
if Supports(aControl, ICPRS508, aCPRS508) then
begin
aCPRS508.OnSetFontSize(Self, fFontSize);
aCPRS508.OnSetScreenReaderStatus(Self, fScreenReaderActive);
end;
{ Make sure we have enough columns in this row (we are now using IGridPanelDisplay) }
while (fCoverSheetRows[aParam.DisplayRow].ColumnCount - 1) < aParam.DisplayColumn do
fCoverSheetRows[aParam.DisplayRow].AddColumn;
{ Finally add the control }
fCoverSheetRows[aParam.DisplayRow].AddControl(aControl, aParam.DisplayColumn, 0, alClient);
end;
{ We have a complete set of frames in the Main TGridPanel and it's rows!!! Align some stuff }
try
aGridPanel.RowCollection.BeginUpdate;
for aRow := 0 to aGridPanel.RowCollection.Count - 1 do
begin
aGridPanel.RowCollection[aRow].SizeStyle := ssPercent;
aGridPanel.RowCollection[aRow].Value := (100 / aGridPanel.RowCollection.Count);
for aCol := 0 to fCoverSheetRows[aRow].ColumnCount - 1 do
begin
fCoverSheetRows[aRow].ColumnStyle[aCol] := ssPercent;
fCoverSheetRows[aRow].ColumnValue[aCol] := (100 / fCoverSheetRows[aRow].ColumnCount);
end;
fCoverSheetRows[aRow].AlignGrid;
end;
finally
aGridPanel.RowCollection.EndUpdate;
end;
aGridPanel.Align := alClient;
aGridPanel.Show;
aGridPanel.Repaint;
except
on e: Exception do
raise ECoverSheetException.CreateFmt('ECoverSheetException: Error: %s', [e.Message]);
end;
end;
procedure TCoverSheet.OnExpandAllPanels(Sender: TObject);
var
i: integer;
begin
for i := 0 to High(fCoverSheetRows) do
fCoverSheetRows[i].ExpandAllControls;
end;
function TCoverSheet.getIsFinishedLoading: boolean;
var
aControl: TControl;
aCoverSheetDisplayPanel: ICoverSheetDisplayPanel;
aList: TStringList;
begin
Result := True;
aList := TStringList.Create;
try
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aCoverSheetDisplayPanel) then
if not aCoverSheetDisplayPanel.IsFinishedLoading then
begin
aList.Add(aCoverSheetDisplayPanel.Title + ' not finished');
Result := False;
end
else
aList.Add(aCoverSheetDisplayPanel.Title + ' finished');
finally
FreeAndNil(aList);
end;
end;
procedure TCoverSheet.OnFocusFirstControl(Sender: TObject);
var
aCPRS508: ICPRS508;
begin
if fControls.Count > 0 then
if Supports(fControls[0], ICPRS508, aCPRS508) then
aCPRS508.OnFocusFirstControl(Sender);
end;
function TCoverSheet.getOnRefreshCWAD: TNotifyEvent;
begin
Result := fOnRefreshCWAD;
end;
function TCoverSheet.getOnRefreshReminders: TNotifyEvent;
begin
Result := fOnRefreshReminders;
end;
procedure TCoverSheet.setOnRefreshCWAD(const aValue: TNotifyEvent);
begin
if Assigned(aValue) then
fOnRefreshCWAD := aValue
else
fOnRefreshCWAD := fRefreshCWAD;
end;
procedure TCoverSheet.setOnRefreshReminders(const aValue: TNotifyEvent);
begin
if Assigned(aValue) then
fOnRefreshReminders := aValue
else
fOnRefreshReminders := fRefreshReminders;
end;
procedure TCoverSheet.fRefreshCWAD(Sender: TObject);
begin
// this is only here in case the method is set nil. See the assesor methods
end;
procedure TCoverSheet.fRefreshReminders(Sender: TObject);
begin
// this is only here in case the method is set nil. See the assesor methods
end;
procedure TCoverSheet.OnRefreshPanel(Sender: TObject; aPanelID: integer);
var
aControl: TControl;
aCoverSheetDisplayPanel: ICoverSheetDisplayPanel;
begin
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aCoverSheetDisplayPanel) then
if aCoverSheetDisplayPanel.Params.ID = aPanelID then
aCoverSheetDisplayPanel.OnRefreshDisplay(Self);
end;
procedure TCoverSheet.OnSetFontSize(Sender: TObject; aNewSize: integer);
var
aControl: TControl;
aCPRS508: ICPRS508;
begin
fFontSize := aNewSize;
for aControl in fControls do
if Supports(aControl, ICPRS508, aCPRS508) then
aCPRS508.OnSetFontSize(Self, fFontSize);
end;
procedure TCoverSheet.OnSetScreenReaderStatus(Sender: TObject; aActive: boolean);
var
aControl: TControl;
aCPRS508: ICPRS508;
begin
fScreenReaderActive := aActive;
for aControl in fControls do
if Supports(aControl, ICPRS508, aCPRS508) then
aCPRS508.OnSetScreenReaderStatus(Self, fScreenReaderActive);
end;
procedure TCoverSheet.OnSwitchToPatient(Sender: TObject; aDFN: string);
var
aDisplayPanel: ICoverSheetDisplayPanel;
aControl: TControl;
aParam: ICoverSheetParam;
aParam_CPRS: ICoverSheetParam_CPRS;
aForeground: string;
begin
try
// Call the background job starter and get those that are run in aForeground
if aDFN <> '' then
begin
CallVistA('ORWCV START', [aDFN, CoverSheet.IPAddress, CoverSheet.UniqueID], aForeground);
for aParam in fParamList do
if Supports(aParam, ICoverSheetParam_CPRS, aParam_CPRS) then
begin
aParam_CPRS.LoadInBackground := Pos(IntToStr(aParam_CPRS.ID), aForeground) = 0;
aParam_CPRS.OnNewPatient(Self);
end;
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aDisplayPanel) then
aDisplayPanel.OnBeginUpdate(Self);
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aDisplayPanel) then
aDisplayPanel.OnRefreshDisplay(Self);
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aDisplayPanel) then
aDisplayPanel.OnEndUpdate(Self);
end
else { DFN passed in as blank, clear the coversheet }
for aControl in fControls do
if Supports(aControl, ICoverSheetDisplayPanel, aDisplayPanel) then
aDisplayPanel.OnClearPtData(Self);
except
on e: Exception do
raise ECoverSheetSwitchPtFail.Create(e.Message);
end;
OnExpandAllPanels(Self);
end;
function TCoverSheet.getIPAddress: string;
begin
Result := fIPAddress;
end;
function TCoverSheet.getPanelCount: integer;
begin
if Assigned(fGridSettings) then
Result := fGridSettings.PanelCount
else
Result := 0;
end;
function TCoverSheet.getParams: ICoverSheetParamList;
begin
fParamList.QueryInterface(ICoverSheetParamList, Result);
end;
function TCoverSheet.getUniqueID: string;
begin
Result := fUniqueID;
end;
procedure TCoverSheet.OnInitCoverSheet(Sender: TObject);
var
aReturn: TStringList;
aInitStr: string;
aParam: ICoverSheetParam;
begin
aReturn := TStringList.Create;
CoverSheet.Params.Clear;
{ Push in the CPRS style params }
try
try
CallVistA('ORWCV1 COVERSHEET LIST', [], aReturn);
// Proof of concepts!
// aReturn.Insert(0, '1001^My Web Browser^http://www.domain^1');
// aReturn.Insert(0, '1001^My Web Page');
// aReturn.Insert(0, '1000^Clock');
for aInitStr in aReturn do
begin
case StrToIntDef(Copy(aInitStr, 1, Pos('^', aInitStr) - 1), 0) of
CV_CPRS_PROB: TCoverSheetParam_CPRS_ProblemList.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_POST: TCoverSheetParam_CPRS_Postings.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_ALLG: TCoverSheetParam_CPRS_Allergies.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_MEDS: TCoverSheetParam_CPRS_ActiveMeds.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_RMND: TCoverSheetParam_CPRS_Reminders.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_LABS: TCoverSheetParam_CPRS_Labs.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_VITL: TCoverSheetParam_CPRS_Vitals.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_VSIT: TCoverSheetParam_CPRS_Appts.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_IMMU: TCoverSheetParam_CPRS_Immunizations.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_CPRS_WVHT: TCoverSheetParam_CPRS_WH.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_WDGT_CLOCK: TCoverSheetParam_WidgetClock.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
CV_WDGT_MINIBROWSER: TCoverSheetParam_Web.Create(aInitStr).GetInterface(ICoverSheetParam, aParam);
else
aParam := nil;
end;
if aParam <> nil then
CoverSheet.Params.Add(aParam);
end;
except
on e: Exception do
raise ECoverSheetInitFail.Create(e.Message);
end;
finally
FreeAndNil(aReturn);
end;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls,
SysUtils, Dialogs, OpenGL;
const
MaxVideoModes = 200; // этого должно хватить
type TVideoMode = record
Width,
Height,
ColorDepth : Word;
Description : String[20];
end;
type
TLowResMode = record
Width,
Height,
ColorDepth : Word;
end;
const
NumberLowResModes = 60;
LowResModes : array[0..NumberLowResModes-1] of TLowResMode =
((Width:320;Height:200;ColorDepth: 8),(Width:320;Height:200;ColorDepth:15),
(Width:320;Height:200;ColorDepth:16),(Width:320;Height:200;ColorDepth:24),
(Width:320;Height:200;ColorDepth:32),(Width:320;Height:240;ColorDepth: 8),
(Width:320;Height:240;ColorDepth:15),(Width:320;Height:240;ColorDepth:16),
(Width:320;Height:240;ColorDepth:24),(Width:320;Height:240;ColorDepth:32),
(Width:320;Height:350;ColorDepth: 8),(Width:320;Height:350;ColorDepth:15),
(Width:320;Height:350;ColorDepth:16),(Width:320;Height:350;ColorDepth:24),
(Width:320;Height:350;ColorDepth:32),(Width:320;Height:400;ColorDepth: 8),
(Width:320;Height:400;ColorDepth:15),(Width:320;Height:400;ColorDepth:16),
(Width:320;Height:400;ColorDepth:24),(Width:320;Height:400;ColorDepth:32),
(Width:320;Height:480;ColorDepth: 8),(Width:320;Height:480;ColorDepth:15),
(Width:320;Height:480;ColorDepth:16),(Width:320;Height:480;ColorDepth:24),
(Width:320;Height:480;ColorDepth:32),(Width:360;Height:200;ColorDepth: 8),
(Width:360;Height:200;ColorDepth:15),(Width:360;Height:200;ColorDepth:16),
(Width:360;Height:200;ColorDepth:24),(Width:360;Height:200;ColorDepth:32),
(Width:360;Height:240;ColorDepth: 8),(Width:360;Height:240;ColorDepth:15),
(Width:360;Height:240;ColorDepth:16),(Width:360;Height:240;ColorDepth:24),
(Width:360;Height:240;ColorDepth:32),(Width:360;Height:350;ColorDepth: 8),
(Width:360;Height:350;ColorDepth:15),(Width:360;Height:350;ColorDepth:16),
(Width:360;Height:350;ColorDepth:24),(Width:360;Height:350;ColorDepth:32),
(Width:360;Height:400;ColorDepth: 8),(Width:360;Height:400;ColorDepth:15),
(Width:360;Height:400;ColorDepth:16),(Width:360;Height:400;ColorDepth:24),
(Width:360;Height:400;ColorDepth:32),(Width:360;Height:480;ColorDepth: 8),
(Width:360;Height:480;ColorDepth:15),(Width:360;Height:480;ColorDepth:16),
(Width:360;Height:480;ColorDepth:24),(Width:360;Height:480;ColorDepth:32),
(Width:400;Height:300;ColorDepth: 8),(Width:400;Height:300;ColorDepth:15),
(Width:400;Height:300;ColorDepth:16),(Width:400;Height:300;ColorDepth:24),
(Width:400;Height:300;ColorDepth:32),(Width:512;Height:384;ColorDepth: 8),
(Width:512;Height:384;ColorDepth:15),(Width:512;Height:384;ColorDepth:16),
(Width:512;Height:384;ColorDepth:24),(Width:512;Height:384;ColorDepth:32));
var
VideoModes : array [0..MaxVideoModes] of TVideoMode;
ScreenModeChanged : Boolean;
NumberVideomodes : Integer = 1; // как минимум 1, 'default' режим
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
hrc: HGLRC;
procedure SetDCPixelFormat (DC : HDC);
function SetFullscreenMode(ModeIndex: Integer) : Boolean;
procedure TryToAddToList(DeviceMode: TDevMode);
procedure ReadVideoModes;
procedure RestoreDefaultMode;
public
SelectedMode : Integer;
end;
var
frmGL: TfrmGL;
implementation
uses Unit1;
{$R *.DFM}
function TfrmGL.SetFullscreenMode(ModeIndex: Integer) : Boolean;
// устанавливаем видеорежим согласно аргументу 'ModeIndex'
var
DeviceMode : TDevMode;
begin
with DeviceMode do begin
dmSize := SizeOf(DeviceMode);
dmBitsPerPel := VideoModes[ModeIndex].ColorDepth;
dmPelsWidth := VideoModes[ModeIndex].Width;
dmPelsHeight := VideoModes[ModeIndex].Height;
dmFields := DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT;
// если режим не устанавливается, ScreenModeChanged = False
Result := ChangeDisplaySettings(DeviceMode,CDS_FULLSCREEN) = DISP_CHANGE_SUCCESSFUL;
if Result then ScreenModeChanged := True;
if ModeIndex = 0 then ScreenModeChanged:=False;
end;
end;
procedure TfrmGL.TryToAddToList(DeviceMode: TDevMode);
// Добавить видеорежим в список, если это не дублированный
// и действительно его можно установить
var
I : Integer;
begin
// отделить дублированный режим (может случиться из-за освежения
// показателей, или из-за того, что мы явно пробуем весь низкоуровневые режимы).
for I := 1 to NumberVideomodes - 1 do
with DeviceMode do
if ((dmBitsPerPel = VideoModes[I].ColorDepth) and
(dmPelsWidth = VideoModes[I].Width) and
(dmPelsHeight = VideoModes[I].Height)) then Exit;
// тестирование режима (не устанавливает режим, но сообщает, удалось ли бы это).
if ChangeDisplaySettings(DeviceMode,CDS_TEST or CDS_FULLSCREEN) <> DISP_CHANGE_SUCCESSFUL then Exit;
// это - новый, правильный способ, так что дополняем его в список
with DeviceMode do begin
VideoModes[NumberVideomodes].ColorDepth:=dmBitsPerPel;
VideoModes[NumberVideomodes].Width:=dmPelsWidth;
VideoModes[NumberVideomodes].Height:=dmPelsHeight;
VideoModes[NumberVideomodes].Description:=Format('%d x %d, %d bpp',[dmPelsWidth,dmPelsHeight,dmBitsPerPel]);
end;
Inc(NumberVideomodes);
end;
procedure TfrmGL.ReadVideoModes;
var
I, ModeNumber : Integer;
done : Boolean;
DeviceMode : TDevMode;
DeskDC : HDC;
begin
// подготовим 'default' режим
with VideoModes[0] do
try
DeskDC := GetDC (0);
ColorDepth := GetDeviceCaps (DeskDC, BITSPIXEL);
Width := Screen.Width;
Height := Screen.Height;
Description := 'default';
finally
ReleaseDC(0, DeskDC);
end;
// перечисляем все доступные видеорежимы
ModeNumber:=0;
done := False;
repeat
done := not EnumDisplaySettings(nil,ModeNumber,DeviceMode);
TryToAddToList(DeviceMode);
Inc(ModeNumber);
until (done or (NumberVideomodes >= MaxVideoModes));
// запрашиваем явно о низкоуровневых режимах
with DeviceMode do begin
dmBitsPerPel:=8;
dmPelsWidth:=42;
dmPelsHeight:=37;
dmFields:=DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT;
// убедимся, что драйвер не отвечает "да" во всех тестах
if ChangeDisplaySettings(DeviceMode,CDS_TEST or CDS_FULLSCREEN) <> DISP_CHANGE_SUCCESSFUL then
begin
I:=0;
while (I < NumberLowResModes-1) and (NumberVideoModes < MaxVideoModes) do
begin
dmSize:=Sizeof(DeviceMode);
dmBitsPerPel:=LowResModes[I].ColorDepth;
dmPelsWidth:=LowResModes[I].Width;
dmPelsHeight:=LowResModes[I].Height;
dmFields:=DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT;
TryToAddToList(DeviceMode);
Inc(I);
end;
end;
end;
end;
procedure TfrmGL.RestoreDefaultMode;
// возвращение первоначального режима экрана
var
T : TDevMode absolute 0; // небольшая хитрость, чтобы создать указатель нуля
begin
// Первый параметр должен быть переменной, нельзя использовать непосредственно нуль
// Взамен мы используем переменную с абсолютным адресом 0.
ChangeDisplaySettings(T, CDS_FULLSCREEN);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
var
i : 0..MaxVideoModes;
Form1 : TForm1;
begin
ReadVideoModes;
Form1 := TForm1.Create (Self);
For i := 0 to MaxVideoModes do
If VideoModes[i].Description <> '' then
Form1.ComboBox1.Items.Add (VideoModes[i].Description);
Form1.ComboBox1.ItemIndex := 0;
Form1.Showmodal;
Form1.Free;
SetFullscreenMode(SelectedMode);
WindowState := wsMaximized;
SetDCPixelFormat (Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
If hrc = 0 then
ShowMessage ('Ошибка получения контекста воспроизведения!');
end;
{=======================================================================
Формат пикселей}
procedure TfrmGL.SetDCPixelFormat (DC : HDC);
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
RestoreDefaultMode;
end;
procedure TfrmGL.FormPaint(Sender: TObject);
begin
If hrc = 0 then Close;
wglMakeCurrent(Canvas.Handle, hrc);
glClearColor(0.25, 0.1, 0.75,0.0);
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
wglMakeCurrent(0, 0);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit MetroBase;
//# BEGIN TODO Completed by: author name, id.nr., date
{ E.I.R. van Delden, 0618959, 09-05-08}
//# END TODO
interface
uses
Contnrs, IniFiles,
StringValidators;
//==============================================================================
// Station
// A station has:
// - a code: a short key that serves to identify the station uniquely within
// the system, e.g. 'CDG'
// - a name: the name of the station as it appears on maps etc., e.g.
// 'Charles de Gaulle - Etoile'.
//
// The class TStationR is an abstract class providing read-only access to the
// data of a station.
// The class TStationRW is a descendant of TStationR; it provides a concrete
// representation and read/write access to the data of a station.
//==============================================================================
type
TStationR =
class(TObject)
public
Data: TObject; // scratch data field for use by planners etc.
// primitive queries -------------------------------------------------------
function GetCode: String; virtual; abstract;
// pre: True
function GetName: String; virtual; abstract;
// pre: True
// invariants --------------------------------------------------------------
// I0: ValidStationCode(GetCode) and ValidStationName(GetName)
end;
TStationRW =
class(TStationR)
private
FCode: String;
FName: String;
public
// construction ------------------------------------------------------------
constructor Create(ACode: String; AName: String);
// pre: ValidStationCode(ACode) and ValidStationName(AName)
// post: (GetCode = ACode) and (GetName = AName)
// TStationR overrides =====================================================
// primitive queries -------------------------------------------------------
function GetCode: String; override;
// pre: True
function GetName: String; override;
// pre: True
end;
//==============================================================================
// StationSet
//
// A stationset is a finite enumerable set of stations.
//
// The class TStationSetR is an abstract class providing read-only access to the
// data of a stationset.
// The class TStationSetRW is a descendant of TStationR; it provides a concrete
// representation and read/write access to a stationset.
//
//==============================================================================
TStationSetR =
class(TObject)
public
// primitive queries -------------------------------------------------------
function Count: Integer; virtual; abstract;
// pre: True
// ret: |Abstr|
function GetStation(I: Integer): TStationR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function IsEmpty: Boolean;
// pre: True
// ret: Count = 0
function HasStation(AStation: TStationR): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: GetStation(I) = AStation)
function HasCode(ACode: String): Boolean;
// pre: True
// ret: IndexOfCode(ACode) <> -1
function HasName(AName: String): Boolean;
// pre: True
// ret: IndexOfName(AName) <> -1
function IndexOfCode(ACode: String): Integer;
// pre: True
// ret: I such that GetStation(I).GetCode = ACode, or else -1
function IndexOfName(AName: String): Integer;
// pre: True
// ret: I such that GetStation(I).GetName = AName, or else -1
// model variables ---------------------------------------------------------
// Abstr: set of TStationRW
// invariants --------------------------------------------------------------
// Unique:
// (forall I, J: 0 <= I < J < Count:
// - GetStation(I) <> GetStation(J)
// - GetStation(I).GetCode <> GetStation(J).GetCode
// - GetStation(I).GetName <> GetStation(J).GetName
// )
end;
TStationSetRW =
class(TStationSetR)
protected
FList: TObjectList; // owner
// invariants --------------------------------------------------------------
// Abstr = {set S: 0 <= S < FList.Count: FList[S] as TStationR}
public
// construction/destruction ------------------------------------------------
constructor Create;
// pre: True
// post: Abstr = {}
destructor Destroy; override;
// pre: True
// effect: FList is freed
// TStationSetR overrides ==================================================
// primitive queries -------------------------------------
function Count: Integer; override;
// pre: True
// ret: |Abstr|
function GetStation(I: Integer): TStationR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddStation(AStation: TStationR): Boolean; virtual;
// pre: True
// ret: ValidStationCode(AStation.GetCode) and
// ValidStationName(AStation.GetName) and
// not HasCode(AStation.GetCode) and not HasName(AStation.GetName)
function CanDeleteStation(AStation: TStationR): Boolean; virtual;
// pre: True
// ret: True (may be overridden in subclasses)
function CanDeleteAll: Boolean; virtual;
// pre: True
// ret: True (may be overridden in subclasses)
function CanSetStationCode(AStation: TStationR; ACode: String): Boolean; virtual;
// pre: True
// ret: ValidStationCode(ACode) and HasStation(AStation) and
// not(HasCode(ACode))
function CanSetStationName(AStation: TStationR; AName: String): Boolean; virtual;
// pre: True
// ret: ValidStationName(AName) and HasStation(AStation) and
// not(HasName(AName))
// commands ----------------------------------------------------------------
procedure AddStation(AStation: TStationR);
// pre: CanAddStation(AStation)
// post: Abstr = old Abstr U {AStation}
procedure SetStationCode(AStation: TStationR; ACode: String); virtual;
// pre: CanSetStationCode(AStation, ACode)
// post: AStation.GetCode = ACode
procedure SetStationName(AStation: TStationR; AName: String); virtual;
// pre: CanSetStationName(AStation, AName)
// post: AStation.GetName = AName
procedure DeleteStation(AStation: TStationR);
// pre: CanDeleteStation(AStation)
// post: Abstr = old Abstr \ {AStation}
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = {}
end;
//==============================================================================
// Line
//
// A line has:
// - a code: a short key that serves to identify the line uniquely within
// the system, e.g. 'ERM'.
// - a name: the name of the line as it appears on maps etc., e.g.
// 'Erasmuslijn' or '7bis'.
// - a sequence of stops; each stop is a station.
// - a set of options, e.g.: oneway, circular.
//
// The class TLineR is an abstract class providing read-only access to the
// data of a line.
// The class TLineRW is a descendant of TLineR; it provides a concrete
// representation and read/write access to the data of a line.
//==============================================================================
type
TLineOption = (loOneWay, loCircular);
TLineOptions = set of TLineOption;
TLineR =
class(TObject)
public
Data: TObject; // scratch data field, used by planners etc.
// primitive queries -------------------------------------------------------
function GetCode: String; virtual; abstract;
// pre: True
function GetName: String; virtual; abstract;
// pre: True
function GetOptions: TLineOptions; virtual; abstract;
// pre: True
function Count: Integer; virtual; abstract;
// pre: True
// ret: |Abstr|
function IndexOf(AStation: TStationR): Integer; virtual; abstract;
// pre: True
// ret: I such that Abstr[I] = AStation, or else -1
function Stop(I: Integer): TStationR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function TerminalA: TStationR;
// pre: Count > 0
// ret: Stop(0)
function TerminalB: TStationR;
// pre: Count > 0
// ret: Stop(Count - 1)
function IsOneWay: Boolean;
// pre: True
// ret: loOneWay in GetOptions
function IsCircular: Boolean;
// pre: True
// ret: loCircular in GetOptions
function HasStop(AStation: TStationR): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: Stop(I) = AStation )
// model variables ---------------------------------------------------------
// Abstr: seq of TStationR
// invariants --------------------------------------------------------------
// I0: ValidLineCode(GetCode) and ValidLineName(GetName)
// Stops_Unique:
// (forall I, J: 0 <= I < J < Count: Stop(I) <> Stop(J))
end;
TLineRW =
class(TLineR)
protected
FCode: String;
FName: String;
FOptions: TLineOptions;
FList: TObjectList; // shared
// invariants --------------------------------------------------------------
// A0: Abstr = (seq S: 0 <= S < FList.Count: FList[S] as TStationR)
public
// construction/destruction ------------------------------------------------
constructor Create(ACode: String; AName: String; AOptions: TLineOptions);
// pre: ValidLineCode(ACode), ValidLineName(AName)
// post: GetCode = ACode and GetName = AName and GetOptions = AOptions
// and (Count = 0)
destructor Destroy; override;
// pre: True
// effect: FList is freed
// TLineR overrides ========================================================
// primitive queries -------------------------------------------------------
function GetCode: String; override;
// pre: True
function GetName: String; override;
// pre: True
function GetOptions: TLineOptions; override;
// pre: True
function Count: Integer; override;
// pre: True
// ret: |Abstr|
function IndexOf(AStation: TStationR): Integer; override;
// pre: True
// ret: I such that Abstr[I] = AStation, or else -1
function Stop(I: Integer): TStationR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddStop(AStation: TStationR): Boolean;
// pre: True
// ret: not HasStop(AStation)
function CanInsertStop(I: Integer; AStation: TStationR): Boolean;
// pre: True
// ret: (0 <= I <= Count) and not HasStop(AStation)
function CanSwapStops(I, J: Integer): Boolean; virtual;
// pre: True
// ret: (0 <= I < Count) and (0 <= J < Count)
function CanDeleteStop(I: Integer): Boolean; virtual;
// pre: True
// ret: 0 <= I < Count
function CanDeleteAll: Boolean; virtual;
// pre: True
// ret: True
// commands ----------------------------------------------------------------
procedure AddStop(AStation: TStationR);
// pre: CanAddStop(AStation)
// post: Abstr = old Abstr ++ [AStation]
procedure InsertStop(I: Integer; AStation: TStationR);
// pre: CanInsertStop(I, AStation)
// post: Abstr = (old Abstr[0..I) ++ [AStation] ++ (old Abstr[I..Count))
procedure SetOptions(AOptions: TLineOptions);
// pre: True
// post: GetOptions = AOptions
procedure SwapStops(I, J: Integer);
// pre: CanSwapStops(I,J)
// post:
// let X = old Abstr[I], Y = old Abstr[J},
// S0 = old Abstr[0..I), S1 = old Abstr[I+1..J),
// S2 = old Abstr[J+1..Count)
// in Abstr = S0 ++ [Y] ++ S1 ++ [X] ++ S2
procedure DeleteStop(I: Integer);
// pre: CanDeleteStop(I)
// post: Abstr = old Abstr[0..I) ++ old Abstr[I+1..Count)
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = []
end;
//==============================================================================
// LineSet
//
// A lineset is a finite enumerable set of lines.
//
// The class TLineSetR is an abstract class providing read-only access to the
// data of a lineset.
// The class TLineSetRW is a descendant of TLineSetR; it provides a concrete
// representation and read/write access to a lineset.
//
//
// NOTE: The organization of the LineSet classes is almost the same as that of
// the Stationset classes. What is really needed here is a parameterized class
// Set[T] which can be instantiated for stations and lines respectively.
// Currently, Delphi does not provide such a notion.
//==============================================================================
TLineSetR =
class(TObject)
public
// primitive queries -------------------------------------------------------
function Count: Integer; virtual; abstract;
// pre: True
// ret: |Abstr|
function GetLine(I: Integer): TLineR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function IsEmpty: Boolean;
// pre: True
// ret: Count = 0
function HasLine(ALine: TLineR): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I) = ALine )
function HasCode(ACode: String): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).GetCode = ACode )
function HasName(AName: String): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).GetName = AName )
function HasStop(AStation: TStationR): Boolean;
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).HasStop(AStation))
function IndexOfCode(ACode: String): Integer;
// pre: True
// ret: I such that GetLine(I).GetCode = ACode, or else -1
function IndexOfName(AName: String): Integer;
// pre: True
// ret: I such that GetLine(I).GetName = AName, or else -1
// model variables ---------------------------------------------------------
// Abstr: set of TLineR
// invariants --------------------------------------------------------------
// Unique:
// (forall I,J: 0 <= I < J < Count:
// - GetLine(I) <> GetLine(J)
// - GetLine(I).GetCode <> GetLine(J).GetCode
// - GetLine(I).GetName <> GetLine(J).GetName
// )
end;
TLineSetRW =
class(TLineSetR)
protected
FList: TObjectList; // owner
// invariants --------------------------------------------------------------
// A0: Abstr = (set L: 0 <= L < FList.Count: FList[L] as TLineR)
public
// construction/destruction ------------------------------------------------
constructor Create;
// pre: True
// post: Abstr = {}
destructor Destroy; override;
// pre: True
// effect: FList is freed
// TLineSetR overrides =====================================================
// primitive queries -------------------------------------
function Count: Integer; override;
// pre: True
// ret: |Abstr|
function GetLine(I: Integer): TLineR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddLine(ALine: TLineR): Boolean; virtual;
// pre: True
// ret: ValidLineCode(ALine.GetCode) and ValidLineName(ALine.GetName) and
// not HasCode(ALine.GetCode) and not HasName(ALine.GetName)
function CanDeleteLine(ALine: TLineR): Boolean; virtual;
// pre: True
// ret: True (may be overridden in subclasses)
function CanDeleteAll: Boolean; virtual;
// pre: True
// ret: True (may be overridden in subclasses)
function CanSetLineCode(ALine: TLineR; ACode: String): Boolean; virtual;
// pre: True
// ret: ValidLineCode(ACode) and HasLine(ALine) and
// not(HasCode(ACode))
function CanSetLineName(ALine: TLineR; AName: String): Boolean; virtual;
// pre: True
// ret: ValidLineName(AName) and HasLine(ALine) and
// not(HasName(AName))
// commands ----------------------------------------------------------------
procedure AddLine(ALine: TLineR);
// pre: CanAddLine(ALine)
// post: Abstr = old Abstr U {ALine}
procedure DeleteStation(AStation: TStationR); virtual;
// pre: True
// post: (forall L: L in Abstr: L.Abstr = old L.Abstr \ {AStation})
procedure DeleteLine(ALine: TLineR);
// pre: CanDeleteLine(ALine)
// post: Abstr = old Abstr \ {ALine}
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = {}
procedure SetLineCode(ALine: TLineR; ACode: String);
// pre: CanSetLineCode(ALine, ACode)
// post: ALine.GetCode = ACode
procedure SetLineName(ALine: TLineR; AName: String);
// pre: CanSetLineName(ALine, AName)
// post: ALine.GetName = AName
end;
//==============================================================================
// Network
//
// A network has:
// - a name
// - a stationset S
// - a lineset L
// Consistency invariant
// - every station occurring in a line of L should also occur in S
//
// A network can be read from and written to a .INI file
//
// A network can be edited by adding or deleting a station or a line.
// The preconditions of the editing operations guarantee that the consistency
// invariant is preserved.
//==============================================================================
TNetwork =
class(TObject)
protected
FName: String;
FStationSet: TStationSetRW;
FLineSet: TLineSetRW;
public
// construction/destruction ------------------------------------------------
constructor Create(AName: String; AStationSet: TStationSetRW;
ALineSet: TLineSetRW);
// pre: ValidNetworkName(AName), IsConsistent(AStationSet, ALineSet)
// post: GetName = AName and GetStationset = AStationSet and
// GetLineset = ALineSet
constructor CreateEmpty(AName: String);
// pre: ValidNetworkName(AName)
// post: GetName = AName and GetStationSet.Count = 0 and
// GetLineSet.Count = 0
destructor Destroy; override;
// pre: True
// effect: FLineSet is freed and FStationSet is freed
// basic queries -----------------------------------------------------------
function GetName: String;
// pre: True
function GetStationSet: TStationSetR;
// pre: True
function GetLineSet: TLineSetR;
// pre: True
// derived queries ---------------------------------------------------------
function IsConsistentLine(ALine: TLineR;
AStationSet: TStationSetR): Boolean;
// pre: True
// ret: (forall J: 0 <= J < ALine.Count:
// AStationSet.HasStation(ALine.Stop(J))
function IsConsistentNetwork(AStationSet: TStationSetR;
ALineSet: TLineSetR): Boolean;
// pre: True
// ret:
// let SS = AStationSet, LS = ALineSet
// in (forall I: 0 <= I < LS.Count: IsConsistentLine(LS.GetLine(I), SS)
// preconditions for commands ----------------------------------------------
function CanAddStation(AStation: TStationR): Boolean; virtual;
// pre: True
// ret: GetStationSet.CanAddStation(AStation)
function CanDeleteStation(AStation: TStationR): Boolean; virtual;
// pre: True
// ret: not GetLineSet.HasStop(AStation)
function CanSetLineCode(ALine: TLineR; ACode: String): Boolean; virtual;
// pre: True
// ret: GetLineSet.CanSetLineCode(ALine, ACode)
function CanSetLineName(ALine: TLineR; AName: String): Boolean; virtual;
// pre: True
// ret: GetLineSet.CanSetLineName(ALine, AName)
function CanSetStationCode(AStation: TStationR; ACode: String): Boolean; virtual;
// pre: True
// ret: GetStationSet.CanSetStationCode(AStation, ACode)
function CanSetStationName(AStation: TStationR; AName: String): Boolean; virtual;
// pre: True
// ret: GetStationSet.CanSetStationName(AStation, AName)
function CanAddLine(ALine: TLineR): Boolean; virtual;
// pre: True
// ret: IsConsistentLine(ALine, GetStationSet) and
// GetLineSet.CanAddLine(ALine)
function CanDeleteLine(ALine: TLineR): Boolean; virtual;
// pre: True
// ret: GetLineSet.CanDeleteLine(ALine)
function CanDeleteAll: Boolean; virtual;
// pre: True
// ret: True
// commands ----------------------------------------------------------------
procedure SetName(AName: String);
// pre: ValidNetworkName(AName)
// post: GetName = AName
procedure SetStationCode(AStation: TStationR; ACode: String);
// pre: CanSetStationCode(AStation, ACode)
// post: AStation.GetCode = ACode
procedure SetStationName(AStation: TStationR; AName: String);
// pre: CanSetStationName(AStation, AName)
// post: AStation.GetName = AName
procedure SetLineCode(ALine: TLineR; ACode: String);
// pre: CanSetLineCode(ALine, ACode)
// post: ALine.GetCode = ACode
procedure SetLineName(ALine: TLineR; AName: String);
// pre: CanSetLineName(ALine, AName)
// post: ALine.GetName = AName
procedure AddStation(AStation: TStationR);
// pre: CanAddStation(AStation)
// post: GetStationSet.Abstr = old GetStationSet.Abstr U {AStation}
procedure DeleteStation(AStation: TStationR); virtual;
// pre: True
// post: GetStationSet.Abstr = old GetStation.Abstr \ {AStation} and
// (forall L: L in GetLineSet.Abstr:
// L.Abstr = old L.Abstr \ {AStation})
procedure AddLine(ALine: TLineR); virtual;
// pre: CanAddLine(ALine)
// post: GetLineSet.Abstr = old GetLineSet.Abstr U {ALine}
procedure DeleteLine(ALine: TLineR); virtual;
// pre: CanDeleteLine(ALine: TLineR)
// post: GetLineSet.Abstr = old GetLineSet.Abstr \ {ALine}
procedure DeleteAll; virtual;
// pre: CanDeleteAll
// post: GetStationSet.Count = 0 and GetLineSet.Count = 0
// invariants --------------------------------------------------------------
// Consistent:
// IsConsistentNetwork(GetStationSet, GetLineSet);
// Connected:
// (not yet necessary)
end;
implementation //===============================================================
uses
Classes, StrUtils, SysUtils;
{ TStationRW ------------------------------------------------------------------}
constructor TStationRW.Create(ACode, AName: String);
begin
//# BEGIN TODO
// pre: ValidStationCode(ACode) and ValidStationName(AName)
// post: (GetCode = ACode) and (GetName = AName)
Assert( ValidStationCode(ACode) and ValidStationName(AName),
'TStationRW.Create.pre falied: not a valid station');
inherited Create;
FCode := ACode;
FName := AName;
//# END TODO
end;
function TStationRW.GetCode: String;
begin
//# BEGIN TODO
result := FCode;
//# END TODO
end;
function TStationRW.GetName: String;
begin
//# BEGIN TODO
result := FName;
//# END TODO
end;
{ TStationSetR --------------------------------------------------------------- }
function TStationSetR.HasCode(ACode: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: IndexOfCode(ACode) <> -1
if Count = 0 then
begin
result := false;
end
else
begin
result:= IndexOfCode(Acode) <> -1;
end;
//# END TODO
end;
function TStationSetR.HasName(AName: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: IndexOfName(AName) <> -1
if Count = 0 then
begin
result := false;
end
else
begin
result:= IndexOfName(AName) <> -1;
end;
//# END TODO
end;
function TStationSetR.HasStation(AStation: TStationR): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: GetStation(I) = AStation)
I := 0;
result := true;
while (I < Count) and (GetStation(I) <> ASTation) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TStationSetR.IndexOfCode(ACode: String): Integer;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: I such that GetStation(I).GetCode = ACode, or else -1
I := Count -1;
while (I > -1) and (GetStation(I).GetCode <> ACode) do
begin
Dec(I);
end;
result := I;
{result := -1;
for I := 0 to Count do
begin
if GetStation(I).GetCode = ACode then
result := I;
end; }
//# END TODO
end;
function TStationSetR.IndexOfName(AName: String): Integer;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: I such that GetStation(I).GetName = AName, or else -1
I := Count - 1;
while (I > -1) and (GetStation(I).GetName <> AName) do
begin
Dec(I);
end;
result := I;
//# END TODO
end;
function TStationSetR.IsEmpty: Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: Count = 0
result := Count = 0;
//# END TODO
end;
{ TStationSetRW -------------------------------------------------------------- }
procedure TStationSetRW.SetStationCode(AStation: TStationR; ACode: String);
var VName: String;
begin
//# BEGIN TODO
// pre: CanSetStationCode(AStation, ACode)
// post: AStation.GetCode = ACode
Assert( CanSetStationCode(AStation, ACode), 'TStationSetRW.SetStationCode.pre failed');
// because FCode can't be changed, because of private, we delete the station
// to be changed and recreate with the new code.
VName := AStation.GetName;
DeleteStation(AStation);
TStationRW.Create(ACode, VName);
//# END TODO
end;
procedure TStationSetRW.SetStationName(AStation: TStationR; AName: String);
var VCode: String;
begin
//# BEGIN TODO
// pre: CanSetStationName(AStation, AName)
// post: AStation.GetName = AName
Assert( CanSetStationName(AStation, AName));
VCode := AStation.GetCode;
DeleteStation(AStation);
FList.Add(TStationRW.Create(VCode, AName));
//# END TODO
end;
procedure TStationSetRW.AddStation(AStation: TStationR);
begin
//# BEGIN TODO
// pre: CanAddStation(AStation)
// post: Abstr = old Abstr U {AStation}
Assert( CanAddStation(AStation), 'TStationSetRW.AddStation.pre failed');
// FList.Add( TStationRW.Create(AStation.GetCode, AStation.GetName));
FList.Add(AStation);
//TStationRW.Create(AStation.GetCode, AStation.GetName
//# END TODO
end;
function TStationSetRW.CanAddStation(AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidStationCode(AStation.GetCode) and
// ValidStationName(AStation.GetName) and
// not HasCode(AStation.GetCode) and not HasName(AStation.GetName)
result := ValidStationCode(AStation.GetCode) and
ValidStationName(AStation.GetName) and
not HasCode(AStation.GetCode) and
not HasName(AStation.GetName);
//# END TODO
end;
function TStationSetRW.CanDeleteAll: Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: True (may be overridden in subclasses)
result := true;
//# END TODO
end;
function TStationSetRW.CanDeleteStation(AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: True (may be overridden in subclasses)
result := true;
//# END TODO
end;
function TStationSetRW.Count: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: |Abstr|
result := FList.Count;
//# END TODO
end;
constructor TStationSetRW.Create;
begin
//# BEGIN TODO
// pre: True
// post: Abstr = {}
inherited Create;
FList := TObjectList.Create;
//# END TODO
end;
procedure TStationSetRW.DeleteAll;
begin
//# BEGIN TODO
// pre: CanDeleteAll
// post: Abstr = {}
Assert( CanDeleteAll, 'TStation.SetRW.DeleteAll.pre failed');
FList.Clear;
//# END TODO
end;
procedure TStationSetRW.DeleteStation(AStation: TStationR);
begin
//# BEGIN TODO
FList.Remove(AStation); //??
//# END TODO
end;
destructor TStationSetRW.Destroy;
begin
//# BEGIN TODO
inherited; // Destroy;
// FList.Destroy
FList.Free;
//# END TODO
end;
function TStationSetRW.GetStation(I: Integer): TStationR;
begin
//# BEGIN TODO
// pre: 0 <= I < Count
// ret: Abstr[I]
Assert( (0 <= I) and (I <{=} Count), Format('TStationSetRW.GetStation.pre failed: I= %d', [I]));
result := FList.Items[I] as TStationR;
//# END TODO
end;
{ TLineR --------------------------------------------------------------------- }
function TLineR.HasStop(AStation: TStationR): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: Stop(I) = AStation )
I := 0;
result := true;
while (I < Count) and (Stop(I) <> AStation) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TLineR.IsCircular: Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: loCircular in GetOptions
result := loCircular in GetOptions;
//# END TODO
end;
function TLineR.IsOneWay: Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: loOneWay in GetOptions
result := loOneWay in GetOptions;
//# END TODO
end;
function TLineR.TerminalA: TStationR;
begin
//# BEGIN TODO
// pre: Count > 0
// ret: Stop(0)
Assert( Count > 0, 'TLineR.TerminalA.pre failed');
result := Stop(0);
//# END TODO
end;
function TLineR.TerminalB: TStationR;
begin
//# BEGIN TODO
// pre: Count > 0
// ret: Stop(Count - 1)
Assert( Count > 0, 'TLineR.TerminalB.pre failed');
result := Stop(Count - 1);
//# END TODO
end;
{ TLineRW -------------------------------------------------------------------- }
procedure TLineRW.AddStop(AStation: TStationR);
begin
//# BEGIN TODO
// pre: CanAddStop(AStation)
// post: Abstr = old Abstr ++ [AStation]
Assert( CanAddStop(AStation), 'TLineSetRW.AddStop.pre failed');
FList.Add(AStation);
//# END TODO
end;
function TLineRW.CanAddStop(AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: not HasStop(AStation)
result := not HasStop(AStation);
//# END TODO
end;
function TLineRW.CanDeleteAll: Boolean;
begin
//# BEGIN TODO
result := true;
//# END TODO
end;
function TLineRW.CanDeleteStop(I: Integer): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: 0 <= I < Count
result := (0 <= I) and (I < Count);
//# END TODO
end;
function TLineRW.CanInsertStop(I: Integer; AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: (0 <= I <= Count) and not HasStop(AStation)
result := ( 0<= I) and (I <= Count) and not HasSTop(ASTation);
//# END TODO
end;
function TLineRW.CanSwapStops(I, J: Integer): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: (0 <= I < Count) and (0 <= J < Count)
result := ( 0 <= I) and ( I < Count) and
( 0 <= J) and ( J < Count);
//# END TODO
end;
function TLineRW.Count: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: |Abstr|
result := FList.Count;
//# END TODO
end;
constructor TLineRW.Create(ACode, AName: String; AOptions: TLineOptions);
begin
//# BEGIN TODO
// pre: ValidLineCode(ACode), ValidLineName(AName)
// post: GetCode = ACode and GetName = AName and GetOptions = AOptions
// and (Count = 0)
Assert( ValidLineCode(ACode) and ValidLineName(AName), 'TLineRW.Create.pre falied');
FCode := ACode;
FName := AName;
FOptions := AOptions;
FList := TObjectList.Create(false);
//# END TODO
end;
procedure TLineRW.DeleteAll;
begin
//# BEGIN TODO
// pre: CanDeleteAll
// post: Abstr = []
Assert( CanDeleteAll, 'TLineRW.DeleteAll.pre failed');
FList.Clear;
//# END TODO
end;
procedure TLineRW.DeleteStop(I: Integer);
begin
//# BEGIN TODO
// pre: CanDeleteStop(I)
// post: Abstr = old Abstr[0..I) ++ old Abstr[I+1..Count)
Assert( CanDeleteStop(I), 'TLIneRW.DeleteStop.pre failed');
FList.Delete(I);
//# END TODO
end;
destructor TLineRW.Destroy;
begin
//# BEGIN TODO
// pre: True
// effect: FList is freed
FList.Free;
inherited; // ??
//# END TODO
end;
function TLineRW.GetCode: String;
begin
//# BEGIN TODO
// pre: True
result := FCode;
//# END TODO
end;
function TLineRW.GetName: String;
begin
//# BEGIN TODO
// pre: True
result := FName;
//# END TODO
end;
function TLineRW.GetOptions: TLineOptions;
begin
//# BEGIN TODO
// pre: True
Result := FOptions;
//# END TODO
end;
function TLineRW.IndexOf(AStation: TStationR): Integer;
begin
//# BEGIN TODO
// pre: True
// ret: I such that Abstr[I] = AStation, or else -1
result := FList.IndexOf(AStation);
//# END TODO
end;
procedure TLineRW.InsertStop(I: Integer; AStation: TStationR);
begin
//# BEGIN TODO
// pre: CanInsertStop(I, AStation)
// post: Abstr = (old Abstr[0..I) ++ [AStation] ++ (old Abstr[I..Count))
Assert( CanInsertStop( I, AStation), 'TLineRW.InsertSTop.pre falied');
FList.Insert(I, AStation);
//# END TODO
end;
procedure TLineRW.SetOptions(AOptions: TLineOptions);
begin
//# BEGIN TODO
// pre: True
// post: GetOptions = AOptions
FOptions := AOptions;
//# END TODO
end;
function TLineRW.Stop(I: Integer): TStationR;
begin
//# BEGIN TODO
// pre: 0 <= I < Count
// ret: Abstr[I]
Assert( ( 0<= I) and (I < Count), 'TLineRW.Stop.pre failed');
Result := FList.Items[I] as TStationR;
//# END TODO
end;
procedure TLineRW.SwapStops(I, J: Integer);
begin
//# BEGIN TODO
// pre: CanSwapStops(I,J)
// post:
// let X = old Abstr[I], Y = old Abstr[J},
// S0 = old Abstr[0..I), S1 = old Abstr[I+1..J),
// S2 = old Abstr[J+1..Count)
// in Abstr = S0 ++ [Y] ++ S1 ++ [X] ++ S2
Assert( CanSwapStops( I,J), 'TLineRW.SwapSTops.pre failed');
FList.Exchange(I, J);
//# END TODO
end;
{ TLineSetR ------------------------------------------------------------------ }
function TLineSetR.HasCode(ACode: String): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).GetCode = ACode )
I:= 0;
result := true;
while (I < Count) and (GetLine(I).GetCode <> ACode) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TLineSetR.HasLine(ALine: TLineR): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I) = ALine )
I := 0;
result := true;
while (I < Count) and (GetLine(I) <> ALine) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TLineSetR.HasName(AName: String): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).GetName = AName )
I := 0;
result := true;
while (I < Count) and (GetLine(I).GetName <> AName) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TLineSetR.HasStop(AStation: TStationR): Boolean;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: (exists I: 0 <= I < Count: GetLine(I).HasStop(AStation))
I := 0;
result := true;
while (I < Count) and (not GetLine(I).HasStop(AStation)) do
begin
Inc(I);
end;
if I = Count then
begin
result := false;
end;
//# END TODO
end;
function TLineSetR.IndexOfCode(ACode: String): Integer;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: I such that GetLine(I).GetCode = ACode, or else -1
I := Count;
while (I > -1) and (GetLine(I).GetCode <> ACode) do
begin
Dec(I);
end;
result := I;
//# END TODO
end;
function TLineSetR.IndexOfName(AName: String): Integer;
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: I such that GetLine(I).GetName = AName, or else -1
I := Count;
while (I > -1) and (GetLine(I).GetName <> AName) do
begin
Dec(I);
end;
result := I;
//# END TODO
end;
function TLineSetR.IsEmpty: Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: Count = 0
result := Count = 0;
//# END TODO
end;
{ TLineSetRW ----------------------------------------------------------------- }
procedure TLineSetRW.AddLine(ALine: TLineR);
begin
//# BEGIN TODO
// pre: CanAddLine(ALine)
// post: Abstr = old Abstr U {ALine}
Assert( CanAddLine(ALine), 'TLineSetRW.AddLine.pre failed');
FList.Add(ALine);
//# END TODO
end;
procedure TLineSetRW.DeleteStation(AStation: TStationR);
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// post: (forall L: L in Abstr: L.Abstr = old L.Abstr \ {AStation})
FList.Remove(AStation); // ???
//# END TODO
end;
function TLineSetRW.CanAddLine(ALine: TLineR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidLineCode(ALine.GetCode) and ValidLineName(ALine.GetName) and
// not HasCode(ALine.GetCode) and not HasName(ALine.GetName)
result := ValidLineCode(ALine.GetCode) and ValidLineName(ALine.GetName) and
not HasCode(ALine.GetCode) and not HasName(ALine.GetName);
//# END TODO
end;
function TLineSetRW.CanDeleteAll: Boolean;
begin
//# BEGIN TODO
result := true;
//# END TODO
end;
function TLineSetRW.CanDeleteLine(ALine: TLineR): Boolean;
begin
//# BEGIN TODO
result := true;
//# END TODO
end;
function TLineSetRW.Count: Integer;
begin
//# BEGIN TODO
// pre: True
// ret: |Abstr|
result := FList.Count;
//# END TODO
end;
constructor TLineSetRW.Create;
begin
//# BEGIN TODO
// pre: True
// post: Abstr = {}
inherited Create;
FList := TObjectList.Create;
//# END TODO
end;
procedure TLineSetRW.DeleteAll;
begin
//# BEGIN TODO
// pre: CanDeleteAll
// post: Abstr = {}
Assert( CanDeleteAll, 'TLineSetRW.DeleteAll.pre failed');
FList.Clear;
//# END TODO
end;
procedure TLineSetRW.DeleteLine(ALine: TLineR);
begin
//# BEGIN TODO
// pre: CanDeleteLine(ALine)
// post: Abstr = old Abstr \ {ALine}
Assert( CanDeleteLine(ALine), 'TLineSetRW.DeleteLine.pre failed');
FList.Remove(ALine);
//# END TODO
end;
destructor TLineSetRW.Destroy;
begin
//# BEGIN TODO
// pre: True
// effect: FList is freed
FList.Free;
inherited;
//# END TODO
end;
function TLineSetRW.GetLine(I: Integer): TLineR;
begin
//# BEGIN TODO
// pre: 0 <= I < Count
// ret: Abstr[I]
Assert( (0 <= I) and (I < Count), 'TLineSetRW.GetLine.pre failed');
result := FList.Items[I] as TLineR;
//# END TODO
end;
{ TNetwork ------------------------------------------------------------------- }
procedure TNetwork.AddLine(ALine: TLineR);
begin
//# BEGIN TODO
// pre: CanAddLine(ALine)
// post: GetLineSet.Abstr = old GetLineSet.Abstr U {ALine}
Assert( CanAddLine(ALine), 'TNetwork.AddLine.pre failed');
FLineSet.AddLine(ALine);
//# END TODO
end;
function TNetwork.CanAddLine(ALine: TLineR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: IsConsistentLine(ALine, GetStationSet) and
// GetLineSet.CanAddLine(ALine)
result:= IsConsistentLine(ALine, GetStationSet) and
FLineSet.CanAddLine(ALine);
//# END TODO
end;
function TNetwork.CanAddStation(AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetStationSet.CanAddStation(AStation)
result := FStationSet.CanAddStation(AStation);
//# END TODO
end;
function TNetwork.CanDeleteAll: Boolean;
begin
//# BEGIN TODO
result := true;
//# END TODO
end;
function TNetwork.CanDeleteLine(ALine: TLineR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetLineSet.CanDeleteLine(ALine)
result := FLineSet.CanDeleteLine(ALine);
//# END TODO
end;
function TNetwork.CanDeleteStation(AStation: TStationR): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: not GetLineSet.HasStop(AStation)
result := not FLineSet.HasStop(AStation);
//# END TODO
end;
constructor TNetwork.Create(AName: String; AStationSet: TStationSetRW;
ALineSet: TLineSetRW);
begin
//# BEGIN TODO
// pre: ValidNetworkName(AName), IsConsistent(AStationSet, ALineSet)
// post: GetName = AName and GetStationset = AStationSet and
// GetLineset = ALineSet
Assert( ValidNetworkName(AName) and IsConsistentNetwork(AStationSet, ALineSet),
'TNetwork.Create.pre failed');
inherited Create;
FName := AName;
FStationSet := AStationSet;
FLineSet := ALineSet;
//# END TODO
end;
constructor TNetwork.CreateEmpty(AName: String);
begin
//# BEGIN TODO
// pre: ValidNetworkName(AName)
// post: GetName = AName and GetStationSet.Count = 0 and
// GetLineSet.Count = 0
Assert( ValidNetworkName(AName), 'TNetwork.CreateEmpty.pre failed');
inherited Create;
FName := AName;
FStationSet := TStationSetRW.Create;
FLineSet := TLineSetRW.Create;
//# END TODO
end;
procedure TNetwork.DeleteAll;
begin
//# BEGIN TODO
// pre: CanDeleteAll
// post: GetStationSet.Count = 0 and GetLineSet.Count = 0
Assert( CanDeleteAll, 'TNetwork.DeleteAll.pre failed');
FStationSet.DeleteAll;
//# END TODO
end;
procedure TNetwork.DeleteLine(ALine: TLineR);
begin
//# BEGIN TODO
// pre: CanDeleteLine(ALine: TLineR)
// post: GetLineSet.Abstr = old GetLineSet.Abstr \ {ALine}
Assert( CanDeleteLine(ALine), 'TNetwork.DeleteLine.pre failed');
FLineSet.DeleteLine(ALine);
//# END TODO
end;
procedure TNetwork.DeleteStation(AStation: TStationR);
begin
//# BEGIN TODO
// pre: True
// post: GetStationSet.Abstr = old GetStation.Abstr \ {AStation} and
// (forall L: L in GetLineSet.Abstr:
// L.Abstr = old L.Abstr \ {AStation})
FStationSet.DeleteStation(AStation);
//# END TODO
end;
destructor TNetwork.Destroy;
begin
//# BEGIN TODO
// pre: True
// effect: FLineSet is freed and FStationSet is freed
FLineSet.Free;
FStationSet.Free;
inherited;
//# END TODO
end;
function TNetwork.GetLineSet: TLineSetR;
begin
//# BEGIN TODO
// pre: True
result := FLineSet;
//# END TODO
end;
function TNetwork.GetName: string;
begin
//# BEGIN TODO
// pre: True
result := FName;
//# END TODO
end;
procedure TNetwork.SetName(AName: String);
begin
//# BEGIN TODO
// pre: ValidNetworkName(AName)
// post: GetName = AName
Assert( ValidNetworkName(AName), 'TNetwork.SetName.pre failed');
FName := AName;
//# END TODO
end;
function TNetwork.GetStationSet: TStationSetR;
begin
//# BEGIN TODO
// pre: True
result := FStationSet;
//# END TODO
end;
function TNetwork.IsConsistentLine(ALine: TLineR;
AStationSet: TStationSetR): Boolean;
var
I: integer;
begin
//# BEGIN TODO
// pre: True
// ret: (forall J: 0 <= J < ALine.Count:
// AStationSet.HasStation(ALine.Stop(J))
I := 0;
result := false;
while (I < ALine.Count) and (AStationSet.HasStation(ALine.Stop(I))) do
begin
Inc(I);
end;
if I = ALine.Count then
begin
result := true;
end;
//# END TODO
end;
function TNetwork.IsConsistentNetwork(AStationSet: TStationSetR;
ALineSet: TLineSetR): Boolean;
// ret:
// let SS = AStationSet, LS = ALineSet
// (forall I: 0<=I<LS.Count: IsConsistentLine(LS.GetLine(I), SS)
var
I: Integer;
begin
//# BEGIN TODO
// pre: True
// ret:
// let SS = AStationSet, LS = ALineSet
// in (forall I: 0 <= I < LS.Count: IsConsistentLine(LS.GetLine(I), SS)
I := 0;
result := false;
while (I < ALineSet.Count) and (IsConsistentLine(ALineSet.GetLine(I),AStationSet)) do
begin
Inc(I);
end;
if I = ALineSet.Count then
begin
result := true;
end;
//# END TODO
end;
procedure TNetwork.AddStation(AStation: TStationR);
begin
//# BEGIN TODO
// pre: CanAddStation(AStation)
// post: GetStationSet.Abstr = old GetStationSet.Abstr U {AStation}
Assert( CanAddStation(AStation), 'TNetwork.AddStation.pre failed');
FStationSet.AddStation(AStation);
//# END TODO
end;
function TNetwork.CanSetStationCode(AStation: TStationR;
ACode: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetStationSet.CanSetStationCode(AStation, ACode)
result := FStationSet.CanSetStationCode(AStation, ACode);
//# END TODO
end;
function TNetwork.CanSetStationName(AStation: TStationR;
AName: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetStationSet.CanSetStationName(AStation, AName)
result := FStationSet.CanSetStationName(AStation, AName);
//# END TODO
end;
procedure TNetwork.SetStationCode(AStation: TStationR; ACode: String);
begin
//# BEGIN TODO
// pre: CanSetStationCode(AStation, ACode)
// post: AStation.GetCode = ACode
Assert( CanSetStationCode(AStation, ACode), 'TNetwork.SetStationCode.pre failed');
FStationSet.SetStationCode(AStation, ACode);
//# END TODO
end;
procedure TNetwork.SetStationName(AStation: TStationR; AName: String);
begin
//# BEGIN TODO
// pre: CanSetStationName(AStation, AName)
// post: AStation.GetName = AName
Assert( CanSetStationName(AStation, AName), 'TNetwork.SetStationName.pre failed');
FStationSet.SetStationName(AStation, AName);
//# END TODO
end;
function TNetwork.CanSetLineCode(ALine: TLineR; ACode: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetLineSet.CanSetLineCode(ALine, ACode)
result := FLineSet.CanSetLineCode(ALine, ACode);
//# END TODO
end;
function TNetwork.CanSetLineName(ALine: TLineR; AName: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: GetLineSet.CanSetLineName(ALine, AName)
result := FLineSet.CanSetLineName(ALine, AName);
//# END TODO
end;
procedure TNetwork.SetLineCode(ALine: TLineR; ACode: String);
begin
//# BEGIN TODO
// pre: CanSetLineCode(ALine, ACode)
// post: ALine.GetCode = ACode
Assert( CanSetLineCode(ALine, ACode), 'TNetwork.SetLineCode.pre failed');
FLineSet.SetLineCode(ALine, ACode);
//# END TODO
end;
procedure TNetwork.SetLineName(ALine: TLineR; AName: String);
begin
//# BEGIN TODO
// pre: CanSetLineName(ALine, AName)
// post: ALine.GetName = AName
Assert( CanSetLineName(ALine, AName), 'TNetwork.SetLineName.pre failed');
FLineSet.SetLineName(ALine, AName);
//# END TODO
end;
function TStationSetRW.CanSetStationCode(AStation: TStationR;
ACode: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidStationCode(ACode) and HasStation(AStation) and
// not(HasCode(ACode))
result := ValidStationCode(ACode) and
HasStation(AStation) and
not (HasCode(ACode));
//# END TODO
end;
function TStationSetRW.CanSetStationName(AStation: TStationR;
AName: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidStationName(AName) and HasStation(AStation) and
// not(HasName(AName))
result := ValidStationName(AName) and HasStation(AStation) and
not(HasName(AName));
//# END TODO
end;
function TLineSetRW.CanSetLineCode(ALine: TLineR; ACode: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidLineCode(ACode) and HasLine(ALine) and
// not(HasCode(ACode))
result := ValidLineCode(ACode) and HasLine(ALine) and
not(HasCode(ACode));
//# END TODO
end;
function TLineSetRW.CanSetLineName(ALine: TLineR; AName: String): Boolean;
begin
//# BEGIN TODO
// pre: True
// ret: ValidLineName(AName) and HasLine(ALine) and
// not(HasName(AName))
result := ValidLineName(AName) and HasLine(ALine) and
not(HasName(AName));
//# END TODO
end;
procedure TLineSetRW.SetLineCode(ALine: TLineR; ACode: String);
var VName: string;
VOptions: TLineOptions;
begin
//# BEGIN TODO
// pre: CanSetLineCode(ALine, ACode)
// post: ALine.GetCode = ACode
Assert( CanSetLineCode(ALine, ACode), 'TLineSetRW.SetLineCode.pre failed');
VName := ALine.GetName;
VOptions := ALine.GetOptions;
FList.Remove(ALine);
FList.Add(TLineRW.Create(ACode, VName, VOptions));
//# END TODO
end;
procedure TLineSetRW.SetLineName(ALine: TLineR; AName: String);
var VCode: string;
VOptions: TLineOptions;
begin
//# BEGIN TODO
// pre: CanSetLineName(ALine, AName)
// post: ALine.GetName = AName
Assert( CanSetLineName(ALine, AName), 'TLineSetRW.SetLineName.pre failed');
VCode := ALine.GetCode;
VOptions := ALine.GetOptions;
FList.Remove(ALine);
FList.Add(TLineRW.Create(VCode, AName, VOptions));
//# END TODO
end;
end.
|
unit ACBrLibNFeTestCase;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testutils, testregistry;
type
{ TTestACBrNFeLib }
TTestACBrNFeLib = class(TTestCase)
published
procedure Test_NFE_Inicializar_Com_DiretorioInvalido;
procedure Test_NFE_Inicializar;
procedure Test_NFE_Inicializar_Ja_Inicializado;
procedure Test_NFE_Finalizar;
procedure Test_NFE_Finalizar_Ja_Finalizado;
procedure Test_NFE_Nome_Obtendo_LenBuffer;
procedure Test_NFE_Nome_Lendo_Buffer_Tamanho_Identico;
procedure Test_NFE_Nome_Lendo_Buffer_Tamanho_Maior;
procedure Test_NFE_Nome_Lendo_Buffer_Tamanho_Menor;
procedure Test_NFE_Versao;
procedure Test_NFE_ConfigLerValor;
end;
implementation
uses
ACBrLibNFeStaticImport, ACBrLibNFeConsts, ACBrLibConsts;
procedure TTestACBrNFeLib.Test_NFE_Inicializar_Com_DiretorioInvalido;
begin
AssertEquals(ErrDiretorioNaoExiste, NFE_Inicializar('C:\NAOEXISTE\ACBrLib.ini',''));
end;
procedure TTestACBrNFeLib.Test_NFE_Inicializar;
begin
AssertEquals(ErrOk, NFE_Inicializar('',''));
end;
procedure TTestACBrNFeLib.Test_NFE_Inicializar_Ja_Inicializado;
begin
AssertEquals(ErrOk, NFE_Inicializar('',''));
end;
procedure TTestACBrNFeLib.Test_NFE_Finalizar;
begin
AssertEquals(ErrOk, NFE_Finalizar());
end;
procedure TTestACBrNFeLib.Test_NFE_Finalizar_Ja_Finalizado;
begin
AssertEquals(ErrOk, NFE_Finalizar());
end;
procedure TTestACBrNFeLib.Test_NFE_Nome_Obtendo_LenBuffer;
var
Bufflen: Integer;
begin
// Obtendo o Tamanho //
Bufflen := 0;
AssertEquals(ErrOk, NFE_Nome(Nil, Bufflen));
AssertEquals(Length(CLibNFeNome), Bufflen);
end;
procedure TTestACBrNFeLib.Test_NFE_Nome_Lendo_Buffer_Tamanho_Identico;
var
AStr: String;
Bufflen: Integer;
begin
Bufflen := Length(CLibNFeNome);
AStr := Space(Bufflen);
AssertEquals(ErrOk, NFE_Nome(PChar(AStr), Bufflen));
AssertEquals(Length(CLibNFeNome), Bufflen);
AssertEquals(CLibNFeNome, AStr);
end;
procedure TTestACBrNFeLib.Test_NFE_Nome_Lendo_Buffer_Tamanho_Maior;
var
AStr: String;
Bufflen: Integer;
begin
Bufflen := Length(CLibNFeNome)*2;
AStr := Space(Bufflen);
AssertEquals(ErrOk, NFE_Nome(PChar(AStr), Bufflen));
AStr := copy(AStr, 1, Bufflen);
AssertEquals(Length(CLibNFeNome), Bufflen);
AssertEquals(CLibNFeNome, AStr);
end;
procedure TTestACBrNFeLib.Test_NFE_Nome_Lendo_Buffer_Tamanho_Menor;
var
AStr: String;
Bufflen: Integer;
begin
Bufflen := 4;
AStr := Space(Bufflen);
AssertEquals(ErrOk, NFE_Nome(PChar(AStr), Bufflen));
AssertEquals(Length(CLibNFeNome), Bufflen);
AssertEquals(copy(CLibNFeNome,1,4), AStr);
end;
procedure TTestACBrNFeLib.Test_NFE_Versao;
var
Bufflen: Integer;
AStr: String;
begin
// Obtendo o Tamanho //
Bufflen := 0;
AssertEquals(ErrOk, NFE_Versao(Nil, Bufflen));
AssertEquals(Length(CLibNFeVersao), Bufflen);
// Lendo a resposta //
AStr := Space(Bufflen);
AssertEquals(ErrOk, NFE_Versao(PChar(AStr), Bufflen));
AssertEquals(Length(CLibNFeVersao), Bufflen);
AssertEquals(CLibNFeVersao, AStr);
end;
procedure TTestACBrNFeLib.Test_NFE_ConfigLerValor;
var
Bufflen: Integer;
AStr: String;
begin
// Obtendo o Tamanho //
Bufflen := 255;
AStr := Space(Bufflen);
AssertEquals(ErrOk, NFE_ConfigLerValor(CSessaoVersao, CLibNFeNome, PChar(AStr), Bufflen));
AStr := copy(AStr,1,Bufflen);
AssertEquals(CLibNFeVersao, AStr);
end;
initialization
RegisterTest(TTestACBrNFeLib);
end.
|
program test14;
(* Test procedure *)
var a, b, c, min, rand: real;
var test: boolean;
procedure findMin(x, y, z: real; var m, r: real; var n: boolean);
(* Finds the minimum of the 3 values *)
begin
if x < y then
m:= x
else
m:= y;
if z < m then
m := z;
n := true;
r := 2020;
end;
begin
a := 100;
b := 430;
c := -11;
findMin(a, b, c, min, rand, test); (* Procedure call *)
writeln(a, b, c);
writeln(min);
writeln(rand);
writeln(test);
end.
(*
Expected output:
100.0 430.0 -11.0
-11.0
2020.0
True
*) |
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL, ExtCtrls;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc: HGLRC;
Angle : GLfloat;
wrkX, wrkY : Array [0..49] of GLfloat;
newCount, frameCount, lastCount : LongInt;
fpsRate : GLfloat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
procedure Idle (Sender:TObject;var Done:boolean);
end;
var
frmGL: TfrmGL;
implementation
uses DGLUT;
{$R *.DFM}
procedure TfrmGL.Idle (Sender:TObject;var Done:boolean);
begin
With frmGL do begin
Angle := Angle + 0.1;
If Angle >= 360.0 then Angle := 0.0;
Done := False;
InvalidateRect(Handle, nil, False);
end;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
i : 0..49;
begin
BeginPaint(Handle, ps);
// очистка буфера цвета и буфера глубины
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(2 * Angle, 0.0, 1.0, 0.0); // поворот на угол
glRotatef(Angle, 0.0, 0.0, 1.0); // поворот на угол
{Цикл рисования шести кубиков}
For i := 0 to 49 do begin
glPushMatrix; // запомнили точку
glTranslatef(wrkX [i], wrkY [i], 0.0);
glRotatef(-7.2 * i, 0.0, 0.0, 1.0); // поворот кубика
glScalef (1.0, 7.0, 1.0);
glutSolidCube (0.1);
glPopMatrix; // вернулись в точку
end;
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
// определяем и выводим количество кадров в секунду
newCount := GetTickCount;
Inc(frameCount);
If (newCount - lastCount) > 1000 then begin // прошла секунда
fpsRate := frameCount * 1000 / (newCount - lastCount);
Caption := 'FPS - ' + FloatToStr (fpsRate);
lastCount := newCount;
frameCount := 0;
end;
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
var
i : 0..49;
begin
DC := GetDC (Handle);
SetDCPixelFormat(DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
For i := 0 to 49 do begin
wrkX [i] := sin (Pi / 25 * i);
wrkY [i] := cos (Pi / 25 * i);
end;
glClearColor (1.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);// разрешаем тест глубины
// Добавляем источник света 0
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
glEnable (GL_COLOR_MATERIAL);
glColor3f (0.0, 0.0, 1.0);
Angle := 0;
lastCount := GetTickCount;
frameCount := 0;
Application.OnIdle := Idle;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewPort (0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(18.0, ClientWidth / ClientHeight, 7.0, 13.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -9.0);
glRotatef(60.0, 1.0, 0.0, 1.0);
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
end.
|
unit LauncherSettings;
interface
const
LauncherVersion: Byte = 0; // Defina a versão do seu Launchar (só números!!!!)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{$I Definitions.inc}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const
GlobalSalt: string = 'Sal';
{$IFDEF BEACON}
// Intervalo entre as verificações somas de verificação durante o jogo:
BeaconDelay: Cardinal = 3000; // Em milissegundos!
{$ENDIF}
{$IFDEF EURISTIC_DEFENCE}
// Intervalo entre os clientes que executam em busca paralela:
EuristicDelay: Cardinal = 3000;
{$ENDIF}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var
// IP e porta do seu servidor
PrimaryIP: string = '127.0.0.1'; // IP principal
SecondaryIP: string = '127.0.0.1'; // IP secundário - caso não consiga se conectar pelo principal, o launcher irá tentar pelo secundário
// pode ser o mesmo IP nos dois.
ServerPort: Word = 65533; // Porta de ligação
GamePort: string = '25565'; // Porta do servidor
// IP e porta de escape (caso você use)
{$IFDEF MULTISERVER}
DistributorPrimaryIP: PAnsiChar = '127.0.0.1';
DistributorSecondaryIP: PAnsiChar = '127.0.0.1';
DistributorPort: Word = 65534;
{$ENDIF}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Localização dos arquvios php para envio das skins e capas (deve estar no host do seu site, por exemplo)
SkinUploadAddress: string = 'http://meusite.com/Minecraft/upload_skin.php';
CloakUploadAddress: string = 'http://meusite.com/Minecraft/upload_cloak.php';
// Pastas onde ficarão as skins e capas enviadas:
SkinDownloadAddress: string = 'http://meusite.com/Minecraft/MinecraftSkins';
CloakDownloadAddress: string = 'http://meusite.com/Minecraft/MinecraftCloaks';
// Endereço para atualizações do launcher e jogo
ClientAddress: string = 'http://meusite.com/Minecraft/Main.zip';
AssetsAddress: string = 'http://meusite.com/Minecraft/Assets.zip';
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Não modifique isso:
ClientTempArchiveName: string = '_$RCVR.bin';
AssetsTempArchiveName: string = '_$ASTS.bin';
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// processo da máquina virtual (java.exe - console, javaw.exe - sem console):
JavaApp: string = 'javaw.exe';
// Aqui estão os parâmetros da máquina virtual, você pode alterá-los
JVMParams: string = '';
{
JVMParams: string = '-server ' +
'-D64 ' +
'-XX:MaxPermSize=512m ' +
'-XX:+UnlockCommercialFeatures ' +
'-XX:+UseLargePages ' +
'-XX:+AggressiveOpts ' +
'-XX:+UseAdaptiveSizePolicy ' +
'-XX:+UnlockExperimentalVMOptions ' +
'-XX:+UseG1GC ' +
'-XX:UseSSE=4 ' +
'-XX:+DisableExplicitGC ' +
'-XX:MaxGCPauseMillis=100 ' +
'-XX:ParallelGCThreads=8 ' +
'-DJINTEGRA_NATIVE_MODE ' +
'-DJINTEGRA_COINIT_VALUE=0 ' +
'-Dsun.io.useCanonCaches=false ' +
'-Djline.terminal=jline.UnsupportedTerminal ' +
'-XX:ThreadPriorityPolicy=42 ' +
'-XX:CompileThreshold=1500 ' +
'-XX:+TieredCompilation ' +
'-XX:TargetSurvivorRatio=90 ' +
'-XX:MaxTenuringThreshold=15 ' +
'-XX:+UnlockExperimentalVMOptions ' +
'-XX:+UseAdaptiveGCBoundary ' +
'-XX:PermSize=1024M ' +
'-XX:+UseGCOverheadLimit ' +
'-XX:+UseBiasedLocking ' +
'-Xnoclassgc ' +
'-Xverify:none ' +
'-XX:+UseThreadPriorities ' +
'-Djava.net.preferIPv4Stack=true ' +
'-XX:+UseStringCache ' +
'-XX:+OptimizeStringConcat ' +
'-XX:+UseFastAccessorMethods ' +
'-Xrs ' +
'-XX:+UseCompressedOops ';
}
// Caminho da pasta principal, onde o java.exe se encontra
// juntamente com o cliente (Main.zip):
{$IFDEF CUSTOM_JAVA}
JavaDir: string = 'java\bin'; // O caminho para java(w).exe em %APPDATA%\MainFolder\
{$ENDIF}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MainFolder: string = '\.NTLauncher'; // Pasta do servidor em %APPDATA%: %APPDATA\MainFolder
RegistryPath: string = 'NTLauncher'; // Nome nas keys do windows HKEY_CURRENT_USER\\Software\\
// Local da pasta Natives dentro da MainFolder (%APPDATA%\MainFolder\NativesPath):
NativesPath: string = '\versions\Natives';
// O caminho para a pasta com o cliente em MainFolder (%APPDATA%\MainFolder\MineJarPath):
MineJarFolder: string = '\versions\Region52';
// O caminho para a pasta com os recursos (Assets) na pasta MainFolder (%APPDATA%\MainFolder\MineJarPath):
AssetsFolder: string = '\assets';
GameVersion: string = '1.7.5'; // Versão do jogo (igual do ser servidor)
AssetIndex: string = '1.7.4'; // Suporte até essa versão
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// A classe principal:
// Caso seu servidor seja 1.5.2, utlize:
//MainClass: string = 'net.minecraft.client.Minecraft';
// Para versões acima da 1.6:
//MainClass: string = 'net.minecraft.client.main.Main';
// Forge, Optifine:
MainClass: string = 'net.minecraft.launchwrapper.Launch';
// Classes adicionais para apoiar o Forge, LiteLoader, Optifine, GLSL Shaders, etc.:
// Minecraft puro:
//TweakClass: string = '';
// Forge:
//TweakClass: string = '--tweakClass cpw.mods.fml.common.launcher.FMLTweaker';
// OptiFine + GLSL Shaders sem Forge:
TweakClass: string = '--tweakClass optifine.OptiFineTweaker --tweakClass shadersmodcore.loading.SMCTweaker';
implementation
end.
|
unit Test_UTF8Sources;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework;
type
TestUTF8Sources = class (TGenericTestCase)
private
const
STR_PROJECT_SOURCES_DIR = 'Source\';
STR_PROJECT_TESTS_SOURCES_DIR = 'Tests\';
private
function GetProjectSourcesDir : String;
function GetProjectTestsSourcesDir : String;
function IsUTF8TextFile(const FileName : String) : Boolean;
published
procedure TestFIToolkitSources;
procedure TestFIToolkitTestsSources;
end;
implementation
uses
TestUtils,
System.SysUtils, System.IOUtils, System.Classes;
{ TestUTF8Sources }
function TestUTF8Sources.GetProjectSourcesDir : String;
begin
Result := IncludeTrailingPathDelimiter(GetProjectGroupDir + STR_PROJECT_SOURCES_DIR);
end;
function TestUTF8Sources.GetProjectTestsSourcesDir : String;
begin
Result := IncludeTrailingPathDelimiter(GetProjectGroupDir + STR_PROJECT_TESTS_SOURCES_DIR);
end;
function TestUTF8Sources.IsUTF8TextFile(const FileName : String) : Boolean;
const
BOM : TBytes = [$EF, $BB, $BF];
var
Buffer : TBytes;
FS : TFileStream;
i : Integer;
begin
Result := False;
if TFile.Exists(FileName) then
begin
SetLength(Buffer, Length(BOM));
FS := TFile.Open(FileName, TFileMode.fmOpen, TFileAccess.faRead, TFileShare.fsReadWrite);
try
if FS.Read(Buffer, Length(Buffer)) = Length(BOM) then
begin
Result := True;
for i := 0 to High(Buffer) do
if Buffer[i] <> BOM[i] then
Exit(False);
end;
finally
FS.Free;
end;
end;
end;
procedure TestUTF8Sources.TestFIToolkitSources;
const
ARR_SEARCH_PATTERNS : array of String = ['*.pas', '*.inc'];
var
sPattern, sFile : String;
begin
for sPattern in ARR_SEARCH_PATTERNS do
for sFile in TDirectory.GetFiles(GetProjectSourcesDir, sPattern, TSearchOption.soAllDirectories) do
CheckTrue(IsUTF8TextFile(sFile), 'CheckTrue::<%s>', [sFile]);
end;
procedure TestUTF8Sources.TestFIToolkitTestsSources;
var
S : String;
begin
for S in TDirectory.GetFiles(GetProjectTestsSourcesDir, '*.pas', TSearchOption.soAllDirectories) do
CheckTrue(IsUTF8TextFile(S), 'CheckTrue::<%s>', [S]);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestUTF8Sources.Suite);
end.
|
{
GMMapFMX unit
ES: incluye el componente para usar el mapa de Google Maps
EN: includes the component to use the Google Maps map
=========================================================================
History:
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
=========================================================================
ES: IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
EN: IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMMapFMX unit includes the classes that manages the map specialized in a particular browser.
This browser can be a TChromiumFMX.
You can de/activate this browser into the gmlib.inc file.
By default it isn't active.
HOW TO USE: put the component into a form, link to a browser, activate it and call DoMap method (usually when AfterPageLoaded event is fired with First parameter to True).
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMMapFMX incluye las clases que gestionan el mapa especializados en un determinado navegador.
Este navegador puede ser un TChromiumFMX.
Puedes des/activar este navegador desde el archivo gmlib.inc.
Por defecto no está activo.
MODO DE USO: poner el componente en el formulario, linkarlo a un navegador, activarlo y ejecutar el método DoMap (usualmente en el evento AfterPageLoaded cuando el parámetro First es True).
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
unit GMMapFMX;
{.$DEFINE CHROMIUMFMX}
{$I ..\gmlib.inc}
interface
{$IFDEF CHROMIUMFMX}
uses
ceflib, cefgui, ceffmx,
FMX.Types, System.UITypes, FMX.Dialogs, System.Classes, System.SysUtils,
GMMap, GMFunctionsFMX;
type
{*------------------------------------------------------------------------------
Internal class containing the visual properties of Google Maps map.
This class extends TCustomVisualProp to add BGColor property (into VCL is TColor and into FMX is TAlphaColor).
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase interna que contendrá las propiedades visuales de un mapa de Google Maps.
Esta clase extiende TCustomVisualProp para añadir la propiedad BGColor (en la VCL es de tipo TColor y en FMX es de tipo TAlphaColor).
-------------------------------------------------------------------------------}
TVisualProp = class(TCustomVisualProp)
private
FBGColor: TAlphaColor;
protected
function GetBckgroundColor: string; override;
public
constructor Create; override;
procedure Assign(Source: TPersistent); override;
published
{*------------------------------------------------------------------------------
Color used for the background of the Map when tiles have not yet loaded.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color usado de fondo del Mapa cuando los mosaicos aun no han sido cargados.
-------------------------------------------------------------------------------}
property BGColor: TAlphaColor read FBGColor write FBGColor default clSilver; // backgroundColor
end;
{*------------------------------------------------------------------------------
Base class for classes that want to access the map using FMX.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para las clases que quieran acceder al mapa mediante FMX.
-------------------------------------------------------------------------------}
TCustomGMMapFMX = class(TCustomGMMap)
private
{*------------------------------------------------------------------------------
Visual configuration options.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opciones de configucación visual.
-------------------------------------------------------------------------------}
FVisualProp: TVisualProp; // ES: evento de TWebBrowser - EN: event of TWebBrowser
// internal variables
FTimer: TTimer; // ES: TTimer para el control de eventos - EN: TTimer for events control
protected
function VisualPropToStr: string; override;
procedure SetEnableTimer(State: Boolean); override;
procedure SetIntervalTimer(Interval: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveToJPGFile(FileName: TFileName = ''); override;
published
property VisualProp: TVisualProp read FVisualProp write FVisualProp;
end;
{*------------------------------------------------------------------------------
Class to access to Google Maps map specialized for TChromiumFMX browser.
See the TCustomGMMap class for properties and events description.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para el acceso al mapa de Google Maps especializada para el navegador TChromiumFMX.
Ver la clase TCustomGMMap para la descripción de las propiedades y eventos.
-------------------------------------------------------------------------------}
TGMMapChr = class(TCustomGMMapFMX)
private
// internal variables
OldOnLoadEnd: TOnLoadEnd;
FTChr: TTimer;
FStarTime: TDateTime;
procedure OnTimerChr(Sender: TObject);
procedure OnLoadEnd(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean);
procedure SetWebBrowser(const Value: TChromiumFMX);
function GetWebBrowser: TChromiumFMX;
protected
procedure BrowserEventsControl; override;
function ExecuteScript(NameFunct, Params: string): Boolean; override;
procedure LoadBaseWeb; override;
procedure LoadBlankPage; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{*------------------------------------------------------------------------------
Browser where display the Google Maps map.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Navegador donde se mostrará el mapa de Google Maps.
-------------------------------------------------------------------------------}
property WebBrowser: TChromiumFMX read GetWebBrowser write SetWebBrowser;
end;
{$ENDIF}
implementation
{$IFDEF CHROMIUMFMX}
uses
System.DateUtils,
WebControlFMX, Lang;
{ TGMMapChr }
procedure TGMMapChr.BrowserEventsControl;
begin
if not (FWebBrowser is TChromiumFMX) then Exit;
TChromiumFMX(FWebBrowser).OnLoadEnd := OldOnLoadEnd;
OldOnLoadEnd := nil;
end;
constructor TGMMapChr.Create(AOwner: TComponent);
begin
inherited;
FWC := TWebChromiumFMX.Create(nil);
OldOnLoadEnd := nil;
FTChr := TTimer.Create(Self);
FTChr.Enabled := False;
FTChr.OnTimer := OnTimerChr;
FTChr.Interval := 10;
FStarTime := Now;
end;
destructor TGMMapChr.Destroy;
begin
if Assigned(FTChr) then FreeAndNil(FTChr);
inherited;
end;
function TGMMapChr.ExecuteScript(NameFunct, Params: string): Boolean;
const
Param = '%s(%s)';
begin
Result := Check;
if not (FWebBrowser is TChromiumFMX) then Exit;
if not Result then Exit;
if TChromiumFMX(FWebBrowser).Browser <> nil then
TChromiumFMX(FWebBrowser).Browser.MainFrame.ExecuteJavaScript(Format(Param, [NameFunct, Params]), '', 0);
if MapIsNull then
raise Exception.Create(GetTranslateText('El mapa todavía no ha sido creado', Language));
end;
function TGMMapChr.GetWebBrowser: TChromiumFMX;
begin
Result := nil;
if FWebBrowser is TChromiumFMX then
Result := TChromiumFMX(FWebBrowser);
end;
procedure TGMMapChr.LoadBaseWeb;
begin
if not Assigned(FWebBrowser) then Exit;
if not (FWebBrowser is TChromiumFMX) then Exit;
// cargamos página inicial
if Assigned(TChromiumFMX(FWebBrowser).Browser) then
TChromiumFMX(FWebBrowser).Browser.MainFrame.LoadString(GetBaseHTMLCode, 'http:\\localhost');
end;
procedure TGMMapChr.LoadBlankPage;
begin
if not (FWebBrowser is TChromiumFMX) then Exit;
TChromiumFMX(FWebBrowser).Browser.MainFrame.LoadUrl('about:blank');
end;
procedure TGMMapChr.OnLoadEnd(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; httpStatusCode: Integer; out Result: Boolean);
begin
if Assigned(OldOnLoadEnd) then OldOnLoadEnd(Sender, browser, frame, httpStatusCode, Result);
if Assigned(frame) then
begin
FDocLoaded := True;
if Active and Assigned(AfterPageLoaded) then AfterPageLoaded(Self, True);
end;
end;
procedure TGMMapChr.OnTimerChr(Sender: TObject);
begin
if Active and Assigned(FWebBrowser) and Assigned(TChromiumFMX(FWebBrowser).Browser) then
begin
FTChr.Enabled := False;
LoadBaseWeb;
end;
if Now > IncSecond(FStarTime, 3) then FTChr.Enabled := False;
end;
procedure TGMMapChr.SetWebBrowser(const Value: TChromiumFMX);
begin
if FWebBrowser = Value then Exit;
if (Value <> FWebBrowser) and Assigned(FWebBrowser) then
begin
TChromiumFMX(FWebBrowser).OnLoadEnd := OldOnLoadEnd;
end;
FWebBrowser := Value;
TWebChromiumFMX(FWC).SetBrowser(TChromiumFMX(FWebBrowser));
if csDesigning in ComponentState then Exit;
if Assigned(FWebBrowser) then
begin
OldOnLoadEnd := TChromiumFMX(FWebBrowser).OnLoadEnd;
TChromiumFMX(FWebBrowser).OnLoadEnd := OnLoadEnd;
// if Active then LoadBaseWeb;
if Active then
begin
FStarTime := Now;
FTChr.Enabled := True;
end;
end;
end;
{ TCustomGMMapFMX }
constructor TCustomGMMapFMX.Create(AOwner: TComponent);
begin
inherited;
VisualProp := TVisualProp.Create;
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.Interval := 200;
FTimer.OnTimer := OnTimer;
end;
destructor TCustomGMMapFMX.Destroy;
begin
if Assigned(FTimer) then FreeAndNil(FTimer);
inherited;
end;
procedure TCustomGMMapFMX.SetEnableTimer(State: Boolean);
begin
inherited;
if Assigned(FTimer) then FTimer.Enabled := State;
end;
procedure TCustomGMMapFMX.SetIntervalTimer(Interval: Integer);
begin
inherited;
if Assigned(FTimer) then FTimer.Interval := Interval;
end;
function TCustomGMMapFMX.VisualPropToStr: string;
begin
Result := FVisualProp.ToStr;
end;
procedure TCustomGMMapFMX.SaveToJPGFile(FileName: TFileName);
var
SD: TSaveDialog;
begin
inherited;
if not Assigned(FWebBrowser) or not Assigned(FWC) then Exit;
if FileName = '' then
begin
SD := TSaveDialog.Create(nil);
try
SD.Filter := '*.jpg|*.jpg';
SD.DefaultExt := '*.jpg';
if SD.Execute then FileName := SD.FileName;
finally
FreeAndNil(SD);
end;
end;
FWC.SaveToJPGFile(FileName);
end;
{ TVisualProp }
procedure TVisualProp.Assign(Source: TPersistent);
begin
inherited;
if Source is TVisualProp then
BGColor := TVisualProp(Source).BGColor;
end;
constructor TVisualProp.Create;
begin
inherited;
FBGColor := clSilver;
end;
function TVisualProp.GetBckgroundColor: string;
begin
Result := TTransform.TColorToStr(FBGColor);
end;
{$ENDIF}
end.
|
Unit uRegPgn;
Interface
Uses Registry, WinTypes;
Const
CHAVE_RAIZ = HKEY_CURRENT_USER;
PathNative = 'SOFTWARE\Native';
ChaveNative = 'SOFTWARE\Native';
PathGeradorDeArquivos = PathNative + '\' + 'Gerador';
{ Variáveis publicas da Unit }
Var
Reg : TRegistry;
{Funções de leitura}
Function LerStringReg (ChaveRaiz : HKey; Chave, Valor : String; Default : String) : String;
Function LerNumeroReg (ChaveRaiz : HKey; Chave, Valor : String; Default : integer) : Integer;
Function LerBooleanReg(ChaveRaiz : HKey; Chave, Valor : String; Default : boolean) : boolean;
{Funções de Escrita}
Function EscreverStringReg (ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : String) : Boolean;
Function EscreverIntegerReg(ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : integer) : Boolean;
Function EscreverBooleanReg(ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : boolean) : Boolean;
Implementation
Uses WinProcs, Forms, SysUtils, Dialogs;
Function LerStringReg(ChaveRaiz : HKey; Chave, Valor : String; Default : String) : String;
Var
Resultado : String;
Begin
reg.Access := KEY_EXECUTE;
Result := Default;
Reg.RootKey := ChaveRaiz;
If Not Reg.OpenKey(Chave, (default <> '')) Then
Begin
//ShowMessage('Erro ao ler a chave ' + Chave);
Resultado := 'Erro ao ler a chave ' + Chave;
Exit;
End;
Try
If Reg.ValueExists(Valor) Then
Begin
Resultado := Reg.ReadString(Valor);
If Resultado = '' Then resultado := Default;
End Else
Begin
Reg.CloseKey;
reg.Access := KEY_ALL_ACCESS;
Reg.OpenKey(Chave, (default <> ''));
Reg.LazyWrite := false;
Reg.WriteString(Valor, Default);
End;
Except
{ Erro ao tentar ler o valor - retorna vazio }
Resultado := Default;
End;
Result := Resultado;
Reg.CloseKey;
End;
Function LerNumeroReg(ChaveRaiz : HKey; Chave, Valor : String; Default : integer) : Integer;
Var
Resultado : integer;
Begin
Result := Default;
Reg.RootKey := ChaveRaiz;
Reg.Access := KEY_EXECUTE;
If Not Reg.OpenKey(Chave, false) Then Begin
ShowMessage('Erro ao ler a chave ' + Chave);
exit;
End;
Try
If Reg.ValueExists(Valor) Then
Resultado := Reg.ReadInteger(Valor)
Else
Resultado := Default;
Except
{ Erro ao tentar ler o valor - retorna vazio }
Resultado := Default;
End;
Result := Resultado;
Reg.CloseKey;
End;
Function LerBooleanReg(ChaveRaiz : HKey; Chave, Valor : String; Default : boolean) : boolean;
Var
Resultado : boolean;
Begin
reg.Access := KEY_EXECUTE;
Result := Default;
Reg.RootKey := ChaveRaiz;
Resultado := False;
If Not Reg.OpenKey(Chave, Default) Then Begin
ShowMessage('Erro ao ler a chave ' + Chave);
exit;
End;
Try
If Reg.ValueExists(Valor) Then
begin
Resultado := Reg.ReadBool(Valor);
end Else
begin
Reg.CloseKey;
reg.Access := KEY_ALL_ACCESS;
Reg.OpenKey(Chave, default);
Reg.LazyWrite := false;
Reg.WriteBool(Valor, Default);
end;
Except
{ Erro ao tentar ler o valor - retorna vazaio }
Resultado := Default;
End;
Result := Resultado;
Reg.CloseKey;
End;
Function EscreverStringReg(ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : String) : Boolean;
Begin
Result := True;
reg.Access := KEY_SET_VALUE;
Try
Reg.RootKey := ChaveRaiz;
Reg.LazyWrite := false;
If Reg.OpenKey(Chave, true) Then Begin
Reg.WriteString(Valor, VlrEscr);
End Else Begin
ShowMessage('Erro ao ler a chave ' + Chave);
exit;
End;
Except
On e : Exception Do Begin
messageDlg(e.message, mtError, [mbok], 0);
Result := False;
End;
End;
Try
Reg.LazyWrite := true;
Reg.CloseKey;
Except
{ erro ao tentar fechar a chave }
End;
End;
Function EscreverIntegerReg(ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : integer) : Boolean;
Begin
Result := True;
reg.Access := KEY_SET_VALUE;
Try
Reg.RootKey := ChaveRaiz;
Reg.LazyWrite := false;
If Not Reg.OpenKey(Chave, true) Then Begin
ShowMessage('Erro ao ler a chave ' + Chave);
exit;
End;
Reg.WriteInteger(Valor, VlrEscr);
Except
Result := False;
End;
Try
Reg.LazyWrite := true;
Reg.CloseKey;
Except
{ erro ao tentar fechar a chave }
End;
End;
Function EscreverBooleanReg(ChaveRaiz : HKey; Chave, Valor : String; VlrEscr : boolean) : Boolean;
Begin
Result := True;
Reg.Access := KEY_ALL_ACCESS;
Try
Reg.RootKey := ChaveRaiz;
Reg.LazyWrite := false;
If Not Reg.OpenKey(Chave, true) Then Begin
ShowMessage('Erro ao ler a chave ' + Chave);
exit;
End;
Reg.WriteBool(Valor, VlrEscr);
Except
Result := False;
End;
Try
Reg.LazyWrite := true;
Reg.CloseKey;
Except
{ erro ao tentar fechar a chave }
End;
End;
Initialization
if Reg = nil then
Reg := TRegistry.Create;
Finalization
if Reg <> nil then
begin
Reg.Free;
Reg := nil;
end;
End.
|
unit UFrmEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Contnrs, AdvMemo, AdvmPS, Menus, ActnList,
ExtCtrls, AdvFindDialogForm, AdvReplaceDialogForm;
type
TTabDescriptor = class;
TFrmEditor = class(TForm)
Tab: TTabControl;
AdvMemo1: TAdvMemo;
LblPosition: TLabel;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
PopupMenu1: TPopupMenu;
Abrirnovaaba1: TMenuItem;
Fecharestaaba1: TMenuItem;
ReplaceDialog: TAdvMemoFindReplaceDialog;
AdvReplaceDialog1: TAdvReplaceDialog;
FindDialog: TAdvMemoFindDialog;
AdvFindDialog1: TAdvFindDialog;
procedure AdvMemo1CursorChange(Sender: TObject);
procedure TabChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Abrirnovaaba1Click(Sender: TObject);
procedure Fecharestaaba1Click(Sender: TObject);
procedure AdvMemo1Change(Sender: TObject);
private
{ Private declarations }
TabDescriptorList: TList;
FSemTituloCont: Integer;
FCreatingNewTab: Boolean;
FTabParent: TWinControl;
FPnlProgram: TPanel;
FStatusBar: TStatusBar;
FRichEditDoc: TRichEdit;
FClosingAll: Boolean;
FTabWithActiveLine: TTabDescriptor;
FActiveLine: Integer;
FUltimoDoc: String;
procedure ShowPos;
public
{ Public declarations }
Lume_br_styler: TAdvPascalMemoStyler;
function AddTab(TabContents: TStrings; FileName: String;
IsExample: Boolean): TTabDescriptor;
procedure InitialTab;
function OpenTab: TTabDescriptor;
function NewTab: TTabDescriptor;
function CloseTab(): Integer;
function CloseAllTabs(): Integer;
function SaveFileAs(): Integer;
function SaveFile(): Integer;
function IndexOfFile(FileName: String): Integer;
function SourceCode: TStringList;
function FileName: String;
procedure ShowLine(Line, Col: Integer; Show: Boolean);
procedure ShowLineOld(Line: Integer; Show: Boolean);
procedure ShowTab(FileName: String);
procedure EditorsReadOnly(Value: Boolean);
procedure ShowDoc(ResName: String);
procedure SetMainFormControls(TabParent: TWinControl;
PnlProgram: TPanel;
StatusBar: TStatusBar;
RichEditDoc: TRichEdit);
end;
TTabDescriptor = class
public
FFileName: String;
FIsExample: Boolean;
FMemoSource: TAdvMemoSource;
constructor Create(TabContents: TStrings; FileName: String;
IsExample: Boolean);
destructor Destroy; override;
function TabName: String;
end;
var
FrmEditor: TFrmEditor;
implementation
{$R *.dfm}
uses
UITypes, StrUtils, ULume_br_style, UFrmExample2, port_UFrmConfig, port_UFrmDSL;
{ TTabDescriptor }
constructor TTabDescriptor.Create(TabContents: TStrings; FileName: String;
IsExample: Boolean);
begin
FFileName := FileName;
FIsExample := IsExample;
// cria o MemoSource associado
FMemoSource := TAdvMemoSource.Create(nil);
FMemoSource.SyntaxStyler := FrmEditor.Lume_br_styler;
FMemoSource.Lines.Assign(TabContents);
end;
function TTabDescriptor.TabName: String;
begin
Result := ExtractFileName(FFileName);
// Result := ChangeFileExt(Result, '');
end;
destructor TTabDescriptor.Destroy;
begin
// FMemoSource.Free;
FMemoSource.Lines.Clear; // está havendo um bug com .Free
end;
{ TFrmEditor }
procedure TFrmEditor.ShowPos;
begin
FStatusBar.Panels[0].Text := IntToStr(AdvMemo1.CurY + 1) + ' : ' +
IntToStr(AdvMemo1.CurX + 1);
end;
procedure TFrmEditor.AdvMemo1CursorChange(Sender: TObject);
begin
ShowPos;
if not AdvMemo1.MemoSource.ReadOnly then
begin
AdvMemo1.ActiveLineSettings.ShowActiveLineIndicator := False;
AdvMemo1.ActiveLineSettings.ShowActiveLine := False;
end;
end;
function TFrmEditor.AddTab(TabContents: TStrings; FileName: String;
IsExample: Boolean): TTabDescriptor;
var
Ind: Integer;
begin
// verifica se o arquivo já está carregado
Ind := IndexOfFile(FileName);
if Ind >= 0 then
begin
Tab.TabIndex := Ind;
TabChange(Self);
Result := TTabDescriptor(TabDescriptorList[Ind]);
Exit;
end;
FCreatingNewTab := True;
try
Result := TTabDescriptor.Create(TabContents, FileName, IsExample);
TabDescriptorList.Add(Result);
Tab.Tabs.Add(Result.TabName());
Tab.TabIndex := Tab.Tabs.Count - 1;
AdvMemo1.MemoSource := Result.FMemoSource;
FrmDSL.Caption := 'SW-Tutor - ' + Result.TabName();
FPnlProgram.Caption := Result.TabName();
if AdvMemo1.Visible then
AdvMemo1.SetFocus;
FrmDsl.ActFileSave.Enabled := False;
finally
FCreatingNewTab := False;
end;
end;
procedure TFrmEditor.TabChange(Sender: TObject);
var
Td: TTabDescriptor;
begin
if Tab.TabIndex < 0 then
Exit; // nada a fazer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
AdvMemo1.ActiveLineSettings.ShowActiveLineIndicator := FTabWithActiveLine = Td;
AdvMemo1.ActiveLineSettings.ShowActiveLine := FTabWithActiveLine = Td;
if FTabWithActiveLine <> nil then
AdvMemo1.ActiveLine := FActiveLine;
AdvMemo1.MemoSource := Td.FMemoSource;
if AdvMemo1.Visible then
AdvMemo1.SetFocus;
FPnlProgram.Caption := Td.TabName();
FrmDSL.Caption := 'SW-Tutor - ' + Td.TabName();
ShowPos;
FrmDsl.ActFileSave.Enabled := Td.FMemoSource.Modified;
end;
procedure TFrmEditor.FormCreate(Sender: TObject);
begin
TabDescriptorList := TList.Create;
Lume_br_styler := CreateLumeBrStyler(Self);
end;
procedure TFrmEditor.InitialTab;
begin
FrmExample2.CarregaPrimeiroExemplo;
end;
procedure TFrmEditor.FormDestroy(Sender: TObject);
begin
// TabDescriptorList.Free;
end;
function TFrmEditor.SaveFile: Integer;
var
Td: TTabDescriptor;
begin
Result := mrYes;
if Tab.TabIndex < 0 then
Exit; // nada a fazer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
if ((not Td.FMemoSource.Modified) and (not Td.FIsExample)) then
Exit; // nada a fazer
if Td.FIsExample then
begin
Result := SaveFileAs();
Exit;
end
else
begin
Td.FMemoSource.Lines.SaveToFile(Td.FFileName);;
Td.FIsExample := False;
Td.FMemoSource.Modified := False;
FrmDsl.ActFileSave.Enabled := Td.FMemoSource.Modified;
end;
end;
function TFrmEditor.SaveFileAs: Integer;
const
SWarningText = 'O arquivo %s já existe. Deseja substituí-lo?';
var
Td: TTabDescriptor;
begin
Result := mrNo;
if Tab.TabIndex < 0 then
Exit; // nada a fazer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
SaveDialog.FileName := Td.FFileName;
if not SaveDialog.Execute then
begin
Result := mrCancel;
Exit; // nada a fazer
end
else
Result := mrYes;
if FileExists(SaveDialog.FileName) then
Result := MessageDlg(Format(SWarningText, [Td.FFileName]),
mtConfirmation, [mbYes, mbNo, mbCancel], 0);
if (Result in [mrNo, mrCancel]) then
Exit; // nada mais a fazer
// salva o arquivo
Td.FFileName := SaveDialog.FileName;
Td.FMemoSource.Lines.SaveToFile(Td.FFileName);
Td.FIsExample := False;
Td.FMemoSource.Modified := False;
Tab.Tabs[Tab.TabIndex] := Td.TabName();
TabChange(Self);
end;
function TFrmEditor.CloseTab: Integer;
const
SWarningText = 'Deseja salvar as alterações feitas em %s?';
var
Td: TTabDescriptor;
Ind: Integer;
begin
Result := mrNo;
if Tab.TabIndex < 0 then
Exit; // nada a fazer; não deve acontecer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
if Td.FMemoSource.Modified then
Result := MessageDlg(Format(SWarningText, [Td.FFileName]),
mtConfirmation, [mbYes, mbNo, mbCancel], 0);
// Se cancelou, nada mais a fazer
if Result = mrCancel then
Exit;
// Verifica se é pra salvar antes de fechar
if Result = mrYes then
Result := SaveFile;
// Testa de novo: Se cancelou, nada mais a fazer
if Result = mrCancel then
Exit;
// fecha
Ind := Tab.TabIndex;
TabDescriptorList.Delete(Ind);
Tab.Tabs.Delete(Ind);
if Tab.Tabs.Count > 0 then
begin
if Ind >= Tab.Tabs.Count then
Tab.TabIndex := Tab.Tabs.Count - 1
else
Tab.TabIndex := Ind;
end
else if not FClosingAll then
InitialTab;
Td.Free;
if not FClosingAll then TabChange(Self);
end;
function TFrmEditor.OpenTab: TTabDescriptor;
var
S: TStringList;
Ind: Integer;
begin
Result := nil;
OpenDialog.FileName := '';
if (not OpenDialog.Execute) then
Exit; // nada a fazer
// verifica se o arquivo já está aberto em alguma aba
Ind := IndexOfFile(OpenDialog.FileName);
if Ind >= 0 then
begin
Tab.TabIndex := Ind;
TabChange(Self);
Exit;
end;
S := TStringList.Create;
S.LoadFromFile(OpenDialog.FileName);
Result := AddTab(S, OpenDialog.FileName, False);
S.Free;
end;
function TFrmEditor.NewTab: TTabDescriptor;
var
S: TStringList;
FileName: String;
begin
S := TStringList.Create;
Inc(FSemTituloCont);
FileName := 'sem_título' + IntToStr(FSemTituloCont) +
FrmConfig.ExtensaoDefaultPrg();
Result := AddTab(S, FileName, False);
S.Free;
end;
procedure TFrmEditor.Abrirnovaaba1Click(Sender: TObject);
begin
NewTab;
end;
procedure TFrmEditor.Fecharestaaba1Click(Sender: TObject);
begin
CloseTab;
end;
function TFrmEditor.CloseAllTabs: Integer;
function IndexOfModified(): Integer;
var I: Integer;
begin
Result := -1;
if Tab.Tabs.Count = 0 then
Exit;
for I := Tab.Tabs.Count - 1 downto 0 do
if TTabDescriptor(TabDescriptorList[I]).FMemoSource.Modified then
begin
Result := I;
Exit;
end;
end;
function CloseModified(): Integer;
var
Ind: Integer;
begin
Result := mrCancel;
Ind := IndexOfModified();
if Ind = -1 then
Exit;
Tab.TabIndex := Ind;
Result := CloseTab();
end;
begin
FClosingAll := True;
try
repeat
Result := CloseModified();
until (Result = mrCancel);
if (Tab.Tabs.Count = 0) or (IndexOfModified() = -1) then
Result := mrYes;
finally
FClosingAll := False;
end;
end;
function TFrmEditor.IndexOfFile(FileName: String): Integer;
var
I: Integer;
function FileNamesAreEqual(F1, F2: String): Boolean;
begin
Result := UpperCase(F1) = UpperCase(F2);
end;
begin
Result := -1;
for I := 0 to TabDescriptorList.Count - 1 do
if FileNamesAreEqual(TTabDescriptor(TabDescriptorList.Items[I]).FFileName,
FileName) then
begin
Result := I;
Exit;
end;
end;
function TFrmEditor.SourceCode: TStringList;
var
Td: TTabDescriptor;
begin
Result := nil;
if Tab.TabIndex < 0 then
Exit; // nunca deve acontecer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
Result := Td.FMemoSource.Lines;
end;
function TFrmEditor.FileName: String;
var
Td: TTabDescriptor;
begin
Result := '';
if Tab.TabIndex < 0 then
Exit; // nunca deve acontecer
Td := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex]);
Result := Td.FFileName;
end;
procedure TFrmEditor.ShowLine(Line, Col: Integer; Show: Boolean);
begin
FActiveLine := Line - 1;
if Show then
FTabWithActiveLine := TTabDescriptor(TabDescriptorList.Items[Tab.TabIndex])
else
FTabWithActiveLine := nil;
AdvMemo1.CurX := Col - 1;
AdvMemo1.CurY := Line - 1;
TabChange(Self);
end;
procedure TFrmEditor.ShowTab(FileName: String);
procedure ShowThisFile(FileName: String);
var
Ts: TStringList;
begin
if not FileExists(FileName) then
Exit; // não deve acontecer
Ts := TStringList.Create;
Ts.LoadFromFile(FileName);
AddTab(Ts, FileName, False);
Ts.Free;
end;
var
Ind: Integer;
begin
Ind := IndexOfFile(FileName);
if Ind < 0 then
ShowThisFile(FileName)
else
begin
Tab.TabIndex := Ind;
TabChange(Self);
end;
end;
procedure TFrmEditor.EditorsReadOnly(Value: Boolean);
var
I: Integer;
Td: TTabDescriptor;
begin
for I := 0 to TabDescriptorList.Count - 1 do
begin
Td := TTabDescriptor(TabDescriptorList.Items[I]);
Td.FMemoSource.ReadOnly := Value;
end;
end;
procedure TFrmEditor.SetMainFormControls(TabParent: TWinControl;
PnlProgram: TPanel;
StatusBar: TStatusBar;
RichEditDoc: TRichEdit);
begin
FTabParent := TabParent;
FPnlProgram := PnlProgram;
FStatusBar := StatusBar;
FRichEditDoc := RichEditDoc;
// carrega no editor o primeiro exemplo
Tab.Align := alClient;
Tab.Parent := FTabParent;
InitialTab;
AdvMemo1.Font.Size := FrmConfig.obt_tam_fonte_editor();
end;
procedure TFrmEditor.ShowLineOld(Line: Integer; Show: Boolean);
begin
AdvMemo1.ActiveLine := Line - 1;
// AdvMemo1.ActiveLineSettings.ShowActiveLineIndicator := Show;
// AdvMemo1.ActiveLineSettings.ShowActiveLine := Show;
// AdvMemo1.ActiveLineSettings.ActiveLineAtCursor := Show;
AdvMemo1.HiddenCaret := Show;
if Show then
begin
AdvMemo1.ActiveLineSettings.ActiveLineTextColor := clWhite;
AdvMemo1.ActiveLineSettings.ActiveLineColor := clNavy;
end
else
begin
AdvMemo1.ActiveLineSettings.ActiveLineTextColor := clBlack;
AdvMemo1.ActiveLineSettings.ActiveLineColor := clWhite;
end;
end;
procedure TFrmEditor.ShowDoc(ResName: String);
var
Res: TResourceStream;
begin
if FUltimoDoc = ResName then
Exit;
// cria o resource
try
Res := TResourceStream.Create(HInstance, 'Doc-' + ResName, RT_RCDATA);
except
Exit; // não encontrou o resource
end;
// coloca no rich edit
FRichEditDoc.Lines.LoadFromStream(Res);
FUltimoDoc := ResName;
Res.Free;
end;
procedure TFrmEditor.AdvMemo1Change(Sender: TObject);
begin
FrmDsl.ActFileSave.Enabled := True;
end;
end.
|
unit InfBlock;
(************************************************************************
infblock.h and
infblock.c -- interpret and process block types to last block
Copyright (C) 1995-2002 Mark Adler
Pascal translation
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Aug 2000
- ZLIB 113 changes
Feb 2002
- Source code reformating/reordering
Mar 2002
- ZLIB 114 changes
Mar 2005
- Code cleanup for WWW upload
May 2005
- Trace: use #13#10 like C original
------------------------------------------------------------------------
*************************************************************************)
interface
{$x+}
uses
zlibh, infutil;
function inflate_blocks_new(var z: z_stream;
c: check_func; {check function}
w: uInt {window size}
): pInflate_blocks_state;
function inflate_blocks(var s: inflate_blocks_state;
var z: z_stream;
r: int {initial return code}
): int;
procedure inflate_blocks_reset(var s: inflate_blocks_state; var z: z_stream; c: puLong);
function inflate_blocks_free(s: pInflate_blocks_state; var z: z_stream): int;
procedure inflate_set_dictionary( var s: inflate_blocks_state;
const d: array of byte; {dictionary}
n: uInt); {dictionary length}
function inflate_blocks_sync_point(var s: inflate_blocks_state): int;
implementation
{$I zconf.inc}
uses
zutil, infcodes, inftrees;
{Tables for deflate from PKZIP's appnote.txt.}
const
border: array [0..18] of word {Order of the bit length code lengths}
= (16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
{Notes beyond the 1.93a appnote.txt:
1. Distance pointers never point before the beginning of the output
stream.
2. Distance pointers can point back across blocks, up to 32k away.
3. There is an implied maximum of 7 bits for the bit length table and
15 bits for the actual data.
4. If only one code exists, then it is encoded using one bit. (Zero
would be more efficient, but perhaps a little confusing.) If two
codes exist, they are coded using one bit each (0 and 1).
5. There is no way of sending zero distance codes--a dummy must be
sent if there are none. (History: a pre 2.0 version of PKZIP would
store blocks with no distance codes, but this was discovered to be
too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
zero distance codes, which is sent as one code of zero bits in
length.
6. There are up to 286 literal/length codes. Code 256 represents the
end-of-block. Note however that the static length tree defines
288 codes just to fill out the Huffman codes. Codes 286 and 287
cannot be used though, since there is no length base or extra bits
defined for them. Similarily, there are up to 30 distance codes.
However, static trees define 32 codes (all 5 bits) to fill out the
Huffman codes, but the last two had better not show up in the data.
7. Unzip can check dynamic Huffman blocks for complete code sets.
The exception is that a single code would not be complete (see #4).
8. The five bits following the block type is really the number of
literal codes sent minus 257.
9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
(1+6+6). Therefore, to output three times the length, you output
three codes (1+1+1), whereas to output four times the same length,
you only need two codes (1+3). Hmm.
10. In the tree reconstruction algorithm, Code = Code + Increment
only if BitLength(i) is not zero. (Pretty obvious.)
11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
12. Note: length code 284 can represent 227-258, but length code 285
really is 258. The last length deserves its own, short code
since it gets used a lot in very redundant files. The length
258 is special since 258 - 3 (the min match length) is 255.
13. The literal/length and distance code bit lengths are read as a
single stream of lengths. It is possible (and advantageous) for
a repeat code (16, 17, or 18) to go across the boundary between
the two sets of lengths.}
{---------------------------------------------------------------------------}
procedure inflate_blocks_reset(var s: inflate_blocks_state; var z: z_stream; c: puLong);
{c: check value on output}
begin
with s do begin
if c<>Z_NULL then c^ := check;
if (mode=_BTREE) or (mode=_DTREE) then Z_FREE(z, sub.trees.blens);
if (mode=_CODES) then inflate_codes_free(sub.decode.codes, z);
mode := _ZTYPE;
bitk := 0;
bitb := 0;
write := window;
read := window;
if Assigned(checkfn) then begin
check := checkfn(uLong(0), pBytef(nil), 0);
z.adler := check;
end;
{$ifdef DEBUG}
Tracev('inflate: blocks reset'#13#10);
{$endif}
end;
end;
{---------------------------------------------------------------------------}
function inflate_blocks_new(var z: z_stream;
c: check_func; {check function}
w: uInt {window size}
): pInflate_blocks_state;
var
s: pInflate_blocks_state;
begin
s := pInflate_blocks_state(Z_ALLOC(z,1, sizeof(inflate_blocks_state)));
if s=Z_NULL then begin
inflate_blocks_new := s;
exit;
end;
with s^ do begin
hufts := huft_ptr(Z_ALLOC(z, sizeof(inflate_huft), MANY));
if hufts=Z_NULL then begin
Z_FREE(z, s);
inflate_blocks_new := Z_NULL;
exit;
end;
window := pBytef(Z_ALLOC(z, 1, w));
if window=Z_NULL then begin
Z_FREE(z, hufts);
Z_FREE(z, s);
inflate_blocks_new := Z_NULL;
exit;
end;
zend := window;
inc(zend, w);
checkfn := c;
mode := _ZTYPE;
{$ifdef DEBUG}
Tracev('inflate: blocks allocated'#13#10);
{$endif}
end;
inflate_blocks_reset(s^, z, Z_NULL);
inflate_blocks_new := s;
end;
{---------------------------------------------------------------------------}
function inflate_blocks(var s: inflate_blocks_state;
var z: z_stream;
r: int): int; {initial return code}
label
start_btree, start_dtree,
start_blkdone, start_dry,
start_codes;
var
t: uInt; {temporary storage}
b: uLong; {bit buffer}
k: uInt; {bits in bit buffer}
p: pBytef; {input data pointer}
n: uInt; {bytes available there}
q: pBytef; {output window write pointer}
m: uInt; {bytes to end of window or read pointer}
{fixed code blocks}
var
bl, bd: uInt;
tl, td: pInflate_huft;
var
h: pInflate_huft;
i, j, c: uInt;
var
cs: pInflate_codes_state;
begin
{copy input/output information to locals}
p := z.next_in;
n := z.avail_in;
b := s.bitb;
k := s.bitk;
q := s.write;
if ptr2int(q)<ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else m := uInt(ptr2int(s.zend)-ptr2int(q));
{decompress an inflated block}
{process input based on current state}
while true do begin
case s.mode of
_ZTYPE: begin
{NEEDBITS(3);}
while (k < 3) do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
t := uInt(b) and 7;
s.last := boolean(t and 1);
case t shr 1 of
0: begin {stored}
{$ifdef DEBUG}
if s.last then Tracev('inflate: stored block (last)'#13#10)
else Tracev('inflate: stored block'#13#10);
{$endif}
{DUMPBITS(3);}
b := b shr 3;
dec(k, 3);
t := k and 7; {go to byte boundary}
{DUMPBITS(t);}
b := b shr t;
dec(k, t);
s.mode := _LENS; {get length of stored block}
end;
1: begin {fixed}
{$ifdef DEBUG}
if s.last then Tracev('inflate: fixed codes blocks (last)'#13#10)
else Tracev('inflate: fixed codes blocks'#13#10);
{$endif}
inflate_trees_fixed(bl, bd, tl, td, z);
s.sub.decode.codes := inflate_codes_new(bl, bd, tl, td, z);
if s.sub.decode.codes=Z_NULL then begin
r := Z_MEM_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{DUMPBITS(3);}
b := b shr 3;
dec(k, 3);
s.mode := _CODES;
end;
2: begin {dynamic}
{$ifdef DEBUG}
if s.last then Tracev('inflate: dynamic codes block (last)'#13#10)
else Tracev('inflate: dynamic codes block'#13#10);
{$endif}
{DUMPBITS(3);}
b := b shr 3;
dec(k, 3);
s.mode := _TABLE;
end;
3: begin {illegal}
{DUMPBITS(3);}
b := b shr 3;
dec(k, 3);
s.mode := _BLKBAD;
z.msg := 'invalid block type';
r := Z_DATA_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
end; {case}
end;
_LENS: begin
{NEEDBITS(32);}
while k<32 do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
if (((not b) shr 16) and $ffff) <> (b and $ffff) then begin
s.mode := _BLKBAD;
z.msg := 'invalid stored block lengths';
r := Z_DATA_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
s.sub.left := uInt(b) and $ffff;
k := 0;
b := 0; {dump bits}
{$ifdef DEBUG}
Tracev('inflate: stored length '+IntToStr(s.sub.left)+#13#10);
{$endif}
if s.sub.left <> 0 then s.mode := _STORED
else if s.last then s.mode := _DRY
else s.mode := _ZTYPE;
end;
_STORED: begin
if n=0 then begin
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{NEEDOUT}
if m=0 then begin
{WRAP}
if (q = s.zend) and (s.read <> s.window) then begin
q := s.window;
if ptr2int(q)<ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else m := uInt(ptr2int(s.zend)-ptr2int(q));
end;
if m=0 then begin
{FLUSH}
s.write := q;
r := inflate_flush(s,z,r);
q := s.write;
if ptr2int(q)<ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else m := uInt(ptr2int(s.zend)-ptr2int(q));
{WRAP}
if (q = s.zend) and (s.read <> s.window) then begin
q := s.window;
if ptr2int(q) < ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else m := uInt(ptr2int(s.zend)-ptr2int(q));
end;
if m=0 then begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
end;
end;
r := Z_OK;
t := s.sub.left;
if t>n then t := n;
if t>m then t := m;
zmemcpy(q, p, t);
inc(p, t);
dec(n, t);
inc(q, t);
dec(m, t);
dec(s.sub.left, t);
if s.sub.left=0 then begin
{$ifdef DEBUG}
if (ptr2int(q) >= ptr2int(s.read)) then begin
Tracev('inflate: stored end '+
IntToStr(z.total_out + ptr2int(q) - ptr2int(s.read)) + ' total out'#13#10)
end
else begin
Tracev('inflate: stored end '+
IntToStr(z.total_out + ptr2int(s.zend) - ptr2int(s.read) +
ptr2int(q) - ptr2int(s.window)) + ' total out'#13#10);
end;
{$endif}
if s.last then s.mode := _DRY
else s.mode := _ZTYPE;
end;
end;
_TABLE: begin
{NEEDBITS(14);}
while k<14 do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
t := uInt(b) and $3fff;
s.sub.trees.table := t;
{$ifndef PKZIP_BUG_WORKAROUND}
if ((t and $1f) > 29) or (((t shr 5) and $1f) > 29) then begin
s.mode := _BLKBAD;
z.msg := 'too many length or distance symbols';
r := Z_DATA_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{$endif}
t := 258 + (t and $1f) + ((t shr 5) and $1f);
s.sub.trees.blens := puIntArray(Z_ALLOC(z, t, sizeof(uInt)));
if s.sub.trees.blens=Z_NULL then begin
r := Z_MEM_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{DUMPBITS(14);}
b := b shr 14;
dec(k, 14);
s.sub.trees.index := 0;
{$ifdef DEBUG}
Tracev('inflate: table sizes ok'#13#10);
{$endif}
s.mode := _BTREE;
{fall trough case is handled by the while}
{try goto for speed - Nomssi}
goto start_btree;
end;
_BTREE: begin
start_btree:
while s.sub.trees.index < 4 + (s.sub.trees.table shr 10) do begin
{NEEDBITS(3);}
while k<3 do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
s.sub.trees.blens^[border[s.sub.trees.index]] := uInt(b) and 7;
inc(s.sub.trees.index);
{DUMPBITS(3);}
b := b shr 3;
dec(k, 3);
end;
while s.sub.trees.index<19 do begin
s.sub.trees.blens^[border[s.sub.trees.index]] := 0;
inc(s.sub.trees.index);
end;
s.sub.trees.bb := 7;
t := inflate_trees_bits(s.sub.trees.blens^, s.sub.trees.bb, s.sub.trees.tb, s.hufts^, z);
if t<>Z_OK then begin
{*we 114, move Z_FREE in Z_DATA_ERROR if block}
r := t;
if r=Z_DATA_ERROR then begin
Z_FREE(z, s.sub.trees.blens);
s.mode := _BLKBAD;
end;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
s.sub.trees.index := 0;
{$ifdef DEBUG}
Tracev('inflate: bits tree ok'#13#10);
{$endif}
s.mode := _DTREE;
{fall through again}
goto start_dtree;
end;
_DTREE: begin
start_dtree:
while true do begin
t := s.sub.trees.table;
if not (s.sub.trees.index < 258 + (t and $1f) + ((t shr 5) and $1f)) then break;
t := s.sub.trees.bb;
{NEEDBITS(t);}
while k<t do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
h := s.sub.trees.tb;
inc(h, uInt(b) and inflate_mask[t]);
t := h^.Bits;
c := h^.Base;
if c<16 then begin
{DUMPBITS(t);}
b := b shr t;
dec(k, t);
s.sub.trees.blens^[s.sub.trees.index] := c;
inc(s.sub.trees.index);
end
else begin
{c=16..18}
if c=18 then begin
i := 7;
j := 11;
end
else begin
i := c - 14;
j := 3;
end;
{NEEDBITS(t + i);}
while k<t+i do begin
{NEEDBYTE;}
if n<>0 then r :=Z_OK
else begin
{UPDATE}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p)-ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
dec(n);
b := b or (uLong(p^) shl k);
inc(p);
inc(k, 8);
end;
{DUMPBITS(t);}
b := b shr t;
dec(k, t);
inc(j, uInt(b) and inflate_mask[i]);
{DUMPBITS(i);}
b := b shr i;
dec(k, i);
i := s.sub.trees.index;
t := s.sub.trees.table;
if (i + j > 258 + (t and $1f) + ((t shr 5) and $1f)) or ((c = 16) and (i < 1)) then begin
Z_FREE(z, s.sub.trees.blens);
s.mode := _BLKBAD;
z.msg := 'invalid bit length repeat';
r := Z_DATA_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
if c = 16 then c := s.sub.trees.blens^[i - 1]
else c := 0;
repeat
s.sub.trees.blens^[i] := c;
inc(i);
dec(j);
until j=0;
s.sub.trees.index := i;
end;
end; {while}
s.sub.trees.tb := Z_NULL;
bl := 9; {must be <= 9 for lookahead assumptions}
bd := 6; {must be <= 9 for lookahead assumptions}
t := s.sub.trees.table;
t := inflate_trees_dynamic(257 + (t and $1f),
1 + ((t shr 5) and $1f),
s.sub.trees.blens^, bl, bd, tl, td, s.hufts^, z);
if t<>Z_OK then begin
if t=uInt(Z_DATA_ERROR) then begin
{*we 114}
Z_FREE(z, s.sub.trees.blens);
s.mode := _BLKBAD;
end;
r := t;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{$ifdef DEBUG}
Tracev('inflate: trees ok'#13#10);
{$endif}
{c renamed to cs}
cs := inflate_codes_new(bl, bd, tl, td, z);
if cs=Z_NULL then begin
r := Z_MEM_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
{*we 114}
Z_FREE(z, s.sub.trees.blens);
{*we Apr.2004: Assignent after Z_FREE}
s.sub.decode.codes := cs;
s.mode := _CODES;
{yet another falltrough}
goto start_codes;
end;
_CODES: begin
start_codes:
{update pointers}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
r := inflate_codes(s, z, r);
if r<>Z_STREAM_END then begin
inflate_blocks := inflate_flush(s, z, r);
exit;
end;
r := Z_OK;
inflate_codes_free(s.sub.decode.codes, z);
{load local pointers}
p := z.next_in;
n := z.avail_in;
b := s.bitb;
k := s.bitk;
q := s.write;
if ptr2int(q)<ptr2int(s.read) then m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else m := uInt(ptr2int(s.zend)-ptr2int(q));
{$ifdef DEBUG}
if (ptr2int(q) >= ptr2int(s.read)) then begin
Tracev('inflate: codes end '+ IntToStr(z.total_out + ptr2int(q) - ptr2int(s.read)) + ' total out'#13#10)
end
else begin
Tracev('inflate: codes end '+
IntToStr(z.total_out + ptr2int(s.zend) - ptr2int(s.read) +
ptr2int(q) - ptr2int(s.window)) + ' total out'#13#10);
end;
{$endif}
if not s.last then begin
s.mode := _ZTYPE;
continue; {break for switch statement in C-code}
end;
{*we 113: Code delete (patch112)}
s.mode := _DRY;
{another falltrough}
goto start_dry;
end;
_DRY: begin
start_dry:
{FLUSH}
s.write := q;
r := inflate_flush(s,z,r);
q := s.write;
{not needed anymore, we are done:
if ptr2int(q) < ptr2int(s.read) then
m := uInt(ptr2int(s.read)-ptr2int(q)-1)
else
m := uInt(ptr2int(s.zend)-ptr2int(q));}
if s.read<>s.write then begin
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
s.mode := _BLKDONE;
goto start_blkdone;
end;
_BLKDONE: begin
start_blkdone:
r := Z_STREAM_END;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
_BLKBAD: begin
r := Z_DATA_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
else begin
r := Z_STREAM_ERROR;
{update pointers and return}
s.bitb := b;
s.bitk := k;
z.avail_in := n;
inc(z.total_in, ptr2int(p) - ptr2int(z.next_in));
z.next_in := p;
s.write := q;
inflate_blocks := inflate_flush(s,z,r);
exit;
end;
end; {case s.mode of}
end; {while true}
end;
{---------------------------------------------------------------------------}
function inflate_blocks_free(s: pInflate_blocks_state; var z: z_stream): int;
begin
inflate_blocks_reset(s^, z, Z_NULL);
Z_FREE(z, s^.window);
Z_FREE(z, s^.hufts);
Z_FREE(z, s);
{$ifdef DEBUG}
Trace('inflate: blocks freed'#13#10);
{$endif}
inflate_blocks_free := Z_OK;
end;
{---------------------------------------------------------------------------}
procedure inflate_set_dictionary( var s: inflate_blocks_state;
const d: array of byte; {dictionary}
n: uInt); {dictionary length}
begin
zmemcpy(s.window, pBytef(@d), n);
s.write := s.window;
inc(s.write, n);
s.read := s.write;
end;
{---------------------------------------------------------------------------}
function inflate_blocks_sync_point(var s: inflate_blocks_state): int;
{Returns true if inflate is currently at the end of a block generated
by Z_SYNC_FLUSH or Z_FULL_FLUSH.
IN assertion: s <> Z_NULL}
begin
inflate_blocks_sync_point := int(s.mode=_LENS);
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.Win.ADOConst;
interface
resourcestring
SInvalidEnumValue = 'Valor Numérico Inválido';
SMissingConnection = 'Faltando a Conexão ou String de Conexão';
SNoDetailFilter = 'Propriedade Filter não pode ser usada em uma tabela de detalhes';
SBookmarksRequired = 'Dataset não suporta bookmarks, no qual são requeridos para controle de dados com múltiplos registros';
SMissingCommandText = 'Faltando propriedade %s';
SNoResultSet = 'CommandText não retorna um result set';
SADOCreateError = 'Erro criando objeto. Favor verificar se o Microsoft Data Access Components 2.1 (ou superior) foi instalado adequadamente';
SEventsNotSupported = 'Eventos não são suportados com os cursores do lado TableDirect do servidor';
SUsupportedFieldType = 'Não suportado tipo de campo (%s) em campo %s';
SNoMatchingADOType = 'Nenhum tipo combinando dos dados do ADO para %s';
SConnectionRequired = 'Um componente de conexão é requerido para ExecuteOptions assíncrono';
SCantRequery = 'Não é possível executar um Requery depois que a conexão mudou';
SNoFilterOptions = 'Não é suportada as opções de Filtro';
SRecordsetNotOpen = 'O Recordset não está aberto';
sNameAttr = 'Nome';
sValueAttr = 'Valor';
implementation
end. |
unit xfpwmwidgets;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpg_main, fpg_base, fpg_widget,fpg_label, fpg_button, fpg_impl;
type
{ TXfpgWMTitleBar }
TXfpgWMTitleBar = class(TfpgWidget)
FMenuButton: TfpgButton;
FCloseButton: TfpgButton;
FMinimizeButton: TfpgButton;
FMaximizeRestoreButton: TfpgButton;
//FTitleLabel: TfpgLabel;
protected
FTitleText: String;
FCreating: Boolean;
procedure HandlePaint; override;
procedure HandleLMouseDown(x, y: integer; shiftstate: TShiftState); override;
procedure HandleLMouseUp(x, y: integer; shiftstate: TShiftState); override;
procedure HandleMouseMove(x, y: integer; btnstate: word; shiftstate: TShiftState); override;
private
FOnEndDrag: TMouseButtonEvent;
FOnStartDrag: TMouseButtonEvent;
function GetTitle: String;
procedure Resized(Sender: TObject);
function GetOnCloseButtonClick: TNotifyEvent;
function GetOnMaxRestoreButtonClick: TNotifyEvent;
function GetOnMinimizeButtonClick: TNotifyEvent;
procedure SetOnCloseButtonClick ( const AValue: TNotifyEvent ) ;
procedure SetOnMaxRestoreButtonClick ( const AValue: TNotifyEvent ) ;
procedure SetOnMinimizeButtonClick ( const AValue: TNotifyEvent ) ;
procedure SetTitle ( const AValue: String ) ;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnCloseButtonClick: TNotifyEvent read GetOnCloseButtonClick write SetOnCloseButtonClick;
property OnMinimizeButtonClick: TNotifyEvent read GetOnMinimizeButtonClick write SetOnMinimizeButtonClick;
property OnMaxRestoreButtonClick: TNotifyEvent read GetOnMaxRestoreButtonClick write SetOnMaxRestoreButtonClick;
property OnStartDrag: TMouseButtonEvent read FOnStartDrag write FOnStartDrag;
property OnEndDrag: TMouseButtonEvent read FOnEndDrag write FOnEndDrag;
property Title: String read GetTitle write SetTitle;
property OnMouseMove;
end;
{ TfpgClientWindow }
TfpgClientWindow = class(TfpgWidget)
protected
FWinHandle: TfpgWinHandle;
public
constructor Create(AOwner: TComponent; AWinHandle: TfpgWinHandle);
//procedure DoAllocateWindowHandle(AParent: TfpgWindowBase); override;
end;
implementation
{ TXfpgWMTitleBar }
procedure TXfpgWMTitleBar.HandlePaint;
function SetTextWidth(AWidth: Integer; out ATextWidth: Integer): Integer;
begin
ATextWidth := AWidth;
Result := AWidth;
end;
var
AvailSize: Integer;
TheText: String;
CopySize: Integer;
PaintX, PaintY, PaintWidth: Integer;
begin
if not Visible then exit;
Canvas.Color := BackgroundColor;
Canvas.FillRectangle(0,0,Width,Height);
if FCreating then
Exit;
//exit;
Canvas.TextColor := clWhite;
TheText := Trim(FTitleText);
AvailSize := FMinimizeButton.Left - FMenuButton.Width;
CopySize := Length(TheText);
while (SetTextWidth(Canvas.Font.TextWidth(TheText), PaintWidth) > AvailSize) and (CopySize > 2) do
begin
Dec(CopySize);
TheText := Copy(FTitleText, 1, CopySize)+'...';
end;
PaintY := (Height div 2) - (Canvas.Font.Height div 2);
PaintX := (AvailSize div 2) - (PaintWidth div 2);
Canvas.DrawText(PaintX, PaintY, PaintWidth, Height, TheText);
//Canvas.DrawText(0, 0 , AvailSize, Height, TheText);
end;
procedure TXfpgWMTitleBar.HandleLMouseDown ( x, y: integer;
shiftstate: TShiftState ) ;
begin
inherited HandleLMouseDown ( x, y, shiftstate ) ;
if Assigned(FOnStartDrag) then
FOnStartDrag(Self, mbLeft, shiftstate, Point(x,y));
end;
procedure TXfpgWMTitleBar.HandleLMouseUp ( x, y: integer;
shiftstate: TShiftState ) ;
begin
inherited HandleLMouseUp ( x, y, shiftstate ) ;
if Assigned(FOnEndDrag) then
FOnEndDrag(Self, mbLeft, shiftstate, Point(x,y));
end;
procedure TXfpgWMTitleBar.HandleMouseMove ( x, y: integer; btnstate: word;
shiftstate: TShiftState ) ;
begin
inherited HandleMouseMove ( x, y, btnstate, shiftstate ) ;
if Assigned(OnMouseMove) then
OnMouseMove(Self, shiftstate, Point(x,y));
end;
function TXfpgWMTitleBar.GetTitle: String;
begin
//Result := FTitleLabel.Text;
Result := FTitleText;
end;
procedure TXfpgWMTitleBar.Resized ( Sender: TObject ) ;
begin
FMenuButton.Left := 0;
FMenuButton.Height := Height;
//FTitleLabel.Left := FMenuButton.Left+FMenuButton.Width;
FCloseButton.Left := Width - FCloseButton.Width;
FMaximizeRestoreButton.Left := FCloseButton.Left- FMaximizeRestoreButton.Width;
FMinimizeButton.Left := FMaximizeRestoreButton.Left - FMinimizeButton.Width;
FCloseButton.UpdateWindowPosition;
FMaximizeRestoreButton.UpdateWindowPosition;
FMinimizeButton.UpdateWindowPosition;
FMenuButton.UpdateWindowPosition;
end;
function TXfpgWMTitleBar.GetOnCloseButtonClick: TNotifyEvent;
begin
Result := FCloseButton.OnClick;
end;
function TXfpgWMTitleBar.GetOnMaxRestoreButtonClick: TNotifyEvent;
begin
Result := FMaximizeRestoreButton.OnClick;
end;
function TXfpgWMTitleBar.GetOnMinimizeButtonClick: TNotifyEvent;
begin
Result := FMinimizeButton.OnClick;
end;
procedure TXfpgWMTitleBar.SetOnCloseButtonClick ( const AValue: TNotifyEvent ) ;
begin
FCloseButton.OnClick := AValue
end;
procedure TXfpgWMTitleBar.SetOnMaxRestoreButtonClick ( const AValue: TNotifyEvent ) ;
begin
FMaximizeRestoreButton.OnClick := AValue
end;
procedure TXfpgWMTitleBar.SetOnMinimizeButtonClick ( const AValue: TNotifyEvent ) ;
begin
FMinimizeButton.OnClick := AValue
end;
procedure TXfpgWMTitleBar.SetTitle ( const AValue: String ) ;
begin
if AValue = FTitleText then exit;
{if AValue <> '' then
FTitleLabel.Text := AValue
else
FTitleLabel.Text := 'Untitled';}
if AValue <> '' then
FTitleText := AValue
else
FTitleText := 'Untitled';
Invalidate;
end;
constructor TXfpgWMTitleBar.Create ( AOwner: TComponent ) ;
begin
FCreating := True;
inherited Create ( AOwner ) ;
BackgroundColor := clBlue;
Self.OnResize := @Resized;
MouseCursor := mcArrow;
FMenuButton := TfpgButton.Create(Self);
with FMenuButton do begin
Text := 'M';
Embedded := True;
Width := Height;
Left := 0;
Top := 0;
Visible := True;
MouseCursor := mcArrow;
end;
{FTitleLabel := TfpgLabel.Create(Self);
with FTitleLabel do begin
Parent := Self;
Text := 'Untitled';
TextColor := clWhite;
Left := FMenuButton.Left+ FMenuButton.Width;
Top := 0;
AutoSize := True;
Visible := True;
end;}
Height := FMenuButton.Height;
FCloseButton := TfpgButton.Create(Self);
with FCloseButton do begin
Parent := Self;
Text := 'X';
Embedded := True;
Width := Height;
Left := Self.Width-Width;
Top := 0;
Visible := True;
MouseCursor := mcArrow;
end;
FMaximizeRestoreButton := TfpgButton.Create(Self);
with FMaximizeRestoreButton do begin
Parent := Self;
Text := '+';
Embedded := True;
Width := Height;
Left := FCloseButton.Left-Width;
Top := 0;
Visible := True;
MouseCursor := mcArrow;
end;
FMinimizeButton:= TfpgButton.Create(Self);
with FMinimizeButton do begin
Parent := Self;
Text := '_';
Embedded := True;
Width := Height;
Left := FMaximizeRestoreButton.Left-Width;
Top := 0;
Visible := True;
MouseCursor := mcArrow;
end;
FCreating := False;
end;
destructor TXfpgWMTitleBar.Destroy;
begin
inherited Destroy;
end;
{ TfpgClientWindow }
constructor TfpgClientWindow.Create ( AOwner: TComponent; AWinHandle: TfpgWinHandle ) ;
begin
inherited Create(AOwner);
FWinHandle := AWinHandle;
end;
{procedure TfpgClientWindow.DoAllocateWindowHandle ( AParent: TfpgWindowBase ) ;
begin
inherited DoAllocateWindowHandle ( AParent ) ;
end;}
end.
|
unit TestIndentation;
{ AFS Jan 2003
Test the indentation process }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestIndentation, released January 2004.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2004 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess;
type
TTestIndentation = class(TBaseTestProcess)
private
fbSaveIndentBeginEnd: boolean;
fiSaveIndentSpaces, fiSaveIndentBeginEndSpaces: integer;
fbSaveHasFirstLevelIndent: boolean;
fiSaveFirstLevelIndent: integer;
fbSaveIndentElse: boolean;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestIndent1Space;
procedure TestIndent2Spaces;
procedure TestIndent3Spaces;
procedure TestFirstLevelIndent1;
procedure TestFirstLevelIndent2;
procedure TestFirstLevelIndent3;
procedure TestIndenterBeginEnd1;
procedure TestIndenterBeginEnd2;
procedure TestIndenterBeginEnd3;
procedure TestIndenterTryFinallyEnd1;
procedure TestIndenterTryFinallyEnd2;
procedure TestIndenterTryFinallyEnd3;
procedure TestIndenterTryExceptEnd1;
procedure TestIndenterTryExceptEnd2;
procedure TestIndenterTryExceptEnd3;
procedure TestTwoLevel1;
procedure TestTwoLevel2;
procedure TestTwoLevel3;
end;
implementation
uses
JcfStringUtils,
JcfSettings,
Indenter, SetIndent;
procedure TTestIndentation.Setup;
begin
inherited;
// save settings
fbSaveIndentBeginEnd := JcfFormatSettings.Indent.IndentBeginEnd;
fiSaveIndentSpaces := JcfFormatSettings.Indent.IndentSpaces;
fiSaveIndentBeginEndSpaces := JcfFormatSettings.Indent.IndentBeginEndSpaces;
fbSaveHasFirstLevelIndent := JcfFormatSettings.Indent.HasFirstLevelIndent;
fiSaveFirstLevelIndent := JcfFormatSettings.Indent.FirstLevelIndent;
fbSaveIndentElse := JcfFormatSettings.Indent.IndentElse;
end;
procedure TTestIndentation.Teardown;
begin
inherited;
// restore the settings
JcfFormatSettings.Indent.IndentBeginEnd := fbSaveIndentBeginEnd;
JcfFormatSettings.Indent.IndentSpaces := fiSaveIndentSpaces;
JcfFormatSettings.Indent.IndentBeginEndSpaces := fiSaveIndentBeginEndSpaces;
JcfFormatSettings.Indent.HasFirstLevelIndent := fbSaveHasFirstLevelIndent;
JcfFormatSettings.Indent.FirstLevelIndent := fiSaveFirstLevelIndent;
JcfFormatSettings.Indent.IndentElse := fbSaveIndentElse;
end;
const
BASIC_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
'begin' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
BASIC_TRY_FINALLY_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
'try' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'finally' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
BASIC_TRY_EXCEPT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
'try' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'except' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
BASIC_TWO_LEVEL_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
'begin' + NativeLineBreak +
'try' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'except' + NativeLineBreak +
'result := 2 + 2;' + NativeLineBreak +
'end' + NativeLineBreak +
'end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
{ the various out unit texts differ only in how much white space there is
before the lines of code in procedure foo. }
procedure TTestIndentation.TestIndent1Space;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 1;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndent2Spaces;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndent3Spaces;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 3;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestFirstLevelIndent1;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := True;
JcfFormatSettings.Indent.FirstLevelIndent := 1;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestFirstLevelIndent2;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := True;
JcfFormatSettings.Indent.FirstLevelIndent := 2;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestFirstLevelIndent3;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := False;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := True;
JcfFormatSettings.Indent.FirstLevelIndent := 3;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterBeginEnd1;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 1;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterBeginEnd2;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterBeginEnd3;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 3;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryExceptEnd1;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 1;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_EXCEPT_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryExceptEnd2;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_EXCEPT_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryExceptEnd3;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 3;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_EXCEPT_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryFinallyEnd1;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' finally' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 1;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_FINALLY_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryFinallyEnd2;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' finally' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_FINALLY_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestIndenterTryFinallyEnd3;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' finally' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 3;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TRY_FINALLY_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestTwoLevel1;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 1;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TWO_LEVEL_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestTwoLevel2;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 2;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TWO_LEVEL_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestIndentation.TestTwoLevel3;
const
OUT_UNIT_TEXT = UNIT_HEADER +
'function foo: integer;' + NativeLineBreak +
'begin' + NativeLineBreak +
' begin' + NativeLineBreak +
' try' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' except' + NativeLineBreak +
' result := 2 + 2;' + NativeLineBreak +
' end' + NativeLineBreak +
' end' + NativeLineBreak +
'end;' + UNIT_FOOTER;
begin
JcfFormatSettings.Indent.IndentBeginEnd := True;
JcfFormatSettings.Indent.IndentSpaces := 2;
JcfFormatSettings.Indent.IndentBeginEndSpaces := 3;
JcfFormatSettings.Indent.HasFirstLevelIndent := False;
TestProcessResult(TIndenter, BASIC_TWO_LEVEL_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestIndentation.Suite);
end.
|
unit DialogMultipartFormSelection;
(*
DialogMultipartFormSelection.pas/dfm
-------------------------------------
Begin: 2005/08/15
Last revision: $Date: 2008-12-10 21:03:31 $ $Author: areeves $
Version number: $Revision: 1.9 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2008 Animal Population Health Institute, Colorado State University
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*)
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
Contnrs,
//cArrays,
//cDictionaries,
QStringMaps,
FrameFileSelector
;
type TDlgMultipartAction = (
MULTIPARTNONE,
MULTIPARTSAVE,
MULTIPARTCOPY,
MULTIPARTPRINT
);
type TDialogMultipartFormSelection = class( TForm )
fraFileSelector: TFrameFileSelector;
pnlPartsList: TPanel;
gbxItems: TGroupBox;
pnlButtons: TPanel;
btnCancel: TButton;
btnOK: TButton;
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
protected
_checkboxes: TObjectList;
_accepted: boolean;
procedure translateUI();
function getFileName(): string;
public
constructor create(
AOwner: TComponent;
//objDict: TObjectDictionary;
objDict: TQStringObjectMap;
activity: TDlgMultipartAction;
filter: string = ''
); reintroduce;
destructor destroy(); override;
function execute(): boolean;
function createSelectedIndexArray(): TIntegerArray;
property fileName: string read getFileName;
end
;
implementation
{$R *.dfm}
uses
myStrUtils,
MyDialogs,
I88n
;
constructor TDialogMultipartFormSelection.create(
AOwner: TComponent;
//objDict: TObjectDictionary;
objDict: TQStringObjectMap;
activity: TDlgMultipartAction;
filter: string = ''
);
var
i: integer;
cbx: TCheckBox;
begin
inherited create( AOwner );
translateUI();
// Deal with form scaling
//-----------------------
Assert(not Scaled, 'You should set Scaled property of Form to False!');
// Set this value to the PPI AT WHICH THE FORM WAS ORIGINALLY DESIGNED!!
self.PixelsPerInch := 96;
// FormCreate() will handle the rest.
case activity of
MULTIPARTSAVE:
begin
gbxItems.Caption := tr( 'Items to save:' ) + ' ';
fraFileSelector.Visible := true;
end
;
MULTIPARTCOPY:
begin
gbxItems.Caption := tr( 'Items to copy:' ) + ' ';
fraFileSelector.Visible := false;
end
;
else
begin
raise exception.Create( 'Unsupported action in TDialogMultipartFormSelection.create()' );
end
;
end;
fraFileSelector.filter := filter;
_checkboxes := TObjectList.create( false );
for i := 0 to objDict.count - 1 do
begin
cbx := TCheckBox.Create( gbxItems );
cbx.Caption := objDict.GetKeyByIndex( i );
cbx.Parent := gbxItems;
cbx.Height := 25;
cbx.Left := 25;
cbx.Top := 20 + ( ( 10 + cbx.Height ) * i );
cbx.Checked := true;
cbx.Show();
_checkboxes.Add( cbx );
end
;
end
;
procedure TDialogMultipartFormSelection.translateUI();
begin
// This function was generated automatically by Caption Collector 0.6.0.
// Generation date: Mon Feb 25 15:29:38 2008
// File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/DialogMultipartFormSelection.dfm
// File date: Tue Oct 10 08:22:48 2006
// Set Caption, Hint, Text, and Filter properties
with self do
begin
Caption := tr( 'Form1' );
gbxItems.Caption := tr( 'Items to _____:' );
btnCancel.Caption := tr( 'Cancel' );
btnOK.Caption := tr( 'OK' );
end
;
end
;
procedure TDialogMultipartFormSelection.FormCreate(Sender: TObject);
begin
if Screen.PixelsPerInch <> PixelsPerInch then
ScaleBy( Screen.PixelsPerInch, PixelsPerInch )
;
end
;
destructor TDialogMultipartFormSelection.destroy();
begin
_checkboxes.free();
inherited destroy();
end
;
function TDialogMultipartFormSelection.createSelectedIndexArray(): TIntegerArray;
var
i: integer;
arr: TIntegerArray;
cbx: TCheckbox;
begin
arr := TIntegerArray.Create();
for i := 0 to _checkboxes.Count - 1 do
begin
cbx := _checkboxes.items[i] as TCheckbox;
if( cbx.Checked ) then
arr.AppendItem(i)
;
end
;
result := arr;
end
;
function TDialogMultipartFormSelection.execute(): boolean;
begin
self.ShowModal();
// The user will do stuff for a while here.
// When showModal() eventually returns...
result := _accepted;
end
;
procedure TDialogMultipartFormSelection.btnOKClick(Sender: TObject);
begin
if( fraFileSelector.Visible and ( '' = fileName ) ) then
begin
msgOK( tr( 'Please enter a file name.' ), tr( 'Missing file name' ), IMGWarning, self );
fraFileSelector.SetFocus();
end
else
begin
_accepted := true;
close();
end
;
end
;
procedure TDialogMultipartFormSelection.btnCancelClick(Sender: TObject);
begin
_accepted := false;
close();
end
;
function TDialogMultipartFormSelection.getFileName(): string;
begin
result := fraFileSelector.fileName;
end
;
end.
|
unit fFindingTemplates;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, DateUtils;
type
TfrmFindingTemplates = class(TForm)
animSearch: TAnimate;
lblFind: TLabel;
Label2: TLabel;
btnCancel: TButton;
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
FCanceled: boolean;
FSearchString: string;
FStarted: boolean;
FTree: TTreeView;
FStartNode: TTreeNode;
FCurrentNode :TTreeNode;
FIgnoreCase: boolean;
FWholeWords: boolean;
FFoundNode: TTreeNode;
FIsNext: boolean;
{ Private declarations }
procedure Find;
public
end;
function FindTemplate(SearchString: string; Tree: TTreeView; OwningForm: TForm;
StartNode: TTreeNode; IsNext, IgnoreCase, WholeWords: boolean): TTreeNode;
implementation
uses uTemplates, VAUtils, ORNet;
{$R *.dfm}
const
// search for 1 second before showing dialog - note some loading may have already
// taken place before this call.
DELAY_TIME = 1000;
MESSAGE_TIME = 0;
function FindTemplate(SearchString: string; Tree: TTreeView; OwningForm: TForm;
StartNode: TTreeNode; IsNext, IgnoreCase, WholeWords: boolean): TTreeNode;
var
frmFindingTemplates: TfrmFindingTemplates;
msg: string;
begin
Result := nil;
if (SearchString = '') or (not assigned(Tree)) then exit;
frmFindingTemplates := TfrmFindingTemplates.Create(OwningForm);
try
with frmFindingTemplates do
begin
FSearchString := SearchString;
FTree := Tree;
FStartNode := StartNode;
FIgnoreCase := IgnoreCase;
FWholeWords := WholeWords;
FIsNext := IsNext;
if IsNext then
lblFind.Caption := 'Finding Next Template';
Find;
if assigned(FFoundNode) then
begin
Result := FFoundNode;
end
else
begin
if FCanceled then
msg := 'Find Canceled.'
else
msg := 'Text not Found.';
ShowMsg('Search Completed. ' + msg,'Find Template Failed', smiError);
end;
end;
finally
frmFindingTemplates.Free;
end;
end;
procedure TfrmFindingTemplates.btnCancelClick(Sender: TObject);
begin
FCanceled := True;
btnCancel.Enabled := False;
end;
procedure TfrmFindingTemplates.Find;
var
Found : boolean;
Text: String;
WindowList: Pointer;
NeedToShow: boolean;
StartTime: TDateTime;
begin
WindowList := nil;
NeedToShow := True;
StartTime := Now;
try
if(FIgnoreCase) then
FSearchString := UpperCase(FSearchString);
FCurrentNode := FStartNode;
Found := False;
if FIsNext and assigned(FCurrentNode) then
begin
FCurrentNode.Expand(False);
FCurrentNode := FCurrentNode.GetNext;
end;
while (not FCanceled) and (assigned(FCurrentNode) and (not Found)) do
begin
Application.ProcessMessages;
if not FCanceled then
begin
Text := FCurrentNode.Text;
if(FIgnoreCase) then
Text := UpperCase(Text);
Found := SearchMatch(FSearchString, Text, FWholeWords);
if(not Found) then
begin
FCurrentNode.Expand(False);
FCurrentNode := FCurrentNode.GetNext;
end;
if (not Found) and assigned(FCurrentNode) and NeedToShow then
begin
if MilliSecondsBetween(Now, StartTime) > DELAY_TIME then
begin
WindowList := DisableTaskWindows(0);
AppStartedCursorForm := Self;
Show;
NeedToShow := False;
end;
end;
end;
end;
if Found then
FFoundNode := FCurrentNode;
finally
if not NeedToShow then
begin
AppStartedCursorForm := nil;
EnableTaskWindows(WindowList);
Hide;
end;
end;
end;
procedure TfrmFindingTemplates.FormShow(Sender: TObject);
begin
if not FStarted then
begin
FStarted := True;
animSearch.Active := True;
end;
end;
end.
|
unit MainFormGameUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.Imaging.pngimage,ShellApi;
type
TArrayOfUserImages = array [0 .. 6] of TImage;
TArrayOfColorImages = array [0 .. 3] of TImage;
TMainFormGame = class(TForm)
MainMenu1: TMainMenu;
Menu: TMenuItem;
SkipUserCardsImage: TImage;
BankDeckImage: TImage;
CardImage0: TImage;
CardImage1: TImage;
CardImage2: TImage;
CardImage3: TImage;
CardImage4: TImage;
CardImage5: TImage;
CardImage6: TImage;
DropDeckImage: TImage;
NumberOfPageLabel: TLabel;
HelperMemo: TMemo;
HelperBtn: TButton;
UserTimer: TTimer;
DeckOfBotImage: TImage;
Choose1Image: TImage;
Choose2Image: TImage;
Choose3Image: TImage;
Choose4Image: TImage;
TimerLabel: TLabel;
BankLabel: TLabel;
BotLabel: TLabel;
UserCardsLabel: TLabel;
Pause: TMenuItem;
Help: TMenuItem;
BotTimer: TTimer;
CountDownTimer: TTimer;
SkipButton: TButton;
procedure FormCreate(Sender: TObject);
procedure BankDeckImageClick(Sender: TObject);
procedure CardImagesClick(Sender: TObject);
procedure SkipUserCardsImageClick(Sender: TObject);
procedure CardImage0MouseEnter(Sender: TObject);
procedure CardImage0MouseLeave(Sender: TObject);
procedure HelperBtnClick(Sender: TObject);
procedure UserTimerTimer(Sender: TObject);
procedure ExitToMenuClick(Sender: TObject);
procedure BotTimerTimer(Sender: TObject);
procedure CountDownTimerTimer(Sender: TObject);
procedure ChooseColorImageClick(Sender: TObject);
procedure PauseClick(Sender: TObject);
procedure HelperMemoEnter(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure HelpClick(Sender: TObject);
procedure SkipButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure EnableObjects(Bool: boolean);
procedure VisibleUserCardsImages(Bool: boolean);
var
MainFormGame: TMainFormGame;
ArrayOfUserImages: TArrayOfUserImages;
ArrayOfColorImages: TArrayOfColorImages;
UserTime: byte;
NumberOfStep: byte;
TimeCountDown: byte;
implementation
{$R *.dfm}
uses
UnitOfGLobalFunctionsWithCards, UnitOfBot, RegistrationUnit,
MainMenuUnit, AcceptToExitUnit, PauseFormUnit, WinFormUnit;
procedure EnableObjects(Bool: boolean);
var
i: byte;
begin
for i := 0 to 6 do
if ArrayOfUserImages[i].Picture <> nil then
ArrayOfUserImages[i].Enabled := Bool
else
ArrayOfUserImages[i].Enabled := False;
MainFormGame.BankDeckImage.Enabled := Bool;
end;
procedure VisibleUserCardsImages(Bool: boolean);
var
i: byte;
begin
for i := 0 to 6 do
begin
ArrayOfUserImages[i].Visible := Bool;
end;
end;
procedure TMainFormGame.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ExitToMenuClick(Self);
end;
procedure TMainFormGame.FormCreate(Sender: TObject);
begin
LoadingDeckOfBankAndHelper;
MixDeckOfBank;
CountListCardOfUser := 1;
ActiveList := 1;
ArrayOfUserImages[0] := CardImage0;
ArrayOfUserImages[1] := CardImage1;
ArrayOfUserImages[2] := CardImage2;
ArrayOfUserImages[3] := CardImage3;
ArrayOfUserImages[4] := CardImage4;
ArrayOfUserImages[5] := CardImage5;
ArrayOfUserImages[6] := CardImage6;
ArrayOfColorImages[0] := Choose1Image;
ArrayOfColorImages[1] := Choose2Image;
ArrayOfColorImages[2] := Choose3Image;
ArrayOfColorImages[3] := Choose4Image;
TimeCountDown := 3;
NumberOfStep := 0;
HelperMemo.Lines.Add(ArrayOfStringsForHelper[0]);
end;
procedure TMainFormGame.SkipButtonClick(Sender: TObject);
var
i: byte;
begin
NumberOfStep := Length(ArrayOfStringsForHelper) - 1;
BankDeckImage.Visible := True;
BankLabel.Visible := True;
GiveOutCards;
for i := 0 to 6 do
begin
ArrayOfUserImages[i].Enabled := False;
ArrayOfUserImages[i].Visible := True;
end;
UserCardsLabel.Visible := True;
SkipUserCardsImage.Visible := True;
NumberOfPageLabel.Visible := True;
for i := 0 to 6 do
begin
DeckOfBot[i] := DeckOfBank[Length(DeckOfBank) - 1];
SetLength(DeckOfBank, Length(DeckOfBank) - 1);
end;
DeckOfBotImage.Visible := True;
BotLabel.Visible := True;
CardOfDrop := DeckOfBank[Length(DeckOfBank) - 1];
DeckOfDrop[Length(DeckOfDrop) - 1] := DeckOfBank[Length(DeckOfBank) - 1];
SetLength(DeckOfBank, Length(DeckOfBank) - 1);
VisualInitializationOfTable;
DropDeckImage.Visible := True;
EnableObjects(False);
HelperMemo.Lines.Add('Краткое описание пропущено. Начать игру?');
HelperBtn.Caption := 'Начать игру';
HelperBtn.Width := 409;
SkipButton.Visible := False;
SkipButton.Enabled := False;
end;
procedure TMainFormGame.SkipUserCardsImageClick(Sender: TObject);
begin
if ActiveList < CountListCardOfUser then
inc(ActiveList)
else
ActiveList := 1;
VisualInitializationOfTable;
end;
procedure TMainFormGame.UserTimerTimer(Sender: TObject);
begin
dec(UserTime);
case UserTime of
0:
begin
TimerLabel.Caption := 'Ваш ход(' + IntToStr(UserTime) + ' сек)';
HelperMemo.Lines.Add('Ваше время истекло!');
UserTime := 15;
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
UserTimer.Enabled := False;
BankDeckImageClick(Self);
end;
14:
begin
VisualInitializationOfTable;
TimerLabel.Caption := 'Ваш ход(' + IntToStr(UserTime) + ' сек)';
end;
else
TimerLabel.Caption := 'Ваш ход(' + IntToStr(UserTime) + ' сек)';
end;
end;
procedure TMainFormGame.BotTimerTimer(Sender: TObject);
var
NumberOfColor: byte;
begin
EnableObjects(False);
CompareBotCardsWithDrop;
if Length(DeckToDropOfBot) > 0 then
begin
DeleteCardOfBotAndRefrechDrop;
if Length(DeckOfBot) = 0 then
begin
MainFormGame.BotTimer.Enabled := False;
WinForm.ShowModal;
exit;
end;
end
else
begin
MainFormGame.HelperMemo.Lines.Add('Бот берет карту и пропускает ход');
AddCardToDeckOfPlayer(DeckOfBot, 1);
VisualInitializationOfTable;
TimerLabel.Caption := 'Ваш ход(15 сек)';
UserTime := 15;
BotTimer.Enabled := False;
VisualInitializationOfTable;
BankDeckImage.Enabled := True;
UserTimer.Enabled := True;
exit;
end;
case StrToInt(Copy(CardOfDrop, 3, 1)) of
1:
begin
HelperMemo.Lines.Add('Вы пропускаете ход');
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
exit;
end;
3:
begin
HelperMemo.Lines.Add('Вы берете 2 карты и пропускаете ход');
AddCardToDeckOfPlayer(DeckOfUser, 2);
VisualInitializationOfTable;
EnableObjects(False);
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
exit;
end;
4:
begin
NumberOfColor := Random(3) + 1;
case NumberOfColor of
1:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал красный цвет');
2:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал желтый цвет');
3:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал зеленый цвет');
4:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал синий цвет');
end;
delete(CardOfDrop, 1, 1);
insert(IntToStr(NumberOfColor), CardOfDrop, 1);
exit;
end;
5:
begin
HelperMemo.Lines.Add('Вы берете 4 карты и пропускаете ход');
NumberOfColor := Random(3) + 1;
case NumberOfColor of
1:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал красный цвет');
2:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал желтый цвет');
3:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал зеленый цвет');
4:
MainFormGame.HelperMemo.Lines.Add('Бот выбрал синий цвет');
end;
delete(CardOfDrop, 1, 1);
insert(IntToStr(NumberOfColor), CardOfDrop, 1);
AddCardToDeckOfPlayer(DeckOfUser, 4);
VisualInitializationOfTable;
EnableObjects(False);
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
exit;
end;
end;
TimerLabel.Caption := 'Ваш ход(15 сек)';
UserTime := 15;
BankDeckImage.Enabled := True;
VisualInitializationOfTable;
UserTimer.Enabled := True;
BotTimer.Enabled := False;
end;
procedure TMainFormGame.BankDeckImageClick(Sender: TObject);
begin
AddCardToDeckOfPlayer(DeckOfUser, 1);
VisualInitializationOfTable;
HelperMemo.Lines.Add('Вы пропускаете ход');
TimerLabel.Caption := 'Ход Бота';
EnableObjects(False);
BotTimer.Enabled := True;
UserTimer.Enabled := False;
end;
procedure TMainFormGame.HelpClick(Sender: TObject);
begin
WinExec('hh HelpUNO.chm', SW_ShowNormal);
//ShellExecute(Application.Handle,'open','HelpUNO.chm',nil,nil,0);
//Application.HelpCommand(15, 0);
VisibleUserCardsImages(False);
if UserTimer.Enabled then
UserTimer.Enabled := False
else
BotTimer.Enabled := False;
PauseForm.ShowModal;
end;
procedure TMainFormGame.HelperBtnClick(Sender: TObject);
var
i: byte;
str: string;
begin
if HelperBtn.Caption = 'Очистить' then
begin
if not(CountDownTimer.Enabled) then
begin
str := HelperMemo.Lines[HelperMemo.Lines.Count - 1];
HelperMemo.Clear;
HelperMemo.Lines.Add('*-Последнее совершенное действие-*');
HelperMemo.Lines.Add(str);
end;
exit;
end;
inc(NumberOfStep);
if NumberOfStep = Length(ArrayOfStringsForHelper) then
begin
HelperMemo.Lines.Add('Игра начнется через...');
HelperBtn.Width := 189;
HelperBtn.Left := 8;
HelperBtn.Caption := 'Очистить';
UserTime := 15;
MainMenu1.Items[0].Enabled := False;
MainMenu1.Items[1].Enabled := False;
MainMenu1.Items[2].Enabled := False;
CountDownTimer.Enabled := True;
SkipUserCardsImage.Enabled := True;
exit;
end;
case NumberOfStep of
1:
begin
HelperBtn.Width := 193;
SkipButton.Visible := True;
// 409
end;
2:
begin
HelperBtn.Width := 409;
SkipButton.Visible := False;
SkipButton.Enabled := False;
BankDeckImage.Visible := True;
BankLabel.Visible := True;
end;
3:
begin
GiveOutCards;
VisualInitializationOfTable;
for i := 0 to 6 do
begin
ArrayOfUserImages[i].Enabled := False;
ArrayOfUserImages[i].Visible := True;
end;
UserCardsLabel.Visible := True;
end;
4:
begin
SkipUserCardsImage.Visible := True;
NumberOfPageLabel.Visible := True;
end;
5:
begin
for i := 0 to 6 do
begin
DeckOfBot[i] := DeckOfBank[Length(DeckOfBank) - 1];
SetLength(DeckOfBank, Length(DeckOfBank) - 1);
end;
// VisualInitializationOfTable;
DeckOfBotImage.Visible := True;
BotLabel.Visible := True;
end;
6:
begin
CardOfDrop := DeckOfBank[Length(DeckOfBank) - 1];
DeckOfDrop[Length(DeckOfDrop) - 1] :=
DeckOfBank[Length(DeckOfBank) - 1];
SetLength(DeckOfBank, Length(DeckOfBank) - 1);
VisualInitializationOfTable;
DropDeckImage.Visible := True;
EnableObjects(False);
end;
7:
begin
HelperBtn.Caption := 'Начать игру';
end;
end;
HelperMemo.Lines.Add(ArrayOfStringsForHelper[NumberOfStep]);
end;
procedure TMainFormGame.HelperMemoEnter(Sender: TObject);
begin
ActiveControl := HelperBtn;
end;
procedure TMainFormGame.PauseClick(Sender: TObject);
begin
VisibleUserCardsImages(False);
if UserTimer.Enabled then
UserTimer.Enabled := False
else
BotTimer.Enabled := False;
PauseForm.ShowModal;
end;
procedure TMainFormGame.ExitToMenuClick(Sender: TObject);
begin
VisibleUserCardsImages(False);
if UserTimer.Enabled then
UserTimer.Enabled := False
else
BotTimer.Enabled := False;
AcceptToExitForm.ShowModal;
end;
procedure TMainFormGame.CardImage0MouseEnter(Sender: TObject);
begin
(Sender as TImage).Top := 586;
end;
procedure TMainFormGame.CardImage0MouseLeave(Sender: TObject);
begin
(Sender as TImage).Top := 616;
end;
procedure TMainFormGame.CardImagesClick(Sender: TObject);
var
i: byte;
begin
for i := 0 to 6 do
if (Sender as TImage) = ArrayOfUserImages[i] then
begin
if CanPutCardOfPlayerInDrop(DeckOfUser[i + 7 * (ActiveList - 1)]) then
begin
DeleteCardOfUserAndRefrechDrop(i);
if Length(DeckOfUser) = 0 then
begin
UserTimer.Enabled := False;
HelperMemo.Lines.Add('Вы положили [' + DecoderCard(CardOfDrop) + ']');
VisualInitializationOfTable;
WinForm.ShowModal;
exit;
end;
UserTimer.Enabled := False;
UserTime := 15;
break;
end
else
exit;
end;
HelperMemo.Lines.Add('Вы положили [' + DecoderCard(CardOfDrop) + ']');
VisualInitializationOfTable;
if (StrToInt(Copy(CardOfDrop, 3, 1)) = 4) then
begin
TimerLabel.Caption := 'Ваш ход( ∞ сек)';
HelperMemo.Lines.Add('Выберете цвет для следующего хода');
for i := 0 to 3 do
begin
ArrayOfColorImages[i].Visible := True;
ArrayOfColorImages[i].Enabled := True;
end;
EnableObjects(False);
exit;
end;
if (StrToInt(Copy(CardOfDrop, 3, 1)) = 5) then
begin
TimerLabel.Caption := 'Ваш ход( ∞ сек)';
HelperMemo.Lines.Add('Выберете цвет для следующего хода');
for i := 0 to 3 do
begin
ArrayOfColorImages[i].Visible := True;
ArrayOfColorImages[i].Enabled := True;
end;
EnableObjects(False);
exit;
end;
if (StrToInt(Copy(CardOfDrop, 3, 1)) = 3) then
begin
UserTime := 15;
TimerLabel.Caption := 'Ваш ход(15 сек)';
HelperMemo.Lines.Add('Бот берет 2 карты и пропускает ход');
AddCardToDeckOfPlayer(DeckOfBot, 2);
VisualInitializationOfTable;
UserTimer.Enabled := True;
exit;
end;
if (StrToInt(Copy(CardOfDrop, 3, 1)) = 1) then
begin
UserTime := 15;
TimerLabel.Caption := 'Ваш ход(15 сек)';
HelperMemo.Lines.Add('Бот пропускает свой ход');
UserTimer.Enabled := True;
exit;
end;
EnableObjects(False);
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
end;
procedure TMainFormGame.ChooseColorImageClick(Sender: TObject);
var
i: Integer;
begin
delete(CardOfDrop, 1, 1);
insert(Copy((Sender as TImage).Name, 7, 1), CardOfDrop, 1);
case StrToInt(Copy((Sender as TImage).Name, 7, 1)) of
1:
HelperMemo.Lines.Add('Вы выбрали красный цвет');
2:
HelperMemo.Lines.Add('Вы выбрали желтый цвет');
3:
HelperMemo.Lines.Add('Вы выбрали зеленый цвет');
4:
HelperMemo.Lines.Add('Вы выбрали синий цвет');
end;
for i := 0 to 3 do
begin
ArrayOfColorImages[i].Enabled := False;
ArrayOfColorImages[i].Visible := False;
end;
if StrToInt(Copy(CardOfDrop, 3, 1)) = 4 then
begin
TimerLabel.Caption := 'Ход Бота';
BotTimer.Enabled := True;
UserTimer.Enabled := False;
end
else
begin
HelperMemo.Lines.Add('Бот берет 4 карты и пропускает ход');
AddCardToDeckOfPlayer(DeckOfBot, 4);
UserTime := 15;
TimerLabel.Caption := 'Ваш ход(15 сек)';
UserTimer.Enabled := True;
end;
EnableObjects(True);
VisualInitializationOfTable;
end;
procedure TMainFormGame.CountDownTimerTimer(Sender: TObject);
begin
if TimeCountDown = 0 then
begin
HelperMemo.Clear;
HelperMemo.Lines.Add('Игра началась!');
TimerLabel.Visible := True;
HelperBtn.Enabled := True;
CountDownTimer.Enabled := False;
TimerLabel.Caption := 'Ваш ход(15 сек)';
UserTime := 15;
EnableObjects(True);
UserTimer.Enabled := True;
MainMenu1.Items[0].Enabled := True;
MainMenu1.Items[1].Enabled := True;
MainMenu1.Items[2].Enabled := True;
exit;
end;
HelperMemo.Lines.Add(IntToStr(TimeCountDown));
dec(TimeCountDown);
end;
end.
|
unit UCliente;
interface
uses UPessoa, UCondicaoPagamento;
type Cliente = class(Pessoa)
protected
umaCondicaoPgto : CondicaoPagamento;
TipoPessoa : String[8];
public
verificaNome : Boolean;
verificaTel : Boolean;
constructor CrieObjeto;
destructor destrua_se;
Procedure setUmaCondicaoPgto (vCondicaoPgto : CondicaoPagamento);
Procedure setTipoPessoa (vTipoPessoa : String);
Function getUmaCondicaoPgto : CondicaoPagamento;
Function getTipoPessoa : String;
end;
implementation
{ Cliente }
constructor Cliente.CrieObjeto;
begin
inherited;
TipoPessoa := '';
umaCondicaoPgto := CondicaoPagamento.CrieObjeto;
end;
destructor Cliente.destrua_se;
begin
inherited;
end;
function Cliente.getTipoPessoa: String;
begin
Result := TipoPessoa;
end;
function Cliente.getUmaCondicaoPgto: CondicaoPagamento;
begin
Result := umaCondicaoPgto;
end;
procedure Cliente.setTipoPessoa(vTipoPessoa: String);
begin
TipoPessoa := vTipoPessoa;
end;
procedure Cliente.setUmaCondicaoPgto(vCondicaoPgto: CondicaoPagamento);
begin
umaCondicaoPgto := vCondicaoPgto;
end;
end.
|
unit fODMedOut;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fODBase, ORCtrls, StdCtrls, ORFn, ExtCtrls, uConst, ComCtrls, uCore, Mask,
Menus, Buttons, VA508AccessibilityManager;
type
TfrmODMedOut = class(TfrmODBase)
lblMedication: TLabel;
cboMedication: TORComboBox;
lblDosage: TLabel;
lblRoute: TLabel;
cboRoute: TORComboBox;
lblSchedule: TLabel;
cboSchedule: TORComboBox;
lblDispense: TLabel;
cboDispense: TORComboBox;
memComments: TMemo;
cboPriority: TORComboBox;
Bevel1: TBevel;
cboMedAlt: TORComboBox;
cboInstructions: TORComboBox;
lblQuantity: TLabel;
cboPickup: TORComboBox;
lblPickup: TLabel;
cboSC: TORComboBox;
lblSC: TLabel;
lblRefills: TLabel;
txtQuantity: TCaptionEdit;
lblComment: TLabel;
lblPriority: TLabel;
txtRefills: TCaptionEdit;
spnRefills: TUpDown;
cmdComplex: TButton;
btnUnits: TSpeedButton;
txtSIG: TCaptionEdit;
lblSIG: TLabel;
popUnits: TPopupMenu;
memComplex: TMemo;
procedure cboMedicationNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cboMedicationSelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ControlChange(Sender: TObject);
procedure cboDispenseExit(Sender: TObject);
procedure cboDispenseMouseClick(Sender: TObject);
procedure cboSCEnter(Sender: TObject);
procedure txtQuantityEnter(Sender: TObject);
procedure btnUnitsClick(Sender: TObject);
procedure cmdComplexClick(Sender: TObject);
procedure memCommentsEnter(Sender: TObject);
private
{ Private declarations }
FLastDrug: Integer;
FLastMedID: string;
FDispenseMsg: string;
FMedCombo: TORComboBox;
procedure CheckFormAlt;
procedure ResetOnMedChange;
procedure SetAskSC;
procedure SetAltCombo;
procedure SetInstructions;
procedure SetOnOISelect;
procedure SetMaxRefills;
procedure SetupNouns;
procedure SetComplex;
procedure SetSimple;
procedure UnitClick(Sender: TObject);
protected
procedure InitDialog; override;
procedure Validate(var AnErrMsg: string); override;
public
procedure SetupDialog(OrderAction: Integer; const ID: string); override;
end;
implementation
{$R *.DFM}
uses rOrders, rODBase, fODMedFA, fODMedComplex, System.Types, VAUtils;
const
REFILLS_DFLT = '0';
REFILLS_MAX = 11;
TX_NO_MED = 'Medication must be entered.';
TX_NO_DOSE = 'Instructions must be entered.';
TX_NO_AMPER = 'Instructions may not contain the ampersand (&) character.';
TX_NO_ROUTE = 'Route must be entered.';
TX_NF_ROUTE = 'Route not found in the Medication Routes file.';
TX_NO_SCHED = 'Schedule must be entered.';
TX_NO_PICK = 'A method for picking up the medication must be entered.';
TX_RNG_REFILL = 'The number of refills must be in the range of 0 through ';
TX_SCH_QUOTE = 'Schedule must not have quotemarks in it.';
TX_SCH_MINUS = 'Schedule must not have a dash at the beginning.';
TX_SCH_SPACE = 'Schedule must have only one space in it.';
TX_SCH_LEN = 'Schedule must be less than 70 characters.';
TX_SCH_PRN = 'Schedule cannot include PRN - use Comments to enter PRN.';
TX_SCH_ZERO = 'Schedule cannot be Q0';
TX_SCH_LSP = 'Schedule may not have leading spaces.';
TX_SCH_NS = 'Unable to resolve non-standard schedule.';
TX_OUTPT_IV = 'This patient has not been admitted. Only IV orders may be entered.';
TX_QTY_NV = 'Unable to validate quantity.';
TX_QTY_MAIL = 'Quantity for mailed items must be a whole number.';
{ TfrmODBase common methods }
procedure TfrmODMedOut.FormCreate(Sender: TObject);
const
TC_RESTRICT = 'Ordering Restrictions';
var
Restriction: string;
begin
inherited;
AllowQuickOrder := True;
CheckAuthForMeds(Restriction);
if Length(Restriction) > 0 then
begin
InfoBox(Restriction, TC_RESTRICT, MB_OK);
Close;
Exit;
end;
FillerID := 'PSO'; // does 'on Display' order check **KCM**
StatusText('Loading Dialog Definition');
Responses.Dialog := 'PSO OERR'; // loads formatting info
StatusText('Loading Default Values');
CtrlInits.LoadDefaults(ODForMedOut); // ODForMedOut returns TStrings with defaults
InitDialog;
CtrlInits.SetControl(cboPickup, 'Pickup'); // do only once, so don't do in InitDialog
PreserveControl(cboPickup);
end;
procedure TfrmODMedOut.InitDialog;
begin
inherited;
FLastDrug := 0;
FLastMedID := '';
FDispenseMsg := '';
FMedCombo := cboMedication; // this must be before SetControl(cboMedication)
with CtrlInits do
begin
SetControl(cboMedication, 'ShortList');
cboMedication.InsertSeparator;
//SetControl(cboMedAlt, 'ShortList'); can't do this since it calls InitLongList
SetControl(cboSchedule, 'Schedules');
SetControl(cboPriority, 'Priorities');
//SetControl(cboPickup, 'Pickup');
SetControl(cboSC, 'SCStatus');
end;
SetAskSC;
StatusText('Retrieving List of Medications');
cboMedAlt.Visible := False;
cboMedication.Visible := True;
cboMedication.InitLongList('');
ActiveControl := cboMedication; //SetFocusedControl(FMedCombo);
SetSimple;
StatusText('');
end;
procedure TfrmODMedOut.SetupDialog(OrderAction: Integer; const ID: string);
var
AnInstr: string;
begin
inherited;
if OrderAction in [ORDER_COPY, ORDER_EDIT] then Responses.Remove('START', 1);
if OrderAction in [ORDER_COPY, ORDER_EDIT, ORDER_QUICK] then with Responses do
begin
Changing := True;
SetControl(cboMedication, 'ORDERABLE', 1);
ResetOnMedChange;
SetOnOISelect;
SetAltCombo;
//cboMedicationSelect(Self);
SetControl(cboDispense, 'DRUG', 1);
SetInstructions;
SetControl(txtQuantity, 'QTY', 1);
SetControl(txtRefills, 'REFILLS', 1);
spnRefills.Position := StrToIntDef(txtRefills.Text, 0);
SetControl(cboPickup, 'PICKUP', 1);
SetControl(memComments, 'COMMENT', 1);
SetControl(cboPriority, 'URGENCY', 1);
{ prevent the SIG from being part of the comments on pre-CPRS prescriptions }
if (OrderAction in [ORDER_COPY, ORDER_EDIT]) and (cboInstructions.Text = '') then
begin
AnInstr := TextForOrder(ID); //'SIG: ' + memComments.Text;
OrderMessage(AnInstr);
lblSIG.Visible := True;
txtSIG.Visible := True;
txtSIG.Text := memComments.Text;
memComments.Clear;
end;
{ can't edit the orderable item for a med order that has been released }
if (OrderAction = ORDER_EDIT) and OrderIsReleased(EditOrder)
then FMedCombo.Enabled := False;
Changing := False;
ControlChange(Self);
end;
if OrderAction <> ORDER_EDIT then SetFocusedControl(FMedCombo);
end;
procedure TfrmODMedOut.Validate(var AnErrMsg: string);
var
Sched: Integer;
RouteID, RouteAbbr: string;
procedure SetError(const x: string);
begin
if Length(AnErrMsg) > 0 then AnErrMsg := AnErrMsg + CRLF;
AnErrMsg := AnErrMsg + x;
end;
begin
inherited;
if Length(cboMedAlt.Text) = 0 then SetError(TX_NO_MED);
// if memComplex is Visible, then the dosage fields were validated in fMedComplex
if memComplex.Visible = False then
begin
if Length(cboInstructions.Text) = 0 then SetError(TX_NO_DOSE);
if Pos('&', cboInstructions.Text) > 0 then SetError(TX_NO_AMPER);
if (Length(cboRoute.Text) = 0) and (not MedIsSupply(cboMedAlt.ItemIEN))
then SetError(TX_NO_ROUTE);
if (Length(cboRoute.Text) > 0) and (cboRoute.ItemIndex < 0) then
begin
LookupRoute(cboRoute.Text, RouteID, RouteAbbr);
if RouteID = '0'
then SetError(TX_NF_ROUTE)
else Responses.Update('ROUTE', 1, RouteID, RouteAbbr);
end;
if Length(cboSchedule.Text) = 0 then SetError(TX_NO_SCHED);
end;
if cboPickup.ItemID = '' then SetError(TX_NO_PICK);
if StrToIntDef(txtRefills.Text, 99) > spnRefills.Max
then SetError(TX_RNG_REFILL + IntToStr(spnRefills.Max));
with cboSchedule do if Length(Text) > 0 then
begin
Sched := ValidSchedule(Text);
if Sched = -1 then
begin
if Pos('"', Text) > 0 then SetError(TX_SCH_QUOTE);
if Copy(Text, 1, 1) = '-' then SetError(TX_SCH_MINUS);
if Pos(' ', Copy(Text, Pos(' ', Text) + 1, 999)) > 0 then SetError(TX_SCH_SPACE);
if Length(Text) > 70 then SetError(TX_SCH_LEN);
if (Pos('P RN', Text) > 0) or (Pos('PR N', Text) > 0) then SetError(TX_SCH_PRN);
if Pos('Q0', Text) > 0 then SetError(TX_SCH_ZERO);
if TrimLeft(Text) <> Text then SetError(TX_SCH_LSP);
end;
if Sched = 0 then SetError(TX_SCH_NS);
end;
with txtQuantity do if Length(Text) > 0 then
begin
if not ValidQuantity(Text) then SetError(TX_QTY_NV);
//if (cboPickup.ItemID = 'M') and (IntToStr(StrToIntDef(Text,-1)) <> Text)
// then SetError(TX_QTY_MAIL);
end;
end;
{ cboMedication methods }
procedure TfrmODMedOut.ResetOnMedChange;
begin
ClearControl(cboDispense);
ClearControl(cboInstructions);
btnUnits.Caption := '';
ResetControl(cboRoute);
ResetControl(cboSchedule);
ClearControl(txtQuantity);
txtRefills.Text := REFILLS_DFLT;
spnRefills.Max := REFILLS_MAX;
ClearControl(memComments);
ClearControl(memOrder);
end;
procedure TfrmODMedOut.SetAltCombo;
begin
with cboMedication do
begin
FMedCombo := cboMedAlt;
if cboMedAlt.Items.Count = 0 then CtrlInits.SetListOnly(cboMedAlt, 'ShortList');
cboMedAlt.SetExactByIEN(ItemIEN, TrimRight(Piece(Text, '<', 1)));
cboMedication.Visible := False;
cboMedAlt.Visible := True;
end;
end;
procedure TfrmODMedOut.SetOnOISelect;
begin
with CtrlInits do
begin
FLastMedID := FMedCombo.ItemID;
LoadOrderItem(OIForMedOut(FMedCombo.ItemIEN));
SetControl(cboDispense, 'Dispense');
if cboDispense.Items.Count = 1 then cboDispense.ItemIndex := 0;
lblDosage.Caption := DefaultText('Verb');
if lblDosage.Caption = '' then lblDosage.Caption := 'Amount';
SetControl(cboInstructions, 'Instruct');
SetupNouns;
SetControl(cboRoute, 'Route');
if cboRoute.Items.Count = 1 then cboRoute.ItemIndex := 0;
if DefaultText('DefSched') <> '' then cboSchedule.SelectByID(DefaultText('DefSched'));
OrderMessage(TextOf('Message'));
end;
end;
procedure TfrmODMedOut.cboMedicationNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
{ retrieves a subset of inpatient medication orderable items }
begin
inherited;
FMedCombo.ForDataUse(SubSetOfOrderItems(StartFrom, Direction, 'S.O RX', Responses.QuickOrder));
end;
procedure TfrmODMedOut.cboMedicationSelect(Sender: TObject);
{ sets related controls whenever orderable item changes (MouseClick or Exit) }
begin
inherited;
with FMedCombo do
begin
if ItemID <> FLastMedID then FLastMedID := ItemID else Exit;
Changing := True;
if Sender <> Self then Responses.Clear; // Sender=Self when called from SetupDialog
ResetOnMedChange;
if CharAt(ItemID, 1) = 'Q' then
begin
Responses.QuickOrder := ExtractInteger(ItemID);
Responses.SetControl(FMedCombo, 'ORDERABLE', 1);
end;
if ItemIEN > 0 then SetOnOISelect;
end;
with Responses do if QuickOrder > 0 then
begin
SetControl(FMedCombo, 'ORDERABLE', 1);
SetControl(cboDispense, 'DRUG', 1);
SetInstructions;
SetControl(txtQuantity, 'QTY', 1);
SetControl(txtRefills, 'REFILLS', 1);
spnRefills.Position := StrToIntDef(txtRefills.Text, 0);
SetControl(cboPickup, 'PICKUP', 1);
SetControl(memComments, 'COMMENT', 1);
SetControl(cboPriority, 'URGENCY', 1);
end;
Changing := False;
ControlChange(Self);
if FMedCombo = cboMedication then SetAltCombo;
// if the Dispense drug was stuffed - still do the checks (form alt, refills)
if cboDispense.ItemIndex > -1 then cboDispenseMouseClick(Self);
end;
{ cboDispense methods }
procedure TfrmODMedOut.CheckFormAlt;
var
DrugName, OIName: string;
Drug, OI: Integer;
begin
with cboDispense do if (ItemIndex > -1) and (Piece(Items[ItemIndex], U, 4) = 'NF') then
begin
SelectFormularyAlt(ItemIEN, Drug, OI, DrugName, OIName, PST_OUTPATIENT);
if Drug > 0 then
begin
if FMedCombo.ItemIEN <> OI then
begin
FMedCombo.InitLongList(OIName);
FMedCombo.SelectByIEN(OI);
cboMedicationSelect(Self);
end;
cboDispense.SelectByIEN(Drug);
end; {if FormAlt}
end; {if ItemIndex}
SetAskSC; // now check enabled for the service connected prompt
end;
procedure TfrmODMedOut.SetMaxRefills;
begin
with cboDispense do if (ItemIndex > -1) and (Length(Piece(Items[ItemIndex], U, 6)) > 0) then
begin
spnRefills.Max := StrToIntDef(Piece(Items[ItemIndex], U, 6), REFILLS_MAX);
if StrToIntDef(txtRefills.Text, 0) > spnRefills.Max then
begin
txtRefills.Text := IntToStr(spnRefills.Max);
spnRefills.Position := spnRefills.Max;
end;
end;
end;
procedure TfrmODMedOut.cboDispenseExit(Sender: TObject);
var
AMsg: string;
begin
inherited;
SetMaxRefills;
with cboDispense do
begin
if ItemIEN <> FLastDrug then CheckFormAlt;
if ItemIEN > 0 then
begin
AMsg := DispenseMessage(ItemIEN) + CRLF;
if memMessage.Text <> AMsg then OrderMessage(AMsg);
end;
FLastDrug := ItemIEN;
end;
end;
procedure TfrmODMedOut.cboDispenseMouseClick(Sender: TObject);
begin
inherited;
SetMaxRefills;
with cboDispense do
begin
if ItemIEN <> FLastDrug then CheckFormAlt;
if ItemIEN > 0 then OrderMessage(DispenseMessage(ItemIEN));
FLastDrug := ItemIEN;
end;
end;
{ dosage instructions }
procedure TfrmODMedOut.SetupNouns;
var
AvailWidth, MaxWidth: Integer;
begin
CtrlInits.SetPopupMenu(popUnits, UnitClick, 'Nouns');
if popUnits.Items.Count > 0 then
begin
// Make sure cboInstructions is at least 40 pixels wide so it can show values
// like "1/2". Allow for a 3 pixel space between the the Units button & Route.
AvailWidth := (cboRoute.Left - 3) - (cboInstructions.Left + 40);
MaxWidth := popUnits.Tag + 9; // allow 9 pixels for the down arrow & button border
if MaxWidth > AvailWidth then MaxWidth := AvailWidth;
btnUnits.Width := MaxWidth;
btnUnits.Left := cboRoute.Left - MaxWidth - 3;
cboInstructions.Width := btnUnits.Left - cboInstructions.Left;
btnUnits.Caption := popUnits.Items[0].Caption;
btnUnits.Visible := True;
end else
begin
btnUnits.Visible := False;
// Allow for a 6 pixel margin between the Instructions box & Route
cboInstructions.Width := cboRoute.Left - cboInstructions.Left - 6;
end;
end;
procedure TfrmODMedOut.btnUnitsClick(Sender: TObject);
var
APoint: TPoint;
begin
inherited;
APoint := btnUnits.ClientToScreen(Point(0, btnUnits.Height));
popUnits.Popup(APoint.X, APoint.Y);
end;
procedure TfrmODMedOut.UnitClick(Sender: TObject);
begin
btnUnits.Caption := TMenuItem(Sender).Caption;
end;
procedure TfrmODMedOut.SetComplex;
begin
lblDosage.Visible := False;;
lblRoute.Visible := False;;
lblSchedule.Visible := False;;
cboInstructions.Visible := False;
btnUnits.Visible := False;;
cboRoute.Visible := False;
cboSchedule.Visible := False;
memComplex.Visible := True;
cmdComplex.Caption := 'Change Dose...';
end;
procedure TfrmODMedOut.SetSimple;
begin
memComplex.Visible := False;
lblDosage.Visible := True;;
lblRoute.Visible := True;;
lblSchedule.Visible := True;;
cboInstructions.Visible := True;
btnUnits.Visible := (popUnits.Items.Count > 0) or (btnUnits.Caption <> '');
cboRoute.Visible := True;
cboSchedule.Visible := True;
cmdComplex.Caption := 'Complex Dose...';
end;
procedure TfrmODMedOut.SetInstructions;
var
x: string;
AnInstance: Integer;
begin
case Responses.InstanceCount('INSTR') of
0: begin
cboInstructions.ItemIndex := -1;
// there may still be a route & schedule (for copied orders)
if Responses.EValueFor('MISC', 1) <> ''
then btnUnits.Caption := Responses.EValueFor('MISC', 1);
Responses.SetControl(cboRoute, 'ROUTE', 1);
with cboRoute do if ItemIndex > -1 then Text := DisplayText[ItemIndex];
Responses.SetControl(cboSchedule, 'SCHEDULE', 1);
SetSimple;
end;
1: begin
AnInstance := Responses.NextInstance('INSTR', 0);
Responses.SetControl(cboInstructions, 'INSTR', AnInstance);
btnUnits.Caption := Responses.IValueFor('MISC', AnInstance);
Responses.SetControl(cboRoute, 'ROUTE', AnInstance);
with cboRoute do if ItemIndex > -1 then Text := DisplayText[ItemIndex];
Responses.SetControl(cboSchedule, 'SCHEDULE', AnInstance);
SetSimple;
end;
else begin
memComplex.Clear;
AnInstance := Responses.NextInstance('INSTR', 0);
while AnInstance > 0 do
begin
x := Responses.EValueFor('INSTR', AnInstance);
x := x + ' ' + Responses.EValueFor('MISC', AnInstance);
x := x + ' ' + Responses.EValueFor('ROUTE', AnInstance);
x := x + ' ' + Responses.EValueFor('SCHEDULE', AnInstance);
if Length(Responses.EValueFor('DAYS', AnInstance)) > 0
then x := x + ' ' + Responses.EValueFor('DAYS', AnInstance) + ' day(s)';
memComplex.Lines.Add(x);
AnInstance := Responses.NextInstance('INSTR', AnInstance);
end;
SetComplex;
end;
end; {case}
memOrder.Text := Responses.OrderText;
end; {if ExecuteComplexDose}
procedure TfrmODMedOut.cmdComplexClick(Sender: TObject);
begin
inherited;
if FMedCombo.ItemIEN = 0 then
begin
InfoBox(TX_NO_MED, 'Error', MB_OK);
Exit;
end;
if ExecuteComplexDose(CtrlInits, Responses) then SetInstructions;
end;
{ quantity }
procedure TfrmODMedOut.txtQuantityEnter(Sender: TObject);
begin
inherited;
with cboDispense do if ItemIEN > 0 then OrderMessage(QuantityMessage(ItemIEN));
end;
{ service connection }
procedure TfrmODMedOut.SetAskSC;
const
SC_NO = 0;
SC_YES = 1;
begin
if Patient.ServiceConnected and RequiresCopay(FLastDrug) then
begin
lblSC.Font.Color := clWindowText;
cboSC.Enabled := True;
cboSC.Color := clWindow;
if Patient.SCPercent > 50 then cboSC.SelectByIEN(SC_YES) else cboSC.SelectByIEN(SC_NO);
end else
begin
lblSC.Font.Color := clGrayText;
cboSC.Enabled := False;
cboSC.Color := clBtnFace;
cboSC.ItemIndex := -1;
end;
end;
procedure TfrmODMedOut.cboSCEnter(Sender: TObject);
begin
inherited;
OrderMessage(RatedDisabilities);
end;
{ comments }
procedure TfrmODMedOut.memCommentsEnter(Sender: TObject);
begin
inherited;
OrderMessage(''); // make sure Order Message disappears when in comments box
end;
{ all controls }
procedure TfrmODMedOut.ControlChange(Sender: TObject);
begin
inherited;
if csLoading in ComponentState then Exit; // to prevent error caused by txtRefills
if Changing then Exit;
if FMedCombo.ItemIEN = 0 then Exit; // prevent txtRefills from updating early
with FMedCombo do if ItemIEN > 0
then Responses.Update('ORDERABLE', 1, ItemID, Piece(Items[ItemIndex], U, 3))
else Responses.Update('ORDERABLE', 1, '', '');
with cboDispense do if ItemIEN > 0
then Responses.Update('DRUG', 1, ItemID, Piece(Items[ItemIndex], U, 2))
else Responses.Update('DRUG', 1, '', '');
if memComplex.Visible = False then
begin
with cboInstructions do Responses.Update('INSTR', 1, Text, Text);
with btnUnits do if Visible then Responses.Update('MISC', 1, Caption, Caption);
with cboRoute do if ItemIndex > -1
then Responses.Update('ROUTE', 1, ItemID, Piece(Items[ItemIndex], U, 3)) // abbreviation
else Responses.Update('ROUTE', 1, Text, Text);
with cboSchedule do Responses.Update('SCHEDULE', 1, Text, Text);
end;
with txtQuantity do Responses.Update('QTY', 1, Text, Text);
with txtRefills do Responses.Update('REFILLS', 1, Text, Text);
with cboPickup do Responses.Update('PICKUP', 1, ItemID, Text);
with cboPriority do Responses.Update('URGENCY', 1, ItemID, Text);
with memComments do Responses.Update('COMMENT', 1, TX_WPTYPE, Text);
with cboSC do if Enabled then Responses.Update('SC', 1, ItemID, Text);
memOrder.Text := Responses.OrderText;
end;
end.
|
unit uSelectie;
interface
uses
dxmdaset, Contnrs, uPlayer, uHTPredictor, uRatingBijdrages, Classes;
type
TSelectie = class
private
FNaam: String;
FPlayers: TObjectList;
FRatingBijdrages: TRatingBijdrages;
FTegenStander: TObject;
FNotifySelectieChanged: TNotifyEvent;
FTeamGeest: double;
FZelfvertrouwen: double;
FWedstrijdPlaats: TWedstrijdPlaats;
FEigenSelectie: Boolean;
procedure SetTeamGeest(const Value: double);
procedure SetZelfvertrouwen(const Value: double);
procedure SetWedstrdijdPlaats(const Value: TWedstrijdPlaats);
procedure SetEigenSelectie(const Value: Boolean);
public
procedure UpdateOpstellingen;
function GetPlayer(aID:integer):TPlayer;
procedure LoadFromMemDataSet(aDataSet: TdxMemData; aRefresh: boolean);
property Players:TObjectList read FPlayers write FPlayers;
property Naam:String read FNaam write FNaam;
property TegenStander: TObject read FTegenStander write FTegenStander;
property Zelfvertrouwen: double read FZelfvertrouwen write SetZelfvertrouwen;
property TeamGeest: double read FTeamGeest write SetTeamGeest;
property EigenSelectie: Boolean read FEigenSelectie write SetEigenSelectie;
property WedstrijdPlaats: TWedstrijdPlaats read FWedstrijdPlaats write SetWedstrdijdPlaats;
property RatingBijdrages: TRatingBijdrages read FRatingBijdrages write FRatingBijdrages;
property NotifySelectieChanged: TNotifyEvent read FNotifySelectieChanged write FNotifySelectieChanged;
constructor Create;
destructor Destroy;override;
end;
implementation
uses
db, Dialogs;
{ TSelectie }
{-----------------------------------------------------------------------------
Procedure: Create
Author: Harry
Date: 13-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
constructor TSelectie.Create;
begin
FPlayers := TObjectList.Create(TRUE);
FTeamGeest := 5;
FZelfvertrouwen := 5;
end;
{-----------------------------------------------------------------------------
Procedure: Destroy
Author: Harry
Date: 13-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
destructor TSelectie.Destroy;
begin
FPlayers.Free;
inherited;
end;
{-----------------------------------------------------------------------------
Procedure: GetPlayer
Author: Harry
Date: 13-apr-2012
Arguments: aID: integer
Result: TPlayer
-----------------------------------------------------------------------------}
function TSelectie.GetPlayer(aID: integer): TPlayer;
var
I: integer;
begin
result := nil;
if (Players.Count > 0) then
begin
i := 0;
while ((result = nil) and (i < Players.Count)) do
begin
if TPlayer(Players[i]).ID = aID then
begin
result := TPlayer(Players[i]);
end;
inc(i);
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: LoadFromMemDataSet
Author: Harry
Date: 13-apr-2012
Arguments: aDataSet: TdxMemData
Result: None
-----------------------------------------------------------------------------}
procedure TSelectie.LoadFromMemDataSet(aDataSet: TdxMemData; aRefresh: boolean);
var
vBookMark : TBookMark;
vPlayer: TPlayer;
begin
if not(aRefresh) then
begin
Players.Clear;
end;
with aDataSet do
begin
vBookMark := GetBookmark;
DisableControls;
try
First;
while not EOF do
begin
vPlayer := GetPlayer(FieldByName('RecID').asInteger);
if (vPlayer = nil) then
begin
vPlayer := TPlayer.Create;
vPlayer.ID := FieldByName('RecID').asInteger;
vPlayer.Selectie := Self;
Players.Add(vPlayer);
end;
vPlayer.Naam := FieldByName('NAAM').asString;
vPlayer.Spec := FieldByName('SPECIALITEIT').asString;
vPlayer.Vorm := FieldByName('VORM').asFloat;
vPlayer.Conditie := FieldByName('CONDITIE').asFloat;
vPlayer.GK := FieldByName('KEEPEN').asFloat;
vPlayer.DEF := FieldByName('VERDEDIGEN').asFloat;
vPlayer.PM := FieldByName('POSITIESPEL').asFloat;
vPlayer.WNG := FieldByName('VLEUGELSPEL').asFloat;
vPlayer.PAS := FieldByName('PASSEN').asFloat;
vPlayer.SCO := FieldByName('SCOREN').asFloat;
vPlayer.SP := FieldByname('SPELHERVATTEN').asFloat;
vPlayer.XP := FieldByName('ERVARING').asFloat;
vPlayer.Loyaliteit := FieldByName('LOYALITEIT').AsFloat;
vPlayer.RecalculateRatings;
Next;
end;
finally
GotoBookmark(vBookMark);
FreeBookmark(vBookMark);
EnableControls;
end;
end;
if Assigned(FNotifySelectieChanged) then
begin
FNotifySelectieChanged(nil);
end;
end;
procedure TSelectie.SetEigenSelectie(const Value: Boolean);
begin
FEigenSelectie := Value;
end;
procedure TSelectie.SetTeamGeest(const Value: double);
begin
if (FTeamGeest <> Value) then
begin
FTeamGeest := Value;
if Assigned(FNotifySelectieChanged) then
begin
FNotifySelectieChanged(nil);
end;
end;
end;
procedure TSelectie.SetWedstrdijdPlaats(const Value: TWedstrijdPlaats);
begin
if (FWedstrijdPlaats <> Value) then
begin
FWedstrijdPlaats := Value;
if Assigned(FNotifySelectieChanged) then
begin
FNotifySelectieChanged(nil);
end;
end;
end;
procedure TSelectie.SetZelfvertrouwen(const Value: double);
begin
if (FZelfvertrouwen <> Value) then
begin
FZelfvertrouwen := Value;
if Assigned(FNotifySelectieChanged) then
begin
FNotifySelectieChanged(nil);
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: UpdateOpstellingen
Author: Harry
Date: 19-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
procedure TSelectie.UpdateOpstellingen;
begin
// Todo!!!!
ShowMessage('Opstellingen doorrekenen!!');
end;
end.
|
unit Vigilante.Infra.Compilacao.JSONDataAdapter;
interface
uses
System.JSON, Vigilante.Infra.Compilacao.DataAdapter, Vigilante.Aplicacao.SituacaoBuild,
Vigilante.ChangeSetItem.Model;
type
TCompilacaoJSONDataAdapter = class(TInterfacedObject, ICompilacaoAdapter)
private
FJSON: TJSONObject;
FChangesSet: TArray<TChangeSetItem>;
procedure CarregarChangeSet;
function PegarChangeSetItemsJSON(const AChangeSet: TJSONObject): TJSONArray;
function PegarChangeSet: TJSONObject;
protected
function GetNome: string;
function GetNumero: Integer;
function GetSituacao: TSituacaoBuild;
function GetURL: string;
function GetBuilding: boolean;
function GetChangesSet: TArray<TChangeSetItem>;
public
constructor Create(const AJson: TJSONObject);
end;
implementation
uses
System.SysUtils, Vigilante.Infra.ChangeSet.JSONDataAdapter,
Vigilante.Infra.ChangeSet.DataAdapter;
constructor TCompilacaoJSONDataAdapter.Create(const AJson: TJSONObject);
begin
FJSON := AJson;
CarregarChangeSet;
end;
procedure TCompilacaoJSONDataAdapter.CarregarChangeSet;
var
_changeSetAdapter: IChangeSetAdapter;
_items: TJSONArray;
_changeSet: TJSONObject;
begin
FChangesSet := [];
_changeSet := PegarChangeSet;
if not Assigned(_changeSet) then
Exit;
_items := PegarChangeSetItemsJSON(_changeSet);
if not Assigned(_items) then
Exit;
_changeSetAdapter := TChangeSetAdapterJSON.Create(_items);
FChangesSet := _changeSetAdapter.PegarChangesSet;
end;
function TCompilacaoJSONDataAdapter.PegarChangeSet: TJSONObject;
var
_changeSet: TJSONObject;
begin
_changeSet := Nil;
if not FJSON.TryGetValue<TJSONObject>('changeSet', _changeSet) then
FJSON.TryGetValue<TJSONObject>('changeSets', _changeSet);
if not Assigned(_changeSet) then
Exit(Nil);
if _changeSet.Null then
Exit(Nil);
Result := _changeSet;
end;
function TCompilacaoJSONDataAdapter.PegarChangeSetItemsJSON(const AChangeSet: TJSONObject): TJSONArray;
var
_items: TJSONArray;
begin
if not AChangeSet.TryGetValue('items', _items) then
Exit(Nil);
if _items.Null then
Exit(Nil);
Result := _items;
end;
function TCompilacaoJSONDataAdapter.GetBuilding: boolean;
begin
Result := False;
if FJSON.GetValue('building').Null then
Exit;
Result := (FJSON.GetValue('building') as TJSONBool).AsBoolean;
end;
function TCompilacaoJSONDataAdapter.GetChangesSet: TArray<TChangeSetItem>;
begin
Result := FChangesSet;
end;
function TCompilacaoJSONDataAdapter.GetNome: string;
begin
Result := FJSON.GetValue('fullDisplayName').Value;
end;
function TCompilacaoJSONDataAdapter.GetNumero: Integer;
begin
Result := FJSON.GetValue('number').Value.ToInteger;
end;
function TCompilacaoJSONDataAdapter.GetSituacao: TSituacaoBuild;
var
_situacao: string;
begin
_situacao := FJSON.GetValue('result').Value;
Result := TSituacaoBuild.Parse(_situacao);
end;
function TCompilacaoJSONDataAdapter.GetURL: string;
begin
Result := FJSON.GetValue('url').Value;
end;
end.
|
unit uFuncionarioDTO;
interface
uses uDependenteDTO, System.Generics.Collections;
type
TFuncionarioDTO=class
private
FCPF: String;
FSalario: String;
FNome: String;
FListaDependentes: TObjectList<TDependenteDTO>;
public
property Nome: String read FNome write FNome;
property CPF: String read FCPF write FCPF;
property Salario: String read FSalario write FSalario;
property Dependentes: TObjectList<TDependenteDTO> read FListaDependentes
write FListaDependentes;
end;
implementation
end.
|
{
@abstract(@code(google.maps.Map) class from Google Maps API.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(Septembre 30, 2015)
@lastmod(October 1, 2015)
The GMMapVCL contains the implementation of TGMMap class that encapsulate the @code(google.maps.Map) class from Google Maps API and other related classes.
}
unit GMMap.VCL;
{$I ..\..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
Vcl.Graphics, System.Classes, SHDocVw, Vcl.ExtCtrls,
{$ELSE}
Graphics, Classes, SHDocVw, ExtCtrls,
{$ENDIF}
GMMap, GMClasses;
type
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.txt)
TGMMapTypeStyler = class(TGMCustomMapTypeStyler)
private
FColor: TColor;
FHue: TColor;
procedure SetColor(const Value: TColor);
procedure SetHue(const Value: TColor);
protected
// @include(..\..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Color.txt)
property Color: TColor read FColor write SetColor default clBlack;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Hue.txt)
property Hue: TColor read FHue write SetHue default clBlack;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Gamma.txt)
property Gamma;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.InvertLightness.txt)
property InvertLightness;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Lightness.txt)
property Lightness;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Saturation.txt)
property Saturation;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Visibility.txt)
property Visibility;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyler.Weight.txt)
property Weight;
end;
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStylers.txt)
TGMMapTypeStylers = class(TGMInterfacedCollection)
private
function GetItems(I: Integer): TGMMapTypeStyler;
procedure SetItems(I: Integer; const Value: TGMMapTypeStyler);
protected
// @include(..\..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
public
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStylers.Add.txt)
function Add: TGMMapTypeStyler;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStylers.Insert.txt)
function Insert(Index: Integer): TGMMapTypeStyler;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStylers.Items.txt)
property Items[I: Integer]: TGMMapTypeStyler read GetItems write SetItems; default;
end;
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.txt)
TGMMapTypeStyle = class(TGMCustomMapTypeStyle)
private
FStylers: TGMMapTypeStylers;
protected
// @include(..\..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
public
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.Create.txt)
constructor Create(Collection: TCollection); override;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.Destroy.txt)
destructor Destroy; override;
published
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.ElementType.txt)
property ElementType;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.FeatureType.txt)
property FeatureType;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyle.Stylers.txt)
property Stylers: TGMMapTypeStylers read FStylers write FStylers;
end;
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyles.txt)
TGMMapTypeStyles = class(TGMInterfacedCollection)
private
function GetItems(I: Integer): TGMMapTypeStyle;
procedure SetItems(I: Integer; const Value: TGMMapTypeStyle);
protected
// @include(..\..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
public
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyles.Add.txt)
function Add: TGMMapTypeStyle;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyles.Insert.txt)
function Insert(Index: Integer): TGMMapTypeStyle;
// @include(..\..\docs\GMMap.VCL.TGMMapTypeStyles.Items.txt)
property Items[I: Integer]: TGMMapTypeStyle read GetItems write SetItems; default;
end;
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.txt)
TGMMapOptions = class(TGMCustomMapOptions)
private
FBackgroundColor: TColor;
FStyles: TGMMapTypeStyles;
procedure SetBackgroundColor(const Value: TColor);
function GetCountStyles: Integer;
protected
// @include(..\..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
public
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Destroy.txt)
destructor Destroy; override;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.CountStyles.txt)
property CountStyles: Integer read GetCountStyles;
published
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.BackgroundColor.txt)
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor default clBlack;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.Center.txt)
property Center;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.DisableDefaultUI.txt)
property DisableDefaultUI;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.DisableDoubleClickZoom.txt)
property DisableDoubleClickZoom;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.Draggable.txt)
property Draggable;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.DraggableCursor.txt)
property DraggableCursor;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.DraggingCursor.txt)
property DraggingCursor;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.FullScreenControl.txt)
property FullScreenControl;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.FullScreenControlOptions.txt)
property FullScreenControlOptions;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.Heading.txt)
property Heading;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.KeyboardShortcuts.txt)
property KeyboardShortcuts;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.MapMaker.txt)
property MapMaker;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.MapTypeControl.txt)
property MapTypeControl;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.MapTypeControlOptions.txt)
property MapTypeControlOptions;
// @include(..\..\docs\GMMap.TGMCustomMapOptions.MapTypeId.txt)
property MapTypeId;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.MaxZoom.txt)
property MaxZoom;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.MinZoom.txt)
property MinZoom;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.NoClear.txt)
property NoClear;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.OverviewMapControl.txt)
property OverviewMapControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.OverviewMapControlOptions.txt)
property OverviewMapControlOptions;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.PanControl.txt)
property PanControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.PanControlOptions.txt)
property PanControlOptions;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.RotateControl.txt)
property RotateControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.RotateControlOptions.txt)
property RotateControlOptions;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.ScaleControl.txt)
property ScaleControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.ScaleControlOptions.txt)
property ScaleControlOptions;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Scrollwheel.txt)
property Scrollwheel;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.StreetView.txt)
property StreetView;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.StreetViewControl.txt)
property StreetViewControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.StreetViewControlOptions.txt)
property StreetViewControlOptions;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Styles.txt)
property Styles: TGMMapTypeStyles read FStyles write FStyles;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Tilt.txt)
property Tilt;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.Zoom.txt)
property Zoom;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.ZoomControl.txt)
property ZoomControl;
// @include(..\..\docs\GMMap.VCL.TGMMapOptions.ZoomControlOptions.txt)
property ZoomControlOptions;
end;
{ -------------------------------------------------------------------------- }
// @include(..\..\docs\GMMap.VCL.TGMMap.txt)
TGMMap = class(TGMCustomGMMap)
private
FMapOptions: TGMMapOptions;
FTimer: TTimer; // TTimer for map events control
FDocLoaded: Boolean; // Indicates if the map.html page is fully loaded.
CurDispatch: IDispatch; // variable for control of load web page
OldBeforeNavigate2: TWebBrowserBeforeNavigate2; // old TWebBrowser's event
OldDocumentComplete: TWebBrowserDocumentComplete; // old TWebBrowser's event
OldNavigateComplete2: TWebBrowserNavigateComplete2; // old TWebBrowser's event
// ES: eventos del TWebBrowser para el control de la carga de la página
// EN: events of TWebBrowser to control the load page
{$IFDEF DELPHIXE2}
procedure BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
const URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
procedure DocumentComplete(ASender: TObject; const pDisp: IDispatch;
const URL: OleVariant);
procedure NavigateComplete2(ASender: TObject; const pDisp: IDispatch;
const URL: OleVariant);
{$ELSE}
procedure BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
var URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
procedure DocumentComplete(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
procedure NavigateComplete2(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
{$ENDIF}
function GetWebBrowser: TWebBrowser;
procedure SetWebBrowser(const Value: TWebBrowser); (*1 *)
protected
// @include(..\..\docs\GMMap.TGMCustomGMMap.GetTempPath.txt)
function GetTempPath: string; override;
// @include(..\..\docs\GMMap.TGMCustomGMMap.SetIntervalTimer.txt)
procedure SetIntervalTimer(Interval: Integer); override;
// @include(..\..\docs\GMMap.TGMCustomGMMap.LoadMap.txt)
procedure LoadMap; override;
// @include(..\..\docs\GMMap.TGMCustomGMMap.LoadBlankPage.txt)
procedure LoadBlankPage; override;
// @include(..\..\docs\GMMap.TGMCustomGMMap.ExecuteJavaScript.txt)
procedure ExecuteJavaScript(NameFunct, Params: string); override; (*1 *)
// @include(..\..\docs\GMMap.VCL.TGMMap.DoMap.txt)
procedure DoMap;
// @include(..\..\docs\GMMap.TGMCustomGMMap.SignedIn.txt)
property SignedIn;
public
// @include(..\..\docs\GMMap.VCL.TGMMap.Create.txt)
constructor Create(AOwner: TComponent); override;
// @include(..\..\docs\GMMap.VCL.TGMMap.Destroy.txt)
destructor Destroy; override;
// @include(..\..\docs\GMMap.VCL.TGMMap.GetAPIUrl.txt)
function GetAPIUrl: string; override;
published
// @include(..\..\docs\GMMap.VCL.TGMMap.MapOptions.txt)
property MapOptions: TGMMapOptions read FMapOptions write FMapOptions;
// @include(..\..\docs\GMMap.VCL.TGMMap.Active.txt)
property Active;
// @include(..\..\docs\GMMap.VCL.TGMMap.GoogleAPIVer.txt)
property GoogleAPIVer;
// @include(..\..\docs\GMMap.VCL.TGMMap.Language.txt)
property Language;
// @include(..\..\docs\GMMap.VCL.TGMMap.AboutGMLib.txt)
property AboutGMLib;
// @include(..\..\docs\GMMap.VCL.TGMMap.APIUrl.txt)
property APIUrl;
// @include(..\..\docs\GMMap.VCL.TGMMap.GoogleAPIKey.txt)
property GoogleAPIKey;
// @include(..\..\docs\GMMap.VCL.TGMMap.IntervalEvents.txt)
property IntervalEvents;
// @include(..\..\docs\GMMap.TGMCustomGMMap.APILang.txt)
property APILang;
// @include(..\..\docs\GMMap.TGMCustomGMMap.Precision.txt)
property Precision;
// @include(..\..\docs\GMMap.VCL.TGMMap.WebBrowser.txt)
property WebBrowser: TWebBrowser read GetWebBrowser write SetWebBrowser;
// @include(..\..\docs\GMMap.TGMCustomGMMap.OnActiveChange.txt)
property OnActiveChange;
// @include(..\..\docs\GMMap.TGMCustomGMMap.OnIntervalEventsChange.txt)
property OnIntervalEventsChange;
// @include(..\..\docs\GMMap.TGMCustomGMMap.OnPrecisionChange.txt)
property OnPrecisionChange;
// @include(..\..\docs\GMMap.TGMCustomGMMap.OnPropertyChanges.txt)
property OnPropertyChanges;
end;
implementation
uses
MSHTML,
{$IFDEF DELPHIXE2}
System.SysUtils, Winapi.ActiveX, system.DateUtils, Winapi.Windows,
{$ELSE}
SysUtils, ActiveX, DateUtils, Windows,
{$ENDIF}
GMClasses.VCL;
{ TGMMapOptions }
constructor TGMMapOptions.Create(AOwner: TPersistent);
begin
inherited;
FBackgroundColor := clBlack;
FStyles := TGMMapTypeStyles.Create(Self, TGMMapTypeStyle);
end;
destructor TGMMapOptions.Destroy;
begin
if Assigned(FStyles) then FreeAndNil(FStyles);
inherited;
end;
function TGMMapOptions.GetCountStyles: Integer;
begin
Result := FStyles.Count;
end;
function TGMMapOptions.PropToString: string;
const
Str = '%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
QuotedStr(TGMTransformVCL.TColorToStr(FBackgroundColor)),
FStyles.PropToString
]);
end;
procedure TGMMapOptions.SetBackgroundColor(const Value: TColor);
begin
if FBackgroundColor = Value then Exit;
FBackgroundColor := Value;
ControlChanges('BackgroundColor');
end;
{ TGMMapTypeStyler }
function TGMMapTypeStyler.PropToString: string;
const
Str = '%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
TGMTransformVCL.TColorToStr(FColor),
TGMTransformVCL.TColorToStr(FHue)
]);
end;
procedure TGMMapTypeStyler.SetColor(const Value: TColor);
begin
if FColor = Value then Exit;
FColor := Value;
ControlChanges('Color');
end;
procedure TGMMapTypeStyler.SetHue(const Value: TColor);
begin
if FHue = Value then Exit;
FHue := Value;
ControlChanges('Hue');
end;
{ TGMMap }
{$IFDEF DELPHIXE2}
procedure TGMMap.BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
const URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
{$ELSE}
procedure TGMMap.BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
var URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
{$ENDIF}
begin
if Assigned(OldBeforeNavigate2) then
OldBeforeNavigate2(ASender, pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel);
CurDispatch := nil;
FDocLoaded := False;
end;
{$IFDEF DELPHIXE2}
procedure TGMMap.DocumentComplete(ASender: TObject; const pDisp: IDispatch;
const URL: OleVariant);
{$ELSE}
procedure TGMMap.DocumentComplete(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
{$ENDIF}
begin
if Assigned(OldDocumentComplete) then
OldDocumentComplete(ASender, pDisp, URL);
if (pDisp = CurDispatch) then // if equals, page loaded
begin
FDocLoaded := True;
if Active then DoMap;
CurDispatch := nil;
end;
end;
procedure TGMMap.DoMap;
var
Params: string;
begin
Params := FMapOptions.PropToString;
ExecuteJavaScript('DoMap', Params);
end;
procedure TGMMap.ExecuteJavaScript(NameFunct, Params: string);
var
Doc2: IHTMLDocument2;
Win2: IHTMLWindow2;
begin
if not Assigned(FWebBrowser) then
raise EGMUnassignedObject.Create(['WebBrowser'], Language); // Unassigned %s object.
if not Active then
raise EGMNotActive.Create(Language); // Map is not active.
if not (FWebBrowser is TWebBrowser) then
raise EGMIncorrectBrowser.Create(Language); // The browser is not of the desired type.
Doc2 := TWebBrowser(FWebBrowser).Document as IHTMLDocument2;
Win2 := Doc2.parentWindow;
try
Win2.execScript(NameFunct + '(' + Params + ')', 'JavaScript');
except
on E: Exception do
raise EGMJSError.Create([NameFunct, E.Message], Language);
end;
//if MapIsNull then
// raise Exception.Create(GetTranslateText('El mapa todavía no ha sido creado', Language));
end;
{$IFDEF DELPHIXE2}
procedure TGMMap.NavigateComplete2(ASender: TObject; const pDisp: IDispatch;
const URL: OleVariant);
{$ELSE}
procedure TGMMap.NavigateComplete2(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
{$ENDIF}
begin
if Assigned(OldNavigateComplete2) then
OldNavigateComplete2(ASender, pDisp, URL);
if CurDispatch = nil then
CurDispatch := pDisp;
end;
constructor TGMMap.Create(AOwner: TComponent);
begin
inherited;
FMapOptions := TGMMapOptions.Create(Self);
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.Interval := 200;
FTimer.OnTimer := OnTimer;
end;
destructor TGMMap.Destroy;
begin
if Assigned(FMapOptions) then FreeAndNil(FMapOptions);
if Assigned(FTimer) then FreeAndNil(FTimer);
inherited;
end;
function TGMMap.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#Map';
end;
function TGMMap.GetTempPath: string;
var
Len: Integer;
begin
SetLastError(ERROR_SUCCESS);
SetLength(Result, MAX_PATH);
Len := Winapi.Windows.GetTempPath(MAX_PATH, PChar(Result));
if Len <> 0 then
begin
Len := GetLongPathName(PChar(Result), nil, 0);
GetLongPathName(PChar(Result), PChar(Result), Len);
SetLength(Result, Len - 1);
end
else
Result := '';
end;
function TGMMap.GetWebBrowser: TWebBrowser;
begin
Result := nil;
if FWebBrowser is TWebBrowser then
Result := TWebBrowser(FWebBrowser);
end;
procedure TGMMap.LoadBlankPage;
begin
inherited;
if not (FWebBrowser is TWebBrowser) then
raise EGMIncorrectBrowser.Create(Language); // The browser is not of the desired type.
TWebBrowser(FWebBrowser).Navigate('about:blank');
end;
procedure TGMMap.LoadMap;
begin
inherited;
if not Assigned(FWebBrowser) then
raise EGMUnassignedObject.Create(['WebBrowser'], Language); // Object %s unassigned.
if not (FWebBrowser is TWebBrowser) then
raise EGMIncorrectBrowser.Create(Language); // The browser is not of the desired type.
TWebBrowser(FWebBrowser).Navigate(GetBaseHTMLCode);
end;
procedure TGMMap.SetIntervalTimer(Interval: Integer);
begin
inherited;
if Assigned(FTimer) then FTimer.Interval := Interval;
end;
procedure TGMMap.SetWebBrowser(const Value: TWebBrowser);
begin
if FWebBrowser = Value then Exit;
if (Value <> FWebBrowser) and Assigned(FWebBrowser) then
begin
TWebBrowser(FWebBrowser).OnBeforeNavigate2 := OldBeforeNavigate2;
TWebBrowser(FWebBrowser).OnDocumentComplete := OldDocumentComplete;
TWebBrowser(FWebBrowser).OnNavigateComplete2 := OldNavigateComplete2;
end;
FWebBrowser := Value;
{
TWebControl(FWC).SetBrowser(TWebBrowser(FWebBrowser));
}
if csDesigning in ComponentState then Exit;
if Assigned(FWebBrowser) then
begin
OldBeforeNavigate2 := TWebBrowser(FWebBrowser).OnBeforeNavigate2;
OldDocumentComplete := TWebBrowser(FWebBrowser).OnDocumentComplete;
OldNavigateComplete2 := TWebBrowser(FWebBrowser).OnNavigateComplete2;
TWebBrowser(FWebBrowser).OnBeforeNavigate2 := BeforeNavigate2;
TWebBrowser(FWebBrowser).OnDocumentComplete := DocumentComplete;
TWebBrowser(FWebBrowser).OnNavigateComplete2 := NavigateComplete2;
if Active then
LoadMap
else
LoadBlankPage;
end;
end;
{ TGMMapTypeStyles }
function TGMMapTypeStyles.Add: TGMMapTypeStyle;
begin
Result := TGMMapTypeStyle(inherited Add);
end;
function TGMMapTypeStyles.GetItems(I: Integer): TGMMapTypeStyle;
begin
Result := TGMMapTypeStyle(inherited Items[I]);
end;
function TGMMapTypeStyles.Insert(Index: Integer): TGMMapTypeStyle;
begin
Result := TGMMapTypeStyle(inherited Insert(Index));
end;
function TGMMapTypeStyles.PropToString: string;
var
i: Integer;
begin
Result := inherited PropToString;
for i := 0 to Count - 1 do
begin
if Result <> '' then Result := Result + '¬';
Result := Result + Items[i].PropToString;
end;
Result := QuotedStr(Result);
end;
procedure TGMMapTypeStyles.SetItems(I: Integer; const Value: TGMMapTypeStyle);
begin
inherited SetItem(I, Value);
end;
{ TGMMapTypeStylers }
function TGMMapTypeStylers.Add: TGMMapTypeStyler;
begin
Result := TGMMapTypeStyler(inherited Add);
end;
function TGMMapTypeStylers.GetItems(I: Integer): TGMMapTypeStyler;
begin
Result := TGMMapTypeStyler(inherited Items[I]);
end;
function TGMMapTypeStylers.Insert(Index: Integer): TGMMapTypeStyler;
begin
Result := TGMMapTypeStyler(inherited Insert(Index));
end;
function TGMMapTypeStylers.PropToString: string;
var
i: Integer;
begin
Result := inherited PropToString;
for i := 0 to Count - 1 do
begin
if Result <> '' then Result := Result + '&';
Result := Result + Items[i].PropToString;
end;
end;
procedure TGMMapTypeStylers.SetItems(I: Integer; const Value: TGMMapTypeStyler);
begin
inherited SetItem(I, Value);
end;
{ TGMMapTypeStyle }
constructor TGMMapTypeStyle.Create(Collection: TCollection);
begin
inherited;
FStylers := TGMMapTypeStylers.Create(Self, TGMMapTypeStyler);
end;
destructor TGMMapTypeStyle.Destroy;
begin
if Assigned(FStylers) then FreeAndNil(FStylers);
inherited;
end;
function TGMMapTypeStyle.PropToString: string;
const
Str = '%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + '&';
Result := Result +
Format(Str, [
FStylers.PropToString
]);
end;
end.
|
{ Copyright (C) 2006 Darius Blaszijk
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code 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.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit SourcePrinter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Printers, Graphics, PrintersDlgs, ExtCtrls, GraphType;
type
TSourcePrinter = class(TObject)
private
FFont: TFont;
FShowLineNumbers: boolean;
LineHeight: double;
LinesPerPage: integer;
FMargin: integer;
PageCount: integer;
PrintDialog: TPrintDialog;
procedure PrintPage(Text: TStrings; PageNum: integer);
public
constructor Create;
destructor Destroy; override;
procedure Execute(Text: TStrings);
published
property Font: TFont read FFont write FFont;
property ShowLineNumbers: boolean read FShowLineNumbers write FShowLineNumbers;
property Margin: integer read FMargin write FMargin;
end;
implementation
constructor TSourcePrinter.Create;
begin
FFont := TFont.Create;
FFont.Name := 'Courier New';
FFont.Size := 10;
FFont.Color := clBlack;
PrintDialog := TPrintDialog.Create(nil);
ShowLineNumbers := True;
{$ifdef Linux}
Margin := 30;
{$else}
Margin := 0;
{$endif}
end;
destructor TSourcePrinter.Destroy;
begin
FFont.Free;
PrintDialog.Free;
end;
procedure TSourcePrinter.PrintPage(Text: TStrings; PageNum: integer);
var
l: integer;
s: string;
LineNum: integer;
begin
//print all lines on the current page
for l := 1 to LinesPerPage do
begin
LineNum := Pred(PageNum) * LinesPerPage + l;
//check if end of text is reached
if LineNum <= Text.Count then
begin
if ShowLineNumbers then
s := Format('%4d: ',[LineNum])
else
s := ' ';
s := s + Text[Pred(LineNum)];
Printer.Canvas.TextOut(Margin, Round(LineHeight * l), s);
end;
end;
end;
procedure TSourcePrinter.Execute(Text: TStrings);
var
p: integer;
//copies: integer;
begin
if PrintDialog.Execute then
begin
Printer.Title := 'Printers4LazIDE: Source Code Printer Package';
Printer.BeginDoc;
Printer.Canvas.Font := FFont;
//calculate page dimensions
LineHeight := Printer.Canvas.TextHeight('X') * 1.2;
LinesPerPage := Round(Printer.PageHeight / LineHeight -3);
PageCount := Text.Count div LinesPerPage;
if Text.Count mod LinesPerPage <> 0 then
Inc(PageCount);
try
//print each page
for p := 1 to PageCount do
begin
PrintPage(Text, p);
//create a new page
if p <> PageCount then
Printer.NewPage;
end;
Printer.EndDoc;
except
on E:Exception do
begin
Printer.Abort;
raise Exception.Create(e.message);
end;
end;
end;
end;
end.
|
{
*******************************************************************************************************************
SpiderAction: Contains TSpiderAction component that used to handle request with path information
Author: Motaz Abdel Azeem
email: motaz@code.sd
Home page: http://code.sd
License: LGPL
Last modifie: 12.Sept.2009
Jul/2010 - Modified by Luiz Américo
* Remove LCL dependency
*******************************************************************************************************************
}
unit SpiderAction;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SpiderUtils;
type
{ TSpiderAction }
TSpiderAction = class(TComponent)
private
fPath: string;
fOnRequest: TSpiderEvent;
{ Private declarations }
protected
procedure SetPath(const APath: string);
{ Protected declarations }
public
constructor Create(TheOwner: TComponent); override;
procedure DoRequest(fRequest: TSpiderRequest; fResponse: TSpiderResponse);
{ Public declarations }
published
property Path: string read fPath write SetPath;
property OnRequest: TSpiderEvent read fOnRequest write fOnRequest;
{ Published declarations }
end;
implementation
{ TSpiderAction }
procedure TSpiderAction.SetPath(const APath: string);
begin
if (APath <> '') and (APath[Length(APath)] = '/') then
fPath:= Copy(APath, 1, Length(APath) - 1)
else
fPath:= APath;
end;
constructor TSpiderAction.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
fPath:= Name;
end;
procedure TSpiderAction.DoRequest(fRequest: TSpiderRequest; fResponse: TSpiderResponse);
begin
if Assigned(fOnRequest) then
fOnRequest(Self, fRequest, fResponse);
end;
end.
|
unit MediaStream.Framer.Tsm;
interface
uses Windows,SysUtils,Classes,TsmFile,MediaProcessing.Definitions,MediaStream.Framer;
type
TStreamFramerTsmRandomAccess = class;
TStreamFramerTsm = class (TStreamFramer)
private
FReader: TTsmFileReader;
FRandomAccess: TStreamFramerTsmRandomAccess;
FVideoFramesRead: int64;
FAudioFramesRead: int64;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; override;
function VideoStreamType: TStreamType; override;
function VideoInfo: TVideoInfo; override;
function AudioStreamType: TStreamType; override;
function AudioInfo: TAudioInfo; override;
function StreamInfo: TBytes; override;
property Reader: TTsmFileReader read FReader;
function RandomAccess: TStreamFramerRandomAccess; override;
end;
TStreamFramerTsmRandomAccess = class (TStreamFramerRandomAccess)
private
FOwner: TStreamFramerTsm;
FStreamInfo: TStreamInfo;
protected
function GetPosition: int64; override;
procedure SetPosition(const Value: int64); override;
public
function StreamInfo: TStreamInfo; override;
function SeekToPrevVideoKeyFrame: boolean; override;
constructor Create(aOwner: TStreamFramerTsm);
end;
implementation
{ TStreamFramerTsm }
constructor TStreamFramerTsm.Create;
begin
inherited;
FReader:=TTsmFileReader.Create;
end;
destructor TStreamFramerTsm.Destroy;
begin
FreeAndNil(FReader);
FreeAndNil(FRandomAccess);
inherited;
end;
function TStreamFramerTsm.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean;
begin
Assert(FReader<>nil);
result:=FReader.ReadFrame;
if result then
begin
aOutData:=FReader.CurrentFrameData;
aOutDataSize:=FReader.CurrentFrame.Header.DataSize;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.Clear;
if FReader.CurrentFrame.Header.DataType = TsmDataTypeAudio then
begin
aOutFormat.biMediaType:=mtAudio;
aOutFormat.biStreamType:= AudioStreamType;
aOutFormat.biStreamSubType:=FReader.Header.AudioStreamSubType;
aOutFormat.AudioChannels:=FReader.Header.AudioChannels;
aOutFormat.AudioBitsPerSample:=FReader.Header.AudioBitsPerSample;
aOutFormat.AudioSamplesPerSec:=FReader.Header.AudioSamplesPerSec;
aOutFormat.TimeStamp:=FReader.CurrentFrame.Header.TimestampOffs;
inc(FAudioFramesRead);
end
else if FReader.CurrentFrame.Header.DataType = TsmDataTypeVideo then
begin
aOutFormat.biMediaType:=mtVideo;
aOutFormat.biStreamType:= VideoStreamType;
aOutFormat.biStreamSubType:=FReader.Header.VideoStreamSubType;
aOutFormat.VideoWidth:=FReader.Header.VideoWidth;
aOutFormat.VideoHeight:=FReader.Header.VideoHeight;
aOutFormat.VideoBitCount:=FReader.Header.VideoBitCount;
//aOutFormat.biBitCount:=0;
if FReader.CurrentFrame.Header.IsKeyFrame then
Include(aOutFormat.biFrameFlags,ffKeyFrame);
aOutFormat.TimeStamp:=FReader.CurrentFrame.Header.TimestampOffs;
inc(FVideoFramesRead);
end
else if FReader.CurrentFrame.Header.DataType = TsmDataTypeSysData then
begin
aOutFormat.biMediaType:=mtSysData;
aOutFormat.biStreamType:= FReader.CurrentFrame.Extension.StreamType;
aOutFormat.biStreamSubType:=FReader.CurrentFrame.Extension.StreamSubType;
aOutFormat.VideoWidth:=FReader.Header.VideoWidth;
aOutFormat.VideoHeight:=FReader.Header.VideoHeight;
aOutFormat.VideoBitCount:=FReader.Header.VideoBitCount;
if FReader.CurrentFrame.Header.IsKeyFrame then
Include(aOutFormat.biFrameFlags,ffKeyFrame);
aOutFormat.TimeStamp:=(int64(FReader.CurrentFrame.Extension.TimestampHigh) shl 32) or FReader.CurrentFrame.Header.TimestampOffs;
//inc(FVideoFramesRead);*)
end;
aOutFormat.TimeKoeff:=1;
//if aOutFormat.TimeStamp<0 then
// aOutFormat.TimeStamp:=0; //?? Что делать в случае нарушенных временных меток?
end;
end;
procedure TStreamFramerTsm.OpenStream(aStream: TStream);
begin
FreeAndNil(FRandomAccess);
FReader.Open(aStream);
end;
function TStreamFramerTsm.RandomAccess: TStreamFramerRandomAccess;
begin
result:=FRandomAccess;
if result<>nil then
exit;
if not FReader.Opened then
exit;
if not FReader.Header.Valid then
exit;
FReader.ReadIndexTable;
if FReader.IndexTableExists then
begin
try
FReader.IndexTable.CheckTimeStampOrder;
except
exit;
end;
FRandomAccess:=TStreamFramerTsmRandomAccess.Create(self);
end;
result:=FRandomAccess;
end;
function TStreamFramerTsm.StreamInfo: TBytes;
begin
result:=nil;
end;
function TStreamFramerTsm.VideoInfo: TVideoInfo;
begin
result.Width:=FReader.Header.VideoWidth;
result.Height:=FReader.Header.VideoHeight;
if result.Width*Result.Height>0 then
result.State:=isOK
else
result.State:=isNotFound;
end;
function TStreamFramerTsm.VideoStreamType: TStreamType;
begin
if (FReader=nil) then
result:=0
else
result:=FReader.Header.VideoStreamType;
end;
function TStreamFramerTsm.AudioInfo: TAudioInfo;
begin
result.Channels:=FReader.Header.AudioChannels;
result.BitsPerSample:=FReader.Header.AudioBitsPerSample;
result.SamplesPerSec:=FReader.Header.AudioSamplesPerSec;
if result.Channels>0 then
result.State:=isOK
else
result.State:=isNotFound;
end;
function TStreamFramerTsm.AudioStreamType: TStreamType;
begin
if (FReader=nil) then
result:=0
else
result:=FReader.Header.AudioStreamType;
end;
{ TStreamFramerTsmRandomAccess }
constructor TStreamFramerTsmRandomAccess.Create(aOwner: TStreamFramerTsm);
begin
FOwner:=aOwner;
Assert(FOwner.Reader.Header.Valid);
FStreamInfo.VideoFrameCount:=FOwner.FReader.Header.VideoFrameCount;
FStreamInfo.Length:=FOwner.FReader.Header.VideoLastTimeStamp-FOwner.FReader.Header.VideoFirstTimeStamp;
end;
function TStreamFramerTsmRandomAccess.GetPosition: int64;
begin
result:= FOwner.FReader.LastReadVideoTimestamp;
end;
function TStreamFramerTsmRandomAccess.StreamInfo: TStreamInfo;
begin
result:=FStreamInfo;
end;
function TStreamFramerTsmRandomAccess.SeekToPrevVideoKeyFrame: boolean;
begin
result:=FOwner.FReader.SeekToPrevIVideoFrame;
end;
procedure TStreamFramerTsmRandomAccess.SetPosition(const Value: int64);
begin
if Value<=0 then
FOwner.FReader.ResetPos
else begin
if FOwner.FReader.SeekToVideoFrameGE(Value) then
begin
if not FOwner.FReader.CurrentFrame.Header.IsKeyFrame then
FOwner.FReader.SeekToPrevIVideoFrame
end
else
FOwner.FReader.SeekToEnd;
end;
end;
end.
|
unit ncCommandHandlers;
// To disable as much of RTTI as possible (Delphi 2009/2010),
// Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ENDIF}
interface
uses
System.Classes, System.SysUtils, System.SyncObjs, System.Rtti, ncSources;
type
TncCustomCommandHandler = class(TComponent, IncCommandHandler)
private
FSource: TncSourceBase;
FPeerCommandHandler: string;
FOnConnected: TncOnSourceConnectDisconnect;
FOnDisconnected: TncOnSourceConnectDisconnect;
FOnHandleCommand: TncOnSourceHandleCommand;
FOnAsyncExecCommandResult: TncOnAsyncExecCommandResult;
procedure SetSource(const Value: TncSourceBase);
function GetPeerCommandHandler: string;
procedure SetPeerCommandHandler(const Value: string);
function GetOnConnected: TncOnSourceConnectDisconnect;
procedure SetOnConnected(const Value: TncOnSourceConnectDisconnect);
function GetOnDisconnected: TncOnSourceConnectDisconnect;
procedure SetOnDisconnected(const Value: TncOnSourceConnectDisconnect);
function GetOnHandleCommand: TncOnSourceHandleCommand;
procedure SetOnHandleCommand(const Value: TncOnSourceHandleCommand);
function GetOnAsyncExecCommandResult: TncOnAsyncExecCommandResult;
procedure SetOnAsyncExecCommandResult(const Value: TncOnAsyncExecCommandResult);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetComponentName: string;
property Source: TncSourceBase read FSource write SetSource;
property PeerCommandHandler: string read GetPeerCommandHandler write SetPeerCommandHandler;
property OnConnected: TncOnSourceConnectDisconnect read GetOnConnected write SetOnConnected;
property OnDisconnected: TncOnSourceConnectDisconnect read GetOnDisconnected write SetOnDisconnected;
property OnHandleCommand: TncOnSourceHandleCommand read GetOnHandleCommand write SetOnHandleCommand;
property OnAsyncExecCommandResult: TncOnAsyncExecCommandResult read GetOnAsyncExecCommandResult write SetOnAsyncExecCommandResult;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecCommand(aLine: TncSourceLine; const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True;
aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''): TBytes;
published
end;
TncCommandHandler = class(TncCustomCommandHandler)
published
property Source;
property PeerCommandHandler;
property OnConnected;
property OnDisconnected;
property OnHandleCommand;
end;
implementation
{ TncCustomCommandHandler }
constructor TncCustomCommandHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSource := nil;
FOnConnected := nil;
FOnDisconnected := nil;
FOnHandleCommand := nil;
FOnAsyncExecCommandResult := nil;
end;
destructor TncCustomCommandHandler.Destroy;
begin
Source := nil;
inherited Destroy;
end;
procedure TncCustomCommandHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = FSource then
SetSource(nil);
if not(csLoading in ComponentState) then
begin
if Operation = opInsert then
if not Assigned(FSource) then
if AComponent is TncSourceBase then
SetSource(TncSourceBase(AComponent));
end;
end;
function TncCustomCommandHandler.ExecCommand(aLine: TncSourceLine; const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True;
aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''): TBytes;
begin
if not Assigned(Source) then
raise Exception.Create('Cannot execute with no source object');
// If no override, we use the component's command handler (the property)
if aPeerComponentHandler = '' then
Result := Source.ExecCommand(aLine, aCmd, aData, aRequiresResult, aAsyncExecute, PeerCommandHandler)
else
Result := Source.ExecCommand(aLine, aCmd, aData, aRequiresResult, aAsyncExecute, aPeerComponentHandler);
end;
procedure TncCustomCommandHandler.SetSource(const Value: TncSourceBase);
begin
if FSource <> Value then
begin
if Assigned(FSource) then
FSource.RemoveCommandHandler(Self);
FSource := Value;
if Assigned(FSource) then
FSource.AddCommandHandler(Self);
end;
end;
function TncCustomCommandHandler.GetPeerCommandHandler: string;
begin
Result := FPeerCommandHandler;
end;
procedure TncCustomCommandHandler.SetPeerCommandHandler(const Value: string);
begin
FPeerCommandHandler := Value;
end;
function TncCustomCommandHandler.GetComponentName: string;
begin
Result := Name;
end;
function TncCustomCommandHandler.GetOnConnected: TncOnSourceConnectDisconnect;
begin
Result := FOnConnected;
end;
procedure TncCustomCommandHandler.SetOnConnected(const Value: TncOnSourceConnectDisconnect);
begin
FOnConnected := Value;
end;
function TncCustomCommandHandler.GetOnDisconnected: TncOnSourceConnectDisconnect;
begin
Result := FOnDisconnected;
end;
procedure TncCustomCommandHandler.SetOnDisconnected(const Value: TncOnSourceConnectDisconnect);
begin
FOnDisconnected := Value;
end;
function TncCustomCommandHandler.GetOnHandleCommand: TncOnSourceHandleCommand;
begin
Result := FOnHandleCommand;
end;
procedure TncCustomCommandHandler.SetOnHandleCommand(const Value: TncOnSourceHandleCommand);
begin
FOnHandleCommand := Value;
end;
function TncCustomCommandHandler.GetOnAsyncExecCommandResult: TncOnAsyncExecCommandResult;
begin
Result := FOnAsyncExecCommandResult;
end;
procedure TncCustomCommandHandler.SetOnAsyncExecCommandResult(const Value: TncOnAsyncExecCommandResult);
begin
FOnAsyncExecCommandResult := Value;
end;
end.
|
unit uDisplayFile;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics,
uFile;
type
TDisplayItemPtr = Pointer;
{en
Describes the file displayed in the file view.
}
{ TDisplayFile }
TDisplayFile = class
private
FFSFile: TFile; //<en reference to file source's file
FDisplayItem: TDisplayItemPtr; //<en Item that displays this file (for example Node in a tree).
// Other properties.
FTag: PtrInt; //<en File view related info
FSelected: Boolean; //<en If is selected
FIconID: PtrInt; //<en Icon ID for PixmapManager
FIconOverlayID: PtrInt; //<en Overlay icon ID for PixmapManager
FTextColor: TColor; //<en Text color in file list
{en
Used to indicate that the file has been recently updated.
Value goes from 100 to 0. 0 - not recently updated, 100 - just updated.
}
FRecentlyUpdatedPct: Integer;
// Cache of displayed strings.
FDisplayStrings: TStringList;
public
{en
@param(ReferenceFile
Reference file source file that will be associated with this display file.
The TDisplayFile takes ownership and will destroy the FS file.)
}
constructor Create(ReferenceFile: TFile); virtual reintroduce;
destructor Destroy; override;
{en
Creates an identical copy of the object (as far as object data is concerned).
@param(NewReferenceFile
FS file to assign as the reference file (possibly a clone too).)
}
function Clone(NewReferenceFile: TFile): TDisplayFile;
{en
Creates an identical copy of the object (as far as object data is concerned).
@param(CloneFSFile
If @false then the reference FS file must be later manually assigned.
Also, if @false DisplayStrings are not cloned.)
}
function Clone(CloneFSFile: Boolean): TDisplayFile; virtual;
procedure CloneTo(AFile: TDisplayFile); virtual;
property FSFile: TFile read FFSFile write FFSFile;
property DisplayItem: TDisplayItemPtr read FDisplayItem write FDisplayItem;
property Selected: Boolean read FSelected write FSelected;
property IconID: PtrInt read FIconID write FIconID;
property IconOverlayID: PtrInt read FIconOverlayID write FIconOverlayID;
property TextColor: TColor read FTextColor write FTextColor;
property DisplayStrings: TStringList read FDisplayStrings;
property RecentlyUpdatedPct: Integer read FRecentlyUpdatedPct write FRecentlyUpdatedPct;
property Tag: PtrInt read FTag write FTag;
end;
{ TDisplayFiles }
TDisplayFiles = class
private
FList: TFPList;
FOwnsObjects: Boolean;
protected
function GetCount: Integer;
procedure SetCount(Count: Integer);
function Get(Index: Integer): TDisplayFile;
procedure Put(Index: Integer; AFile: TDisplayFile);
public
constructor Create(AOwnsObjects: Boolean = True); virtual;
destructor Destroy; override;
{en
Create a list with cloned files.
@param(CloneFSFiles
If @true automatically clones all FS reference files too.
If @false does not clone reference files and some properties
that are affected by reference FS files.)
}
function Clone(CloneFSFiles: Boolean): TDisplayFiles; virtual;
procedure CloneTo(Files: TDisplayFiles; CloneFSFiles: Boolean); virtual;
function Add(AFile: TDisplayFile): Integer;
procedure Clear;
procedure Delete(Index: Integer);
function Find(AFile: TDisplayFile): Integer;
procedure Remove(AFile: TDisplayFile);
property Count: Integer read GetCount write SetCount;
property Items[Index: Integer]: TDisplayFile read Get write Put; default;
property List: TFPList read FList;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
end;
implementation
constructor TDisplayFile.Create(ReferenceFile: TFile);
begin
FTag := -1;
FIconID := -1;
FIconOverlayID := -1;
FTextColor := clNone;
FFSFile := ReferenceFile;
FDisplayStrings := TStringList.Create;
end;
destructor TDisplayFile.Destroy;
begin
inherited Destroy;
FDisplayStrings.Free;
FSFile.Free;
end;
function TDisplayFile.Clone(NewReferenceFile: TFile): TDisplayFile;
begin
Result := TDisplayFile.Create(NewReferenceFile);
CloneTo(Result);
end;
function TDisplayFile.Clone(CloneFSFile: Boolean): TDisplayFile;
var
AFile: TFile;
begin
if CloneFSFile then
AFile := FSFile.Clone
else
AFile := nil;
Result := TDisplayFile.Create(AFile);
CloneTo(Result);
end;
procedure TDisplayFile.CloneTo(AFile: TDisplayFile);
begin
if Assigned(AFile) then
begin
AFile.FSelected := FSelected;
AFile.FIconID := FIconID;
AFile.FIconOverlayID := FIconOverlayID;
AFile.FTextColor := FTextColor;
if Assigned(AFile.FFSFile) then
begin
AFile.FDisplayStrings.AddStrings(FDisplayStrings);
end;
end;
end;
// ----------------------------------------------------------------------------
constructor TDisplayFiles.Create(AOwnsObjects: Boolean = True);
begin
inherited Create;
FOwnsObjects := AOwnsObjects;
FList := TFPList.Create;
end;
destructor TDisplayFiles.Destroy;
begin
Clear;
FreeAndNil(FList);
inherited Destroy;
end;
function TDisplayFiles.Clone(CloneFSFiles: Boolean): TDisplayFiles;
begin
Result := TDisplayFiles.Create(FOwnsObjects);
CloneTo(Result, CloneFSFiles);
end;
procedure TDisplayFiles.CloneTo(Files: TDisplayFiles; CloneFSFiles: Boolean);
var
i: Integer;
begin
for i := 0 to FList.Count - 1 do
begin
Files.Add(Get(i).Clone(CloneFSFiles));
end;
end;
function TDisplayFiles.GetCount: Integer;
begin
Result := FList.Count;
end;
procedure TDisplayFiles.SetCount(Count: Integer);
begin
FList.Count := Count;
end;
function TDisplayFiles.Add(AFile: TDisplayFile): Integer;
begin
Result := FList.Add(AFile);
end;
procedure TDisplayFiles.Clear;
var
i: Integer;
p: Pointer;
begin
if FOwnsObjects then
begin
for i := 0 to FList.Count - 1 do
begin
p := FList.Items[i];
TDisplayFile(p).Free;
end;
end;
FList.Clear;
end;
procedure TDisplayFiles.Delete(Index: Integer);
begin
if FOwnsObjects then
TDisplayFile(FList.Items[Index]).Free;
FList.Delete(Index);
end;
function TDisplayFiles.Find(AFile: TDisplayFile): Integer;
begin
Result := FList.IndexOf(AFile);
end;
procedure TDisplayFiles.Remove(AFile: TDisplayFile);
var
i: Integer;
begin
i := Find(AFile);
if i >= 0 then
Delete(i);
end;
function TDisplayFiles.Get(Index: Integer): TDisplayFile;
begin
Result := TDisplayFile(FList.Items[Index]);
end;
procedure TDisplayFiles.Put(Index: Integer; AFile: TDisplayFile);
begin
FList.Items[Index] := AFile;
end;
end.
|
unit zkXmlCreateAndAnalyze;
interface
uses
SysUtils, NativeXml, dlyComponent, dlySerializeXml, zkCommandsRC,
zkEntities, zkEntitiesInvoice, zkConsts, zkEntitiesRevenue;
{$REGION '组织请求报文:CreateSendXmlReport'}
procedure Component2XmlNode_TY_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
procedure Component2XmlNode_JS_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
procedure Component2XmlNode_XS_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
procedure Component2XmlNode_JZ_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
procedure Component2XmlNode_Kpd(Node: TXmlNode; Reg: TzkpRegistration);
procedure Component2XmlNode_Kpr(Node: TXmlNode; Kpr: TzkKPR);
{$ENDREGION}
{$REGION '解析返回报文:AnalyzeReportXml'}
(* 解析返回的税控信息报文 *)
procedure AnalyzeReportXml_TaxControl(Node: TXmlNode; tc: TzkpTaxControls);
(* 解析返回的发票库存信息 *)
procedure AnalyzeReportXml_II(Node: TXmlNode; aList: TzkpInvoiceInventories);
(* 解析“通用发票”应答报文到实体类 *)
function AnalyzeReportXml_TY_Filter(Node: TXmlNode): TcmdResRmtComm;
(* 解析“卷式发票”应答报文到实体类 *)
function AnalyzeReportXml_JS_Filter(Node: TXmlNode): TcmdResRmtComm;
(* 解析“不动产发票”应答报文到实体类 *)
function AnalyzeReportXml_XS_Filter(Node: TXmlNode): TcmdResRmtComm;
(* 解析“建安发票”应答报文到实体类 *)
function AnalyzeReportXml_JZ_Filter(Node: TXmlNode): TcmdResRmtComm;
(* 解析返回的开票点信息列表到实体类 *)
procedure AnalyzeReportXml_Kpd(Node: TXmlNode; Regs: TzkpRegistrations);
(* 解析返回的项目信息列表到实体类 *)
procedure AnalyzeReportXml_Project(Node: TXmlNode; Proj: TzkpProjects);
(* 解析返回建安开票选择合同查询时的建安合同信息列表到实体类 *)
procedure AnalyzeReportXml_JaHt_KpCx(Node: TXmlNode; Objs: TzkpJaHts);
{$ENDREGION}
implementation
{$REGION '组织请求报文:CreateSendXmlReport'}
// 通用发票开具、红冲请求报文
procedure Component2XmlNode_TY_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
var
I: Integer;
Fpdata: TzkNSR_ZK_FPSJ_TY;
begin
Fpdata := TzkNSR_ZK_FPSJ_TY(dlySerializeXml.dlyComponentLoadFromString(TcmdReqRC_IR_KJHC(aObj).Invoice.Data.Value));
try
with Node, Fpdata do
begin
Node.Name := 'T_FP_MQKP';
NodeNew('KP_XH').ValueUnicode := FP_DM + FP_HM;
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('SWJG_DM').ValueUnicode := SWJG_DM;
NodeNew('CK_DM').ValueUnicode := CK_DM;
NodeNew('KPR_DM').ValueUnicode := KPR_DM;
NodeNew('KP_SJ').ValueUnicode := KJ_SJAsString;
NodeNew('G_SWDJH').ValueUnicode := FKF_BM;
NodeNew('G_MC').ValueUnicode := FKF_MC;
NodeNew('SE_JE').ValueAsFloat := 0;
NodeNew('SPHM').ValueUnicode := '';
NodeNew('SP_LX').ValueUnicode := '';
NodeNew('PZZB_DM').ValueUnicode := '';
NodeNew('FP_JE').ValueUnicode := FloatToStr(KJ_JE);
NodeNew('JBR').ValueUnicode := KPR;
NodeNew('SSWCGLZMZGHM').ValueUnicode := '';
NodeNew('SKR_DM').ValueUnicode := SKR_DM;
NodeNew('DZ').ValueUnicode := '';
NodeNew('DY_BJ').ValueUnicode := DY_BJ;
NodeNew('ZF_BJ').ValueUnicode := ZF_BJ;
NodeNew('LR_SJ').ValueUnicode := LR_SJAsString;
NodeNew('XG_SJ').ValueUnicode := XG_SJAsString;
NodeNew('JEXX').ValueUnicode := '';
NodeNew('SPXX').ValueUnicode := '';
NodeNew('JMWSH').ValueUnicode := '';
NodeNew('JMYY').ValueUnicode := '';
NodeNew('NSRNBM').ValueUnicode := NSR_NBM;
NodeNew('NSRMC').ValueUnicode := NSR_MC;
NodeNew('FKRDZ').ValueUnicode := FKRDZ;
NodeNew('SKRDZ').ValueUnicode := SKR_DZ;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('GBFSJPZ_HM').ValueUnicode := '';
NodeNew('ZJ_HM').ValueUnicode := '';
NodeNew('GBF').ValueUnicode := '0';
NodeNew('DKFPSQHM').ValueUnicode := '';
NodeNew('GBFHZSJ_HM').ValueUnicode := '';
NodeNew('SKM').ValueUnicode := SKM;
NodeNew('BZ').ValueUnicode := BZ;
NodeNew('SC_BJ').ValueUnicode := '0';
NodeNew('HC_BJ').ValueUnicode := HC_BJ;
NodeNew('HC_SJ').ValueUnicode := HC_SJAsString;
NodeNew('HC_FPZLDM').ValueUnicode := HC_FPZL_DM;
NodeNew('HC_FPDM').ValueUnicode := HC_FP_DM;
NodeNew('HC_FPHM').ValueUnicode := HC_FP_HM;
NodeNew('HC_JBR').ValueUnicode := HC_JBR;
NodeNew('HYFLMC').ValueUnicode := HYFLMC;
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
NodeNew('KPLX').ValueUnicode := KPLX;
end;
// 添加明细信息节点
with Fpdata, Fpdata.MXs, Node.NodeNew('MXS') do
begin
for I := 0 to ItemCount - 1 do
begin
with NodeNew('T_FP_MQKPMX') do
begin
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('JYXM').ValueUnicode := Items[I].JYXM;
NodeNew('ZY').ValueUnicode := '';
NodeNew('JLDW_DM').ValueUnicode := Items[I].JLDW_DM;
NodeNew('SL').ValueUnicode := '0';
NodeNew('DJ').ValueUnicode := '0';
NodeNew('JE').ValueUnicode := FloatToStr(Items[I].JE);
NodeNew('LR_SJ').ValueUnicode := LR_SJAsString;
NodeNew('XG_SJ').ValueUnicode := XG_SJAsString;
NodeNew('MX_XH').ValueUnicode := IntToStr(Items[I].MX_XH);
NodeNew('PZZL_DM').ValueUnicode := '';
NodeNew('PZZB_DM').ValueUnicode := '';
NodeNew('PZHM').ValueUnicode := '';
end;
end;
end;
finally
Fpdata.Free;
end;
end;
// 卷式发票开具、红冲请求报文
procedure Component2XmlNode_JS_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
var
I: Integer;
Fpdata: TzkNSR_ZK_FPSJ_JS;
begin
Fpdata := TzkNSR_ZK_FPSJ_JS(dlySerializeXml.dlyComponentLoadFromString(TcmdReqRC_IR_KJHC(aObj).Invoice.Data.Value));
with Node, Fpdata do
begin
Node.Name := 'T_FP_XPKP';
NodeNew('KP_XH').ValueUnicode := KP_XH;
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('SWJG_DM').ValueUnicode := SWJG_DM;
NodeNew('CK_DM').ValueUnicode := CK_DM;
NodeNew('KPR_DM').ValueUnicode := KPR_DM;
NodeNew('KP_SJ').ValueUnicode := KJ_SJAsString;
NodeNew('G_SWDJH').ValueUnicode := FKF_BM;
NodeNew('G_MC').ValueUnicode := FKF_MC;
NodeNew('SE_JE').ValueAsFloat := 0;
NodeNew('SPHM').ValueUnicode := '';
NodeNew('SP_LX').ValueUnicode := '';
NodeNew('PZZB_DM').ValueUnicode := '';
NodeNew('FP_JE').ValueUnicode := FloatToStr(KJ_JE);
NodeNew('JBR').ValueUnicode := KPR;
NodeNew('SSWCGLZMZGHM').ValueUnicode := '';
NodeNew('DZ').ValueUnicode := '';
NodeNew('DY_BJ').ValueUnicode := DY_BJ;
NodeNew('ZF_BJ').ValueUnicode := ZF_BJ;
NodeNew('LR_SJ').ValueUnicode := LR_SJAsString;
NodeNew('XG_SJ').ValueUnicode := XG_SJAsString;
NodeNew('JEXX').ValueUnicode := '';
NodeNew('SPXX').ValueUnicode := '';
NodeNew('JMWSH').ValueUnicode := '';
NodeNew('JMYY').ValueUnicode := '';
NodeNew('NSRNBM').ValueUnicode := NSR_NBM;
NodeNew('NSRMC').ValueUnicode := NSR_MC;
NodeNew('FKRDZ').ValueUnicode := FKRDZ;
NodeNew('SKRDZ').ValueUnicode := SKRDZ;
NodeNew('GBFSJPZ_HM').ValueUnicode := '';
NodeNew('ZJ_HM').ValueUnicode := '';
NodeNew('GBF').ValueUnicode := '0';
NodeNew('DKFPSQHM').ValueUnicode := '';
NodeNew('GBFHZSJ_HM').ValueUnicode := '';
NodeNew('SKM').ValueUnicode := SKM;
NodeNew('BZ').ValueUnicode := BZ;
NodeNew('SC_BJ').ValueUnicode := '0';
NodeNew('HC_BJ').ValueUnicode := HC_BJ;
NodeNew('HC_SJ').ValueUnicode := HC_SJAsString;
NodeNew('HC_FPZLDM').ValueUnicode := HC_FPZL_DM;
NodeNew('HC_FPDM').ValueUnicode := HC_FP_DM;
NodeNew('HC_FPHM').ValueUnicode := HC_FP_HM;
NodeNew('HC_JBR').ValueUnicode := HC_JBR;
NodeNew('SKR_DM').ValueUnicode := SKR_DM;
NodeNew('HYFLMC').ValueUnicode := HYFLMC;
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
NodeNew('KPLX').ValueUnicode := KPLX;
end;
// 添加明细信息节点
with Fpdata, Fpdata.MXs, Node.NodeNew('MXS') do
begin
for I := 0 to ItemCount - 1 do
begin
with NodeNew('T_FP_XPKPMX') do
begin
NodeNew('KP_XH').ValueUnicode := Items[I].KP_XH;
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('JYXM').ValueUnicode := Items[I].JYXM;
NodeNew('ZY').ValueUnicode := '';
NodeNew('JLDW_DM').ValueUnicode := Items[I].JLDW_DM;
NodeNew('SL').ValueUnicode := '0';
NodeNew('DJ').ValueUnicode := '0';
NodeNew('JE').ValueUnicode := FloatToStr(Items[I].JE);
NodeNew('LR_SJ').ValueUnicode := FormatDateTime(SFormatDataTime,
Items[I].LR_SJ);
NodeNew('XG_SJ').ValueUnicode := FormatDateTime(SFormatDataTime,
Items[I].XG_SJ);
NodeNew('MX_XH').ValueUnicode := IntToStr(Items[I].MX_XH);
NodeNew('PZZL_DM').ValueUnicode := '';
NodeNew('PZZB_DM').ValueUnicode := '';
NodeNew('PZHM').ValueUnicode := '';
end;
end;
end;
end;
// 不动产发票开具、红冲请求报文
procedure Component2XmlNode_XS_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
var
I: Integer;
Fpdata: TzkNSR_ZK_FPSJ_XS;
begin
Fpdata := TzkNSR_ZK_FPSJ_XS(dlySerializeXml.dlyComponentLoadFromString(TcmdReqRC_IR_KJHC(aObj).Invoice.Data.Value));
with Node, Fpdata do
begin
Node.Name := 'T_FP_ZKXSBDCFP';
NodeNew('KP_XH').ValueUnicode := KP_XH;
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('SWJG_DM').ValueUnicode := SWJG_DM;
NodeNew('KPR').ValueUnicode := KPR;
NodeNew('KP_SJ').ValueUnicode := KJ_SJAsString;
NodeNew('FKFBM').ValueUnicode := FKF_BM;
NodeNew('FKFMC').ValueUnicode := FKF_MC;
NodeNew('DY_BJ').ValueUnicode := DY_BJ;
NodeNew('ZF_BJ').ValueUnicode := ZF_BJ;
NodeNew('NSRNBM').ValueUnicode := NSR_NBM;
NodeNew('NSRMC').ValueUnicode := NSR_MC;
NodeNew('FKRDZ').ValueUnicode := FKRDZ;
NodeNew('SKRDZ').ValueUnicode := SKRDZ;
NodeNew('HZFPZL_DM').ValueUnicode := HC_FPZL_DM;
NodeNew('HZFP_DM').ValueUnicode := HC_FP_DM;
NodeNew('HZFP_HM').ValueUnicode := HC_FP_HM;
NodeNew('KJ_ZJE').ValueUnicode := FloatToStr(KJ_JE);
NodeNew('BZ').ValueUnicode := BZ;
NodeNew('MM').ValueUnicode := SKM;
NodeNew('LR_SJ').ValueUnicode := LR_SJAsString;
NodeNew('XG_SJ').ValueUnicode := XG_SJAsString;
NodeNew('FKFZJLX').ValueUnicode := FKFZJLX;
NodeNew('KPLX').ValueUnicode := KPLX;
NodeNew('HC_BJ').ValueUnicode := HC_BJ;
NodeNew('HC_SJ').ValueUnicode := HC_SJAsString;
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
end;
with Node.NodeNew('MXS'), Fpdata, Fpdata.MXs do
begin
for I := 0 to ItemCount - 1 do
begin
with NodeNew('T_FP_ZKXSBDCFPMX') do
begin
NodeNew('KP_XH').ValueUnicode := Items[I].KP_XH;
NodeNew('MX_XH').ValueUnicode := IntToStr(Items[I].MX_XH);
NodeNew('BDCXMMC').ValueUnicode := Items[I].BDCXMMC;
NodeNew('BDCXMBH').ValueUnicode := Items[I].BDCXMBH;
NodeNew('XSDBDCLPH').ValueUnicode := Items[I].XSDBDCLPH;
NodeNew('JSLX').ValueUnicode := Items[I].JSLX;
NodeNew('JZMJ').ValueUnicode := FloatToStr(Items[I].JZMJ);
NodeNew('DJ').ValueUnicode := FloatToStr(Items[I].DJ);
NodeNew('JE').ValueUnicode := FloatToStr(Items[I].JE);
NodeNew('KXXZ').ValueUnicode := Items[I].KXXZ;
NodeNew('XZMS').ValueUnicode := Items[I].XZMS;
NodeNew('LR_SJ').ValueUnicode := FormatDateTime(SFormatDataTime, Items[I].LR_SJ);
NodeNew('XG_SJ').ValueUnicode := FormatDateTime(SFormatDataTime, Items[I].XG_SJ);
NodeNew('KPLX').ValueUnicode := Items[I].KPLX;
NodeNew('FY_ID').ValueUnicode := Items[I].FY_ID;
end;
end;
end;
end;
// 建安发票开具、红冲请求报文
procedure Component2XmlNode_JZ_KJHC(Node: TXmlNode; aObj: TcmdReqRmtComm);
var
I: Integer;
Fpdata: TzkNSR_ZK_FPSJ_JZ;
begin
Fpdata := TzkNSR_ZK_FPSJ_JZ(dlySerializeXml.dlyComponentLoadFromString(TcmdReqRC_IR_KJHC(aObj).Invoice.Data.Value));
with Node, Fpdata do
begin
Node.Name := 'T_FP_ZKJAFP';
NodeNew('KP_XH').ValueUnicode := KP_XH;
NodeNew('FPZL_DM').ValueUnicode := FPZL_DM;
NodeNew('FP_DM').ValueUnicode := FP_DM;
NodeNew('FP_HM').ValueUnicode := FP_HM;
NodeNew('SWJG_DM').ValueUnicode := SWJG_DM;
NodeNew('KPR').ValueUnicode := KPR;
NodeNew('KP_SJ').ValueUnicode := KJ_SJAsString;
NodeNew('FKFBM').ValueUnicode := FKF_BM;
NodeNew('FKFMC').ValueUnicode := FKF_MC;
NodeNew('KJ_ZJE').ValueUnicode := FloatToStr(KJ_JE);
NodeNew('ZBRBJ').ValueUnicode := ZBRBJ;
NodeNew('FBRBJ').ValueUnicode := FBRBJ;
NodeNew('DY_BJ').ValueUnicode := DY_BJ;
NodeNew('ZF_BJ').ValueUnicode := ZF_BJ;
NodeNew('LR_SJ').ValueUnicode := LR_SJAsString;
NodeNew('XG_SJ').ValueUnicode := XG_SJAsString;
NodeNew('NSRNBM').ValueUnicode := NSR_NBM;
NodeNew('NSRMC').ValueUnicode := NSR_MC;
NodeNew('FKRDZ').ValueUnicode := FKRDZ;
NodeNew('SKRDZ').ValueUnicode := SKRDZ;
NodeNew('BZ').ValueUnicode := BZ;
NodeNew('HZFPZL_DM').ValueUnicode := HC_FPZL_DM;
NodeNew('HZFP_DM').ValueUnicode := HC_FP_DM;
NodeNew('HZFP_HM').ValueUnicode := HC_FP_HM;
NodeNew('FKFZJLX').ValueUnicode := FKFZJLX;
NodeNew('SKM').ValueUnicode := SKM;
NodeNew('HC_BJ').ValueUnicode := HC_BJ;
NodeNew('HC_SJ').ValueUnicode := HC_SJAsString;
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
NodeNew('KPLX').ValueUnicode := KPLX;
NodeNew('ISJSFP').ValueUnicode := ISJSFP;
end;
// 添加明细信息节点
with Fpdata, Fpdata.MXs, Node.NodeNew('MXS') do
begin
for I := 0 to ItemCount - 1 do
begin
with NodeNew('T_FP_ZKJAFPMX') do
begin
NodeNew('KP_XH').ValueUnicode := Items[I].KP_XH;
NodeNew('MX_XH').ValueUnicode := IntToStr(Items[I].MX_XH);
NodeNew('JYXMMC').ValueUnicode := Items[I].JYXMMC;
NodeNew('JYXMBH').ValueUnicode := Items[I].JYXMBH;
NodeNew('HTBH').ValueUnicode := Items[I].HTBH;
NodeNew('JSXM').ValueUnicode := Items[I].JSXM;
NodeNew('JE').ValueUnicode := FloatToStr(Items[I].JE);
NodeNew('DKDJWSPZHM').ValueUnicode := Items[I].DKDJWSPZHM;
NodeNew('LR_SJ').ValueUnicode := FormatDateTime(SFormatDataTime, Items[I].LR_SJ);
NodeNew('XG_SJ').ValueUnicode := FormatDateTime(SFormatDataTime, Items[I].XG_SJ);
NodeNew('ZXMBH').ValueUnicode := Items[I].ZXMBH;
NodeNew('JSXMDM').ValueUnicode := Items[I].JSXMDM;
//NodeNew('KPLX').ValueUnicode := Items[I].KPLX;
end;
end;
end;
end;
// 组织开票点注册、修改提交报文
procedure Component2XmlNode_Kpd(Node: TXmlNode; Reg: TzkpRegistration);
begin
with Node, Reg do
begin
Node.Name := 'T_CS_KPD';
NodeNew('UNIQUE_ID').ValueUnicode := Unique_ID;
NodeNew('KPD_DM').ValueUnicode := KPD_DM;
NodeNew('KPD_MC').ValueUnicode := KPD_MC;
NodeNew('KPD_LXR').ValueUnicode := KPD_LXR;
NodeNew('KPD_LXDH').ValueUnicode := KPD_LXDH;
NodeNew('TY_BJ').ValueUnicode := IntToStr(Integer(TY_BJ));
NodeNew('KPDTYPE').ValueUnicode := IntToStr(Ord(KPDTYPE));
NodeNew('BIOSCODE').ValueUnicode := BIOSCODE;
NodeNew('KPD_LXDZ').ValueUnicode := KPD_LXDZ;
NodeNew('NSRNBM').ValueUnicode := NSRNBM;
NodeNew('NSRBM').ValueUnicode := NSRBM;
NodeNew('NSRMC').ValueUnicode := NSRMC;
NodeNew('REGISTDATE').ValueUnicode := FormatDateTime(SFormatDataTime, REGISTDATE);
NodeNew('NSRSBM').ValueUnicode := NSRSBM;
NodeNew('ZCDZ').ValueUnicode := ZCDZ;
NodeNew('GLJG_DM').ValueUnicode := GLJG_DM;
NodeNew('GLJG_MC').ValueUnicode := GLJG_MC;
WriteInteger('SYNSIGN', SYNSIGN);
end;
end;
procedure Component2XmlNode_Kpr(Node: TXmlNode; Kpr: TzkKPR);
begin
with Node, Kpr do
begin
Node.Name := 'T_CS_MANAGER';
NodeNew('KEYID').ValueUnicode := Unique_ID;
NodeNew('LOGINID').ValueUnicode := ID;
NodeNew('LOGINPASS').ValueUnicode := PW;
NodeNew('MANAGERNAME').ValueUnicode := Kpr.Name;
NodeNew('STATUS').ValueAsInteger := Integer(Locked);
NodeNew('REMARK').ValueUnicode := REMARK;
NodeNew('NSRBM').ValueUnicode := NSRBM;
NodeNew('ISSUPER').ValueAsInteger := Integer(IsSuper);
NodeNew('KPD_ID').ValueUnicode := KPD_ID;
NodeNew('BIOSCODE').ValueUnicode := BIOSCODE;
end;
end;
{$ENDREGION}
{$REGION '解析返回报文:AnalyzeReportXml'}
// 通用发票报文解析
function AnalyzeReportXml_TY_Filter(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
FpData: TzkNSR_ZK_FPSJ_TY;
begin
FpData := TzkNSR_ZK_FPSJ_TY.Create;
try
with Node, FpData do
begin
FPZL_DM := ReadString('FPZL_DM');
FP_HM := ReadString('FP_HM');
SWJG_DM := ReadString('SWJG_DM');
CK_DM := ReadString('CK_DM');
KPR_DM := ReadString('KPR_DM');
KJ_SJ := StrToDateTime(ReadString('KP_SJ'));
FKF_BM := ReadString('G_SWDJH');
FKF_MC := ReadString('G_MC');
// NodeByName('SE_JE').ValueAsFloat := 0;
// NodeByName('SPHM').ValueUnicode := '';
// NodeByName('SP_LX').ValueUnicode := '';
// NodeByName('PZZB_DM').ValueUnicode := '';
KJ_JE := StrToFloatDef(ReadString('FP_JE'), 0);
KPR := ReadString('JBR');
// NodeByName('SSWCGLZMZGHM').ValueUnicode := '';
SKR_DM := ReadString('SKR_DM');
// NodeByName('DZ').ValueUnicode := '';
DY_BJ := ReadString('DY_BJ');
ZF_BJ := ReadString('ZF_BJ');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
// NodeByName('JEXX').ValueUnicode := '';
// NodeByName('SPXX').ValueUnicode := '';
// NodeByName('JMWSH').ValueUnicode := '';
// NodeByName('JMYY').ValueUnicode := '';
NSR_NBM := ReadString('NSRNBM');
NSR_MC := ReadString('NSRMC');
FKRDZ := ReadString('FKRDZ');
SKR_DZ := ReadString('SKRDZ');
FP_DM := ReadString('FP_DM');
// NodeByName('GBFSJPZ_HM').ValueUnicode := '';
// NodeByName('ZJ_HM').ValueUnicode := '';
// NodeByName('GBF').ValueUnicode := '0';
// NodeByName('DKFPSQHM').ValueUnicode := '';
// NodeByName('GBFHZSJ_HM').ValueUnicode := '';
SKM := ReadString('SKM');
BZ := ReadString('BZ');
// NodeByName('SC_BJ').ValueUnicode := '0';
HC_BJ := ReadString('HC_BJ');
if ReadString('HC_SJ') <> '' then
HC_SJ := StrToDateTime(ReadString('HC_SJ'));
HC_FPZL_DM := ReadString('HC_FPZLDM');
HC_FP_DM := ReadString('HC_FPDM');
HC_FP_HM := ReadString('HC_FPHM');
HC_JBR := ReadString('HC_JBR');
HYFLMC := ReadString('HYFLMC');
KPD_ID := ReadString('KPD_ID');
end;
// 读取明细信息节点
with Node.NodeByName('MXS') do
begin
for I := 0 to NodeCount - 1 do
begin
with Nodes[I], TzkNSR_ZK_FPSJ_MX_TY(FpData.MXs.AddNew) do
begin
JYXM := ReadString('JYXM');
MX_XH := ReadInteger('MX_XH');
SL := ReadFloat('SL');
DJ := ReadFloat('DJ');
JE := ReadFloat('JE');
JLDW_DM := ReadString('JLDW_DM');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
// NodeByName('FPZL_DM').ValueUnicode := FPZL_DM;
// NodeByName('FP_DM').ValueUnicode := FP_DM;
// NodeByName('FP_HM').ValueUnicode := FP_HM;
// NodeByName('ZY').ValueUnicode := '';
// NodeByName('XG_SJ').ValueUnicode := XG_SJAsString;
// NodeByName('PZZL_DM').ValueUnicode := '';
// NodeByName('PZZB_DM').ValueUnicode := '';
// NodeByName('PZHM').ValueUnicode := '';
end;
end;
end;
Result := TcmdResRC_IR_Get.Create;
with TcmdResRC_IR_Get(Result).Invoice do
begin
Properties.Category_Code := FpData.FPZL_DM;
Properties.Code := FpData.FP_DM;
Properties.NO := FpData.FP_HM;
Payer_Code := FpData.FKF_BM;
Payer_Name := FpData.FKF_MC;
Realty_Project_Code := '';
Realty_NO := '';
Realty_Payment_Type := -1;
Amount := FpData.KJ_JE;
if FpData.ZF_BJ = '1' then
Status := isCancelled
else if FpData.HC_BJ = '1' then
Status := isStriked
else
Status := isNormal;
Data.Value := dlySerializeXml.dlyComponentSaveToString(FpData);
end;
finally
FpData.Free;
end;
end;
// 卷式发票报文
function AnalyzeReportXml_JS_Filter(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
FpData: TzkNSR_ZK_FPSJ_JS;
begin
FpData := TzkNSR_ZK_FPSJ_JS.Create;
try
with Node, FpData do
begin
KP_XH := ReadString('KP_XH');
FPZL_DM := ReadString('FPZL_DM');
FP_DM := ReadString('FP_DM');
FP_HM := ReadString('FP_HM');
SWJG_DM := ReadString('SWJG_DM');
CK_DM := ReadString('CK_DM');
KPR_DM := ReadString('KPR_DM');
KJ_SJ := StrToDateTime(ReadString('KP_SJ'));
FKF_BM := ReadString('G_SWDJH');
FKF_MC := ReadString('G_MC');
SE_JE := ReadFloat('SE_JE');
SPHM := ReadString('SPHM');
SP_LX := ReadString('SP_LX');
PZZB_DM := ReadString('PZZB_DM');
KJ_JE := ReadFloat('FP_JE');
KPR := ReadString('JBR');
SSWCGLZMZGHM := ReadString('SSWCGLZMZGHM');
DZ := ReadString('DZ');
DY_BJ := ReadString('DY_BJ');
ZF_BJ := ReadString('ZF_BJ');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
JEXX := ReadString('JEXX');
SPXX := ReadString('SPXX');
JMWSH := StrToIntDef(ReadString('JMWSH'), 0);
JMYY := ReadString('JMYY');
NSR_NBM := ReadString('NSRNBM');
NSR_MC := ReadString('NSRMC');
FKRDZ := ReadString('FKRDZ');
SKRDZ := ReadString('SKRDZ');
GBFSJPZ_HM := ReadString('GBFSJPZ_HM');
ZJ_HM := ReadString('ZJ_HM');
GBF := ReadFloat('GBF');
DKFPSQHM := ReadString('DKFPSQHM');
GBFHZSJ_HM := ReadString('GBFHZSJ_HM');
SKM := ReadString('SKM');
BZ := ReadString('BZ');
SC_BJ := ReadString('SC_BJ');
HC_BJ := ReadString('HC_BJ');
if ReadString('HC_SJ') <> '' then
HC_SJ := StrToDateTime(ReadString('HC_SJ'));
HC_FPZL_DM := ReadString('HC_FPZLDM');
HC_FP_DM := ReadString('HC_FPDM');
HC_FP_HM := ReadString('HC_FPHM');
HC_JBR := ReadString('HC_JBR');
SKR_DM := ReadString('SKR_DM');
HYFLMC := ReadString('HYFLMC');
KPD_ID := ReadString('KPD_ID');
end;
// 添加明细信息节点
with Node.NodeByName('MXS') do
begin
for I := 0 to NodeCount - 1 do
begin
with Nodes[I], TzkNSR_ZK_FPSJ_MX_JS(FpData.MXs.AddNew) do
begin
KP_XH := ReadString('KP_XH');
FPZL_DM := ReadString('FPZL_DM');
FP_DM := ReadString('FP_DM');
FP_HM := ReadString('FP_HM');
JYXM := ReadString('JYXM');
ZY := ReadString('ZY');
JLDW_DM := ReadString('JLDW_DM');
SL := ReadFloat('SL');
DJ := ReadFloat('DJ');
JE := ReadFloat('JE');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
MX_XH := ReadInteger('MX_XH');
PZZL_DM := ReadString('PZZL_DM');
PZZB_DM := ReadString('');
PZHM := ReadString('PZHM');
end;
end;
end;
Result := TcmdResRC_IR_Get.Create;
with TcmdResRC_IR_Get(Result).Invoice do
begin
Properties.Category_Code := FpData.FPZL_DM;
Properties.Code := FpData.FP_DM;
Properties.NO := FpData.FP_HM;
Payer_Code := FpData.FKF_BM;
Payer_Name := FpData.FKF_MC;
Realty_Project_Code := '';
Realty_NO := '';
Realty_Payment_Type := -1;
Amount := FpData.KJ_JE;
if FpData.ZF_BJ = '1' then
Status := isCancelled
else if FpData.HC_BJ = '1' then
Status := isStriked
else
Status := isNormal;
Data.Value := dlySerializeXml.dlyComponentSaveToString(FpData);
end;
finally
FpData.Free;
end;
end;
// 建筑业发票报文解析
function AnalyzeReportXml_JZ_Filter(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
FpData: TzkNSR_ZK_FPSJ_JZ;
begin
FpData := TzkNSR_ZK_FPSJ_JZ.Create;
try
with Node, FpData do
begin
KP_XH := ReadString('KP_XH');
FPZL_DM := ReadString('FPZL_DM');
FP_DM := ReadString('FP_DM');
FP_HM := ReadString('FP_HM');
SWJG_DM := ReadString('SWJG_DM');
KPR := ReadString('KPR');
KJ_SJ := StrToDateTime(ReadString('KP_SJ'));
FKF_BM := ReadString('FKFBM');
FKF_MC := ReadString('FKFMC');
KJ_JE := ReadFloat('KJ_ZJE');
ZBRBJ := ReadString('ZBRBJ');
FBRBJ := ReadString('FBRBJ');
DY_BJ := ReadString('DY_BJ');
ZF_BJ := ReadString('ZF_BJ');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
NSR_NBM := ReadString('NSRNBM');
NSR_MC := ReadString('NSRMC');
FKRDZ := ReadString('FKRDZ');
SKRDZ := ReadString('SKRDZ');
BZ := ReadString('BZ');
HC_FPZL_DM := ReadString('HZFPZL_DM');
HC_FP_DM := ReadString('HZFP_DM');
HC_FP_HM := ReadString('HZFP_HM');
FKFZJLX := ReadString('FKFZJLX');
SKM := ReadString('SKM');
HC_BJ := ReadString('HC_BJ');
if ReadString('HC_SJ') <> '' then
HC_SJ := StrToDateTime(ReadString('HC_SJ'));
KPD_ID := ReadString('KPD_ID');
ISJSFP := ReadString('ISJSFP');
KPLX := ReadString('KPLX');
end;
// 添加明细信息节点
with Node.NodeByName('MXS') do
begin
for I := 0 to NodeCount - 1 do
begin
with Nodes[I], TzkNSR_ZK_FPSJ_MX_JZ(FpData.MXs.AddNew) do
begin
KP_XH := ReadString('KP_XH');
MX_XH := ReadInteger('MX_XH');
JYXMMC := ReadString('JYXMMC');
JYXMBH := ReadString('JYXMBH');
HTBH := ReadString('HTBH');
JSXM := ReadString('JSXM');
JE := ReadFloat('JE');
DKDJWSPZHM := ReadString('DKDJWSPZHM');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
ZXMBH := ReadString('ZXMBH');
JSXMDM := ReadString('JSXMDM');
end;
end;
end;
Result := TcmdResRC_IR_Get.Create;
with TcmdResRC_IR_Get(Result).Invoice do
begin
Properties.Category_Code := FpData.FPZL_DM;
Properties.Code := FpData.FP_DM;
Properties.NO := FpData.FP_HM;
Payer_Code := FpData.FKF_BM;
Payer_Name := FpData.FKF_MC;
Realty_Project_Code := '';
Realty_NO := '';
Realty_Payment_Type := -1;
Amount := FpData.KJ_JE;
if FpData.ZF_BJ = '1' then
Status := isCancelled
else if FpData.HC_BJ = '1' then
Status := isStriked
else
Status := isNormal;
Data.Value := dlySerializeXml.dlyComponentSaveToString(FpData);
end;
finally
FpData.Free;
end;
end;
// 销售不动产返回报文解析
function AnalyzeReportXml_XS_Filter(Node: TXmlNode): TcmdResRmtComm;
var
I: Integer;
Fpdata: TzkNSR_ZK_FPSJ_XS;
begin
Fpdata := TzkNSR_ZK_FPSJ_XS.Create;
try
with Node, Fpdata do
begin
KP_XH := ReadString('KP_XH');
FPZL_DM := ReadString('FPZL_DM');
FP_DM := ReadString('FP_DM');
FP_HM := ReadString('FP_HM');
SWJG_DM := ReadString('SWJG_DM');
KPR := ReadString('KPR');
KJ_SJ := StrToDateTime(ReadString('KP_SJ'));
FKF_BM := ReadString('FKFBM');
FKF_MC := ReadString('FKFMC');
DY_BJ := ReadString('DY_BJ');
ZF_BJ := ReadString('ZF_BJ');
NSR_NBM := ReadString('NSRNBM');
NSR_MC := ReadString('NSRMC');
FKRDZ := ReadString('FKRDZ');
SKRDZ := ReadString('SKRDZ');
HC_FPZL_DM := ReadString('HZFPZL_DM');
HC_FP_DM := ReadString('HZFP_DM');
HC_FP_HM := ReadString('HZFP_HM');
KJ_JE := ReadFloat('KJ_ZJE');
BZ := ReadString('BZ');
SKM := ReadString('MM');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
FKFZJLX := ReadString('FKFZJLX');
KPLX := ReadString('KPLX');
HC_BJ := ReadString('HC_BJ');
if ReadString('HC_SJ') <> '' then
HC_SJ := StrToDateTime(ReadString('HC_SJ'));
KPD_ID := ReadString('KPD_ID');
end;
// 添加明细信息节点
with Node.NodeByName('MXS') do
begin
for I := 0 to NodeCount - 1 do
begin
with Nodes[I], TzkNSR_ZK_FPSJ_MX_XS(Fpdata.MXs.AddNew) do
begin
KP_XH := ReadString('KP_XH');
MX_XH := ReadInteger('MX_XH');
BDCXMMC := ReadString('BDCXMMC');
BDCXMBH := ReadString('BDCXMBH');
XSDBDCLPH := ReadString('XSDBDCLPH');
JSLX := ReadString('JSLX');
JZMJ := ReadFloat('JZMJ');
DJ := ReadFloat('DJ');
JE := ReadFloat('JE');
KXXZ := ReadString('KXXZ');
XZMS := ReadString('XZMS');
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
if ReadString('XG_SJ') <> '' then
XG_SJ := StrToDateTime(ReadString('XG_SJ'));
KPLX := ReadString('KPLX');
FY_ID := ReadString('FY_ID');
end;
end;
end;
Result := TcmdResRC_IR_Get.Create;
with TcmdResRC_IR_Get(Result).Invoice do
begin
Properties.Category_Code := FpData.FPZL_DM;
Properties.Code := FpData.FP_DM;
Properties.NO := FpData.FP_HM;
Payer_Code := FpData.FKF_BM;
Payer_Name := FpData.FKF_MC;
Realty_Project_Code := Fpdata.MXs.Items[0].BDCXMBH;
Realty_NO := Fpdata.MXs.Items[0].XSDBDCLPH;
Realty_Payment_Type := StrToInt(Fpdata.MXs.Items[0].KXXZ);
Amount := FpData.KJ_JE;
if FpData.ZF_BJ = '1' then
Status := isCancelled
else if FpData.HC_BJ = '1' then
Status := isStriked
else
Status := isNormal;
Data.Value := dlySerializeXml.dlyComponentSaveToString(FpData);
end;
finally
Fpdata.Free
end;
end;
// 税控信息设置 初始化
procedure AnalyzeReportXml_TaxControl(Node: TXmlNode; tc: TzkpTaxControls);
procedure SetTaxControlsData(aNode: TXmlNode);
var
I: Integer;
begin
for I := 0 to aNode.NodeCount - 1 do
begin
with aNode.Nodes[I], TzkpTaxControl(tc.AddNew) do
begin
NSRNBM := ReadString('NSRNBM');
FPZL_DM := ReadString('FPZL_DM');
DZ_KJXE := ReadFloat('DZ_XE');
KJ_ZXE := ReadFloat('ZD_XE');
ZF_BJ := Boolean(ReadInteger('ZF_BJ'));
DZ_ZFXE := ReadFloat('DZ_ZFXE');
ZF_ZXE := ReadFloat('ZF_ZXE');
DZ_HCXE := ReadFloat('DZ_HCXE');
HC_ZXE := ReadFloat('HC_ZXE');
KPD_ID := ReadString('KPD_ID');
IsLocked := Boolean(ReadInteger('LOCKED'));
//Unique_ID := '';
if ReadString('UNIQUE_ID') <> '' then
Unique_ID := ReadString('UNIQUE_ID');
YKJ_ZE := ReadFloat('YKJ_ZE');
YZF_ZE := ReadFloat('YZF_ZE');
YHC_ZE := ReadFloat('YHC_ZE');
end;
end;
end;
var
subNode: TXmlNode;
begin
subNode := Node.NodeByName('LIST');
if not Assigned(subNode) then Exit;
subNode := subNode.NodeByName('T_FP_NSRZKMXS');
if Assigned(subNode) then
if Assigned(subNode.NodeByName('LIST')) then
SetTaxControlsData(subNode.NodeByName('LIST'));
subNode := Node.NodeByName('LIST').NodeByName('T_FP_NSRZKMX_KPDS');
if Assigned(subNode) then
if Assigned(subNode.NodeByName('LIST')) then
SetTaxControlsData(subNode.NodeByName('LIST'));
end;
// 解析返回的发票库存信息
procedure AnalyzeReportXml_II(Node: TXmlNode; aList: TzkpInvoiceInventories);
var
I: Integer;
subNode: TXmlNode;
begin
subNode := Node.NodeByName('LIST');
if not Assigned(subNode) then Exit;
subNode := subNode.NodeByName('T_FP_NSRFPKCS');
if not Assigned(subNode) then Exit;
subNode := subNode.NodeByName('LIST');
if not Assigned(subNode) then Exit;
with subNode do
begin
for I := 0 to NodeCount - 1 do
begin
with Nodes[I], TzkpInvoiceInventory(aList.AddNew) do
begin
NSRNBM := ReadString('NSRNBM');
FPZL_DM := ReadString('FPZL_DM');
FP_DM := ReadString('FP_DM');
FP_QSHM := ReadString('FP_QSHM');
FP_ZZHM := ReadString('FP_ZZHM');
IsLocked := ReadInteger('ISLOCKED') = 1;
KPD_ID := ReadString('KPD_ID');
if ReadString('LR_SJ') <> '' then
LR_SJ := StrToDateTime(ReadString('LR_SJ'));
end;
end;
end;
end;
// 解析返回的开票点信息
procedure AnalyzeReportXml_Kpd(Node: TXmlNode; Regs: TzkpRegistrations);
var
I: Integer;
begin
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
with Nodes[I], TzkpRegistration(Regs.AddNew) do
begin
Unique_ID := ReadString('UNIQUE_ID');
KPD_DM := ReadString('KPD_DM');
KPD_MC := ReadString('KPD_MC');
KPD_LXR := ReadString('KPD_LXR');
KPD_LXDH := ReadString('KPD_LXDH');
TY_BJ := ReadInteger('TY_BJ') = 1;
KPDTYPE := TKPDType(ReadInteger('KPDTYPE'));
BIOSCODE := ReadString('BIOSCODE');
KPD_LXDZ := ReadString('KPD_LXDZ');
NSRNBM := ReadString('NSRNBM');
NSRBM := ReadString('NSRBM');
NSRMC := ReadString('NSRMC');
REGISTDATE := StrToDateTime(ReadString('REGISTDATE'));
NSRSBM := ReadString('NSRSBM');
ZCDZ := ReadString('ZCDZ');
GLJG_DM := ReadString('GLJG_DM');
GLJG_MC := ReadString('GLJG_MC');
end;
end;
procedure AnalyzeReportXml_Project(Node: TXmlNode; Proj: TzkpProjects);
var
I: Integer;
begin
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
begin
with TzkpProject(Proj.AddNew), Nodes[I] do
begin
NSRSBH := ReadString('NSRSBH');
NSR_MC := ReadString('NSR_MC');
NSRNBM := ReadString('NSRNBM');
XMDJ_DM := ReadString('XMDJ_DM');
DJJG_DM := ReadString('DJJG_DM');
GLJG_DM := ReadString('GLJG_DM');
SWGLRY_DM := ReadString('SWGLRY_DM');
DJ_ZT := ReadString('DJ_ZT');
JWDJXMM := ReadString('JWDJXMM');
XM_MC := ReadString('XM_MC');
XM_DZ := ReadString('XM_DZ');
GCZZJ_JE := ReadFloat('GCZZJ_JE');
LX_RQ := ReadDateTime('LX_RQ');
YJJG_RQ := ReadDateTime('YJJG_RQ');
XMFZR_MC := ReadString('XMFZR_MC');
XMFZRLX_DH := ReadString('XMFZRLX_DH');
DJJBR_DM := ReadString('DJJBR_DM');
DJ_RQ := ReadDateTime('DJ_RQ');
ZXJBR_DM := ReadString('ZXJBR_DM');
ZX_RQ := ReadDateTime('ZX_RQ');
SKQJ_BJ := ReadString('SKQJ_BJ');
XMYT_DM := ReadString('XMYT_DM');
WS_ZT := ReadString('WS_ZT');
XMZTZ_JE := ReadFloat('XMZTZ_JE');
YJKG_RQ := ReadDateTime('YJKG_RQ');
JZMJ := ReadFloat('JZMJ');
LRRY_DM := ReadString('LRRY_DM');
LR_SJ := ReadDateTime('LR_SJ');
XGRY_DM := ReadString('XGRY_DM');
XG_SJ := ReadDateTime('XG_SJ');
XMJZYS_JE := ReadFloat('XMJZYS_JE');
XMXZ_DM := ReadString('XMXZ_DM');
XMLX_DM := ReadString('XMLX_DM');
XMSZDGLJG := ReadString('XMSZDGLJG');
PZWH := ReadString('PZWH');
WCJYGLZM := ReadString('WCJYGLZM');
XM_JC := ReadString('XM_JC');
YJSF_SJ := ReadDateTime('YJSF_SJ');
ZDMJ := ReadFloat('ZDMJ');
XQLJL := ReadFloat('XQLJL');
XMZJZL_DM := ReadString('XMZJZL_DM');
ZJBH := ReadString('ZJBH');
FZRQ := ReadDateTime('FZRQ');
BZ := ReadString('BZ');
ZJ_XH := ReadInteger('ZJ_XH');
FZJG_DM := ReadString('FZJG_DM');
MX_XH := ReadInteger('MX_XH');
SL_LSH := ReadString('SL_LSH');
TDSYZH := ReadString('TDSYZH');
ZD_BH := ReadString('ZD_BH');
ZD_MJ := ReadFloat('ZD_MJ');
ZD_DZ := ReadString('ZD_DZ');
PROVINCE := ReadString('PROVINCE');
CITY := ReadString('CITY');
COUNTY := ReadString('COUNTY');
COUNTRY := ReadString('COUNTRY');
LY_BJ := ReadString('LY_BJ');
ZDFS_DM := ReadString('ZDFS_DM');
JY_JE := ReadFloat('JY_JE');
ZF_BJ := ReadString('ZF_BJ');
ZHDMJ := ReadFloat('ZHDMJ');
TDSYQWS := ReadString('TDSYQWS');
TDSYQWSH := ReadString('TDSYQWSH');
FKFBM := ReadString('FKFBM');
FKFMC := ReadString('FKFMC');
KPD_ID := ReadString('KPD_ID');
end;
end;
end;
procedure AnalyzeReportXml_JaHt_KpCx(Node: TXmlNode; Objs: TzkpJaHts);
var
I: Integer;
begin
if not Assigned(Node.NodeByName('LIST')) then Exit;
with Node.NodeByName('LIST') do
for I := 0 to NodeCount - 1 do
begin
with TzkpJaHt(Objs.AddNew), Nodes[I] do
begin
XMDJ_DM := ReadString('XMDJ_DM');
HT_BH := ReadString('HT_BH');
HTLX := ReadString('HTLX');
FKFS := ReadString('FKFS');
HTZJE := ReadFloat('HTZJE');
YKFPJE := ReadFloat('YKFPJE');
SFZB := ReadString('SFZB');
FB_BJ := ReadString('FB_BJ');
ZHTBH := ReadString('ZHTBH');
BC_BJ := ReadString('BC_BJ');
FKFMC := ReadString('FKFMC');
FKFBM := ReadString('FKFBM');
KJ_ZJE := ReadFloat('KJ_ZJE');
KPD_ID := ReadString('KPD_ID');
end;
end;
end;
{$ENDREGION}
end.
|
{******************************************}
{ TeeChart Pro SVG Canvas and Exporting }
{ SVG : Scalable Vector Graphics }
{ www.w3.org/Graphics/SVG }
{ }
{ Copyright (c) 2001-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeSVGCanvas;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, QForms, Types, QControls, QStdCtrls,
{$ELSE}
Graphics, Forms, Controls, StdCtrls,
{$ENDIF}
TeCanvas, TeeProcs, TeeExport;
type
TSVGCanvas = class(TTeeCanvas3D)
private
{ Private declarations }
FBackColor : TColor;
FBackMode : TCanvasBackMode;
FTextAlign : TCanvasTextAlign;
FX : Integer;
FY : Integer;
FStrings : TStrings;
IClipCount : Integer;
IClipStack : Integer;
IGradientCount : Integer;
// IPenEndStyle : TPenEndStyle;
IPenStyle : TPenStyle;
IPenWidth : Integer;
ITransp : TTeeTransparency;
Procedure Add(Const S:String);
procedure AddEnd(const s:String);
procedure ChangedPen(Sender: TObject);
Procedure InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean);
Function PointToStr(X,Y:Integer):String;
Procedure PrepareShape;
Function SVGBrushPen(UsePen:Boolean=True):String;
procedure SVGClip;
Function SVGEllipse(X1,Y1,X2,Y2:Integer):String;
procedure SVGEndClip;
Function SVGPen:String;
Function SVGPoints(const Points: Array of TPoint):String;
Function SVGRect(Const Rect:TRect):String;
Function TotalBounds:String;
protected
{ Protected declarations }
Procedure PolygonFour; override;
{ 2d }
procedure SetPixel(X, Y: Integer; Value: TColor); override;
Function GetTextAlign:TCanvasTextAlign; override;
{ 3d }
procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); override;
Procedure SetBackMode(Mode:TCanvasBackMode); override;
Procedure SetBackColor(Color:TColor); override;
Function GetBackMode:TCanvasBackMode; override;
Function GetBackColor:TColor; override;
procedure SetTextAlign(Align:TCanvasTextAlign); override;
public
{ Public declarations }
Antialias : Boolean;
DocType : String;
Constructor Create(AStrings:TStrings);
Function InitWindow( DestCanvas:TCanvas;
A3DOptions:TView3DOptions;
ABackColor:TColor;
Is3D:Boolean;
Const UserRect:TRect):TRect; override;
procedure AssignVisiblePenColor(APen:TPen; AColor:TColor); override; // 7.0
procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Draw(X, Y: Integer; Graphic: TGraphic); override;
procedure FillRect(const Rect: TRect); override;
procedure Ellipse(X1, Y1, X2, Y2: Integer); override;
procedure LineTo(X,Y:Integer); override;
procedure MoveTo(X,Y:Integer); override;
procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override;
procedure Rectangle(X0,Y0,X1,Y1:Integer); override;
procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); override;
procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); override;
Procedure TextOut(X,Y:Integer; const Text:String); override;
Procedure DoHorizLine(X0,X1,Y:Integer); override;
Procedure DoVertLine(X,Y0,Y1:Integer); override;
procedure ClipEllipse(Const Rect:TRect; Inverted:Boolean=False); override;
procedure ClipRectangle(Const Rect:TRect); override;
Procedure ClipRectangle(Const Rect:TRect; RoundSize:Integer); override;
Procedure ClipPolygon(Var Points:Array of TPoint; NumPoints:Integer); override;
procedure UnClipRectangle; override;
Function BeginBlending(const R:TRect; Transparency:TTeeTransparency):TTeeBlend; override;
procedure EndBlending(Blend:TTeeBlend); override;
Procedure GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50); override;
procedure RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); override;
procedure RotateLabel3D(x,y,z:Integer;
Const St:String; RotDegree:Double); override;
Procedure Line(X0,Y0,X1,Y1:Integer); override;
Procedure Polygon(const Points: array of TPoint); override;
{$IFDEF D5}
Procedure Polyline(const Points:Array of TPoint); override;
{$ELSE}
Procedure Polyline(const Points:TPointArray); override;
{$ENDIF}
{ 3d }
Procedure ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); override;
Procedure HorizLine3D(Left,Right,Y,Z:Integer); override;
procedure LineTo3D(X,Y,Z:Integer); override;
Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); override;
procedure MoveTo3D(X,Y,Z:Integer); override;
Procedure TextOut3D(X,Y,Z:Integer; const Text:String); override;
Procedure VertLine3D(X,Top,Bottom,Z:Integer); override;
Procedure ZLine3D(X,Y,Z0,Z1:Integer); override;
published
end;
TSVGOptions = class(TForm)
CBAntiAlias: TCheckBox;
private
{ Private declarations }
public
{ Public declarations }
end;
TSVGExportFormat=class(TTeeExportFormat)
private
Procedure CheckProperties;
protected
FProperties : TSVGOptions;
Procedure DoCopyToClipboard; override;
public
Destructor Destroy; override;
function Description:String; override;
function FileExtension:String; override;
function FileFilter:String; override;
Function SVG:TStringList;
Function Options(Check:Boolean=True):TForm; override;
Procedure SaveToStream(Stream:TStream); override;
end;
procedure TeeSaveToSVGFile( APanel:TCustomTeePanel; FileName: String;
AWidth:Integer=0; AHeight: Integer=0);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses {$IFDEF CLX}
QClipbrd,
{$ELSE}
Clipbrd,
{$ENDIF}
SysUtils;
Const TeeMsg_SVGFilter ='SVG files (*.svg)|*.svg';
{ TSVGCanvas }
Constructor TSVGCanvas.Create(AStrings:TStrings);
begin
inherited Create;
FStrings:=AStrings;
UseBuffer:=False;
Antialias:=True;
{ start }
Add('<?xml version="1.0" standalone="no"?>');
DocType:='<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
end;
Procedure TSVGCanvas.ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect);
begin { finish }
Add('</svg>');
Pen.OnChange:=nil;
end;
Procedure TSVGCanvas.Add(Const S:String);
begin
FStrings.Add(S);
end;
Function SVGColor(AColor:TColor):String;
begin
AColor:=ColorToRGB(AColor);
case AColor of
clBlack: result:='"black"';
clWhite: result:='"white"';
clRed: result:='"red"';
clGreen: result:='"green"';
clBlue: result:='"blue"';
clYellow: result:='"yellow"';
clGray: result:='"gray"';
clNavy: result:='"navy"';
clOlive: result:='"olive"';
clLime: result:='"lime"';
clTeal: result:='"teal"';
clSilver: result:='"silver"';
clPurple: result:='"purple"';
clFuchsia: result:='"fuchsia"';
clMaroon: result:='"maroon"';
else
result:='"rgb('+TeeStr(GetRValue(AColor))+','+
TeeStr(GetGValue(AColor))+','+
TeeStr(GetBValue(AColor))+')"';
end;
end;
procedure TSVGCanvas.Rectangle(X0,Y0,X1,Y1:Integer);
begin
InternalRect(TeeRect(X0,Y0,X1,Y1),True,False);
end;
procedure TSVGCanvas.MoveTo(X, Y: Integer);
begin
FX:=X;
FY:=Y;
end;
procedure TSVGCanvas.AddEnd(const s:String);
begin
Add(s+'/>');
end;
procedure TSVGCanvas.LineTo(X, Y: Integer);
var tmpSt : String;
begin
tmpSt:='<line x1="'+IntToStr(FX)+'" y1="'+IntToStr(FY)+'" '+
'x2="'+IntToStr(X)+ '" y2="'+IntToStr(Y)+'" fill="none" '+SVGPen;
AddEnd(tmpSt);
FX:=X;
FY:=Y;
end;
Function TSVGCanvas.SVGRect(Const Rect:TRect):String;
var tmp : TRect;
begin
tmp:=OrientRectangle(Rect);
with tmp do
result:=' x="'+TeeStr(Left)+'" y="'+TeeStr(Top)+'" '+
' width="'+TeeStr(Right-Left-1)+'"'+
' height="'+TeeStr(Bottom-Top-1)+'"';
end;
procedure TSVGCanvas.SVGClip;
var ClipName : String;
begin
Inc(IClipStack);
Inc(IClipCount);
ClipName:='Clip'+IntToStr(IClipCount);
Add('<g clip-path="url(#'+ClipName+')">');
Add('<defs>');
Add('<clipPath id="'+ClipName+'" style="clip-rule:nonzero">');
end;
procedure TSVGCanvas.ClipRectangle(Const Rect:TRect);
begin
SVGClip;
AddEnd('<rect '+SVGRect(Rect));
SVGEndClip;
end;
Function TSVGCanvas.SVGEllipse(X1,Y1,X2,Y2:Integer):String;
begin
result:='cx="'+IntToStr((X1+X2) div 2)+'" cy="'+IntToStr((Y1+Y2) div 2)+
'" rx="'+IntToStr((X2-X1) div 2)+'" ry="'+IntToStr((Y2-Y1) div 2)+'"';
end;
procedure TSVGCanvas.ClipEllipse(Const Rect:TRect; Inverted:Boolean=False);
begin
SVGClip;
with Rect do
AddEnd('<ellipse '+SVGEllipse(Left,Top,Right,Bottom));
SVGEndClip;
end;
Procedure TSVGCanvas.ClipPolygon(Var Points:Array of TPoint; NumPoints:Integer);
begin
SVGClip;
AddEnd('<polygon '+SVGPoints(Points));
SVGEndClip;
end;
procedure TSVGCanvas.UnClipRectangle;
begin
if IClipStack=0 then
raise exception.create('oops');
Dec(IClipStack);
Add('</g>');
end;
function TSVGCanvas.GetBackColor:TColor;
begin
result:=FBackColor;
end;
procedure TSVGCanvas.SetBackColor(Color:TColor);
begin
FBackColor:=Color;
end;
procedure TSVGCanvas.SetBackMode(Mode:TCanvasBackMode);
begin
FBackMode:=Mode;
end;
procedure TSVGCanvas.StretchDraw(const Rect: TRect; Graphic: TGraphic);
begin
end;
procedure TSVGCanvas.Draw(X, Y: Integer; Graphic: TGraphic);
begin
end;
Function TSVGCanvas.TotalBounds:String;
begin
result:='width="'+IntToStr(Bounds.Right-Bounds.Left)+'px" '+
'height="'+IntToStr(Bounds.Bottom-Bounds.Top)+'px"';
// 'viewbox="'+IntToStr(Bounds.Left)+' '+IntToStr(Bounds.Top)+' '+
// IntToStr(Bounds.Right)+' '+IntToStr(Bounds.Bottom);
end;
Function TSVGCanvas.PointToStr(X,Y:Integer):String;
begin
result:=IntToStr(X)+','+IntToStr(Y);
end;
Procedure TSVGCanvas.GradientFill( Const Rect:TRect;
StartColor,EndColor:TColor;
Direction:TGradientDirection;
Balance:Integer=50);
Function GradientTransform:String;
begin
result:='';
exit;
result:=' gradientTransform=';
// TODO:
Case Direction of
gdTopBottom : result:=result+'"rotate(270)"';
gdBottomTop : result:=result+'"rotate(90)"';
gdLeftRight : result:=result+'"rotate(180)"';
gdRightLeft : result:=result+'';
gdFromCenter : result:=result+''; { to-do }
gdFromTopLeft: result:=result+'"rotate(45)"';
else
result:=result+'"rotate(315)"';
end;
end;
var tmp : String;
begin
Inc(IGradientCount);
Add('<defs>');
Add('<linearGradient id="Gradient'+TeeStr(IGradientCount)+'" '+GradientTransform+'>');
AddEnd('<stop offset="0%" stop-color='+SVGColor(StartColor));
AddEnd('<stop offset="100%" stop-color='+SVGColor(EndColor));
Add('</linearGradient>');
Add('</defs>');
tmp:='<rect fill="url(#Gradient'+TeeStr(IGradientCount)+')" stroke="none" ';
tmp:=tmp+SVGRect(Rect);
AddEnd(tmp);
end;
procedure TSVGCanvas.FillRect(const Rect: TRect);
begin
InternalRect(Rect,False,False);
end;
Procedure TSVGCanvas.InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean);
var tmp : String;
begin
if (Brush.Style<>bsClear) or (UsePen and (Pen.Style<>psClear)) then
begin
tmp:='<rect '+SVGRect(Rect)+SVGBrushPen(UsePen);
if IsRound then tmp:=tmp+' rx="5"';
AddEnd(tmp);
end;
end;
procedure TSVGCanvas.Ellipse(X1, Y1, X2, Y2: Integer);
var tmpSt : String;
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
tmpSt:='<ellipse '+SVGEllipse(X1,Y1,X2,Y2);
AddEnd(tmpSt+SVGBrushPen);
end;
end;
procedure TSVGCanvas.SetPixel3D(X,Y,Z:Integer; Value: TColor);
begin
if Pen.Style<>psClear then
begin
Calc3DPos(x,y,z);
Pen.Color:=Value;
MoveTo(x,y);
LineTo(x,y);
end;
end;
procedure TSVGCanvas.SetPixel(X, Y: Integer; Value: TColor);
begin
if Pen.Style<>psClear then
begin
Pen.Color:=Value;
MoveTo(x,y);
LineTo(x,y);
end;
end;
procedure TSVGCanvas.AssignVisiblePenColor(APen:TPen; AColor:TColor);
begin
IPenStyle:=APen.Style;
IPenWidth:=APen.Width;
Pen.OnChange:=nil;
inherited;
Pen.OnChange:=ChangedPen;
end;
procedure TSVGCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
var tmpSt : String;
begin
if Pen.Style<>psClear then
begin
PrepareShape;
tmpSt:='points="'+PointToStr(X1,Y1)+' '+PointToStr(X2,Y2)+' '+
PointToStr(X3,Y3)+' '+PointToStr(X4,Y4)+'"';
AddEnd(tmpSt);
end;
end;
procedure TSVGCanvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);
var tmpSt : String;
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
PrepareShape;
tmpSt:=' points="'+PointToStr((X2+X1) div 2,(Y2+Y1) div 2)+' ';
tmpSt:=tmpSt+PointToStr(X1,Y1)+' '+PointToStr(X2,Y2)+' '+
PointToStr(X3,Y3)+' '+PointToStr(X4,Y4)+'"';
AddEnd(tmpSt);
end;
end;
procedure TSVGCanvas.RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer);
begin
InternalRect(TeeRect(X1,Y1,X2,Y2),True,True);
end;
Procedure TSVGCanvas.TextOut3D(X,Y,Z:Integer; const Text:String);
begin
Calc3DPos(x,y,z);
TextOut(x,y,Text);
end;
Procedure TSVGCanvas.TextOut(X,Y:Integer; const Text:String);
Procedure DoText(AX,AY:Integer; AColor:TColor);
Function VerifySpecial(S:String):String;
const AllowedSVGChars=['!'..'z'];
var t : Integer;
begin
result:='';
for t:=1 to Length(S) do
if {$IFDEF CLR}AnsiChar{$ENDIF}(S[t]) in AllowedSVGChars then
result:=result+S[t]
else
result:=result+'&#'+IntToStr(Ord(S[t]))+';'
end;
var tmpSt : String;
begin
if (TextAlign and TA_CENTER)=TA_CENTER then
Dec(AX,TextWidth(Text) div 2)
else
if (TextAlign and TA_RIGHT)=TA_RIGHT then
Dec(AX,TextWidth(Text));
tmpSt:='<text x="'+IntToStr(AX)+'" y="'+IntToStr(AY)+'"'+
' font-family="'+Font.Name+'" font-size="'+IntToStr(Font.Size)+'pt" ';
// tmpSt:=tmpSt+' transform="translate(0,100) rotate(90)"';
if fsItalic in Font.Style then
tmpSt:=tmpSt+' font-style="italic"';
if fsBold in Font.Style then
tmpSt:=tmpSt+' font-weight="bold"';
if fsUnderline in Font.Style then
tmpSt:=tmpSt+' text-decoration="underline"'
else
if fsStrikeOut in Font.Style then
tmpSt:=tmpSt+' text-decoration="line-through"';
tmpSt:=tmpSt+' fill='+SVGColor(AColor)+'>';
Add(tmpSt);
Add(VerifySpecial(Text));
Add('</text>');
end;
Var tmpX : Integer;
tmpY : Integer;
begin
if TextAlign<TA_BOTTOM then
Inc(y,Round(Font.Size*Screen.PixelsPerInch/72.0)); // align top
if Assigned(IFont) then
With IFont.Shadow do
if (HorizSize<>0) or (VertSize<>0) then
begin
if HorizSize<0 then
begin
tmpX:=X;
X:=X-HorizSize;
end
else tmpX:=X+HorizSize;
if VertSize<0 then
begin
tmpY:=Y;
Y:=Y-VertSize;
end
else tmpY:=Y+VertSize;
DoText(tmpX,tmpY,IFont.Shadow.Color)
end;
DoText(X,Y,IFont.Color);
end;
procedure TSVGCanvas.MoveTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
MoveTo(x,y);
end;
procedure TSVGCanvas.LineTo3D(X,Y,Z:Integer);
begin
Calc3DPos(x,y,z);
LineTo(x,y);
end;
Function TSVGCanvas.GetTextAlign:TCanvasTextAlign;
begin
result:=FTextAlign;
end;
Procedure TSVGCanvas.DoHorizLine(X0,X1,Y:Integer);
begin
MoveTo(X0,Y);
LineTo(X1,Y);
end;
Procedure TSVGCanvas.DoVertLine(X,Y0,Y1:Integer);
begin
MoveTo(X,Y0);
LineTo(X,Y1);
end;
procedure TSVGCanvas.RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double);
begin
Calc3DPos(x,y,z);
RotateLabel(x,y,St,RotDegree);
end;
procedure TSVGCanvas.RotateLabel(x,y:Integer; Const St:String; RotDegree:Double);
begin
//TODO: RotDegree text rotation
TextOut(X,Y,St);
end;
Procedure TSVGCanvas.Line(X0,Y0,X1,Y1:Integer);
begin
MoveTo(X0,Y0);
LineTo(X1,Y1);
end;
Procedure TSVGCanvas.HorizLine3D(Left,Right,Y,Z:Integer);
begin
MoveTo3D(Left,Y,Z);
LineTo3D(Right,Y,Z);
end;
Procedure TSVGCanvas.VertLine3D(X,Top,Bottom,Z:Integer);
begin
MoveTo3D(X,Top,Z);
LineTo3D(X,Bottom,Z);
end;
Procedure TSVGCanvas.ZLine3D(X,Y,Z0,Z1:Integer);
begin
MoveTo3D(X,Y,Z0);
LineTo3D(X,Y,Z1);
end;
Procedure TSVGCanvas.LineWithZ(X0,Y0,X1,Y1,Z:Integer);
begin
MoveTo3D(X0,Y0,Z);
LineTo3D(X1,Y1,Z);
end;
Function TSVGCanvas.GetBackMode:TCanvasBackMode;
begin
result:=FBackMode;
end;
Procedure TSVGCanvas.PolygonFour;
begin
Polygon(IPoints);
end;
Function TSVGCanvas.SVGBrushPen(UsePen:Boolean=True):String;
begin
if Brush.Style<>bsClear then
begin
result:=' fill='+SVGColor(Brush.Color);
if ITransp>0 then
result:=result+' fill-opacity="'+FloatToStr(ITransp*0.01)+'"';
end
else
result:=' fill="none"';
if UsePen then result:=result+SVGPen;
end;
Function TSVGCanvas.SVGPen:String;
Function PenStyle:String;
begin
if Pen is TChartPen and TChartPen(Pen).SmallDots then
result:='2, 2'
else
case IPenStyle of
psDash: result:='4, 2';
psDot: result:='2, 2';
psDashDot: result:='4, 2, 2, 2';
psDashDotDot: result:='4, 2, 2, 2, 2, 2';
else
result:='';
end;
end;
begin
if Pen.Style=psClear then
result:=' stroke="none"'
else
begin
result:=' stroke='+SVGColor(Pen.Color);
if IPenWidth>1 then
result:=result+' stroke-width="'+TeeStr(IPenWidth)+'"';
if IPenStyle<>psSolid then
result:=result+' stroke-dasharray="'+PenStyle+'" '; // fill="none" breaks brush ??
if Pen is TChartPen then
case TChartPen(Pen).EndStyle of
esSquare: result:=result+' stroke-linecap="square"';
esFlat: result:=result+' stroke-linecap="flat"';
end;
end;
end;
Procedure TSVGCanvas.PrepareShape;
begin
Add('<polygon'+SVGBrushPen);
end;
Function TSVGCanvas.SVGPoints(const Points: Array of TPoint):String;
var t : Integer;
begin
result:='points="';
for t:=Low(Points) to High(Points) do
result:=result+PointToStr(Points[t].X,Points[t].Y)+' ';
result:=result+'"';
end;
Procedure TSVGCanvas.Polygon(const Points: Array of TPoint);
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
PrepareShape;
AddEnd(SVGPoints(Points));
end;
end;
{$IFDEF D5}
Procedure TSVGCanvas.Polyline(const Points:Array of TPoint);
{$ELSE}
Procedure TSVGCanvas.Polyline(const Points:TPointArray);
{$ENDIF}
begin
if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then
begin
Add('<polyline fill="none" '+SVGPen);
AddEnd(SVGPoints(Points));
end;
end;
function TSVGCanvas.InitWindow(DestCanvas: TCanvas;
A3DOptions: TView3DOptions; ABackColor: TColor; Is3D: Boolean;
const UserRect: TRect): TRect;
var tmp : String;
begin
result:=inherited InitWindow(DestCanvas,A3DOptions,ABackColor,Is3D,UserRect);
Add(DocType);
tmp:='<svg '+TotalBounds;
if Antialias then tmp:=tmp+' style="text-antialiasing:true"';
Add(tmp+'>');
Pen.OnChange:=ChangedPen;
end;
procedure TSVGCanvas.ChangedPen(Sender: TObject);
begin
IPenStyle:=Pen.Style;
IPenWidth:=Pen.Width;
end;
procedure TSVGCanvas.SetTextAlign(Align: TCanvasTextAlign);
begin
FTextAlign:=Align;
end;
function TSVGCanvas.BeginBlending(const R: TRect;
Transparency: TTeeTransparency): TTeeBlend;
begin
ITransp:=Transparency;
result:=nil;
end;
procedure TSVGCanvas.EndBlending(Blend: TTeeBlend);
begin
ITransp:=0;
end;
procedure TSVGCanvas.SVGEndClip;
begin
Add('</clipPath>');
Add('</defs>');
end;
procedure TSVGCanvas.ClipRectangle(const Rect: TRect; RoundSize: Integer);
begin
SVGClip;
AddEnd('<rect '+SVGRect(Rect)+' rx="'+IntToStr(RoundSize)+'"');
SVGEndClip;
end;
{ TSVGExportFormat }
function TSVGExportFormat.Description: String;
begin
result:='as &SVG';
end;
procedure TSVGExportFormat.DoCopyToClipboard;
begin
with SVG do
try
Clipboard.AsText:=Text;
finally
Free;
end;
end;
function TSVGExportFormat.FileExtension: String;
begin
result:='SVG';
end;
function TSVGExportFormat.FileFilter: String;
begin
result:=TeeMsg_SVGFilter;
end;
Procedure TSVGExportFormat.CheckProperties;
begin
if not Assigned(FProperties) then
FProperties:=TSVGOptions.Create(nil);
end;
function TSVGExportFormat.Options(Check:Boolean=True):TForm;
begin
if Check then CheckProperties;
result:=FProperties;
end;
procedure TSVGExportFormat.SaveToStream(Stream: TStream);
begin
with SVG do
try
SaveToStream(Stream);
finally
Free;
end;
end;
type TTeePanelAccess=class(TCustomTeePanel);
function TSVGExportFormat.SVG: TStringList;
var tmp : TCanvas3D;
begin { return a panel or chart in SVG format into a StringList }
CheckSize;
result:=TStringList.Create;
Panel.AutoRepaint:=False;
try
tmp:=Panel.Canvas;
{$IFNDEF CLR} // Protected across assemblies
TTeePanelAccess(Panel).InternalCanvas:=nil;
{$ENDIF}
Panel.Canvas:=TSVGCanvas.Create(result);
try
Panel.Canvas.Assign(tmp);
TSVGCanvas(Panel.Canvas).Antialias:=FProperties.CBAntiAlias.Checked;
Panel.Draw(Panel.Canvas.ReferenceCanvas,TeeRect(0,0,Width,Height));
finally
Panel.Canvas:=tmp;
end;
finally
Panel.AutoRepaint:=True;
end;
end;
procedure TeeSaveToSVGFile( APanel:TCustomTeePanel; FileName: String;
AWidth:Integer=0; AHeight: Integer=0);
begin { save panel or chart to filename in SVG format }
with TSVGExportFormat.Create do
try
Panel:=APanel;
Height:=AHeight;
Width:=AWidth;
if ExtractFileExt(FileName)='' then
FileName:=FileName+'.'+FileExtension;
SaveToFile(FileName);
finally
Free;
end;
end;
destructor TSVGExportFormat.Destroy;
begin
// FreeAndNil(FProperties); ?? 6.02
inherited;
end;
initialization
RegisterTeeExportFormat(TSVGExportFormat);
finalization
UnRegisterTeeExportFormat(TSVGExportFormat);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.Touch.GestureMgr;
interface
uses
Winapi.Windows, System.SysUtils, System.Generics.Collections, System.Classes,
Vcl.Controls, Vcl.ActnList, Vcl.Touch.Gestures;
type
TGestureCollectionItem = class;
TGestureManager = class;
TGestureCollectionItem = class(TCustomGestureCollectionItem)
private
FAction: TBasicAction;
FDeviation: Integer;
FErrorMargin: Integer;
FGestureID: TGestureID;
FName: string;
FOptions: TGestureOptions;
FPoints: TGesturePointArray;
procedure ReadDeviation(Reader: TReader);
procedure ReadErrorMargin(Reader: TReader);
procedure ReadGestureID(Reader: TReader);
procedure ReadName(Reader: TReader);
procedure ReadOptions(Reader: TReader);
procedure ReadPoints(Stream: TStream);
procedure WriteDeviation(Writer: TWriter);
procedure WriteErrorMargin(Writer: TWriter);
procedure WriteGestureID(Writer: TWriter);
procedure WriteName(Writer: TWriter);
procedure WriteOptions(Writer: TWriter);
procedure WritePoints(Stream: TStream);
strict protected
function GetAction: TBasicAction; override;
function GetDeviation: Integer; override;
function GetErrorMargin: Integer; override;
function GetGestureID: TGestureID; override;
function GetGestureType: TGestureType; override;
function GetOptions: TGestureOptions; override;
function GetName: string; override;
function GetPoints: TGesturePointArray; override;
procedure SetAction(const Value: TBasicAction); override;
procedure SetDeviation(const Value: Integer); override;
procedure SetErrorMargin(const Value: Integer); override;
procedure SetGestureID(const Value: TGestureID); override;
procedure SetName(const Value: string); override;
procedure SetOptions(const Value: TGestureOptions); override;
procedure SetPoints(const Value: TGesturePointArray); override;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure DefineProperties(Filer: TFiler); override;
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
property Action;
end;
TGestureNotification = (gnChanged, gnDeleted);
TGestureItemChangeEvent = procedure(Sender: TObject; Action: TGestureNotification;
Item: TCustomGestureCollectionItem) of object;
TGestureCollection = class(TCustomGestureCollection)
strict private
FGestureManager: TGestureManager;
FOnItemChange: TGestureItemChangeEvent;
protected
FStreamGestureDetails: Boolean; // For internal use only
function GetGestureManager: TCustomGestureManager; override;
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override;
procedure Update(Item: TCollectionItem); override;
public
constructor Create; overload; virtual;
constructor Create(AGestureManager: TGestureManager); overload; virtual;
destructor Destroy; override;
function Add: TGestureCollectionItem;
function AddGesture: TCustomGestureCollectionItem; override;
function FindGesture(AGestureID: TGestureID): TCustomGestureCollectionItem; overload; override;
function FindGesture(const AName: string): TCustomGestureCollectionItem; overload; override;
function GetUniqueGestureID: TGestureID; override;
procedure RemoveGesture(AGestureID: TGestureID); override;
property OnItemChange: TGestureItemChangeEvent read FOnItemChange write FOnItemChange;
end;
TGestureManager = class(TCustomGestureManager)
strict private
class var FInstanceList: TList<TCustomGestureManager>;
class var FNextGestureID: TGestureID;
class var FRegisteredGestures: TGestureCollection;
class constructor Create;
class destructor Destroy;
class function GetRegisteredGestureCount: Integer; static;
class function GetRegisteredGestures: TGestureArray; static;
strict private type
TGestureControlList = TDictionary<TControl, TGestureCollection>;
TDesignerHook = procedure(AGesture: TCustomGestureCollectionItem) of object;
strict private
FControls: TGestureControlList;
FFileName: TFileName;
FLoading: Boolean;
FNotifyList: TList<TControl>;
FRecordedGestures: TGestureCollection;
FSaved: Boolean;
FStreamCollection: TCollection;
FUpdating: Boolean;
procedure GestureItemChanged(Sender: TObject;
Action: TGestureNotification; Item: TCustomGestureCollectionItem);
function GetCustomGestureCount: Integer;
function GetCustomGestures: TGestureArray;
function GetRecordedGestureCount: Integer;
function GetRecordedGestures: TGestureArray;
procedure ReadControlData(Reader: TReader);
procedure ReadRecordedGestures(Reader: TReader);
procedure WriteControlData(Writer: TWriter);
procedure WriteRecordedGestures(Writer: TWriter);
protected
class var FDesignerHook: TDesignerHook; // For internal use only
protected
procedure DefineProperties(Filer: TFiler); override;
function GetGestureList(Control: TControl): TGestureArray; override;
function GetStandardGestures(AControl: TControl): TStandardGestures; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure NotifyControls(Msg: Cardinal; Operation: Integer; GestureID: TGestureID);
procedure SetStandardGestures(AControl: TControl; AStandardGestures: TStandardGestures); override;
property Loading: Boolean read FLoading;
public
class function RegisterGesture(AGesture: TCustomGestureCollectionItem): TGestureID; static;
class procedure UnregisterGesture(AGesture: TGestureID); static;
class property RegisteredGestureCount: Integer read GetRegisteredGestureCount;
class property RegisteredGestures: TGestureArray read GetRegisteredGestures;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddRecordedGesture(Item: TCustomGestureCollectionItem): TGestureID; override;
procedure ChangeNotification(AControl: TControl);
function FindCustomGesture(AGestureID: TGestureID): TCustomGestureCollectionItem; override;
function FindCustomGesture(const AName: string): TCustomGestureCollectionItem; override;
function FindGesture(AControl: TControl; AGestureID: TGestureID): TCustomGestureCollectionItem; override;
function FindGesture(AControl: TControl; const AName: string): TCustomGestureCollectionItem; override;
procedure LoadFromFile(const Filename: string);
procedure LoadFromStream(S: TStream);
procedure RegisterControl(AControl: TControl); override;
procedure RemoveChangeNotification(AControl: TControl);
procedure RemoveRecordedGesture(AGestureID: TGestureID); override;
procedure RemoveRecordedGesture(AGesture: TCustomGestureCollectionItem); override;
procedure SaveToFile(const Filename: string);
procedure SaveToStream(S: TStream);
function SelectGesture(AControl: TControl; AGestureID: TGestureID): Boolean; override;
function SelectGesture(AControl: TControl; const AName: string): Boolean; override;
procedure SetRecordedGestures(Gestures: TGestureArray); // For designtime support only
procedure UnregisterControl(AControl: TControl); override;
procedure UnselectGesture(AControl: TControl; AGestureID: TGestureID); override;
property CustomGestureCount: Integer read GetCustomGestureCount;
property CustomGestures: TGestureArray read GetCustomGestures;
property RecordedGestureCount: Integer read GetRecordedGestureCount;
property RecordedGestures: TGestureArray read GetRecordedGestures;
published
property FileName: TFileName read FFileName write FFileName;
end;
implementation
uses
System.RTLConsts, Vcl.Consts, Vcl.Touch.GestureConsts, System.Types, Vcl.Dialogs, Vcl.Forms;
{ TGestureListItem }
constructor TGestureCollectionItem.Create(Collection: TCollection);
begin
inherited;
FDeviation := 20;
FErrorMargin := 20;
FOptions := [goUniDirectional, goRotate];
end;
destructor TGestureCollectionItem.Destroy;
begin
if (FAction <> nil) and (Collection <> nil) and
(TGestureCollection(Collection).GestureManager <> nil) then
FAction.RemoveFreeNotification(TGestureCollection(Collection).GestureManager);
inherited;
end;
procedure TGestureCollectionItem.AssignTo(Dest: TPersistent);
begin
if Dest is TGestureCollectionItem then
with TGestureCollectionItem(Dest) do
begin
FAction := Self.FAction;
FDeviation := Self.FDeviation;
FErrorMargin := Self.FErrorMargin;
FGestureID := Self.FGestureID;
FName := Self.FName;
FOptions := Self.FOptions;
FPoints := Copy(Self.FPoints, 0, Length(Self.FPoints));
end
else
inherited;
end;
procedure TGestureCollectionItem.DefineProperties(Filer: TFiler);
function DoStream: Boolean;
begin
// GestureType will be gtNone while streaming in
Result := ((GestureType = gtRecorded) or (GestureType = gtNone)) and
TGestureCollection(Collection).FStreamGestureDetails;
end;
begin
inherited;
Filer.DefineProperty('Deviation', ReadDeviation, WriteDeviation, DoStream); // do not localize
Filer.DefineProperty('ErrorMargin', ReadErrorMargin, WriteErrorMargin, DoStream);// do not localize
Filer.DefineProperty('GestureID', ReadGestureID, WriteGestureID, GestureType <> gtRegistered); // do not localize
Filer.DefineProperty('Name', ReadName, WriteName, (GestureType = gtRegistered) or DoStream); // do not localize
Filer.DefineProperty('Options', ReadOptions, WriteOptions, DoStream); // do not localize
Filer.DefineBinaryProperty('Points', ReadPoints, WritePoints, DoStream); // do not localize
end;
function TGestureCollectionItem.GetAction: TBasicAction;
begin
Result := FAction;
end;
function TGestureCollectionItem.GetDeviation: Integer;
begin
Result := FDeviation;
end;
function TGestureCollectionItem.GetDisplayName: string;
var
S: string;
begin
if GestureType = gtStandard then
begin
GestureToIdent(FGestureID, S);
Result := Copy(S, 4, Length(S) - 3); // trim "sgi" from ID name
end
else
Result := FName;
end;
function TGestureCollectionItem.GetErrorMargin: Integer;
begin
Result := FErrorMargin;
end;
function TGestureCollectionItem.GetGestureID: TGestureID;
begin
Result := FGestureID;
end;
function TGestureCollectionItem.GetGestureType: TGestureType;
begin
case FGestureID of
sgiNoGesture: Result := gtNone;
sgiFirst..sgiLast: Result := gtStandard;
cgiFirst..cgiLast: Result := gtRecorded;
rgiFirst..rgiLast: Result := gtRegistered;
else
raise EGestureException.CreateResFmt(@SInvalidGestureID, [FGestureID]);
end;
end;
function TGestureCollectionItem.GetName: string;
begin
case GestureType of
gtNone, gtStandard:
Result := DisplayName;
gtRecorded, gtRegistered:
Result := FName;
end;
end;
function TGestureCollectionItem.GetOptions: TGestureOptions;
begin
Result := FOptions;
end;
function TGestureCollectionItem.GetPoints: TGesturePointArray;
begin
Result := FPoints;
end;
procedure TGestureCollectionItem.ReadDeviation(Reader: TReader);
begin
FDeviation := Reader.ReadInteger;
end;
procedure TGestureCollectionItem.ReadErrorMargin(Reader: TReader);
begin
FErrorMargin := Reader.ReadInteger;
end;
procedure TGestureCollectionItem.ReadGestureID(Reader: TReader);
var
I: Integer;
Ident: string;
begin
if Reader.NextValue = vaIdent then
begin
Ident := Reader.ReadIdent;
if IdentToGesture(Ident, I) then
FGestureID := I
else
begin
if TryStrToInt(Ident, I) then
FGestureID := I
else
raise EReadError.CreateRes(@SInvalidPropertyValue);
end;
end
else
FGestureID := Reader.ReadInteger;
end;
procedure TGestureCollectionItem.ReadName(Reader: TReader);
begin
FName := Reader.ReadString;
end;
procedure TGestureCollectionItem.ReadOptions(Reader: TReader);
begin
FOptions := TGestureOptions(Byte(Reader.ReadInteger));
end;
const
StreamVersion1 = 1;
procedure TGestureCollectionItem.ReadPoints(Stream: TStream);
var
I, Len: Integer;
LPoint: TSmallPoint;
LStreamVersion: Byte;
begin
Stream.Read(LStreamVersion, SizeOf(Byte));
if LStreamVersion <> StreamVersion1 then
raise EGestureException.CreateRes(@SInvalidStreamFormat);
Stream.Read(Len, SizeOf(Integer));
SetLength(FPoints, Len);
for I := 0 to Len - 1 do
begin
Stream.Read(LPoint, SizeOf(LPoint));
FPoints[I] := SmallPointToPoint(LPoint);
end;
end;
procedure TGestureCollectionItem.SetAction(const Value: TBasicAction);
begin
if Value <> FAction then
begin
if (FAction <> nil) and (TGestureCollection(Collection).GestureManager <> nil) then
FAction.RemoveFreeNotification(TGestureCollection(Collection).GestureManager);
FAction := Value;
if (FAction <> nil) and (TGestureCollection(Collection).GestureManager <> nil) then
FAction.FreeNotification(TGestureCollection(Collection).GestureManager);
Changed(False);
end;
end;
procedure TGestureCollectionItem.SetDeviation(const Value: Integer);
begin
if Value <> FDeviation then
begin
FDeviation := Value;
Changed(False);
end;
end;
procedure TGestureCollectionItem.SetErrorMargin(const Value: Integer);
begin
if Value <> FErrorMargin then
begin
FErrorMargin := Value;
Changed(False);
end;
end;
procedure TGestureCollectionItem.SetGestureID(const Value: TGestureID);
begin
FGestureID := Value;
end;
procedure TGestureCollectionItem.SetName(const Value: string);
begin
if Value <> FName then
begin
if Collection <> nil then
begin
if TCustomGestureCollection(Collection).FindGesture(Value) <> nil then
raise EGestureException.CreateResFmt(@SDuplicateGestureName, [Value]);
end;
FName := Value;
Changed(False);
end;
end;
procedure TGestureCollectionItem.SetOptions(const Value: TGestureOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
Changed(False);
end;
end;
procedure TGestureCollectionItem.SetPoints(const Value: TGesturePointArray);
begin
if Value <> FPoints then
FPoints := Value;
end;
procedure TGestureCollectionItem.WriteDeviation(Writer: TWriter);
begin
Writer.WriteInteger(FDeviation);
end;
procedure TGestureCollectionItem.WriteErrorMargin(Writer: TWriter);
begin
Writer.WriteInteger(FErrorMargin);
end;
procedure TGestureCollectionItem.WriteGestureID(Writer: TWriter);
var
Ident: string;
begin
if not GestureToIdent(FGestureID, Ident) then
Ident := IntToStr(FGestureID);
Writer.WriteIdent(Ident);
end;
procedure TGestureCollectionItem.WriteName(Writer: TWriter);
begin
Writer.WriteString(FName);
end;
procedure TGestureCollectionItem.WriteOptions(Writer: TWriter);
begin
Writer.WriteInteger(Byte(FOptions));
end;
procedure TGestureCollectionItem.WritePoints(Stream: TStream);
var
I: Integer;
LPoint: TSmallPoint;
LStreamVersion: Byte;
begin
LStreamVersion := StreamVersion1;
Stream.Write(LStreamVersion, SizeOf(Byte));
I := Length(FPoints);
Stream.Write(I, SizeOf(Integer));
for I := 0 to Length(FPoints) - 1 do
begin
LPoint := PointToSmallPoint(FPoints[I]);
Stream.Write(LPoint, SizeOf(LPoint));
end;
end;
{ TGestureCollection }
constructor TGestureCollection.Create;
begin
inherited Create(TGestureCollectionItem);
FStreamGestureDetails := False;
end;
constructor TGestureCollection.Create(AGestureManager: TGestureManager);
begin
Create;
FGestureManager := AGestureManager;
end;
destructor TGestureCollection.Destroy;
begin
inherited;
end;
function TGestureCollection.AddGesture: TCustomGestureCollectionItem;
var
LItem: TGestureCollectionItem;
LGestureID: TGestureID;
begin
LGestureID := GetUniqueGestureID;
LItem := TGestureCollectionItem(inherited Add);
LItem.GestureID := LGestureID;
Result := LItem;
end;
function TGestureCollection.Add: TGestureCollectionItem;
begin
Result := TGestureCollectionItem(AddGesture);
end;
function TGestureCollection.FindGesture(AGestureID: TGestureID): TCustomGestureCollectionItem;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if Items[I].GestureID = AGestureID then
begin
Result := Items[I];
Break;
end;
end;
function TGestureCollection.FindGesture(const AName: string): TCustomGestureCollectionItem;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if CompareText(Items[I].Name, AName, loUserLocale) = 0 then
begin
Result := Items[I];
Break;
end;
end;
function TGestureCollection.GetUniqueGestureID: TGestureID;
begin
Result := cgiLast;
while FindGesture(Result) <> nil do
Dec(Result);
end;
function TGestureCollection.GetGestureManager: TCustomGestureManager;
begin
Result := FGestureManager;
end;
procedure TGestureCollection.Notify(Item: TCollectionItem; Action: TCollectionNotification);
begin
inherited;
if (Action = cnDeleting) and Assigned(FOnItemChange) then
FOnItemChange(Self, gnDeleted, TCustomGestureCollectionItem(Item));
end;
procedure TGestureCollection.RemoveGesture(AGestureID: TGestureID);
var
LGesture: TCustomGestureCollectionItem;
begin
LGesture := FindGesture(AGestureID);
if LGesture <> nil then
LGesture.Free;
end;
procedure TGestureCollection.Update(Item: TCollectionItem);
begin
if Assigned(FOnItemChange) then
FOnItemChange(Self, gnChanged, TCustomGestureCollectionItem(Item));
end;
type
TGestureStreamData = class(TCollectionItem)
private
FControl: TControl;
FCollection: TGestureCollection;
published
constructor Create(Collection: TCollection); override;
property Control: TControl read FControl write FControl;
property Collection: TGestureCollection read FCollection write FCollection;
end;
TGestureStreamDataClass = class of TGestureStreamData;
TGestureStreamList = class(TCollection)
private
FReading: Boolean;
function GetItem(Index: Integer): TGestureStreamData;
procedure SetItem(Index: Integer; const Value: TGestureStreamData);
public
constructor Create(Reading: Boolean);
function Add: TGestureStreamData;
property Items[Index: Integer]: TGestureStreamData read GetItem write SetItem; default;
end;
{ TGestureStreamData }
constructor TGestureStreamData.Create(Collection: TCollection);
begin
inherited;
if TGestureStreamList(Collection).FReading then
FCollection := TGestureCollection.Create;
end;
{ TGestureStreamList }
constructor TGestureStreamList.Create(Reading: Boolean);
begin
inherited Create(TGestureStreamData);
FReading := Reading;
end;
function TGestureStreamList.Add: TGestureStreamData;
begin
Result := TGestureStreamData(inherited Add);
end;
function TGestureStreamList.GetItem(Index: Integer): TGestureStreamData;
begin
Result := TGestureStreamData(inherited GetItem(Index));
end;
procedure TGestureStreamList.SetItem(Index: Integer; const Value: TGestureStreamData);
begin
inherited SetItem(Index, TCollectionItem(Value));
end;
{ TCustomGestureManager }
class constructor TGestureManager.Create;
begin
FInstanceList := TList<TCustomGestureManager>.Create;
FRegisteredGestures := TGestureCollection.Create;
FNextGestureID := rgiLast;
end;
constructor TGestureManager.Create(AOwner: TComponent);
begin
inherited;
FControls := TGestureControlList.Create;
FInstanceList.Add(Self);
FRecordedGestures := TGestureCollection.Create;
FRecordedGestures.OnItemChange := GestureItemChanged;
FNotifyList := TList<TControl>.Create;
FUpdating := False;
end;
class destructor TGestureManager.Destroy;
begin
FreeAndNil(FInstanceList);
FreeAndNil(FRegisteredGestures);
end;
destructor TGestureManager.Destroy;
begin
FInstanceList.Remove(Self);
FreeAndNil(FControls);
FreeAndNil(FRecordedGestures);
FreeAndNil(FNotifyList);
inherited;
end;
function TGestureManager.AddRecordedGesture(Item: TCustomGestureCollectionItem): TGestureID;
var
NewItem: TGestureCollectionItem;
begin
if FRecordedGestures.FindGesture(Item.Name) <> nil then
raise EGestureException.CreateResFmt(@SDuplicateRecordedGestureName, [Item.Name]);
NewItem := FRecordedGestures.Add;
Result := NewItem.GestureID;
NewItem.Assign(Item);
NewItem.GestureID := Result;
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnAdded, Result);
end;
procedure TGestureManager.ChangeNotification(AControl: TControl);
begin
if AControl <> nil then
begin
FNotifyList.Add(AControl);
AControl.FreeNotification(Self);
end;
end;
procedure TGestureManager.DefineProperties(Filer: TFiler);
function StreamData: Boolean;
var
P: TPair<TControl, TGestureCollection>;
begin
Result := False;
for P in FControls do
if P.Value.Count > 0 then
begin
Result := True;
Break;
end;
end;
begin
inherited;
Filer.DefineProperty('CustomGestures', ReadRecordedGestures, WriteRecordedGestures, FRecordedGestures.Count > 0); // do not localize
Filer.DefineProperty('GestureData', ReadControlData, WriteControlData, StreamData); // do not localize
end;
function TGestureManager.FindCustomGesture(AGestureID: TGestureID): TCustomGestureCollectionItem;
begin
Result := FRecordedGestures.FindGesture(AGestureID);
if Result = nil then
Result := FRegisteredGestures.FindGesture(AGestureID);
end;
function TGestureManager.FindCustomGesture(const AName: string): TCustomGestureCollectionItem;
begin
Result := FRecordedGestures.FindGesture(AName);
if Result = nil then
Result := FRegisteredGestures.FindGesture(AName);
end;
function TGestureManager.FindGesture(AControl: TControl;
const AName: string): TCustomGestureCollectionItem;
begin
Result := FControls.Items[AControl].FindGesture(AName);
end;
function TGestureManager.FindGesture(AControl: TControl;
AGestureID: TGestureID): TCustomGestureCollectionItem;
begin
Result := FControls.Items[AControl].FindGesture(AGestureID);
end;
procedure TGestureManager.GestureItemChanged(Sender: TObject;
Action: TGestureNotification; Item: TCustomGestureCollectionItem);
var
I: Integer;
LAction: TBasicAction;
P: TPair<TControl, TGestureCollection>;
begin
case Action of
gnChanged:
if Item <> nil then
begin
// Refresh gesture items preserving the Action property
for P in FControls do
for I := P.Value.Count - 1 downto 0 do
if (P.Value[I].GestureID = Item.GestureID) then
begin
LAction := P.Value[I].Action;
P.Value[I].Assign(Item);
P.Value[I].Action := LAction;
end;
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnModified, Item.GestureID);
end;
gnDeleted:
if not FUpdating and (Item <> nil) then
// Remove Item.GestureID from all control's gesture lists
for P in FControls do
for I := P.Value.Count - 1 downto 0 do
if (P.Value[I].GestureID = Item.GestureID) then
P.Value.Delete(I);
end;
end;
function TGestureManager.GetCustomGestureCount: Integer;
begin
Result := FRecordedGestures.Count + FRegisteredGestures.Count;
end;
function TGestureManager.GetCustomGestures: TGestureArray;
var
LItems: TGestureArray;
begin
Result := RecordedGestures;
if FRegisteredGestures.Count > 0 then
begin
LItems := RegisteredGestures;
SetLength(Result, Length(Result) + Length(LItems));
Move(LItems[0], Result[RecordedGestureCount], Length(LItems) * SizeOf(LItems[0]));
end;
end;
function TGestureManager.GetGestureList(Control: TControl): TGestureArray;
var
LList: TCustomGestureCollection;
I: Integer;
begin
if FControls.ContainsKey(Control) then
LList := FControls.Items[Control]
else
raise EGestureException.CreateRes(@SControlNotFound);
SetLength(Result, LList.Count);
for I := 0 to LList.Count - 1 do
Result[I] := LList[I];
end;
function TGestureManager.GetRecordedGestureCount: Integer;
begin
Result := FRecordedGestures.Count;
end;
function TGestureManager.GetRecordedGestures: TGestureArray;
var
Count: Integer;
Item: TCollectionItem;
begin
Count := 0;
SetLength(Result, FRecordedGestures.Count);
for Item in FRecordedGestures do
begin
Result[Count] := TCustomGestureCollectionItem(Item);
Inc(Count);
end;
SetLength(Result, Count);
end;
class function TGestureManager.GetRegisteredGestureCount: Integer;
begin
Result := FRegisteredGestures.Count;
end;
class function TGestureManager.GetRegisteredGestures: TGestureArray;
var
Count: Integer;
Item: TCollectionItem;
begin
Count := 0;
SetLength(Result, FRegisteredGestures.Count);
for Item in FRegisteredGestures do
begin
Result[Count] := TCustomGestureCollectionItem(Item);
Inc(Count);
end;
SetLength(Result, Count);
end;
function TGestureManager.GetStandardGestures(AControl: TControl): TStandardGestures;
var
I: Integer;
List: TGestureCollection;
begin
Result := [];
// Get list of gestures for the AControl
List := FControls.Items[AControl];
// Add predefined gestures to set
for I := 0 to List.Count - 1 do
if List[I].GestureType = gtStandard then
Include(Result, TStandardGesture(List[I].GestureID));
end;
procedure TGestureManager.Loaded;
var
S: string;
I, J: Integer;
LControl: TControl;
LStreamCollection: TGestureStreamList;
LItem, LSourceItem: TCustomGestureCollectionItem;
MissingGestures: TList<TCustomGestureCollectionItem>;
// Copy properties except Action from Source to Dest
procedure UpdateProperties(Source, Dest: TCustomGestureCollectionItem);
var
LAction: TBasicAction;
begin
if Source <> nil then
begin
LAction := Dest.Action;
Dest.Assign(Source);
Dest.Action := LAction;
end;
end;
begin
inherited Loaded;
if FLoading then Exit;
if not (csDesigning in ComponentState) and FileExists(FFileName) then
LoadFromFile(FFileName)
else if FStreamCollection <> nil then
begin
MissingGestures := TList<TCustomGestureCollectionItem>.Create;
try
LStreamCollection := TGestureStreamList(FStreamCollection);
for I := 0 to FStreamCollection.Count - 1 do
begin
LControl := LStreamCollection[I].Control;
if LControl is TWinControl then
RegisterControl(TWinControl(LControl))
else
RegisterControl(LControl);
// Free any existing collection rather than assign the new one to it
// so linked component references can be fixed up later.
if FControls.Items[LControl] <> nil then
FControls.Items[LControl].Free;
FControls.Items[LControl] := LStreamCollection[I].Collection;
// Add properties to items for custom and registered gestures.
// For custom gestures these are streamed once with the GestureManager,
// with only the ID streamed for each control. For registered
// gestures only the name is streamed since the ID may change.
for J := 0 to FControls.Items[LControl].Count - 1 do
begin
LItem := FControls.Items[LControl][J];
case LItem.GestureType of
gtRecorded:
begin
LSourceItem := FRecordedGestures.FindGesture(LItem.GestureID);
UpdateProperties(LSourceItem, LItem);
end;
// Registered gestures will appear as gtNone since only the name
// was streamed. Once the gesture properties have been assigned,
// they will appear as gtRegistsred.
gtNone:
begin
LSourceItem := FRegisteredGestures.FindGesture(LItem.Name);
if LSourceItem <> nil then
UpdateProperties(LSourceItem, LItem)
else
MissingGestures.Add(LItem);
end;
end;
end;
// If any registered gestures weren't found, display a message and
// free the corresponding collection items. Don't throw and exception
// as we want the application to continue lolading normally.
if MissingGestures.Count > 0 then
begin
S := '';
for LItem in MissingGestures do
begin
S := S + LItem.Name + #13#10;
LItem.Free;
end;
MessageDlg(Format(SRegisteredGestureNotFound, [S]), mtError, [mbClose], 0);
end;
end;
finally
MissingGestures.Free;
end;
FreeAndNil(FStreamCollection);
end;
end;
procedure TGestureManager.LoadFromFile(const Filename: string);
var
LStream: TFileStream;
begin
LStream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
try
try
LoadFromStream(LStream);
except
// swallow exceptions here because we still want the app to start
FreeAndNil(LStream);
if MessageDlg(Format(SErrorLoadingFile, [FileName]), mtError,
[mbYes, mbNo], 0) = mrYes then
DeleteFile(FileName);
end;
finally
LStream.Free;
end;
end;
procedure TGestureManager.LoadFromStream(S: TStream);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
FLoading := True;
try
Stream.LoadFromStream(S);
Stream.Position := 0;
Stream.ReadComponent(Self);
inherited Loaded; // Reset the csLoading flag
finally
FLoading := False;
Stream.Free;
end;
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnRefreshAll, 0);
end;
procedure TGestureManager.Notification(AComponent: TComponent; Operation: TOperation);
var
I: Integer;
LGestureID: TGestureID;
LCustomGestureChanged: Boolean;
LStandardGestureChanged: Boolean;
P: TPair<TControl, TGestureCollection>;
begin
inherited;
if Application.Terminated and (Length(FFileName) > 0) and not FSaved then
begin
SaveToFile(FFileName);
FSaved := True;
end;
if Operation = opRemove then
begin
if AComponent is TBasicAction then
begin
// Remove Action from gestures
LGestureID := 0; // suppress compiler warning
LCustomGestureChanged := False;
LStandardGestureChanged := False;
for P in FControls do
for I := 0 to P.Value.Count - 1 do
if (P.Value[I].Action = AComponent) then
begin
P.Value[I].Action := nil;
LGestureID := P.Value[I].GestureID;
if P.Value[I].GestureType = gtStandard then
LStandardGestureChanged := True
else
LCustomGestureChanged := True;
end;
// Notify controls to refresh gesture lists
if LStandardGestureChanged then
NotifyControls(CM_STANDARDGESTURESCHANGED, gcnModified, LGestureID);
if LCustomGestureChanged then
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnModified, LGestureID);
end
else
if AComponent is TControl then
begin
if FNotifyList.Contains(TControl(AComponent)) then
FNotifyList.Remove(TControl(AComponent))
else
if not (csDestroying in ComponentState) then
UnregisterControl(TControl(AComponent));
end;
end;
end;
procedure TGestureManager.NotifyControls(Msg: Cardinal; Operation: Integer;
GestureID: TGestureID);
var
I: Integer;
begin
for I := 0 to FNotifyList.Count - 1 do
FNotifyList[I].Perform(Msg, Operation, GestureID);
end;
procedure TGestureManager.ReadRecordedGestures(Reader: TReader);
begin
Reader.ReadValue;
Reader.ReadCollection(FRecordedGestures);
end;
procedure TGestureManager.ReadControlData(Reader: TReader);
begin
FStreamCollection := TGestureStreamList.Create(csReading in ComponentState);
Reader.ReadValue;
Reader.ReadCollection(FStreamCollection);
end;
procedure TGestureManager.RegisterControl(AControl: TControl);
begin
if AControl <> nil then
begin
// Create entry in dictionary
if not FControls.ContainsKey(AControl) then
FControls.Add(AControl, TGestureCollection.Create(Self));
// Copy standard gestures into the control's collection
if not (csLoading in ComponentState) then
StandardGestures[AControl] := AControl.Touch.StandardGestures;
// Create a gesture engine if not at design time
if not (csDesigning in AControl.ComponentState) then
TGestureEngine.CreateEngine(AControl);
end;
end;
class function TGestureManager.RegisterGesture(AGesture: TCustomGestureCollectionItem): TGestureID;
var
LItem: TGestureCollectionItem;
LGestureManager: TCustomGestureManager;
begin
if FNextGestureID = rgiFirst then
raise EGestureException.CreateRes(@STooManyRegisteredGestures);
if FRegisteredGestures.FindGesture(AGesture.Name) <> nil then
raise EGestureException.CreateResFmt(@SDuplicateRegisteredGestureName, [AGesture.Name]);
LItem := FRegisteredGestures.Add;
LItem.Assign(AGesture);
LItem.GestureID := FNextGestureID;
Result := LItem.GestureID;
Dec(FNextGestureID);
if Assigned(FDesignerHook) then
FDesignerHook(AGesture);
for LGestureManager in FInstanceList do
if LGestureManager is TGestureManager then
TGestureManager(LGestureManager).NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnAdded, Result);
end;
procedure TGestureManager.RemoveChangeNotification(AControl: TControl);
begin
if FNotifyList.Contains(AControl) then
begin
FNotifyList.Remove(AControl);
AControl.RemoveFreeNotification(Self);
end;
end;
procedure TGestureManager.RemoveRecordedGesture(AGesture: TCustomGestureCollectionItem);
begin
if AGesture <> nil then
begin
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnRemoved, AGesture.GestureID);
AGesture.Free;
end;
end;
procedure TGestureManager.RemoveRecordedGesture(AGestureID: TGestureID);
begin
RemoveRecordedGesture(FRecordedGestures.FindGesture(AGestureID));
end;
procedure TGestureManager.SaveToFile(const Filename: string);
var
LStream: TStream;
begin
try
LStream := TFileStream.Create(ExpandFileName(Filename), fmCreate);
try
try
SaveToStream(LStream);
except
// catch all exceptions because we still want the app to shutdown
end;
finally
LStream.Free;
end;
except
ShowMessage(SUnableToSaveSettings);
end;
end;
procedure TGestureManager.SaveToStream(S: TStream);
var
BinaryStream: TMemoryStream;
begin
BinaryStream := TMemoryStream.Create;
try
BinaryStream.WriteComponent(Self);
BinaryStream.Position := 0;
S.CopyFrom(BinaryStream, BinaryStream.Size);
finally
BinaryStream.Free;
end;
end;
function TGestureManager.SelectGesture(AControl: TControl;
AGestureID: TGestureID): Boolean;
var
LGesture: TCustomGestureCollectionItem;
LGestureList: TCustomGestureCollection;
begin
if FControls.ContainsKey(AControl) then
LGestureList := FControls.Items[AControl]
else
raise EGestureException.CreateRes(@SControlNotFound);
case AGestureID of
sgiFirst..sgiLast:
begin
LGestureList.AddGesture.GestureID := AGestureID;
Result := True;
end;
cgiFirst..cgiLast,
rgiFirst..rgiLast:
begin
LGesture := FindCustomGesture(AGestureID);
Result := LGesture <> nil;
if Result then
LGestureList.AddGesture.Assign(LGesture);
end
else
raise EGestureException.CreateResFmt(@SInvalidGestureID, [AGestureID]);
end;
end;
function TGestureManager.SelectGesture(AControl: TControl;
const AName: string): Boolean;
var
LGestureID: TGestureID;
LGesture: TCustomGestureCollectionItem;
begin
LGesture := FindCustomGesture(AName);
Result := LGesture <> nil;
if not Result then
Result := FindStandardGesture(AName, LGestureID)
else
LGestureID := LGesture.GestureID;
if Result then
Result := SelectGesture(AControl, LGestureID)
else
raise EGestureException.CreateResFmt(@SInvalidGestureName, [AName]);
end;
procedure TGestureManager.SetRecordedGestures(Gestures: TGestureArray);
var
I, J: Integer;
Item: TCustomGestureCollectionItem;
P: TPair<TControl, TGestureCollection>;
begin
FUpdating := True;
try
FRecordedGestures.Clear;
for Item in Gestures do
FRecordedGestures.Add.Assign(Item);
finally
FUpdating := False;
end;
// Allow designers to modify list
if not (csDesigning in ComponentState) then
begin
// Iterate through each control's list and remove custom gestures
for P in FControls do
for I := P.Value.Count - 1 downto 0 do
if (P.Value[I].GestureType = gtRecorded) then
P.Value.Delete(I);
end
else
// Iterate through each control's list and remove gesture ID's
// that don't exist in the updated FCustomGestures list
for P in FControls do
for I := P.Value.Count - 1 downto 0 do
for J := 0 to FRecordedGestures.Count - 1 do
begin
if (P.Value[I].GestureType = gtRecorded) and
(FRecordedGestures.FindGesture(P.Value[I].GestureID) = nil) then
P.Value.Delete(I);
end;
// Notify controls registered for notifications
NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnRefreshAll, 0);
end;
procedure TGestureManager.SetStandardGestures(AControl: TControl;
AStandardGestures: TStandardGestures);
var
I: Integer;
List: TGestureCollection;
LGesture: TStandardGesture;
begin
// Get list of gestures for the AControl
List := FControls.Items[AControl];
// Remove any predefined gestures
for I := List.Count - 1 downto 0 do
if List[I].GestureType = gtStandard then
List[I].Free;
// Add new set of predefined gestures
for LGesture := Low(TStandardGesture) to High(TStandardGesture) do
if LGesture in AStandardGestures then
List.Add.GestureID := TGestureID(LGesture);
end;
procedure TGestureManager.UnregisterControl(AControl: TControl);
var
List: TGestureCollection;
begin
if (AControl <> nil) and FControls.ContainsKey(AControl) then
begin
List := FControls.Items[AControl];
FControls.Remove(AControl);
List.Free;
end;
end;
class procedure TGestureManager.UnregisterGesture(AGesture: TGestureID);
var
LItem: TCustomGestureCollectionItem;
LGestureManager: TCustomGestureManager;
begin
for LGestureManager in FInstanceList do
if LGestureManager is TGestureManager then
TGestureManager(LGestureManager).NotifyControls(CM_CUSTOMGESTURESCHANGED, gcnRemoved, AGesture);
LItem := FRegisteredGestures.FindGesture(AGesture);
if LItem <> nil then
LItem.Free;
end;
procedure TGestureManager.UnselectGesture(AControl: TControl; AGestureID: TGestureID);
var
LGestureList: TCustomGestureCollection;
begin
if FControls.ContainsKey(AControl) then
LGestureList := FControls.Items[AControl]
else
raise EGestureException.CreateRes(@SControlNotFound);
LGestureList.RemoveGesture(AGestureID);
end;
procedure TGestureManager.WriteRecordedGestures(Writer: TWriter);
begin
FRecordedGestures.FStreamGestureDetails := True;
try
Writer.WriteCollection(FRecordedGestures);
finally
FRecordedGestures.FStreamGestureDetails := False;
end;
end;
procedure TGestureManager.WriteControlData(Writer: TWriter);
var
P: TPair<TControl, TGestureCollection>;
LStreamCollection: TGestureStreamList;
begin
LStreamCollection := TGestureStreamList.Create(csReading in ComponentState);
try
for P in FControls do
with LStreamCollection.Add do
begin
Control := P.Key;
Collection := P.Value;
end;
Writer.WriteCollection(LStreamCollection);
finally
LStreamCollection.Free;
end;
end;
end.
|
unit AProdutosCliente;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Grids, CGrades, Componentes1, ExtCtrls, PainelGradiente, StdCtrls,
Buttons, UnDados, UnProdutos, Localizacao, UnClientes, Menus;
type
TFProdutosCliente = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
BFechar: TBitBtn;
ConsultaPadrao1: TConsultaPadrao;
ECliente: TEditLocaliza;
SpeedButton1: TSpeedButton;
Label1: TLabel;
Label2: TLabel;
EDono: TEditLocaliza;
PanelColor3: TPanelColor;
Grade: TRBStringGridColor;
Splitter1: TSplitter;
EObservacoes: TMemoColor;
PopupMenu1: TPopupMenu;
MProdutoReserva: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GradeNovaLinha(Sender: TObject);
procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure EDonoRetorno(Retorno1, Retorno2: String);
procedure EDonoCadastrar(Sender: TObject);
procedure GradeDadosValidosForaGrade(Sender: TObject;
var VpaValidos: Boolean);
procedure EObservacoesChange(Sender: TObject);
procedure EObservacoesExit(Sender: TObject);
procedure MProdutoReservaClick(Sender: TObject);
procedure GradeRowMoved(Sender: TObject; FromIndex, ToIndex: Integer);
private
{ Private declarations }
VprCodCliente : Integer;
VprAcao : Boolean;
VprProdutoAnterior : String;
VprDItem : TRBDProdutoCliente;
VprProdutos : TList;
procedure CarTitulosGrade;
function ExisteProduto : boolean;
function ExisteDonoProduto : Boolean;
function LocalizaProduto : Boolean;
procedure CarDItemProduto;
public
{ Public declarations }
function CadastraProdutos(VpaCodCliente : Integer):boolean;
end;
var
FProdutosCliente: TFProdutosCliente;
implementation
uses APrincipal, FunObjeto, Constantes, ALocalizaProdutos, FunString, ConstMsg, FunData,
ADonoProduto, AProdutosClientePeca;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFProdutosCliente.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprAcao := false;
VprProdutos := TList.Create;
Grade.ADados := VprProdutos;
CarTitulosGrade;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFProdutosCliente.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FreeTObjectsList(VprProdutos);
VprProdutos.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFProdutosCliente.CarTitulosGrade;
begin
Grade.Cells[1,0] := 'Código';
Grade.Cells[2,0] := 'Produto';
Grade.Cells[3,0] := 'UM';
Grade.Cells[4,0] := 'Quantidade';
Grade.Cells[5,0] := 'Garantia';
Grade.Cells[6,0] := 'Qtd Cópias';
Grade.Cells[7,0] := 'Código';
Grade.Cells[8,0] := 'Proprietário';
Grade.Cells[9,0] := 'Val Concorrente';
Grade.Cells[10,0] := 'Numero Série Produto';
Grade.Cells[11,0] := 'Numero Série Interno';
Grade.Cells[12,0] := 'Setor';
Grade.Cells[13,0] := 'Código';
Grade.Cells[14,0] := 'Suprimento';
end;
{******************************************************************************}
function TFProdutosCliente.ExisteProduto : Boolean;
begin
if (Grade.Cells[1,Grade.ALinha] <> '') then
begin
if Grade.Cells[1,Grade.ALinha] = VprProdutoAnterior then
result := true
else
begin
VprDItem.CodProduto := Grade.Cells[1,Grade.ALinha];
result := FunProdutos.ExisteProduto(VprDItem.CodProduto,VprDItem.SeqProduto,VprDItem.NomProduto,VprDItem.UM);
if result then
begin
VprDItem.UnidadeParentes.free;
VprDItem.UnidadeParentes := FunProdutos.RUnidadesParentes(VprDItem.UM);
Grade.Cells[1,Grade.ALinha] := VprDItem.CodProduto;
VprProdutoAnterior := VprDItem.CodProduto;
Grade.Cells[2,Grade.ALinha] := VprDItem.NomProduto;
VprDItem.UMOriginal := VprDItem.UM;
Grade.Cells[3,Grade.ALinha] := VprDItem.UM;
VprDItem.QtdProduto := 1;
Grade.Cells[4,Grade.ALinha] := FormatFloat(varia.MascaraQTd,VprDItem.Qtdproduto);
end;
end;
end
else
result := false;
end;
{******************************************************************************}
function TFProdutosCliente.ExisteDonoProduto : Boolean;
begin
result := true;
if (Grade.Cells[7,Grade.Alinha]<> '') then
begin
result := FunProdutos.ExisteDonoProduto(StrtoInt(Grade.Cells[7,Grade.ALinha]));
if result then
begin
EDono.text := Grade.Cells[7,Grade.ALinha];
EDono.Atualiza;
end;
end;
end;
{******************************************************************************}
function TFProdutosCliente.LocalizaProduto : Boolean;
var
VpfClaFiscal : String;
begin
FlocalizaProduto := TFlocalizaProduto.criarSDI(Application,'',FPrincipal.VerificaPermisao('FlocalizaProduto'));
Result := FlocalizaProduto.LocalizaProduto(VprDItem.SeqProduto,VprDItem.CodProduto,VprDItem.NomProduto,VprDItem.UM,VpfClaFiscal);
FlocalizaProduto.free;
if result then // se o usuario nao cancelou a consulta
begin
VprDItem.UnidadeParentes.free;
VprDItem.UnidadeParentes := FunProdutos.RUnidadesParentes(VprDItem.UM);
VprProdutoAnterior := VprDItem.CodProduto;
Grade.Cells[1,Grade.ALinha] := VprDItem.CodProduto;
Grade.Cells[2,Grade.ALinha] := VprDItem.NomProduto;
Grade.Cells[3,Grade.ALinha] := VprDItem.UM;
VprDItem.QtdProduto := 1;
Grade.Cells[4,Grade.ALinha] := FormatFloat(varia.MascaraQTd,VprDItem.Qtdproduto);
end;
end;
procedure TFProdutosCliente.MProdutoReservaClick(Sender: TObject);
begin
FProdutosClientePeca := TFProdutosClientePeca.CriarSDI(application,'', FPrincipal.VerificaPermisao('FCelulaTrabalho'));
FProdutosClientePeca.AtualizaConsulta(VprDItem);
FProdutosClientePeca.Showmodal;
FProdutosClientePeca.free;
end;
{******************************************************************************}
procedure TFProdutosCliente.CarDItemProduto;
begin
VprDItem.CodProduto := Grade.Cells[1,Grade.Alinha];
VprDItem.UM := Grade.Cells[3,Grade.Alinha];
VprDItem.QtdProduto := StrToFloat(DeletaChars(Grade.Cells[4,Grade.ALinha],'.'));
if Grade.Cells[5,Grade.ALinha] <> '' then
VprDItem.DatGarantia := StrToDate(Grade.Cells[5,Grade.ALinha])
else
VprDItem.DatGarantia := MontaData(1,1,1900);
if Grade.Cells[6,Grade.ALinha] <> '' then
VprDItem.QtdCopias := strtoInt(Grade.Cells[6,Grade.ALinha])
else
VprDItem.QtdCopias := 0;
if Grade.Cells[7,Grade.ALinha] <> '' then
VprDItem.CodDono := strtoInt(Grade.Cells[7,Grade.ALinha])
else
VprDItem.CodDono := 0;
if Grade.Cells[9,grade.ALinha] <> '' then
VprDItem.ValConcorrente := StrToFloat(Grade.Cells[9,Grade.ALinha])
else
VprDItem.ValConcorrente := 0;
VprDItem.NumSerieProduto := Grade.Cells[10,Grade.ALinha];
VprDItem.NumSerieInterno := Grade.Cells[11,Grade.ALinha];
VprDItem.DesSetorEmpresa := Grade.Cells[12,Grade.ALinha];
VprDItem.DatUltimaAlteracao := now;
end;
{******************************************************************************}
function TFProdutosCliente.CadastraProdutos(VpaCodCliente : Integer):boolean;
begin
VprCodCliente := VpaCodCliente;
ECliente.AInteiro := VpaCodCliente;
ECliente.Atualiza;
FunClientes.CarDProdutoCliente(VpaCodCliente,VprProdutos);
Grade.CarregaGrade;
showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFProdutosCliente.BCancelarClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFProdutosCliente.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFProdutosCliente.BGravarClick(Sender: TObject);
var
VpfResultado : String;
begin
VpfResultado := FunClientes.GravaDProdutoCliente(VprCodCliente,VprProdutos);
if VpfResultado = '' then
begin
VprAcao := true;
close;
end
else
aviso(VpfREsultado);
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDItem := TRBDProdutoCliente(VprProdutos.Items[vpaLinha-1]);
Grade.Cells[1,VpaLinha] := VprDItem.CodProduto;
Grade.Cells[2,VpaLinha] := VprDItem.NomProduto;
Grade.Cells[3,VpaLinha] := VprDItem.UM;
if VprDItem.QtdProduto > 0 then
Grade.Cells[4,VpaLinha] := FormatFloat(Varia.MascaraQtd,VprDItem.QtdProduto)
else
Grade.Cells[4,VpaLinha] := '';
if VprDItem.DatGarantia > MontaData(1,1,1900) then
Grade.Cells[5,VpaLinha] := FormatDatetime('DD/MM/YYYY', VprDItem.DatGarantia)
else
Grade.Cells[5,VpaLinha] := '';
if VprDItem.QtdCopias <> 0 then
Grade.Cells[6,VpaLinha] := inttoStr(VprDItem.QtdCopias)
else
Grade.Cells[6,VpaLinha] := '';
if VprDItem.CodDono <> 0 then
Grade.Cells[7,VpaLinha] := inttoStr(VprDItem.CodDono)
else
Grade.Cells[7,VpaLinha] := '';
Grade.Cells[8,VpaLinha] := VprDItem.NomDono;
if VprDItem.ValConcorrente > 0 then
Grade.Cells[9,VpaLinha] := FormatFloat(Varia.MascaraValorUnitario,VprDItem.ValConcorrente)
else
Grade.Cells[9,VpaLinha] := '';
Grade.Cells[10,VpaLinha] := VprDItem.NumSerieProduto;
Grade.Cells[11,VpaLinha] := VprDItem.NumSerieInterno;
Grade.Cells[12,VpaLinha] := VprDItem.DesSetorEmpresa;
EObservacoes.Lines.Text := VprDItem.DesObservacoes;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
if Grade.Cells[1,Grade.ALinha] = '' then
begin
VpaValidos := false;
aviso(CT_PRODUTONAOCADASTRADO);
end
else
if not ExisteProduto then
begin
VpaValidos := false;
aviso(CT_PRODUTONAOCADASTRADO);
Grade.Col := 1;
end
else
if (VprDItem.UnidadeParentes.IndexOf(Grade.Cells[3,Grade.Alinha]) < 0) then
begin
VpaValidos := false;
aviso(CT_UNIDADEVAZIA);
Grade.col := 3;
end
else
if (Grade.Cells[4,Grade.ALinha] = '') then
begin
VpaValidos := false;
aviso(CT_QTDPRODUTOINVALIDO);
Grade.Col := 4;
end
else
if not ExisteDonoProduto then
begin
VpaValidos := false;
aviso(CT_DONOPRODUTONAOCADATRADO);
Grade.Col := 7;
end;
if Vpavalidos then
begin
CarDItemProduto;
if (VprDItem.QtdProduto = 0) then
begin
VpaValidos := false;
aviso(CT_QTDPRODUTOINVALIDO);
Grade.col :=4;
end
end;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
114 :
begin
case Grade.AColuna of
1: LocalizaProduto;
7: EDono.AAbreLocalizacao;
end;
end;
end;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
begin
if VprProdutos.Count >0 then
begin
VprDItem := TRBDProdutoCliente(VprProdutos.Items[VpaLinhaAtual-1]);
VprProdutoAnterior := VprDItem.CodProduto;
EObservacoes.Lines.Text := VprDItem.DesObservacoes;
end;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeNovaLinha(Sender: TObject);
begin
VprDItem := TRBDProdutoCliente.cria;
VprDItem.CodCliente:= VprCodCliente;
VprProdutos.add(VprDItem);
end;
procedure TFProdutosCliente.GradeRowMoved(Sender: TObject; FromIndex,
ToIndex: Integer);
begin
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
if Grade.AEstadoGrade in [egInsercao,EgEdicao] then
if Grade.AColuna <> ACol then
begin
case Grade.AColuna of
1 :if not ExisteProduto then
begin
if not LocalizaProduto then
begin
Grade.Cells[1,Grade.ALinha] := '';
abort;
end;
end;
7 : if not ExisteDonoProduto then
begin
if not EDono.AAbreLocalizacao then
begin
Grade.Cells[7,Grade.ALinha] := '';
abort;
end;
end;
end;
end;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeGetEditMask(Sender: TObject; ACol,
ARow: Integer; var Value: String);
begin
case ACol of
5 : Value := DeletaChars(Fprincipal.CorFoco.AMascaraData,'\');
7 : Value := '00000;0; ';
end;
end;
{******************************************************************************}
procedure TFProdutosCliente.EDonoRetorno(Retorno1, Retorno2: String);
begin
VprDItem.CodDono := EDono.AInteiro;
VprDItem.NomDono := retorno1;
Grade.cells[7,Grade.ALinha] := EDono.text;
Grade.Cells[8,grade.Alinha] := VprDItem.Nomdono;
end;
procedure TFProdutosCliente.EDonoCadastrar(Sender: TObject);
begin
FDonoProduto := TFDonoProduto.CriarSDI(self,'',FPrincipal.VerificaPermisao('FDonoProduto'));
FDonoProduto.BotaoCadastrar1.Click;
FDonoProduto.ShowModal;
ConsultaPadrao1.AtualizaConsulta;
FDonoProduto.free;
end;
{******************************************************************************}
procedure TFProdutosCliente.GradeDadosValidosForaGrade(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
end;
{******************************************************************************}
procedure TFProdutosCliente.EObservacoesChange(Sender: TObject);
begin
Grade.AEstadoGrade := egEdicao;
end;
procedure TFProdutosCliente.EObservacoesExit(Sender: TObject);
begin
VprDItem.DesObservacoes := EObservacoes.Lines.text;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFProdutosCliente]);
end.
|
(*
AVR Basic Compiler
Copyright 1997-2002 Silicon Studio Ltd.
Copyright 2008 Trioflex OY
http://www.trioflex.com
*)
unit ToolStd;
// Copyright 2000 Case2000
// Generic Services for Tool Output Processing.
// Must compile/link under Delphi/FPC and run in console/gui mode.
interface
uses
EventIntf,
C2Types;
var
WriteStdOutput: TWriteStringProc;
WriteStdError: TWriteStringProc;
GetErrorLineNumber: TGetErrorLineNumberProc;
GetErrorFileName: TGetErrorFileNameProc;
ClearErrorOutput: TClearErrorOutput;
procedure AbstractStringWrite(line: string);
procedure AbstractClearErrorOutput;
implementation
// Raise exception ?
procedure AbstractClearErrorOutput;
begin
// raise EAbstractError.Create('Abstract Error[ClearErrorOutput]');
DebugWrite('AbstractClearErrorOutput');
end;
procedure AbstractStringWrite(line: string);
begin
// raise EAbstractError.Create('Abstract Error[StringWrite]');
DebugWrite('AbstractStringWrite '+line);
end;
// Return unknown line number always
function AbstractGetErrorLineNumber(str: string): integer;
begin
result := -1;
end;
initialization
WriteStdOutput := @AbstractStringWrite;
WriteStdError := @AbstractStringWrite;
ClearErrorOutput := @AbstractClearErrorOutput;
finalization
end.
|
unit ClassKontrola;
interface
uses StdCtrls, Windows, Classes;
type PZast = ^TZast;
TZast = record
Nazov : string;
Sur : TPoint;
Pasmo : byte;
end;
TKontrola = class
private
ListBox : TListBox;
MemoChyby : TMemo;
LabelZast, LabelLinky : TLabel;
Zastavky : TList;
PocetLiniek : word;
procedure PrejdiDatoveSubory;
function UpravNazov( Nazov : string ) : string;
procedure PrejdiSubor( iCesta : string );
procedure ZoradZastavky;
public
constructor Create( iListBox : TListBox; iMemoChyby : TMemo;
iLabelPocetZast, iLabelPocetLiniek : TLabel );
destructor Destroy; override;
end;
implementation
uses SysUtils, Konstanty;
type PMinuty = ^TMinuty;
TStav = (Plus,Minus,Normal);
TMinuty = record
Stav : TStav;
Cas : integer;
Next : PMinuty;
end;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TKontrola.Create( iListBox : TListBox; iMemoChyby : TMemo;
iLabelPocetZast, iLabelPocetLiniek : TLabel );
begin
inherited Create;
ListBox := iListBox;
MemoChyby := iMemoChyby;
LabelZast := iLabelPocetZast;
LabelLinky := iLabelPocetLiniek;
Zastavky := TList.Create;
PocetLiniek := 0;
PrejdiDatoveSubory;
ZoradZastavky;
LabelZast.Caption := 'Počet zastávok : '+IntToStr( Zastavky.Count );
LabelLinky.Caption := 'Počet liniek : '+IntToStr( PocetLiniek );
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TKontrola.Destroy;
var I : integer;
begin
for I := 0 to Zastavky.Count-1 do
Dispose( PZast( Zastavky[I] ) );
Zastavky.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Praca so subormi
//
//==============================================================================
//==============================================================================
function TKontrola.UpravNazov( Nazov : string ) : string;
var I : integer;
begin
I := 1;
while (Nazov[I] = ' ') or
(Nazov[I] = 'z') do
Delete( Nazov , i , 1 );
Result := Nazov;
end;
procedure TKontrola.PrejdiSubor( iCesta : string );
var S : string;
CisloLinky : string;
I, J, N : integer;
A : PMinuty;
Vzdialenost, Pasmo : integer;
PNewZast : PZast;
function NacitajMinuty : PMinuty;
var c : char;
S : string;
begin
Result := nil;
Read( c );
while (c = ' ') and
(not EoLn( Input )) do
Read( c );
if EoLn( Input ) then
begin
readln;
exit;
end;
S := c;
repeat
Read( c );
if c <> ' ' then S := S + c;
until (c = ' ') or
(EoLn( Input ));
if EoLn( Input ) then readln;
if S = '-1' then exit;
New( Result );
c := S[Length(S)];
case c of
'+' : begin
Result^.Stav := Plus;
Delete( S , Length(S) , 1 );
end;
'-' : begin
Result^.Stav := Minus;
Delete( S , Length(S) , 1 );
end;
else Result^.Stav := Normal;
end;
Result^.Cas := StrToInt( S );
Result^.Next := nil;
end;
begin
AssignFile( Input , ROZVRHY_DIR+'\'+iCesta );
Reset( Input );
// MemoChyby.Lines.Add( 'C:\Delphi\Mhd\'+ROZVRHY_DIR+iCesta );
Readln( CisloLinky );
try
StrToInt( CisloLinky );
except
MemoChyby.Lines.Add( 'Nesprávne číslo linky : '+CisloLinky );
end;
Readln( S );
if (S <> 'A') and
(S <> 'E') and
(S <> 'T') and
(S <> 'N') then
MemoChyby.Lines.Add( 'Nesprávny typ spoja : '+CisloLinky );
Readln( S );
Readln( S );
Readln( Vzdialenost , Pasmo , S );
repeat
New( PNewZast );
Zastavky.Add( PNewZast );
with PNewZast^ do
begin
Nazov := UpravNazov( S );
Sur.X := 0;
Sur.Y := 0;
Pasmo := Pasmo;
end;
for I := 0 to ListBox.Items.Count-1 do
if (ListBox.Items.Strings[I] = PNewZast^.Nazov) and
(ListBox.Selected[I]) then
MemoChyby.Lines.Add( 'Nájdený názov hľadanej zastávky : '+PNewZast^.Nazov+' v súbore '+iCesta );
Readln( Vzdialenost , Pasmo , S );
until UpravNazov( S ) = 'KONIEC';
Readln( N );
for I := 1 to N do
for J := 0 to 23 do
begin
repeat
A := NacitajMinuty;
if A = nil then break;
if (A^.Cas > 59) or
(EoLn( Input )) then
begin
MemoChyby.Lines.Add( 'Chyba v rozvrhu :' );
MemoChyby.Lines.Add( 'Linka číslo '+CisloLinky );
MemoChyby.Lines.Add( 'Časť : '+IntToStr( I ) );
MemoChyby.Lines.Add( 'Hodina : '+IntToStr( J ) );
end;
Dispose( A );
until (A^.Cas = -1) or
(EoF( Input) );
if (J < 23) and
(EoF( Input ) ) then
begin
MemoChyby.Lines.Add( 'Predčasný koniec súboru '+iCesta );
break;
end;
end;
if not EoF( Input ) then MemoChyby.Lines.Add( 'Nečakane dlhý súbor '+iCesta );
// MemoChyby.Lines.Add( '' );
CloseFile( Input );
end;
procedure TKontrola.PrejdiDatoveSubory;
var SearchRec : TSearchRec;
begin
if FindFirst( ROZVRHY_DIR+'\*.mhd' , faAnyFile , SearchRec ) <> 0 then
begin
MemoChyby.Lines.Add( 'Nebol nájdený žiadny dátový súbor' );
exit;
end;
Inc( PocetLiniek );
PrejdiSubor( SearchRec.Name );
while FindNext( SearchRec ) = 0 do
begin
Inc( PocetLiniek );
PrejdiSubor( SearchRec.Name );
end;
FindClose( SearchRec );
end;
function Porovnaj( P1, P2 : pointer ) : integer;
var S1, S2 : string;
begin
S1 := string( P1^ );
S2 := string( P2^ );
Result := 0;
if S1 < S2 then Result := -1;
if S1 > S2 then Result := 1;
end;
procedure TKontrola.ZoradZastavky;
var I : integer;
begin
Zastavky.Sort( Porovnaj );
for I := 1 to Zastavky.Count-1 do
if (TZast( Zastavky[I-1]^ ).Nazov = TZast( Zastavky[I]^ ).Nazov) then
begin
Dispose( PZast( Zastavky[I-1] ) );
Zastavky[I-1] := nil;
end;
Zastavky.Pack;
ListBox.Clear;
for I := 0 to Zastavky.Count-1 do
ListBox.Items.Add( TZast( Zastavky[I]^ ).Nazov );
end;
end.
|
unit uDados;
interface
uses
SysUtils, Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
uDWConstsData, uRESTDWPoolerDB, uDWAbout, uniGUIBaseClasses,
uniGUIClasses, UniFSToast, uniImageList, FireDAC.Stan.Async,
FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait,
FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs;
type
TdmDados = class(TDataModule)
Toast: TUniFSToast;
QueryUsuario: TFDQuery;
QueryAuxiliar: TFDQuery;
QueryLogSys: TFDQuery;
QueryLogSysID: TIntegerField;
QueryLogSysDIA: TSQLTimeStampField;
QueryLogSysLOGIN: TStringField;
QueryLogSysOPERACAO: TStringField;
QueryLogSysOCORRENCIA: TStringField;
FDTransaction1: TFDTransaction;
FDConnection1: TFDConnection;
QueryUsuarioID: TIntegerField;
QueryUsuarioNOME: TStringField;
QueryUsuarioEMAIL: TStringField;
QueryUsuarioLOGIN: TStringField;
QueryUsuarioSENHA: TStringField;
QueryUsuarioPERFIL: TStringField;
QueryUsuarioDATA_CADASTRO: TSQLTimeStampField;
QueryUsuarioEMPRESA: TIntegerField;
QueryGrupo: TFDQuery;
QueryGrupoID: TIntegerField;
QueryGrupoNOME: TStringField;
QueryProduto: TFDQuery;
QueryProdutoID: TIntegerField;
QueryProdutoID_GRUPO: TIntegerField;
QueryProdutoCODIGO: TIntegerField;
QueryProdutoCOMPOSICAO: TStringField;
QueryProdutoFOTO: TStringField;
QueryProdutoVALOR: TFloatField;
QueryProdutoGRUPO: TStringField;
QueryGrupoFOTO: TStringField;
UniNativeImageList1: TUniNativeImageList;
QueryGrupoDESCRICAO: TStringField;
QueryProdutoDESCRICAO: TStringField;
FDQueryCaixa: TFDQuery;
QueryProdutoUNIDADE: TStringField;
FDQueryFimPedido: TFDQuery;
FDQueryFimPedidoID: TIntegerField;
FDQueryFimPedidoID_GRUPO: TIntegerField;
FDQueryFimPedidoDESCRICAO: TStringField;
FDQueryFimPedidoVALOR: TFloatField;
FDQueryFimPedidoIDPEDIDO: TIntegerField;
FDQueryFimPedidoCOD_USUARIO: TIntegerField;
FDQueryFimPedidoUNIDADE: TStringField;
FDQueryCaixaDATA_SAIDA: TSQLTimeStampField;
FDQueryCaixaNOMEPRODUTO: TStringField;
FDQueryCaixaPRECO: TFloatField;
FDQueryCaixaQT: TIntegerField;
FDQueryCaixaSUB_PRECO: TFloatField;
FDQueryCaixaCODPRODUTO: TIntegerField;
FDQueryCaixaCOD_BARRA: TIntegerField;
FDQueryCaixaCOD_CLIENTE: TIntegerField;
FDQueryCaixaUNIDADE: TStringField;
FDQueryCaixaINICIO: TSQLTimeStampField;
FDQueryCaixaCOD_VENDA: TIntegerField;
FDQueryCaixaID: TIntegerField;
private
{ Private declarations }
public
{ Public declarations }
end;
function dmDados: TdmDados;
implementation
{$R *.dfm}
uses
UniGUIVars, uniGUIMainModule, MainModule;
function dmDados: TdmDados;
begin
Result := TdmDados(UniMainModule.GetModuleInstance(TdmDados));
end;
initialization
RegisterModuleClass(TdmDados);
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.UITypes, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
//GLScene
GLScene, GLObjects, GLCadencer, GLWin32Viewer, GLTexture, GLCrossPlatform,
GLMaterial, GLCoordinates, GLUtils, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
ColorDialog1: TColorDialog;
GLMaterialLibrary1: TGLMaterialLibrary;
GLLightSource1: TGLLightSource;
Panel1: TPanel;
CBFogEnable: TCheckBox;
LFogStart: TLabel;
LFogEnd: TLabel;
EFogStart: TEdit;
EFogEnd: TEdit;
RGFogDistance: TRadioGroup;
RGFogMode: TRadioGroup;
GBTexture: TGroupBox;
CBTextureEnabled: TCheckBox;
CBTextureIgnoreFog: TCheckBox;
LFogColor: TLabel;
SFogColor: TShape;
CBApplyToBackground: TCheckBox;
LFogDensity: TLabel;
EFogDensity: TEdit;
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure CBFogEnableClick(Sender: TObject);
procedure SEFogStartChange(Sender: TObject);
procedure SFogColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure RGFogModeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBApplyToBackgroundClick(Sender: TObject);
procedure CBTextureEnabledClick(Sender: TObject);
procedure CBTextureIgnoreFogClick(Sender: TObject);
procedure EFogStartChange(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
MX: integer;
MY: integer;
procedure ApplyFogSettings;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
// applyfogsettings
//
procedure TForm1.ApplyFogSettings;
begin
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogMode := TFogMode(RGFogMode.ItemIndex);
FogDistance := TFogDistance(RGFogDistance.ItemIndex);
FogColor.AsWinColor := SFogColor.Brush.Color;
FogColor.Alpha := StrToInt(EFogDensity.Text) / 1000;
if CBApplyToBackground.Checked then
GLSceneViewer1.Buffer.BackgroundColor := SFogColor.Brush.Color;
FogStart := StrToInt(EFogStart.Text);
FogEnd := StrToInt(EFogEnd.Text);
end;
GLSceneViewer1.Buffer.FogEnable := CBFogEnable.Checked;
end;
// glsceneviewer1mousedown
//
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
MX := X;
MY := Y;
end;
// glsceneviewer1mousemove
//
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if Shift <> [] then
GLSceneViewer1.Camera.MoveAroundTarget(MY - Y, MX - X);
MX := X;
MY := Y;
end;
// cbfogenableclick
//
procedure TForm1.CBFogEnableClick(Sender: TObject);
begin
ApplyFogSettings;
end;
// sestartfogchange
//
procedure TForm1.SEFogStartChange(Sender: TObject);
begin
try
ApplyFogSettings;
except
end;
end;
// sgfogcolormousedown
//
procedure TForm1.SFogColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ColorDialog1.Execute then begin
SFogColor.Brush.Color := ColorDialog1.Color;
ApplyFogSettings;
end;
end;
// rgfogmodeclick
//
procedure TForm1.RGFogModeClick(Sender: TObject);
begin
ApplyFogSettings;
end;
// formcreate
//
procedure TForm1.FormCreate(Sender: TObject);
const
cSpacing = 2;
cEdgeLength = 0.7;
cNb = 4;
var
X: integer;
Y: integer;
Z: integer;
Cube : TGLCube;
begin
SetGLSceneMediaDir();
GLMaterialLibrary1.AddTextureMaterial('glscene', 'glscene.bmp');
for X := -cNb to cNb do
for Y := -cNb to cNb do
for Z := -cNb to cNb do
if (X and Y and Z) <> 0 then begin
Cube := TGLCube(GLDummyCube1.AddNewChild(TGLCube));
Cube.Material.MaterialLibrary := GLMaterialLibrary1;
Cube.Material.LibMaterialName := 'glscene';
Cube.Position.SetPoint(X * cSpacing, Y * cSpacing, Z * cSpacing);
Cube.CubeWidth := cEdgeLength;
Cube.CubeHeight := cEdgeLength;
Cube.CubeDepth := cEdgeLength;
end;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta/120));
Handled := true
end;
// cbapplytobackgroundclick
//
procedure TForm1.CBApplyToBackgroundClick(Sender: TObject);
begin
ApplyFogSettings;
end;
// cbtextureenabledclick
//
procedure TForm1.CBTextureEnabledClick(Sender: TObject);
begin
GLMaterialLibrary1.Materials[0].Material.Texture.Enabled := CBTextureEnabled.Checked;
end;
// cbtextureignorefogclick
//
procedure TForm1.CBTextureIgnoreFogClick(Sender: TObject);
begin
if CBTextureIgnoreFog.Checked then
GLMaterialLibrary1.Materials[0].Material.MaterialOptions := GLMaterialLibrary1.Materials[0].Material.MaterialOptions + [moIgnoreFog]
else
GLMaterialLibrary1.Materials[0].Material.MaterialOptions := GLMaterialLibrary1.Materials[0].Material.MaterialOptions - [moIgnoreFog];
end;
procedure TForm1.EFogStartChange(Sender: TObject);
begin
if TEdit(Sender).Text <> '' then
ApplyFogSettings;
end;
end.
|
{ Copyright (C) 1998-2018, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This component allow to scroll the ToolButton's in ToolBar, if they are not fit
on a screen (like Delphi Component Palette)
}
unit ScrlTool;
interface
{$I SMVersion.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
extctrls, comctrls,
{$IFDEF SMForDelphi6} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF}
;
type
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TScrollToolBar = class(TWinControl)
private
{ Private declarations }
FScrollerToolBar: TToolBar;
FLeftBtn, FRightBtn: TImage; {left and right scroll}
FVisibleCount: Integer; {count of visible buttons from toolbar on a frame}
FShiftCount: Integer; {button count before "left/start frame"}
procedure SwitchEnableImages;
procedure FLeftClick(Sender: TObject);
procedure FRightClick(Sender: TObject);
procedure FReVisibleCount(Sender: TObject);
procedure ShowHideButtons(Sender: TObject);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property ScrollerToolBar: TToolBar read FScrollerToolBar write FScrollerToolBar;
end;
{ TScrollToolBarEditor }
TScrollToolBarEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure Register;
implementation
{ $R SCRLTOOL.RES}
{$R *.RES}
procedure Register;
begin
RegisterComponentEditor(TScrollToolBar, TScrollToolBarEditor);
RegisterComponents('SMComponents', [TScrollToolBar]);
end;
constructor TScrollToolBar.Create(AOwner: TComponent);
//var
// i: integer;
begin
if not (AOwner is TWinControl) then
begin
MessageDlg('Parent component must to be a inherited from TWinControl', mtError, [mbOk], 0);
Abort;
end;
inherited Create(AOwner);
Height := 32;
Parent := AOwner as TWinControl;
Align := alTop;
FLeftBtn := TImage.Create(Self);
FLeftBtn.Enabled := False;
FLeftBtn.Width := 16;
FLeftBtn.Parent := Self;
FLeftBtn.Stretch := True;
FLeftBtn.Align := alLeft;
FLeftBtn.OnClick := FLeftClick;
FRightBtn := TImage.Create(Self);
FRightBtn.Enabled := False;
FRightBtn.Width := 16;
FRightBtn.Parent := Self;
FRightBtn.Stretch := True;
FRightBtn.Align := alRight;
FRightBtn.OnClick := FRightClick;
FScrollerToolBar := TToolBar.Create(Self);
FScrollerToolBar.Parent := Self;
FScrollerToolBar.Align := alClient;
FScrollerToolBar.ShowCaptions := True;
FScrollerToolBar.Wrapable := False;
FScrollerToolBar.OnResize := FReVisibleCount;
{ for i := 1 to 10 do
with TToolButton.Create(Self) do
begin
Caption := 'new_' + inttostr(i);
Enabled := True;
Style := tbsButton;
Visible := True;
Parent := FScrollerToolBar;
end;
}
FShiftCount := 0;
FReVisibleCount(FScrollerToolBar);
end;
destructor TScrollToolBar.Destroy;
begin
FScrollerToolBar.Free;
FLeftBtn.Free;
FLeftBtn := nil;
FRightBtn.Free;
FRightBtn := nil;
inherited Destroy;
end;
procedure TScrollToolBar.SwitchEnableImages;
begin
with FLeftBtn do
begin
Enabled := (FShiftCount > 0);
if Enabled then
Picture.Bitmap.Handle := LoadBitmap(hInstance, 'LEFTBTNENABLED')
else
Picture.Bitmap.Handle := LoadBitmap(hInstance, 'LEFTBTNDISABLED')
end;
with FRightBtn do
begin
Enabled := (FScrollerToolBar.ButtonCount - FShiftCount - FVisibleCount > 0);
if Enabled then
Picture.Bitmap.Handle := LoadBitmap(hInstance, 'RIGHTBTNENABLED')
else
Picture.Bitmap.Handle := LoadBitmap(hInstance, 'RIGHTBTNDISABLED')
end;
ShowHideButtons(FScrollerToolBar);
end;
procedure TScrollToolBar.FLeftClick(Sender: TObject);
begin
if (FLeftBtn.Enabled = True) and (FShiftCount > 0) then
begin
Dec(FShiftCount);
SwitchEnableImages;
end;
end;
procedure TScrollToolBar.FRightClick(Sender: TObject);
begin
if (FRightBtn.Enabled = True) and (FScrollerToolBar.ButtonCount - FShiftCount - FVisibleCount > 0) then
begin
Inc(FShiftCount);
SwitchEnableImages;
end;
end;
procedure TScrollToolBar.FReVisibleCount(Sender: TObject);
begin
if (FScrollerToolBar.ButtonCount > 0) then
FVisibleCount := FScrollerToolBar.Width div FScrollerToolBar.Buttons[0].Width
// FVisibleCount := FScrollerToolBar.Width div FScrollerToolBar.Buttons[FScrollerToolBar.ButtonCount-1].Width
else
FVisibleCount := 0;
SwitchEnableImages;
end;
procedure TScrollToolBar.ShowHideButtons(Sender: TObject);
var i: Integer;
begin
for i := 0 to FScrollerToolBar.ButtonCount - 1 do
FScrollerToolBar.Buttons[i].Visible := (i > FShiftCount - 1) and (i < FShiftCount + FVisibleCount + 1);
end;
{ TScrollToolBarEditor }
procedure TScrollToolBarEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: MessageDlg('Index = ' + IntToStr(Index), mtInformation, [mbOk], 0);
1: MessageDlg('Index = ' + IntToStr(Index), mtInformation, [mbOk], 0);
//ShowProxyEditor(Designer, TPageManager(Component));
end;
end;
function TScrollToolBarEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'New Button';
1: Result := 'New Separator';
end;
end;
function TScrollToolBarEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.