text stringlengths 14 6.51M |
|---|
unit uspQuery;
interface
uses
System.SysUtils, System.Classes, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client;
type
TspQuery = class(TFDQuery)
private
FspCondicoes: TStrings;
FspColunas: TStrings;
FspTabelas: TStrings;
procedure VerificaErros;
function CriarClausulaSelect: String;
function CriarClausulaFrom: String;
function CriarClausulaWhere: String;
{ Private declarations }
protected
{ Protected declarations }
public
procedure GeraSQL;
{ Public declarations }
published
property spCondicoes: TStrings read FspCondicoes write FspCondicoes;
property spColunas: TStrings read FspColunas write FspColunas;
property spTabelas: TStrings read FspTabelas write FspTabelas;
{ Published declarations }
end;
const
NL = #13#10;
SP = #32#32;
implementation
{ TspQuery }
function TspQuery.CriarClausulaFrom: String;
begin
Result := 'from' + NL + SP + FspTabelas.DelimitedText;
end;
function TspQuery.CriarClausulaSelect: String;
begin
if (not Assigned(FspColunas)) or (FspColunas.Count <1) then
Result := 'select' + NL + SP + '*'
else
begin
FspColunas.Delimiter := ',';
Result := 'select' + NL + SP + FspColunas.DelimitedText.Replace(',', ', ');
end;
end;
function TspQuery.CriarClausulaWhere: String;
begin
if (not Assigned(FspCondicoes)) or (FspCondicoes.Count < 1) then
Result := EmptyStr
else
begin
FspCondicoes.Delimiter := ',';
Result := 'where' + NL + SP + FspCondicoes.DelimitedText.Replace(',', ' and ');
end;
end;
procedure TspQuery.GeraSQL;
begin
VerificaErros;
SQL.Clear;
SQL.Add(CriarClausulaSelect);
SQL.Add(CriarClausulaFrom);
SQL.Add(CriarClausulaWhere);
end;
procedure TspQuery.VerificaErros;
begin
if (not Assigned(FspTabelas)) or (not (FspTabelas.Count = 1))then
raise Exception.Create('TspQuery - Deve ser informado uma tabela');
end;
end.
|
unit ScrollingWinControlWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ScrollingWinControlWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ScrollingWinControlWordsPack" MUID: (54F5881101AC)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, Controls
, Forms
, tfwPropertyLike
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, Windows
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *54F5881101ACimpl_uses*
//#UC END# *54F5881101ACimpl_uses*
;
type
TkwPopControlVScrollerVisible = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:VScrollerVisible }
private
function VScrollerVisible(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:VScrollerVisible }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlVScrollerVisible
TkwPopControlHScrollerVisible = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:HScrollerVisible }
private
function HScrollerVisible(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:HScrollerVisible }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlHScrollerVisible
TkwPopScrollingWinControlVScrollerVisible = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:ScrollingWinControl:VScrollerVisible }
private
function VScrollerVisible(const aCtx: TtfwContext;
aScrollingWinControl: TScrollingWinControl): Boolean;
{* Реализация слова скрипта pop:ScrollingWinControl:VScrollerVisible }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopScrollingWinControlVScrollerVisible
TkwPopScrollingWinControlHScrollerVisible = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:ScrollingWinControl:HScrollerVisible }
private
function HScrollerVisible(const aCtx: TtfwContext;
aScrollingWinControl: TScrollingWinControl): Boolean;
{* Реализация слова скрипта pop:ScrollingWinControl:HScrollerVisible }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopScrollingWinControlHScrollerVisible
function TkwPopControlVScrollerVisible.VScrollerVisible(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:VScrollerVisible }
//#UC START# *54F878D80349_54F878D80349_47E124E90272_Word_var*
var
l_PageMax: Integer;
l_RangeMax: Integer;
l_Err: Integer;
l_PageInfo: TScrollInfo;
//#UC END# *54F878D80349_54F878D80349_47E124E90272_Word_var*
begin
//#UC START# *54F878D80349_54F878D80349_47E124E90272_Word_impl*
if (aControl Is TScrollingWinControl) then
Result := TScrollingWinControl(aControl).VertScrollBar.IsScrollBarVisible
else
begin
with l_PageInfo do
begin
cbSize := SizeOf(l_PageInfo);
fMask := SIF_ALL;
end;//with l_ScrollInfo
if GetScrollInfo(aControl.Handle, SB_VERT, l_PageInfo) then
begin
l_PageMax := l_PageInfo.nPage;
l_RangeMax := l_PageInfo.nMax;
Result := l_RangeMax > l_PageMax;
end
else
begin
l_Err := GetLastError;
if l_Err = 1447 then // 1447: Окно не имеет полос прокрутки.
Result := False
else
RunnerAssert(False, 'Ошибка при вызове GetScrollInfo. Код ошибки: ' + IntToStr(l_Err), aCtx);
end;
end;//aControl Is TScrollingWinControl
//#UC END# *54F878D80349_54F878D80349_47E124E90272_Word_impl*
end;//TkwPopControlVScrollerVisible.VScrollerVisible
class function TkwPopControlVScrollerVisible.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:VScrollerVisible';
end;//TkwPopControlVScrollerVisible.GetWordNameForRegister
function TkwPopControlVScrollerVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopControlVScrollerVisible.GetResultTypeInfo
function TkwPopControlVScrollerVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlVScrollerVisible.GetAllParamsCount
function TkwPopControlVScrollerVisible.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlVScrollerVisible.ParamsTypes
procedure TkwPopControlVScrollerVisible.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству VScrollerVisible', aCtx);
end;//TkwPopControlVScrollerVisible.SetValuePrim
procedure TkwPopControlVScrollerVisible.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(VScrollerVisible(aCtx, l_aControl));
end;//TkwPopControlVScrollerVisible.DoDoIt
function TkwPopControlHScrollerVisible.HScrollerVisible(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:HScrollerVisible }
//#UC START# *54F878EC0363_54F878EC0363_47E124E90272_Word_var*
var
l_PageMax: Integer;
l_RangeMax: Integer;
l_Err: Integer;
l_PageInfo: TScrollInfo;
//#UC END# *54F878EC0363_54F878EC0363_47E124E90272_Word_var*
begin
//#UC START# *54F878EC0363_54F878EC0363_47E124E90272_Word_impl*
if (aControl Is TScrollingWinControl) then
Result := TScrollingWinControl(aControl).HorzScrollBar.IsScrollBarVisible
else
begin
with l_PageInfo do
begin
cbSize := SizeOf(l_PageInfo);
fMask := SIF_ALL;
end;//with l_ScrollInfo
if GetScrollInfo(aControl.Handle, SB_HORZ, l_PageInfo) then
begin
l_PageMax := l_PageInfo.nPage;
l_RangeMax := l_PageInfo.nMax;
Result := l_RangeMax > l_PageMax;
end
else
begin
l_Err := GetLastError;
if l_Err = 1447 then // 1447: Окно не имеет полос прокрутки.
Result := False
else
RunnerAssert(False, 'Ошибка при вызове GetScrollInfo. Код ошибки: ' + IntToStr(l_Err), aCtx);
end;
end;//aControl Is TScrollingWinControl
//#UC END# *54F878EC0363_54F878EC0363_47E124E90272_Word_impl*
end;//TkwPopControlHScrollerVisible.HScrollerVisible
class function TkwPopControlHScrollerVisible.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:HScrollerVisible';
end;//TkwPopControlHScrollerVisible.GetWordNameForRegister
function TkwPopControlHScrollerVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopControlHScrollerVisible.GetResultTypeInfo
function TkwPopControlHScrollerVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlHScrollerVisible.GetAllParamsCount
function TkwPopControlHScrollerVisible.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlHScrollerVisible.ParamsTypes
procedure TkwPopControlHScrollerVisible.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству HScrollerVisible', aCtx);
end;//TkwPopControlHScrollerVisible.SetValuePrim
procedure TkwPopControlHScrollerVisible.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(HScrollerVisible(aCtx, l_aControl));
end;//TkwPopControlHScrollerVisible.DoDoIt
function TkwPopScrollingWinControlVScrollerVisible.VScrollerVisible(const aCtx: TtfwContext;
aScrollingWinControl: TScrollingWinControl): Boolean;
{* Реализация слова скрипта pop:ScrollingWinControl:VScrollerVisible }
//#UC START# *54F878D80349_54F878D80349_495259490229_Word_var*
//#UC END# *54F878D80349_54F878D80349_495259490229_Word_var*
begin
//#UC START# *54F878D80349_54F878D80349_495259490229_Word_impl*
Result := aScrollingWinControl.VertScrollBar.IsScrollBarVisible;
//#UC END# *54F878D80349_54F878D80349_495259490229_Word_impl*
end;//TkwPopScrollingWinControlVScrollerVisible.VScrollerVisible
class function TkwPopScrollingWinControlVScrollerVisible.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:ScrollingWinControl:VScrollerVisible';
end;//TkwPopScrollingWinControlVScrollerVisible.GetWordNameForRegister
function TkwPopScrollingWinControlVScrollerVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopScrollingWinControlVScrollerVisible.GetResultTypeInfo
function TkwPopScrollingWinControlVScrollerVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopScrollingWinControlVScrollerVisible.GetAllParamsCount
function TkwPopScrollingWinControlVScrollerVisible.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TScrollingWinControl)]);
end;//TkwPopScrollingWinControlVScrollerVisible.ParamsTypes
procedure TkwPopScrollingWinControlVScrollerVisible.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству VScrollerVisible', aCtx);
end;//TkwPopScrollingWinControlVScrollerVisible.SetValuePrim
procedure TkwPopScrollingWinControlVScrollerVisible.DoDoIt(const aCtx: TtfwContext);
var l_aScrollingWinControl: TScrollingWinControl;
begin
try
l_aScrollingWinControl := TScrollingWinControl(aCtx.rEngine.PopObjAs(TScrollingWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aScrollingWinControl: TScrollingWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(VScrollerVisible(aCtx, l_aScrollingWinControl));
end;//TkwPopScrollingWinControlVScrollerVisible.DoDoIt
function TkwPopScrollingWinControlHScrollerVisible.HScrollerVisible(const aCtx: TtfwContext;
aScrollingWinControl: TScrollingWinControl): Boolean;
{* Реализация слова скрипта pop:ScrollingWinControl:HScrollerVisible }
//#UC START# *54F878EC0363_54F878EC0363_495259490229_Word_var*
//#UC END# *54F878EC0363_54F878EC0363_495259490229_Word_var*
begin
//#UC START# *54F878EC0363_54F878EC0363_495259490229_Word_impl*
Result := aScrollingWinControl.HorzScrollBar.IsScrollBarVisible;
//#UC END# *54F878EC0363_54F878EC0363_495259490229_Word_impl*
end;//TkwPopScrollingWinControlHScrollerVisible.HScrollerVisible
class function TkwPopScrollingWinControlHScrollerVisible.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:ScrollingWinControl:HScrollerVisible';
end;//TkwPopScrollingWinControlHScrollerVisible.GetWordNameForRegister
function TkwPopScrollingWinControlHScrollerVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopScrollingWinControlHScrollerVisible.GetResultTypeInfo
function TkwPopScrollingWinControlHScrollerVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopScrollingWinControlHScrollerVisible.GetAllParamsCount
function TkwPopScrollingWinControlHScrollerVisible.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TScrollingWinControl)]);
end;//TkwPopScrollingWinControlHScrollerVisible.ParamsTypes
procedure TkwPopScrollingWinControlHScrollerVisible.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству HScrollerVisible', aCtx);
end;//TkwPopScrollingWinControlHScrollerVisible.SetValuePrim
procedure TkwPopScrollingWinControlHScrollerVisible.DoDoIt(const aCtx: TtfwContext);
var l_aScrollingWinControl: TScrollingWinControl;
begin
try
l_aScrollingWinControl := TScrollingWinControl(aCtx.rEngine.PopObjAs(TScrollingWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aScrollingWinControl: TScrollingWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(HScrollerVisible(aCtx, l_aScrollingWinControl));
end;//TkwPopScrollingWinControlHScrollerVisible.DoDoIt
initialization
TkwPopControlVScrollerVisible.RegisterInEngine;
{* Регистрация pop_Control_VScrollerVisible }
TkwPopControlHScrollerVisible.RegisterInEngine;
{* Регистрация pop_Control_HScrollerVisible }
TkwPopScrollingWinControlVScrollerVisible.RegisterInEngine;
{* Регистрация pop_ScrollingWinControl_VScrollerVisible }
TkwPopScrollingWinControlHScrollerVisible.RegisterInEngine;
{* Регистрация pop_ScrollingWinControl_HScrollerVisible }
TtfwTypeRegistrator.RegisterType(TypeInfo(TWinControl));
{* Регистрация типа TWinControl }
TtfwTypeRegistrator.RegisterType(TypeInfo(TScrollingWinControl));
{* Регистрация типа TScrollingWinControl }
TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean));
{* Регистрация типа Boolean }
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
{$include lem_directives.inc}
unit LemTriggers;
interface
type
TTrigger = class
end;
(*
// Object Trigger Effects
ote_None = 0; // no effect (harmless)
ote_Exit = 1; // lemming reaches the exit
ote_BlockerLeft = 2; // not used in DOS metadata, but reserved for 2D-objectmap
ote_BlockerRight = 3; // not used in DOS metadata, but reserved for 2D-objectmap
ote_TriggeredTrap = 4; // trap that animates once and kills a lemming
ote_Drown = 5; // used for watertype objects
ote_Vaporize = 6; // desintegration
ote_OneWayWallLeft = 7; // bash en mine restriction (arrows)
ote_OneWayWallRight = 8; // bash en mine restriction (arrows)
ote_Steel = 9; // not used by DOS metadata, but reserved for 2D-objectmap
*)
implementation
end.
|
{ *************************************************************************** }
{ }
{ This file is part of the XPde project }
{ }
{ Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> }
{ }
{ This program is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU General Public }
{ License as published by the Free Software Foundation; either }
{ version 2 of the License, or (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ General Public License for more details. }
{ }
{ You should have received a copy of the GNU General Public License }
{ along with this program; see the file COPYING. If not, write to }
{ the Free Software Foundation, Inc., 59 Temple Place - Suite 330, }
{ Boston, MA 02111-1307, USA. }
{ }
{ *************************************************************************** }
unit uXPStartButton;
interface
uses
Classes, QExtCtrls, uCommon,
QControls, QForms, QGraphics,
QDialogs, Sysutils, Types;
type
TXPStartButton=class(TPanel)
private
FDown: boolean;
FOver: TBitmap;
FNormal: TBitmap;
FPressed: TBitmap;
FOnShowMenu: TNotifyEvent;
procedure SetOnShowMenu(const Value: TNotifyEvent);
public
procedure release;
procedure MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer);override;
procedure mouseenter(AControl:TControl);override;
procedure mouseleave(AControl:TControl);override;
procedure setup;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
published
property OnShowMenu: TNotifyEvent read FOnShowMenu write SetOnShowMenu;
end;
implementation
{ TXPStartButton }
constructor TXPStartButton.Create(AOwner: TComponent);
begin
inherited;
FDown:=false;
FOnShowMenu:=nil;
FOver:=TBitmap.create;
FNormal:=TBitmap.create;
FPressed:=TBitmap.create;
setup;
end;
destructor TXPStartButton.Destroy;
begin
FOver.free;
FNormal.free;
FPressed.free;
inherited;
end;
procedure TXPStartButton.MouseDown(button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
inherited;
if (not FDown) then begin
FDown:=true;
bitmap.assign(FPressed);
if assigned(FOnShowMenu) then FOnShowMenu(self);
end
else begin
FDown:=false;
if ptinrect(clientrect,point(x,y)) then bitmap.assign(FOver)
else bitmap.assign(FNormal);
end;
end;
procedure TXPStartButton.mouseenter(AControl: TControl);
begin
inherited;
if (not FDown) then bitmap.assign(FOver);
end;
procedure TXPStartButton.mouseleave(AControl: TControl);
begin
inherited;
if (not FDown) then bitmap.assign(FNormal);
end;
procedure TXPStartButton.release;
begin
FDown:=false;
if ptinrect(clientrect,ScreenToClient(mouse.CursorPos)) then bitmap.assign(FOver)
else bitmap.assign(FNormal);
SetMouseGrabControl(nil);
end;
procedure TXPStartButton.SetOnShowMenu(const Value: TNotifyEvent);
begin
FOnShowMenu := Value;
end;
procedure TXPStartButton.setup;
var
dir: string;
const
st_x=24;
st_y=7;
title='StartMenu';
style=[fsBold];
fsize=11;
begin
BevelOuter:=bvNone;
dir:=getSystemInfo(XP_TASKBAR_DIR);
FNormal.LoadFromFile(dir+'/start_button_normal.png');
FNormal.canvas.font.Size:=fsize;
FNormal.canvas.font.Style:=style;
FNormal.canvas.font.color:=clGray;
FNormal.Canvas.TextOut(st_x+1,st_y+1,title);
FNormal.canvas.font.color:=clWhite;
FNormal.Canvas.TextOut(st_x,st_y,title);
FOver.LoadFromFile(dir+'/start_button_over.png');
FOver.canvas.font.Size:=fsize;
FOver.canvas.font.Style:=style;
FOver.canvas.font.color:=clGray;
FOver.Canvas.TextOut(st_x+1,st_y+1,title);
FOver.canvas.font.color:=clWhite;
FOver.Canvas.TextOut(st_x,st_y,title);
FPressed.LoadFromFile(dir+'/start_button_press.png');
FPressed.canvas.font.Size:=fsize;
FPressed.canvas.font.Style:=style;
FPressed.canvas.font.color:=clGray;
FPressed.Canvas.TextOut(st_x+1,st_y+1,title);
FPressed.canvas.font.color:=clWhite;
FPressed.Canvas.TextOut(st_x,st_y,title);
bitmap.assign(FNormal);
width:=bitmap.width;
height:=bitmap.height;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StPtrns.pas 4.04 *}
{*********************************************************}
{* SysTools: Pattern Classes *}
{*********************************************************}
{$include StDefine.inc}
unit StPtrns;
interface
uses
Windows, SysUtils, Classes;
{------ S I N G L E T O N ---------------------}
type
TStSingleton = class(TObject)
private
FRefCount : integer;
protected
public
class function NewInstance : TObject; override;
procedure FreeInstance; override;
procedure AllocResources; virtual;
procedure FreeResources; virtual;
end;
{------ M E D I A T O R ------------------------}
type
TStMediatorAction = procedure(aInputData, aResultData : TObject) of object;
TStMediator = class
private
FEventTable : TStringList;
protected
function GetCount : Integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(const aEventName : string; aHandler : TStMediatorAction);
procedure Remove(const aEventName : string);
procedure Handle(const aEventName : string; aInputData, aResultData : TObject);
function IsHandled(const aEventName : string) : boolean;
property Count : Integer read GetCount;
end;
{-------O B S E R V E R ------------------------}
type
TStObserverAction = procedure(aInputData : TObject) of object;
TStObserver = class
private
FEventTable : TList;
protected
function GetObserver(Index : Integer) : TStObserverAction;
procedure SetObserver(Index : Integer; InObserver : TStObserverAction);
function GetCount : Integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(aHandler : TStObserverAction);
procedure Remove(aIndex : Integer);
procedure Notify(aInputData : TObject);
property Handler[aIndex : Integer] : TStObserverAction
read GetObserver write SetObserver;
property Count : Integer read GetCount;
end;
{------- C H A I N ---------------------------------}
type
TStChainAction = procedure(aInputData, aResultData : TObject; var aStopNow : boolean) of object;
TStChain = class
private
FEventTable : TList;
protected
function GetHandler(Index : Integer) : TStChainAction;
procedure SetHandler(Index : Integer; InHandler : TStChainAction);
function GetCount : Integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(aHandler : TStChainAction);
procedure Remove(aIndex : Integer);
procedure Handle(aInputData, aResultData : TObject);
procedure Insert(aIndex : Integer; aHandler : TStChainAction);
property Handler[aIndex : Integer] : TStChainAction
read GetHandler write SetHandler;
property Count : Integer read GetCount;
end;
{====================================================================}
{====================================================================}
implementation
{------ S I N G L E T O N ---------------------}
var
Instances : TStringList;
SingletonLock : TRTLCriticalSection;
procedure TStSingleton.AllocResources;
begin
{nothing at this level}
end;
{--------}
procedure TStSingleton.FreeInstance;
var
Temp : pointer;
Inx : integer;
begin
EnterCriticalSection(SingletonLock);
try
dec(FRefCount);
if (FRefCount = 0) then begin
FreeResources;
Temp := Self;
CleanupInstance;
if Instances.Find(ClassName, Inx) then
Instances.Delete(Inx);
FreeMem(Temp);
end;
finally
LeaveCriticalSection(SingletonLock);
end;
end;
{--------}
procedure TStSingleton.FreeResources;
begin
{nothing at this level}
end;
{--------}
class function TStSingleton.NewInstance : TObject;
var
Inx : integer;
begin
EnterCriticalSection(SingletonLock);
try
if not Instances.Find(ClassName, Inx) then begin
GetMem(pointer(Result), InstanceSize);
InitInstance(Result);
Instances.AddObject(ClassName, Result);
TStSingleton(Result).AllocResources;
end
else
Result := Instances.Objects[Inx];
inc(TStSingleton(Result).FRefCount);
finally
LeaveCriticalSection(SingletonLock);
end;
end;
{====================================================================}
{------ M E D I A T O R ------------------------}
{The action holder is a class that encapsulates the action method}
type
TStMedActionHolder = class(TObject)
private
FAction : TStMediatorAction;
public
property Action : TStMediatorAction read FAction write FAction;
end;
{--------}
constructor TStMediator.Create;
begin
inherited Create;
FEventTable := TStringList.Create;
FEventTable.Sorted := true;
end;
destructor TStMediator.Destroy;
var
i : integer;
begin
if (FEventTable <> nil) then begin
for i := 0 to pred(FEventTable.Count) do
FEventTable.Objects[i].Free;
FEventTable.Free;
end;
inherited Destroy;
end;
procedure TStMediator.Add(const aEventName : string; aHandler : TStMediatorAction);
var
MedAction : TStMedActionHolder;
begin
MedAction := TStMedActionHolder.Create;
MedAction.Action := aHandler;
if (FEventTable.AddObject(aEventName, MedAction) = -1) then begin
MedAction.Free;
raise Exception.Create(
Format('TStMediator.Add: event name [%s] already exists',
[aEventName]));
end;
end;
function TStMediator.GetCount : Integer;
begin
Result := FEventTable.Count;
end;
procedure TStMediator.Handle(const aEventName : string; aInputData, aResultData : TObject);
var
Index : Integer;
MediatorActionHolder : TStMedActionHolder;
begin
Index := FEventTable.IndexOf(aEventName);
if (Index < 0) then
raise Exception.Create(
Format('TStMediator.Handle: event name [%s] not found',
[aEventName]));
MediatorActionHolder := TStMedActionHolder(FEventTable.Objects[Index]);
MediatorActionHolder.Action(aInputData, aResultData);
end;
function TStMediator.IsHandled(const aEventName : string) : boolean;
var
Index : Integer;
begin
Result := FEventTable.Find(aEventName, Index);
end;
procedure TStMediator.Remove(const aEventName : string);
var
Index : Integer;
begin
Index := FEventTable.IndexOf(aEventName);
if (Index >= 0) then begin
FEventTable.Objects[Index].Free;
FEventTable.Delete(Index);
end;
end;
{====================================================================}
{-------O B S E R V E R ------------------------}
{The action holder is a class that encapsulates the action method}
type
TStObActionHolder = class(TObject)
private
FAction : TStObserverAction;
public
property Action : TStObserverAction read FAction write FAction;
end;
{--------}
constructor TStObserver.Create;
begin
inherited Create;
FEventTable := TList.Create;
end;
destructor TStObserver.Destroy;
var
i : integer;
begin
if (FEventTable <> nil) then begin
for i := 0 to pred(FEventTable.Count) do
TStObActionHolder(FEventTable[i]).Free;
FEventTable.Free;
end;
inherited Destroy;
end;
procedure TStObserver.Add(aHandler : TStObserverAction);
var
ObsAction : TStObActionHolder;
begin
ObsAction := TStObActionHolder.Create;
try
ObsAction.Action := aHandler;
FEventTable.Add(TObject(ObsAction));
except
ObsAction.Free;
raise;
end;
end;
function TStObserver.GetCount : Integer;
begin
Result := FEventTable.Count;
end;
function TStObserver.GetObserver(Index : Integer) : TStObserverAction;
var
ObserverHolder : TStObActionHolder;
begin
Assert((Index >= 0) and (Index < FEventTable.Count),
Format('TStObserver.GetObserver: Invalid index value: %d', [Index]));
ObserverHolder := TStObActionHolder(FEventTable.Items[Index]);
Result := ObserverHolder.Action;
end;
procedure TStObserver.Notify(aInputData : TObject);
var
Index : integer;
ObserverHolder : TStObActionHolder;
begin
for Index := 0 to FEventTable.Count-1 do begin
ObserverHolder := TStObActionHolder(FEventTable.Items[Index]);
ObserverHolder.Action(aInputData);
end;
end;
procedure TStObserver.Remove(aIndex : Integer);
begin
Assert((aIndex >= 0) and (aIndex < FEventTable.Count),
Format('TStObserver.Remove: Invalid index value: %d', [aIndex]));
TStObActionHolder(FEventTable.Items[aIndex]).Free;
FEventTable.Delete(aIndex);
end;
procedure TStObserver.SetObserver(Index : Integer;
InObserver : TStObserverAction);
begin
Assert((Index >= 0) and (Index < FEventTable.Count),
Format('TStObserver.SetObserver: Invalid index value: %d', [Index]));
TStObActionHolder(FEventTable.Items[Index]).Action := InObserver;
end;
{====================================================================}
{------- C H A I N ---------------------------------}
{The action holder is a class that encapsulates the action method}
type
TStChActionHolder = class(TObject)
private
FAction : TStChainAction;
public
property Action : TStChainAction read FAction write FAction;
end;
{--------}
constructor TStChain.Create;
begin
inherited Create;
FEventTable := TList.create;
end;
destructor TStChain.Destroy;
var
i : integer;
begin
if (FEventTable <> nil) then begin
for i := 0 to pred(FEventTable.Count) do
TStChActionHolder(FEventTable[i]).Free;
FEventTable.Free;
end;
inherited Destroy;
end;
procedure TStChain.Add(aHandler : TStChainAction);
var
ChainAction : TStChActionHolder;
begin
ChainAction := TStChActionHolder.Create;
try
ChainAction.Action := aHandler;
FEventTable.Add(TObject(ChainAction));
except
ChainAction.Free;
raise;
end;
end;
function TStChain.GetCount : Integer;
begin
Result := FEventTable.Count;
end;
function TStChain.GetHandler(Index : Integer) : TStChainAction;
var
ChainAction : TStChActionHolder;
begin
Assert((Index >= 0) and (Index < FEventTable.Count),
Format('TStChain.GetHandler: Invalid index value: %d', [Index]));
ChainAction := TStChActionHolder(FEventTable.Items[Index]);
Result := ChainAction.Action;
end;
procedure TStChain.Handle(aInputData, aResultData : TObject);
var
Index : integer;
Stop : boolean;
ChainAction : TStChActionHolder;
begin
Stop := false;
for Index := 0 to (FEventTable.Count - 1) do begin
ChainAction := TStChActionHolder(FEventTable.Items[Index]);
ChainAction.Action(aInputData, aResultData, Stop);
if Stop then
Exit;
end;
end;
procedure TStChain.Insert(aIndex : integer; aHandler : TStChainAction);
var
ChainAction : TStChActionHolder;
begin
ChainAction := TStChActionHolder.Create;
try
ChainAction.Action := aHandler;
FEventTable.Insert(aIndex, ChainAction);
except
ChainAction.Free;
raise;
end;
end;
procedure TStChain.Remove(aIndex : Integer);
begin
Assert((aIndex >= 0) and (aIndex < FEventTable.Count),
Format('TStChain.Remove: Invalid index value: %d', [aIndex]));
TStChActionHolder(FEventTable.Items[aIndex]).Free;
FEventTable.Delete(aIndex);
end;
procedure TStChain.SetHandler(Index : Integer; InHandler : TStChainAction);
begin
Assert((Index >= 0) and (Index < FEventTable.Count),
Format('TStObserver.SetObserver: Invalid index value: %d', [Index]));
TStChActionHolder(FEventTable.Items[Index]).Action := InHandler;
end;
procedure InitUnit;
begin
InitializeCriticalSection(SingletonLock);
Instances := TStringList.Create;
Instances.Sorted := true;
end;
procedure DoneUnit;
var
i : integer;
OldCount : integer;
begin
EnterCriticalSection(SingletonLock);
{continue 'freeing' the last singleton object in the Instances
stringlist until its FreeInstance method actually frees the object
and removes the class name from the stringlist: we detect this
condition by the fact that the number of items in the stringlist
decreases.}
OldCount := Instances.Count;
for i := pred(OldCount) downto 0 do begin
repeat
Instances.Objects[i].Free;
until (Instances.Count <> OldCount);
OldCount := Instances.Count;
end;
{free the global variables}
Instances.Free;
DeleteCriticalSection(SingletonLock);
end;
initialization
InitUnit;
finalization
DoneUnit;
end.
|
// Filename : XmlChars.pas
// Version : 1.1 (Delphi)
// Date : July 4, 2003
// Author : Jeff Rafter
// Details : http://xml.defined.net/SAX/aelfred2
// License : Please read License.txt
unit XmlChars;
interface
uses SAX;
// !! Eventually I may need to add a version attribute
// !! for alternate XML characters maps
function isExtender(const c : SAXChar) : Boolean;
function isDigit(const c : SAXChar) : Boolean;
function isCombiningChar(const c : SAXChar) : Boolean;
function isIdeographic(const c : SAXChar) : Boolean;
function isBaseChar(const c : SAXChar) : Boolean;
function isPubidChar(const c : SAXChar) : Boolean;
function isWhitespace(const c : SAXChar) : Boolean;
function isXMLChar(const c : SAXChar) : Boolean;
function isNameChar(const c : SAXChar) : Boolean;
function isNameStartChar(const c : SAXChar) : Boolean;
function isLetter(const c : SAXChar) : Boolean;
implementation
// Appendix B - Unicode Constructs
// 84 Letter ::= BaseChar , Ideographic
function isLetter(const c : SAXChar) : Boolean;
begin
Result:= (isBaseChar(c)) or (isIdeographic(c));
end;
// 85 BaseChar
function isBaseChar(const c : SAXChar) : Boolean;
begin
case (Word(c)) of
$0041..$005A , $0061..$007A , $00C0..$00D6 , $00D8..$00F6 ,
$00F8..$00FF , $0100..$0131 , $0134..$013E , $0141..$0148 ,
$014A..$017E , $0180..$01C3 , $01CD..$01F0 , $01F4..$01F5 ,
$01FA..$0217 , $0250..$02A8 , $02BB..$02C1 , $0386 ,
$0388..$038A , $038C , $038E..$03A1 , $03A3..$03CE ,
$03D0..$03D6 , $03DA , $03DC , $03DE , $03E0 , $03E2..$03F3 ,
$0401..$040C , $040E..$044F , $0451..$045C , $045E..$0481 ,
$0490..$04C4 , $04C7..$04C8 , $04CB..$04CC , $04D0..$04EB ,
$04EE..$04F5 , $04F8..$04F9 , $0531..$0556 , $0559 ,
$0561..$0586 , $05D0..$05EA , $05F0..$05F2 , $0621..$063A ,
$0641..$064A , $0671..$06B7 , $06BA..$06BE , $06C0..$06CE ,
$06D0..$06D3 , $06D5 , $06E5..$06E6 , $0905..$0939 , $093D ,
$0958..$0961 , $0985..$098C , $098F..$0990 , $0993..$09A8 ,
$09AA..$09B0 , $09B2 , $09B6..$09B9 , $09DC..$09DD ,
$09DF..$09E1 , $09F0..$09F1 , $0A05..$0A0A , $0A0F..$0A10 ,
$0A13..$0A28 , $0A2A..$0A30 , $0A32..$0A33 , $0A35..$0A36 ,
$0A38..$0A39 , $0A59..$0A5C , $0A5E , $0A72..$0A74 ,
$0A85..$0A8B , $0A8D , $0A8F..$0A91 , $0A93..$0AA8 ,
$0AAA..$0AB0 , $0AB2..$0AB3 , $0AB5..$0AB9 , $0ABD , $0AE0 ,
$0B05..$0B0C , $0B0F..$0B10 , $0B13..$0B28 , $0B2A..$0B30 ,
$0B32..$0B33 , $0B36..$0B39 , $0B3D , $0B5C..$0B5D ,
$0B5F..$0B61 , $0B85..$0B8A , $0B8E..$0B90 , $0B92..$0B95 ,
$0B99..$0B9A , $0B9C , $0B9E..$0B9F , $0BA3..$0BA4 ,
$0BA8..$0BAA , $0BAE..$0BB5 , $0BB7..$0BB9 , $0C05..$0C0C ,
$0C0E..$0C10 , $0C12..$0C28 , $0C2A..$0C33 , $0C35..$0C39 ,
$0C60..$0C61 , $0C85..$0C8C , $0C8E..$0C90 , $0C92..$0CA8 ,
$0CAA..$0CB3 , $0CB5..$0CB9 , $0CDE , $0CE0..$0CE1 ,
$0D05..$0D0C , $0D0E..$0D10 , $0D12..$0D28 , $0D2A..$0D39 ,
$0D60..$0D61 , $0E01..$0E2E , $0E30 , $0E32..$0E33 ,
$0E40..$0E45 , $0E81..$0E82 , $0E84 , $0E87..$0E88 , $0E8A ,
$0E8D , $0E94..$0E97 , $0E99..$0E9F , $0EA1..$0EA3 , $0EA5 ,
$0EA7 , $0EAA..$0EAB , $0EAD..$0EAE , $0EB0 , $0EB2..$0EB3 ,
$0EBD , $0EC0..$0EC4 , $0F40..$0F47 , $0F49..$0F69 ,
$10A0..$10C5 , $10D0..$10F6 , $1100 , $1102..$1103 ,
$1105..$1107 , $1109 , $110B..$110C , $110E..$1112 , $113C ,
$113E , $1140 , $114C , $114E , $1150 , $1154..$1155 , $1159 ,
$115F..$1161 , $1163 , $1165 , $1167 , $1169 , $116D..$116E ,
$1172..$1173 , $1175 , $119E , $11A8 , $11AB , $11AE..$11AF ,
$11B7..$11B8 , $11BA , $11BC..$11C2 , $11EB , $11F0 , $11F9 ,
$1E00..$1E9B , $1EA0..$1EF9 , $1F00..$1F15 , $1F18..$1F1D ,
$1F20..$1F45 , $1F48..$1F4D , $1F50..$1F57 , $1F59 , $1F5B ,
$1F5D , $1F5F..$1F7D , $1F80..$1FB4 , $1FB6..$1FBC , $1FBE ,
$1FC2..$1FC4 , $1FC6..$1FCC , $1FD0..$1FD3 , $1FD6..$1FDB ,
$1FE0..$1FEC , $1FF2..$1FF4 , $1FF6..$1FFC , $2126 ,
$212A..$212B , $212E , $2180..$2182 , $3041..$3094 ,
$30A1..$30FA , $3105..$312C , $AC00..$D7A3 :
Result:= True;
else
Result:= False;
end;
end;
// 86 Ideographic
function isIdeographic(const c : SAXChar) : Boolean;
begin
case (Word(c)) of
$4E00..$9FA5 , $3007 , $3021..$3029 :
Result:= True;
else
Result:= False;
end;
end;
// 87 CombiningChar
function isCombiningChar(const c : SAXChar) : Boolean;
begin
case (Word(c)) of
$0300..$0345 , $0360..$0361 , $0483..$0486 , $0591..$05A1 ,
$05A3..$05B9 , $05BB..$05BD , $05BF , $05C1..$05C2 , $05C4 ,
$064B..$0652 , $0670 , $06D6..$06DC , $06DD..$06DF ,
$06E0..$06E4 , $06E7..$06E8 , $06EA..$06ED , $0901..$0903 ,
$093C , $093E..$094C , $094D , $0951..$0954 , $0962..$0963 ,
$0981..$0983 , $09BC , $09BE , $09BF , $09C0..$09C4 ,
$09C7..$09C8 , $09CB..$09CD , $09D7 , $09E2..$09E3 , $0A02 ,
$0A3C , $0A3E , $0A3F , $0A40..$0A42 , $0A47..$0A48 ,
$0A4B..$0A4D , $0A70..$0A71 , $0A81..$0A83 , $0ABC ,
$0ABE..$0AC5 , $0AC7..$0AC9 , $0ACB..$0ACD , $0B01..$0B03 ,
$0B3C , $0B3E..$0B43 , $0B47..$0B48 , $0B4B..$0B4D ,
$0B56..$0B57 , $0B82..$0B83 , $0BBE..$0BC2 , $0BC6..$0BC8 ,
$0BCA..$0BCD , $0BD7 , $0C01..$0C03 , $0C3E..$0C44 ,
$0C46..$0C48 , $0C4A..$0C4D , $0C55..$0C56 , $0C82..$0C83 ,
$0CBE..$0CC4 , $0CC6..$0CC8 , $0CCA..$0CCD , $0CD5..$0CD6 ,
$0D02..$0D03 , $0D3E..$0D43 , $0D46..$0D48 , $0D4A..$0D4D ,
$0D57 , $0E31 , $0E34..$0E3A , $0E47..$0E4E , $0EB1 ,
$0EB4..$0EB9 , $0EBB..$0EBC , $0EC8..$0ECD , $0F18..$0F19 ,
$0F35 , $0F37 , $0F39 , $0F3E , $0F3F , $0F71..$0F84 ,
$0F86..$0F8B , $0F90..$0F95 , $0F97 , $0F99..$0FAD ,
$0FB1..$0FB7 , $0FB9 , $20D0..$20DC , $20E1 , $302A..$302F ,
$3099 , $309A :
Result:= True;
else
Result:= False;
end;
end;
// 88 Digit
function isDigit(const c : SAXChar) : Boolean;
begin
case (Word(c)) of
$0030..$0039 , $0660..$0669 , $06F0..$06F9 , $0966..$096F ,
$09E6..$09EF , $0A66..$0A6F , $0AE6..$0AEF , $0B66..$0B6F ,
$0BE7..$0BEF , $0C66..$0C6F , $0CE6..$0CEF , $0D66..$0D6F ,
$0E50..$0E59 , $0ED0..$0ED9 , $0F20..$0F29 :
Result:= True;
else
Result:= False;
end;
end;
// 89 Extender
function isExtender(const c : SAXChar) : Boolean;
begin
case (Word(c)) of
$00B7 , $02D0 , $02D1 , $0387 , $0640 , $0E46 , $0EC6 , $3005 ,
$3031..$3035 , $309D..$309E , $30FC..$30FE :
Result:= True;
else
Result:= False;
end;
end;
function isPubidChar(const c : SAXChar) : Boolean;
begin
case (c) of
#32, #13, #10, 'a'..'z', 'A'..'Z', '0'..'9', '-', '''', '(', ')',
'+', ',', '.', '/', ':', '=', '?', ';', '!', '*', '#', '@', '$', '_', '%' :
Result:= True;
else
Result:= False;
end;
end;
function isWhitespace(const c : SAXChar) : Boolean;
begin
case Word(c) of
$20 , $9 , $D , $A :
Result:= True;
else
Result:= False;
end;
end;
function isXMLChar(const c : SAXChar) : Boolean;
begin
case Word(c) of
//!! Upper 4-byte range $10000..$10FFFF omitted !!
$9 , $A , $D , $20..$D7FF , $E000..$FFFD :
Result:= True;
else
Result:= False;
end;
end;
function isNameChar(const c : SAXChar) : Boolean;
begin
Result:= (c = '.') or (c = '-') or (c = '_') or (c = ':') or
isBaseChar(c) or isIdeographic(c) or isDigit(c) or isCombiningChar(c) or
isExtender(c);
end;
function isNameStartChar(const c : SAXChar) : Boolean;
begin
Result:= (c = '_') or (c = ':') or isBaseChar(c) or isIdeographic(c);
end;
end.
|
unit TextViaEditorProcessorWithExternalSave;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Abstract Tests"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/Abstract_Tests/TextViaEditorProcessorWithExternalSave.pas"
// Начат: 14.12.2010 16:31
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Tests::Abstract Tests::EditorTests::TTextViaEditorProcessorWithExternalSave
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Abstract_Tests\TestDefine.inc.pas}
interface
{$If defined(nsTest) AND not defined(NoScripts)}
uses
l3Filer
{$If defined(nsTest) AND not defined(NoVCM)}
,
TextViaEditorProcessor
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
,
PrimTextLoad_Form
{$IfEnd} //nsTest AND not NoVCM
;
{$IfEnd} //nsTest AND not NoScripts
{$If defined(nsTest) AND not defined(NoScripts)}
type
TTextViaEditorProcessorWithExternalSave = {abstract} class(TTextViaEditorProcessor)
protected
// overridden protected methods
{$If defined(nsTest) AND not defined(NoVCM)}
procedure Save(aForm: TPrimTextLoadForm); override;
{* Сохраняет текст из редактора в стандартный выходной файл }
{$IfEnd} //nsTest AND not NoVCM
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
protected
// protected methods
procedure DoSave(aForm: TPrimTextLoadForm;
aFiler: Tl3CustomFiler); virtual; abstract;
end;//TTextViaEditorProcessorWithExternalSave
{$IfEnd} //nsTest AND not NoScripts
implementation
{$If defined(nsTest) AND not defined(NoScripts)}
uses
SysUtils,
TestFrameWork
;
{$IfEnd} //nsTest AND not NoScripts
{$If defined(nsTest) AND not defined(NoScripts)}
// start class TTextViaEditorProcessorWithExternalSave
{$If defined(nsTest) AND not defined(NoVCM)}
procedure TTextViaEditorProcessorWithExternalSave.Save(aForm: TPrimTextLoadForm);
//#UC START# *4BE12AEE0190_4D0771BA0367_var*
var
l_F : Tl3CustomFiler;
//#UC END# *4BE12AEE0190_4D0771BA0367_var*
begin
//#UC START# *4BE12AEE0190_4D0771BA0367_impl*
l_F := FilerForOutput;
try
l_F.Open;
try
DoSave(aForm, l_F);
finally
l_F.Close;
end;//try..finally
finally
FreeAndNil(l_F);
end;//try..finally
//#UC END# *4BE12AEE0190_4D0771BA0367_impl*
end;//TTextViaEditorProcessorWithExternalSave.Save
{$IfEnd} //nsTest AND not NoVCM
function TTextViaEditorProcessorWithExternalSave.GetFolder: AnsiString;
{-}
begin
Result := 'EditorTests';
end;//TTextViaEditorProcessorWithExternalSave.GetFolder
function TTextViaEditorProcessorWithExternalSave.GetModelElementGUID: AnsiString;
{-}
begin
Result := '4D0771BA0367';
end;//TTextViaEditorProcessorWithExternalSave.GetModelElementGUID
{$IfEnd} //nsTest AND not NoScripts
end. |
{
Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LogViewer.Subscribers.ZeroMQ;
interface
uses
System.Classes,
ZeroMQ,
Spring,
LogViewer.Interfaces, LogViewer.Subscribers.Base;
type
TZMQSubscriber = class(TSubscriber, ISubscriber, IZMQ)
private
FZMQ : IZeroMQ;
FSubscriber : IZMQPair;
FPoll : IZMQPoll;
FZMQStream : TStringStream;
procedure CreateSubscriberSocket(const AEndPoint: string);
protected
{$REGION 'property access methods'}
procedure SetEnabled(const Value: Boolean); override;
function GetSourceId: UInt32; override;
{$ENDREGION}
procedure Poll; override;
public
constructor Create(
const AReceiver : IChannelReceiver;
const AZMQ : IZeroMQ;
const AEndPoint : string;
ASourceId : UInt32;
const AKey : string;
const ASourceName : string;
AEnabled : Boolean
); reintroduce; virtual;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
implementation
uses
System.SysUtils,
DDuce.Logger;
{$REGION 'construction and destruction'}
constructor TZMQSubscriber.Create(const AReceiver: IChannelReceiver; const AZMQ:
IZeroMQ; const AEndPoint: string; ASourceId: UInt32; const AKey: string;
const ASourceName: string; AEnabled: Boolean);
begin
Guard.CheckNotNull(AZMQ, 'AZMQ');
FZMQ := AZMQ;
CreateSubscriberSocket(AEndPoint);
inherited Create(AReceiver, ASourceId, AKey, ASourceName, AEnabled);
end;
procedure TZMQSubscriber.AfterConstruction;
begin
inherited AfterConstruction;
FZMQStream := TStringStream.Create;
end;
procedure TZMQSubscriber.BeforeDestruction;
begin
FZMQStream.Free;
FPoll := nil;
FSubscriber := nil;
FZMQ := nil;
inherited BeforeDestruction;
end;
{$ENDREGION}
{$REGION 'property access methods'}
procedure TZMQSubscriber.SetEnabled(const Value: Boolean);
begin
if Value <> Enabled then
begin
inherited SetEnabled(Value);
if Enabled then
FSubscriber.Subscribe('')
else
FSubscriber.UnSubscribe('');
end;
end;
function TZMQSubscriber.GetSourceId: UInt32;
begin
Result := UInt32(Self);
end;
{$ENDREGION}
{$REGION 'private methods'}
{ Creates a ZMQ subscriber socket, connects it to the given endpoint and
registers a dedicated poller to handle incomming messages. }
procedure TZMQSubscriber.CreateSubscriberSocket(const AEndPoint: string);
begin
FSubscriber := FZMQ.Start(ZMQSocket.Subscriber);
FSubscriber.Connect(AEndPoint);
FPoll := FZMQ.Poller;
FPoll.RegisterPair(
FSubscriber,
[PollEvent.PollIn],
procedure(Event: PollEvents)
begin
FZMQStream.WriteString(FSubscriber.ReceiveString);
Receiver.DoReceiveMessage(
FZMQStream, SourceId, 0, FSubscriber.LastEndPoint
);
FZMQStream.Clear;
end
);
end;
{$ENDREGION}
{$REGION 'protected methods'}
procedure TZMQSubscriber.Poll;
begin
if Enabled then
begin
while FPoll.PollOnce(10) > 0 do
begin
FPoll.FireEvents;
end;
end;
end;
{$ENDREGION}
end.
|
(*
* 接收数据的专用单元
*
* C/S、WebSocket 模式数据接收器
*)
unit iocp_receivers;
interface
{$I in_iocp.inc} // 模式设置
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, {$ELSE}
Windows, Classes, SysUtils, {$ENDIF}
iocp_base, iocp_md5, iocp_mmHash,
iocp_msgPacks, iocp_WsJSON;
type
// ============ 数据接收器 基类 =============
TBaseReceiver = class(TObject)
protected
FBuffer: PAnsiChar; // 输入内存块
FBufSize: Cardinal; // 未处理的数据长度
FRecvCount: TFileSize; // 每消息收到的字节数
FCancel: Boolean; // 取消操作(保留给WS)
FCheckPassed: Boolean; // 校验成功(保留给WS)
FCompleted: Boolean; // 主体或全部接收完毕
FErrorCode: Integer; // 异常代码
procedure IncBufferPos(Offset: Cardinal); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure InterInit(ACancel, ACompleted: Boolean); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure SetCompleted(const Value: Boolean);
public
constructor Create;
procedure Clear; virtual;
procedure Prepare(const AData: PAnsiChar; const ASize: Cardinal); virtual; abstract;
procedure Receive(const AData: PAnsiChar; const ASize: Cardinal); virtual; abstract;
procedure Reset; virtual; // 保留
public
property CheckPassed: Boolean read FCheckPassed;
property Completed: Boolean read FCompleted write SetCompleted;
property ErrorCode: Integer read FErrorCode;
property RecvCount: TFileSize read FRecvCount;
end;
// ============ C/S 模式数据接收器 基类 =============
TCSBaseReceiver = class(TBaseReceiver)
private
FMsgPack: TReceivePack; // 当前接收的消息
FCheckCode: TIOCPHashCode; // 主体校验码
FCheckCode2: TIOCPHashCode; // 附件校验码
FMainLackSize: Cardinal; // 主体欠缺的内容长度
FAttachLackSize: TFilesize; // 附件欠缺的内容长度
FReadHead: Boolean; // 已经读取协议头信息
procedure ExtractMessage;
procedure VerifyMainStream;
procedure VerifyAttachmentStream;
procedure UZipPretreatMainStream;
procedure UZipTreatAttachmentStream;
protected
procedure IncRecvCount(RecvCount, DataType: Cardinal); virtual;
procedure RecvSubqueueData; virtual;
procedure ReceiveMainFinish; virtual;
procedure ReceiveAttachmentFinish; virtual;
procedure WriteMainStream(ByteCount: Cardinal); virtual;
procedure WriteAttachmentStream(ByteCount: Cardinal); virtual;
protected
procedure CreateAttachment; virtual; abstract;
procedure GetCheckCodes; virtual; abstract;
public
procedure Clear; override;
procedure Reset; override;
procedure OwnerClear;
public
property Cancel: Boolean read FCancel;
property MsgPack: TReceivePack read FMsgPack;
end;
// ============ 服务端数据接收器 类 =============
// 主体或附件数据接收完毕 -> 进入应用层
TServerReceiver = class(TCSBaseReceiver)
protected
procedure IncRecvCount(RecvCount, DataType: Cardinal); override;
protected
procedure CreateAttachment; override;
procedure GetCheckCodes; override;
public
constructor Create(AMsgPack: TReceivePack);
procedure Prepare(const AData: PAnsiChar; const ASize: Cardinal); override;
procedure Receive(const AData: PAnsiChar; const ASize: Cardinal); override;
end;
// ============ 客户端数据接收器 类 =============
// 可能同时收到反馈消息和推送消息,一个消息接收完整后即投放到应用层,
// 数据包混有推送消息时,可能协议头或校验码被折断。
// 协议头空间
TMsgHeadBuffers = array[0..IOCP_SOCKET_SIZE - 1] of AnsiChar;
// 接收消息事件
TRecvMsgEvent = procedure(Msg: TBasePackObject; Part: TMessagePart;
RecvCount: Cardinal) of object;
// 提交消息事件
TPostMsgEvent = procedure(Msg: TBasePackObject) of object;
// 新建消息事件
TCreateMsgEvent = procedure(Msg: TBasePackObject) of object;
// 接收异常事件
TRecvErrorEvent = procedure(Msg: TBasePackObject; ErrorCode: Integer) of object;
TClientReceiver = class(TCSBaseReceiver)
private
// 被折断的协议头
FHeadBuffers: TMsgHeadBuffers;
FHeadLackSize: Cardinal; // 协议的缺少内容长度
FHashCode: PAnsiChar; // 待写校验码地址
FCodeLackSize: Cardinal; // 校验码的缺少长度
FLocalPath: string; // 附件存放路径
FOnError: TRecvErrorEvent; // 异常事件
FOnNewMsg: TCreateMsgEvent; // 建消息对象事件
FOnPost: TPostMsgEvent; // 提交消息事件
FOnReceive: TRecvMsgEvent; // 接收消息事件
procedure ScanRecvBuffers;
procedure WriteHashCode(ByteCount: Cardinal);
protected
procedure IncRecvCount(RecvCount, DataType: Cardinal); override;
procedure ReceiveMainFinish; override;
procedure ReceiveAttachmentFinish; override;
procedure WriteAttachmentStream(ByteCount: Cardinal); override;
protected
procedure CreateAttachment; override;
procedure GetCheckCodes; override;
public
constructor Create;
destructor Destroy; override;
procedure PostMessage;
procedure Prepare(const AData: PAnsiChar; const ASize: Cardinal); override;
procedure Receive(const AData: PAnsiChar; const ASize: Cardinal); override;
public
property Completed: Boolean read FCompleted;
property LocalPath: String read FLocalPath write FLocalPath;
property OnError: TRecvErrorEvent read FOnError write FOnError;
property OnNewMsg: TCreateMsgEvent read FOnNewMsg write FOnNewMsg;
property OnPost: TPostMsgEvent read FOnPost write FOnPost;
property OnReceive: TRecvMsgEvent read FOnReceive write FOnReceive;
end;
// ============ WebSocket 数据接收器 =============
{ byte: 0 1 2 3
bit: 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data... |
+-------------------------------- - - - - - - - - - - - - - - - + }
// 注:WebSocket 支持多帧,但单帧已经支持大数据传输,
// 当多帧数据,且每帧很小时,增加解码的复杂性,这种情况比较少用。
// 一块数据有多帧时:服务器只接收单帧,客户端全部接收处理。
TWSBaseReceiver = class(TBaseReceiver)
private
FOwner: TObject; // 宿主(Socket或连接)
FHeader: TWebSocketFrame; // 折断的协议头
FHeadAddr: PAnsiChar; // 写入 FFrameHeader 的位置
FLackSize: Cardinal; // 帧内容不足的长度
FData: PAnsiChar; // 数据开始位置
FFrameSize: UInt64; // 当前帧数据大小
FFrameRecvSize: UInt64; // 当前帧累计收到长度
FLastFrame: Boolean; // 最后一帧
FOpCode: TWSOpCode; // 操作类型
FMsgType: TWSMsgType; // 当前、期待的消息类型
FMask: TWSMask; // 掩码
FMaskBit: PByte; // 掩码指示位置
FMaskExists: Boolean; // 有否掩码
FJSON: TBaseJSON; // JSON,客户端为 TJSONResult
FStream: TMemoryStream; // 原始/JSON 数据流
function CheckInIOCPFlag(ABuf: PAnsiChar; ASize: Integer): TWSMsgType; {$IFDEF USE_INLINE} inline; {$ENDIF}
function GetContentSize(InSize: Cardinal): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF}
function GetFrameSize(Byte2: Byte): Cardinal; {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure ExtractFrame(ABuf: PAnsiChar; ASize: Integer; RecvData: Boolean);
procedure IncRecvCount(RecvCount: Cardinal); {$IFDEF USE_INLINE} inline; {$ENDIF}
procedure ScanRecvWSBuffers;
protected
procedure InitResources(ASize: Cardinal); virtual; abstract;
procedure InterReceiveData(ASize: Cardinal); virtual; abstract;
procedure SaveRemainData; virtual; abstract;
procedure WriteStream(ASize: Cardinal); virtual;abstract;
public
constructor Create(AConnection: TObject; AJSON: TBaseJSON);
destructor Destroy; override;
procedure Clear; override;
procedure Prepare(const AData: PAnsiChar; const ASize: Cardinal); override;
public
property JSON: TBaseJSON read FJSON;
property OpCode: TWSOpCode read FOpCode;
end;
// ============ WebSocket 服务端数据接收器 =============
// 非扩展的消息不保存到数据流
TWSServerReceiver = class(TWSBaseReceiver)
private
procedure UnMarkData(ASize: Cardinal);
protected
procedure InitResources(ASize: Cardinal); override;
procedure InterReceiveData(ASize: Cardinal); override;
procedure SaveRemainData; override;
procedure WriteStream(ASize: Cardinal); override;
public
procedure ClearMask(var Data: PAnsiChar; Overlapped: POverlapped);
procedure Receive(const AData: PAnsiChar; const ASize: Cardinal); override;
end;
// ============ WebSocket 客户端数据接收器 =============
// 准备接收附件事件
TAttachmentEvent = procedure(Msg: TBaseJSON) of object;
// 保存非扩展的消息到数据流
TWSClientReceiver = class(TWSBaseReceiver)
private
FOnError: TRecvErrorEvent; // 异常事件
FOnNewMsg: TCreateMsgEvent; // 建消息对象事件
FOnPost: TPostMsgEvent; // 提交消息事件
FOnReceive: TRecvMsgEvent; // 接收消息事件
FOnAttachment: TAttachmentEvent; // 附件事件
procedure PostJSON(AOpCode: TWSOpCode; AMsgType: TWSMsgType; AStream: TMemoryStream);
protected
procedure InitResources(ASize: Cardinal); override;
procedure InterReceiveData(ASize: Cardinal); override;
procedure SaveRemainData; override;
procedure WriteStream(ASize: Cardinal); override;
public
destructor Destroy; override;
procedure Receive(const AData: PAnsiChar; const ASize: Cardinal); override;
public
property OnAttachment: TAttachmentEvent read FOnAttachment write FOnAttachment;
property OnError: TRecvErrorEvent read FOnError write FOnError;
property OnNewMsg: TCreateMsgEvent read FOnNewMsg write FOnNewMsg;
property OnPost: TPostMsgEvent read FOnPost write FOnPost;
property OnReceive: TRecvMsgEvent read FOnReceive write FOnReceive;
end;
implementation
uses
iocp_zlib, iocp_utils, iocp_sockets,
iocp_clientBase, iocp_clients, iocp_wsClients;
type
TIOCPDocumentRef = class(TIOCPDocument);
TResultParamsRef = class(TResultParams);
TServerWebSocket = class(TWebSocket);
TJSONResultRef = class(TJSONResult);
{ TBaseReceiver }
procedure TBaseReceiver.Clear;
begin
InterInit(False, True);
end;
constructor TBaseReceiver.Create;
begin
inherited;
FCheckPassed := True;
FCompleted := True;
end;
procedure TBaseReceiver.IncBufferPos(Offset: Cardinal);
begin
Inc(FBuffer, Offset); // 内存地址前移
Dec(FBufSize, Offset); // 未处理的数据减少
Inc(FRecvCount, Offset); // 总数+
end;
procedure TBaseReceiver.InterInit(ACancel, ACompleted: Boolean);
begin
FCancel := ACancel;
FCheckPassed := True;
FCompleted := ACompleted;
FErrorCode := 0;
end;
procedure TBaseReceiver.Reset;
begin
InterInit(True, True);
end;
procedure TBaseReceiver.SetCompleted(const Value: Boolean);
begin
InterInit(False, Value);
end;
{ TCSBaseReceiver }
procedure TCSBaseReceiver.Clear;
begin
inherited;
FMsgPack.Clear;
end;
procedure TCSBaseReceiver.ExtractMessage;
begin
// 提取一个消息
// ReadHead: 要取协议信息
// 格式:IOCP_SOCKET_FLAG + TMsgHead + [Hash + Hash] + [Data]
// 推送消息不能带附件,自身消息的附件不在此数据包
// 1. 取协议信息
if FReadHead then // 取协议信息
begin
FMsgPack.SetHeadMsg(PMsgHead(FBuffer + IOCP_SOCKET_FLEN));
IncBufferPos(IOCP_SOCKET_SIZE); // 到 Hash 位置
FReadHead := False;
end;
// 1.1 取长度,在前
FCompleted := False; // 未完成
FMainLackSize := FMsgPack.DataSize;
FAttachLackSize := FMsgPack.AttachSize;
if (FBufSize = 0) then // 只有协议头
IncRecvCount(0, 1)
else // 1.2 取校验码
case FMsgPack.CheckType of
ctMurmurHash:
GetCheckCodes;
ctMD5:
GetCheckCodes;
end;
// 2. 处理主体数据
if (FMainLackSize = 0) then
ReceiveMainFinish // 接收完毕
else begin
// 准备空间
FMsgPack.Main.Initialize(FMainLackSize);
if (FBufSize > 0) then // 有数据
if (FBufSize > FMainLackSize) then // 有多个消息(服务端不会出现)
WriteMainStream(FMainLackSize)
else
WriteMainStream(FBufSize);
end;
end;
procedure TCSBaseReceiver.IncRecvCount(RecvCount, DataType: Cardinal);
begin
// 收到一段数据,调整统计数字
IncBufferPos(RecvCount); // 推进
case DataType of // 欠缺长度-
1: Dec(FMainLackSize, RecvCount);
2: Dec(FAttachLackSize, RecvCount);
end;
end;
procedure TCSBaseReceiver.OwnerClear;
begin
// 清除 FMsgObj 数据
if (FMainLackSize = 0) and (FAttachLackSize = 0) then
FMsgPack.Clear;
end;
procedure TCSBaseReceiver.ReceiveAttachmentFinish;
begin
// 附件数据接收完毕
// 1. 校验数据
if (FMsgPack.CheckType > ctNone) then
VerifyAttachmentStream
else // 不用校验
FCheckPassed := True;
// 2. 解压附件流(可能是续传)
if FCheckPassed and Assigned(FMsgPack.Attachment) then
UZipTreatAttachmentStream; // 接收完毕
end;
procedure TCSBaseReceiver.ReceiveMainFinish;
begin
// 主体数据接收完毕(可能只有协议头)
// 1. 校验主体; 2. 解压、解析变量; 3. 继续写附件
if (FMsgPack.DataSize = 0) then
FCheckPassed := True
else begin
// 1. 校验数据
if (FMsgPack.CheckType > ctNone) then
VerifyMainStream
else // 不用校验
FCheckPassed := True;
// 2. 解压数据流、解析变量
if FCheckPassed then
begin
UZipPretreatMainStream; // 解压预处理
if (FMsgPack.VarCount > 0) then // 解析变量
FMsgPack.Initialize(FMsgPack.Main);
end;
end;
// 3. 建附件流,写内容
if FCheckPassed and (FMsgPack.AttachSize > 0) then
begin
CreateAttachment; // 服务端不自动建附件流
if (FBufSize > 0) and Assigned(FMsgPack.Attachment) then // 写剩余内容
if (FBufSize <= FMsgPack.AttachSize) then
WriteAttachmentStream(FBufSize)
else
WriteAttachmentStream(FMsgPack.AttachSize);
end;
end;
procedure TCSBaseReceiver.RecvSubqueueData;
begin
// 接收后续数据
// 1. 写主体流
if (FMainLackSize > 0) then
if (FBufSize <= FMainLackSize) then // 1.1 未接收完毕
WriteMainStream(FBufSize)
else // 1.2 太长,只写主体部分
WriteMainStream(FMainLackSize);
// 2. 写附件流
if (FBufSize > 0) and (FAttachLackSize > 0) then
if (FBufSize <= FAttachLackSize) then // 2.1 附件未结束
WriteAttachmentStream(FBufSize)
else // 2.2 太长,只写附件部分
WriteAttachmentStream(FAttachLackSize);
// 可能 FBufSize > 0
end;
procedure TCSBaseReceiver.Reset;
begin
inherited;
// 取消,重置接收器
FMsgPack.Cancel;
FMainLackSize := 0;
FAttachLackSize := 0;
end;
procedure TCSBaseReceiver.UZipTreatAttachmentStream;
var
OldFileName, RealFileName: String;
mStream: TIOCPDocument;
begin
// 解压、处理附件
// 1. 文件未压缩 -> 改为原名(可能失败)
// 2. 已压缩,解压到新文件 -> 改为原名
// TIOCPDocument 文件流被关闭,但不释放,可以使用 TIOCPDocument.FileName
// 如果是续传,但未完全接收完毕,只简单关闭!
if (FMsgPack.Action in FILE_CHUNK_ACTIONS) and
(FMsgPack.OffsetEnd + 1 < FMsgPack.Attachment.OriginSize) then
begin
FMsgPack.Attachment.Close; // 只关闭,OriginSize 不变
Exit;
end;
OldFileName := FMsgPack.Attachment.FileName;
RealFileName := ExtractFilePath(OldFileName) + FMsgPack.FileName;
if (FMsgPack.ZipLevel = zcNone) then
begin
// 直接关闭、改名
FMsgPack.Attachment.Close;
TIOCPDocumentRef(FMsgPack.Attachment).RenameDoc(RealFileName);
end else
begin
// 先解压流到新文件,再改名
mStream := TIOCPDocument.Create(OldFileName + '_UNZIP', True);
try
try
FMsgPack.Attachment.Position := 0;
iocp_zlib.ZDecompressStream(FMsgPack.Attachment, mStream);
finally
FMsgPack.Attachment.Close(True); // 关闭,同时删除文件
TIOCPDocumentRef(mStream).RenameDoc(RealFileName); // 自动关闭, 改名
TIOCPDocumentRef(FMsgPack.Attachment).FFileName := RealFileName; // 直接改名
mStream.Free; // 释放
end;
except
FErrorCode := GetLastError;
end;
end;
end;
procedure TCSBaseReceiver.UZipPretreatMainStream;
var
NewBuffers: Pointer;
NewSize: Integer;
begin
// 解压、预处理主体流
// 内容被解压到 NewBuffers,NewBuffers 挂到 FMsgObj.Main 下
if (FMsgPack.ZipLevel = zcNone) then
FMsgPack.Main.Position := 0
else
try
try
iocp_zlib.ZDecompress(FMsgPack.Main.Memory, FMsgPack.DataSize,
NewBuffers, NewSize, FMsgPack.DataSize);
finally
FMsgPack.Main.SetMemory(NewBuffers, NewSize);
end;
except
FErrorCode := GetLastError;
end;
end;
procedure TCSBaseReceiver.VerifyAttachmentStream;
begin
// 检查附件校验码
case FMsgPack.CheckType of
ctMurmurHash: // MurmurHash
if (FMsgPack.Action in FILE_CHUNK_ACTIONS) then // 检查一段范围的 Hash
FCheckPassed := (FCheckCode2.MurmurHash =
iocp_mmHash.MurmurHashPart64(FMsgPack.Attachment.Handle,
FMsgPack.Offset, FMsgPack.AttachSize))
else // 检查整个文件的 Hash
FCheckPassed := (FCheckCode2.MurmurHash =
iocp_mmHash.MurmurHash64(FMsgPack.Attachment.Handle));
ctMD5: // MD5
if (FMsgPack.Action in FILE_CHUNK_ACTIONS) then // 检查一段范围的 MD5
FCheckPassed := MD5MatchEx(@FCheckCode2.MD5Code,
iocp_md5.MD5Part(FMsgPack.Attachment.Handle,
FMsgPack.Offset, FMsgPack.AttachSize))
else // 检查整个文件的 MD5
FCheckPassed := MD5MatchEx(@FCheckCode2.MD5Code,
iocp_md5.MD5File(FMsgPack.Attachment.Handle));
else
FCheckPassed := True;
end;
end;
procedure TCSBaseReceiver.VerifyMainStream;
begin
// 检查主体校验码
case FMsgPack.CheckType of
ctMurmurHash: // MurmurHash
FCheckPassed := (FCheckCode.MurmurHash =
iocp_mmHash.MurmurHash64(FMsgPack.Main.Memory, FMsgPack.DataSize));
ctMD5: // MD5
FCheckPassed := MD5MatchEx(@FCheckCode.MD5Code,
iocp_md5.MD5Buffer(FMsgPack.Main.Memory, FMsgPack.DataSize));
else
FCheckPassed := True;
end;
end;
procedure TCSBaseReceiver.WriteAttachmentStream(ByteCount: Cardinal);
begin
// 写数据到附件
if Assigned(FMsgPack.Attachment) then
begin
FMsgPack.Attachment.Write(FBuffer^, ByteCount);
IncRecvCount(ByteCount, 2);
if FCompleted then // 接收完毕 -> 校验、解压
ReceiveAttachmentFinish;
end else
IncRecvCount(ByteCount, 2);
end;
procedure TCSBaseReceiver.WriteMainStream(ByteCount: Cardinal);
begin
// 写数据到主体(先写入,后推进)
FMsgPack.Main.Write(FBuffer^, ByteCount);
IncRecvCount(ByteCount, 1); // 推进
if (FMainLackSize = 0) then // 完毕
ReceiveMainFinish;
end;
{ TServerReceiver }
constructor TServerReceiver.Create(AMsgPack: TReceivePack);
begin
inherited Create;
FMsgPack := AMsgPack;
end;
procedure TServerReceiver.CreateAttachment;
begin
// 在应用层建附件
end;
procedure TServerReceiver.GetCheckCodes;
begin
// 取校验码:
// 格式:IOCP_HEAD_FLAG + TMsgHead + [校验码 + 校验码] + [主体数据]
// 见:TBaseMessage.GetCheckCode
case FMsgPack.CheckType of
ctMurmurHash: begin // MurmurHash=64位
if (FMsgPack.DataSize > 0) then // 主体校验码
begin
FCheckCode.MurmurHash := PMurmurHash(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE);
end;
if (FMsgPack.AttachSize > 0) then // 附件校验码
begin
FCheckCode2.MurmurHash := PMurmurHash(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE);
end;
end;
ctMD5: begin // MD5=128位
if (FMsgPack.DataSize > 0) then // 主体校验码
begin
FCheckCode.MD5Code := PMD5Digest(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE * 2);
end;
if (FMsgPack.AttachSize > 0) then // 附件校验码
begin
FCheckCode2.MD5Code := PMD5Digest(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE * 2);
end;
end;
end;
end;
procedure TServerReceiver.IncRecvCount(RecvCount, DataType: Cardinal);
begin
inherited;
// 主体完成 或 附件完成 均进入应用层
case DataType of
1: FCompleted := (FMainLackSize = 0);
2: FCompleted := (FAttachLackSize = 0);
end;
end;
procedure TServerReceiver.Prepare(const AData: PAnsiChar; const ASize: Cardinal);
begin
// 接收首数据包,准备资源
// 只有一个主体,附件数据不在当前数据包!
FBuffer := AData;
FBufSize := ASize;
FCancel := False;
FReadHead := False; // 调用前已读取协议信息
IncBufferPos(IOCP_SOCKET_SIZE); // 跳到内容处
ExtractMessage; // 提取信息
end;
procedure TServerReceiver.Receive(const AData: PAnsiChar; const ASize: Cardinal);
begin
// 接收后续数据
// 客户端发送附件时要请求,主体和附件数据不会混在一起
FBuffer := AData;
FBufSize := ASize;
if (ASize = IOCP_CANCEL_LENGTH) and MatchSocketType(FBuffer, IOCP_SOCKET_CANCEL) then
Reset
else
RecvSubqueueData;
end;
{ TClientReceiver }
constructor TClientReceiver.Create;
begin
inherited;
FMsgPack := TResultParams.Create; // 先建一个
end;
procedure TClientReceiver.CreateAttachment;
begin
// 自动建附件流
TResultParamsRef(FMsgPack).CreateAttachment(FLocalPath);
end;
destructor TClientReceiver.Destroy;
begin
if Assigned(FMsgPack) then
FMsgPack.Free;
inherited;
end;
procedure TClientReceiver.GetCheckCodes;
procedure WriteMurmurHash(Hash: PIOCPHashCode);
begin
if (FBufSize >= HASH_CODE_SIZE) then // 内容够长
begin
Hash^.MurmurHash := PMurmurHash(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE);
end else
begin
// 内容不够长,被折断!
FCodeLackSize := HASH_CODE_SIZE; // 不足字节数
FHashCode := @Hash^.MurmurHash; // 设置写校验码的地址
if (FBufSize > 0) then
WriteHashCode(FBufSize);
end;
end;
procedure WriteMD5(MD5: PIOCPHashCode);
begin
if (FBufSize >= HASH_CODE_SIZE * 2) then // 内容够长
begin
MD5^.MD5Code := PMD5Digest(FBuffer)^;
IncBufferPos(HASH_CODE_SIZE * 2);
end else
begin
// 内容不够长,被折断!
FCodeLackSize := HASH_CODE_SIZE * 2;
FHashCode := @MD5^.MD5Code;
if (FBufSize > 0) then
WriteHashCode(FBufSize);
end;
end;
begin
// 取校验码:
// 接收自身消息和广播消息,可能校验码被折断
if (FBufSize > 0) then
case FMsgPack.CheckType of
ctMurmurHash: begin // MurmurHash=64位
if (FMsgPack.DataSize > 0) then // 主体校验码
WriteMurmurHash(@FCheckCode);
if (FBufSize > 0) and (FMsgPack.AttachSize > 0) then // 附件校验码
WriteMurmurHash(@FCheckCode2);
end;
ctMD5: begin // MD5=128位
if (FMsgPack.DataSize > 0) then // 主体校验码
WriteMD5(@FCheckCode);
if (FBufSize > 0) and (FMsgPack.AttachSize > 0) then // 附件校验码
WriteMD5(@FCheckCode2);
end;
end;
end;
procedure TClientReceiver.IncRecvCount(RecvCount, DataType: Cardinal);
begin
inherited;
// 接收数增加,主体+附件全接收完毕 -> 应用层
FCompleted := (FMainLackSize = 0) and (FAttachLackSize = 0);
end;
procedure TClientReceiver.PostMessage;
begin
// 把消息加入投放线程
try
FOnPost(FMsgPack);
finally
FReadHead := True; // 要重新读协议头了
FRecvCount := 0; // 接收长度清零
FMsgPack := TResultParams.Create; // 建新主体
if Assigned(FOnNewMsg) then
FOnNewMsg(FMsgPack); // 新消息事件
end;
end;
procedure TClientReceiver.Prepare(const AData: PAnsiChar; const ASize: Cardinal);
begin
FBuffer := AData;
FBufSize := ASize;
FCancel := False;
FHeadLackSize := 0; // 协议头未折断
FHashCode := nil; // 校验码未折断
FReadHead := True; // 取协议信息情况
ScanRecvBuffers; // 扫描提取消息
end;
procedure TClientReceiver.Receive(const AData: PAnsiChar; const ASize: Cardinal);
begin
// 接收后续数据,保存到流
// 可能同时包含主体和附件数据,也可能包含推送消息
FBuffer := AData;
FBufSize := ASize;
// 1. 检查推送消息的折断
// 1.1 协议头被折断;1.2 校验码被折断
if (FHeadLackSize > 0) then // 1.1 协议头被折断
begin
if (FBufSize >= FHeadLackSize) then
begin
// 内容够长,准备协议头信息
System.Move(AData^, FHeadBuffers[IOCP_SOCKET_SIZE - FHeadLackSize], FHeadLackSize);
FMsgPack.SetHeadMsg(PMsgHead(@FHeadBuffers[IOCP_SOCKET_FLEN]));
IncBufferPos(FHeadLackSize); // 到 Hash 位置
FReadHead := False; // 不用再次读协议头
FHeadLackSize := 0;
ScanRecvBuffers; // 扫描、提取消息
end else
begin
// 内容不够长
System.Move(AData^, FHeadBuffers[IOCP_SOCKET_SIZE - FHeadLackSize], FBufSize);
Dec(FHeadLackSize, FBufSize); // 先减
IncBufferPos(FBufSize); // 推进 -> FBufSize = 0
end;
end else
if Assigned(FHashCode) then // 1.2 校验码被折断
begin
if (FBufSize >= FCodeLackSize) then
WriteHashCode(FCodeLackSize)
else
WriteHashCode(FBufSize);
end;
// 2. 协议头 + 校验码处理完毕
if (FHeadLackSize = 0) and (FHashCode = nil) then
begin
// 2.1 接收后继或附件数据
if (FBufSize > 0) then
RecvSubqueueData;
// 2.2 继续提取消息
if (FBufSize > 0) then
ScanRecvBuffers;
end;
end;
procedure TClientReceiver.ReceiveAttachmentFinish;
begin
inherited;
try
if (FCheckPassed = False) and Assigned(FOnError) then
FOnError(FMsgPack, ERR_CHECK_CODE) // 校验异常 -> 清空
else
if Assigned(FOnReceive) then // 调用接收事件
FOnReceive(FMsgPack, mdtAttachment, 0); // 0 表示结束
finally
PostMessage; // 全部接收完毕,投放
end;
end;
procedure TClientReceiver.ReceiveMainFinish;
begin
inherited;
// 接收完主体数据、解释变量后才调用 FOnReceive
try
if (FCheckPassed = False) and Assigned(FOnError) then
FOnError(FMsgPack, ERR_CHECK_CODE) // 校验异常 -> 清空
else
if Assigned(FOnReceive) then // 调用接收事件
FOnReceive(FMsgPack, mdtEntity, FRecvCount);
finally
if (FCheckPassed = False) or (FMsgPack.AttachSize = 0) then
PostMessage; // 当作接收完毕,投放
end;
end;
procedure TClientReceiver.ScanRecvBuffers;
begin
// 接收首数据包,准备资源
// 格式:IOCP_SOCKET_FLAG + TMsgHead + [Hash + Hash] + [Data]
// 1. 客户端可能有多个消息(推送来的),要分解!
// 2. 多消息时,协议头可能被折断
// 逐个提取消息
while (FReadHead = False) and (FBufSize > 0) or (FBufSize >= IOCP_SOCKET_SIZE) do
ExtractMessage;
// 还有剩余,应小于 IOCP_SOCKET_SIZE
if (FBufSize > 0) then
begin
// 剩余长度 < 协议头长度, 被折断!
// 保存剩余内容到 FHeadBuffers,下次拼接起来
FCompleted := False;
FHeadLackSize := IOCP_SOCKET_SIZE - FBufSize; // 缺少字节数
System.Move(FBuffer^, FHeadBuffers[0], FBufSize);
IncBufferPos(FBufSize);
end;
end;
procedure TClientReceiver.WriteAttachmentStream(ByteCount: Cardinal);
begin
// ByteCount:当前收到字节数
if Assigned(FOnReceive) then // 调用接收事件
FOnReceive(FMsgPack, mdtAttachment, FRecvCount);
inherited; // 可能接收完毕,在这里 POST
end;
procedure TClientReceiver.WriteHashCode(ByteCount: Cardinal);
begin
// 校验码被折断,先保存收到的部分
System.Move(FBuffer^, FHashCode^, ByteCount);
IncBufferPos(ByteCount); // 推进
Inc(FHashCode, ByteCount); // 推进,下次写的位置
Dec(FCodeLackSize, ByteCount); // 不足字节数-
if (FCodeLackSize = 0) then // 写完校验码
FHashCode := nil;
end;
{ TWSBaseReceiver }
function TWSBaseReceiver.CheckInIOCPFlag(ABuf: PAnsiChar; ASize: Integer): TWSMsgType;
begin
// 检查扩展的 INIOCP_JSON_FLAG
if (ABuf = nil) then
Result := mtDefault
else
if (ASize >= INIOCP_JSON_FLAG_LEN) and
(PInIOCPJSONField(ABuf)^ = INIOCP_JSON_FLAG) then
Result := mtJSON
else
Result := mtDefault;
end;
procedure TWSBaseReceiver.Clear;
begin
// 清除收到的信息
FData := nil;
FFrameSize := 0;
FFrameRecvSize := 0;
if Assigned(FStream) and (FStream.Size > 0) then
FStream.Clear;
inherited;
end;
constructor TWSBaseReceiver.Create(AConnection: TObject; AJSON: TBaseJSON);
begin
inherited Create;
FOwner := AConnection;
FJSON := AJSON;
end;
destructor TWSBaseReceiver.Destroy;
begin
Clear;
if Assigned(FStream) then
FStream.Free;
inherited;
end;
procedure TWSBaseReceiver.ExtractFrame(ABuf: PAnsiChar; ASize: Integer; RecvData: Boolean);
var
i: Integer;
iByte: Byte;
OffSet: Integer;
procedure _MovePos(Step: Integer);
begin
Inc(ABuf, Step);
Dec(ASize, Step); // 可能 < 0
Inc(OffSet, Step);
end;
begin
// 从帧结构取信息
// 必须避免帧描述长度不足 ASize >= 2
OffSet := 0;
FFrameRecvSize := 0; // 当前帧接收量=0
// 1. 第 1 字节
// 是否为末帧
iByte := PByte(ABuf)^;
FLastFrame := (iByte shr 7 > 0);
// 不处理保留的数据位 RSV1、RSV2、RSV3
// 取操作代码
iByte := (iByte and $0F);
if (TWSOpCode(iByte) in TWSOpCodeSet) then
FOpCode := TWSOpCode(iByte)
else
FOpCode := ocClose; // 操作异常,关闭!
// 2. 第 2 字节
_MovePos(1);
// 掩码位置
FMaskBit := PByte(ABuf);
iByte := PByte(ABuf)^;
// 是否带掩码:高位,客户端无
FMaskExists := (iByte shr 7 > 0);
// 帧长度:低7位
FFrameSize := (iByte and $7F);
// 3. 取帧长度
_MovePos(1); // 到第 3 字节
case FFrameSize of
126: begin // <= max(UInt16),前2字节 -> 长度
FFrameSize := 0;
if (ASize >= 2) then
begin
TByteAry(@FFrameSize)[1] := TByteAry(ABuf)[0];
TByteAry(@FFrameSize)[0] := TByteAry(ABuf)[1];
end;
_MovePos(2); // 跳过
end;
127: begin // <= max(UInt64),长前8字节 -> 长度
FFrameSize := 0;
if (ASize >= 8) then
for i := 0 to 7 do
TByteAry(@FFrameSize)[7 - i] := TByteAry(ABuf)[i];
_MovePos(8); // 跳过
end;
end;
// 4. 取掩码(第4字节,客户端无)
if FMaskExists then // 服务端
begin
if (ASize >= 4) then
FMask := PWSMask(ABuf)^;
_MovePos(4); // 跳过
end;
// 5. 保存数据
// ASize = 0 -> 描述刚结束
// ASize > 0 -> 后面带数据
if RecvData and (ASize >= 0) then
begin
IncBufferPos(OffSet); // 移动 FBuffer
InterReceiveData(ASize); // 接收数据
end;
end;
function TWSBaseReceiver.GetContentSize(InSize: Cardinal): Integer;
begin
// 判断要写入流的长度
if (InSize = 0) then
Result := 0
else
if (FFrameRecvSize + InSize <= FFrameSize) then
Result := InSize
else
Result := FFrameSize - FFrameRecvSize;
end;
function TWSBaseReceiver.GetFrameSize(Byte2: Byte): Cardinal;
begin
// 检查帧描述的长度
// 客户端:Close/Ping/Pong 的描述 2 字节(最小值)
case (Byte2 and $7F) of
126: Result := 4;
127: Result := 10;
else Result := 2;
end;
end;
procedure TWSBaseReceiver.IncRecvCount(RecvCount: Cardinal);
begin
Inc(FFrameRecvSize, RecvCount); // 接收长度+
FCompleted := FLastFrame and (FFrameRecvSize = FFrameSize); // 是否接收完毕
end;
procedure TWSBaseReceiver.Prepare(const AData: PAnsiChar; const ASize: Cardinal);
begin
FBuffer := AData;
FBufSize := ASize;
ScanRecvWSBuffers; // 扫描接收
end;
procedure TWSBaseReceiver.ScanRecvWSBuffers;
begin
// 接收首数据包
// 1. 接收快时可能有多个消息,要分解!
// 2. 多消息时,协议头可能被折断
if Assigned(FHeadAddr) then // 从拼接内容取帧信息
begin
ExtractFrame(@FHeader[0], FHeadAddr - PAnsiChar(@FHeader[0]), False); // 内容刚够长
InterReceiveData(FBufSize); // 接收前帧数据,自动取 GetContentSize(FBufSize)
FHeadAddr := nil;
end;
while (FBufSize >= 2) and (FBufSize >= GetFrameSize(Byte((FBuffer + 1)^))) do
ExtractFrame(FBuffer, FBufSize, True);
if (FBufSize > 0) then // 是下一消息的内容
SaveRemainData;
end;
{ TWSServerReceiver }
procedure TWSServerReceiver.ClearMask(var Data: PAnsiChar; Overlapped: POverlapped);
var
i: Integer;
Buf: PAnsiChar;
begin
// 修改消息,以便发回给客户端或广播
// 清除掩码指示、掩码,内容前移
if FMaskExists and Assigned(FMaskBit) then
begin
FData := Data; // Data 是 TWSData.Data
Buf := PAnsiChar(FData - 4);
for i := 1 to FFrameRecvSize do
begin
Buf^ := FData^;
Inc(Buf); Inc(FData);
end;
// 清除掩码标志
FMaskBit^ := FMaskBit^ and Byte($7F);
FMaskBit := nil;
Dec(Overlapped^.InternalHigh, 4);
Dec(Data, 4);
end;
end;
procedure TWSServerReceiver.InitResources(ASize: Cardinal);
begin
// 初始化资源:
// JSON 标志、数据流、更新 Socket 属性
FData := FBuffer; // 数据开始位置
if (FOpCode = ocText) then // 检查 JSON 标志,见:TBaseJSON.SaveToStream
FMsgType := CheckInIOCPFlag(FBuffer, ASize);
case FMsgType of
mtDefault: // 不用设置流
TServerWebSocket(FOwner).SetProps(FOpCode, mtDefault, Pointer(FData),
FFrameSize, ASize);
mtJSON: begin // JSON 消息
if (Assigned(FStream) = False) then
FStream := TMemoryStream.Create;
FStream.Size := FFrameSize; // 有后续帧时写入时自动扩大
TServerWebSocket(FOwner).SetProps(FOpCode, mtJSON,
Pointer(FData), 0, 0);
end;
mtAttachment:
TServerWebSocket(FOwner).SetProps(FOpCode, mtAttachment,
Pointer(FData), 0, 0);
end;
end;
procedure TWSServerReceiver.InterReceiveData(ASize: Cardinal);
var
RecvCount: Cardinal;
begin
// 准备接收数据
RecvCount := GetContentSize(ASize); // 取有效长度
try
// 带掩码 -> 解码
if (RecvCount > 0) then
UnMarkData(RecvCount);
// 准备资源
InitResources(RecvCount);
// 保存到流
if (RecvCount > 0) then
WriteStream(RecvCount);
finally
// 最后推进
if (RecvCount > 0) then
IncBufferPos(RecvCount);
end;
end;
procedure TWSServerReceiver.Receive(const AData: PAnsiChar; const ASize: Cardinal);
var
RecvCount: Integer;
begin
// 接收后续数据
FBuffer := AData;
FBufSize := ASize;
FData := FBuffer; // 数据开始位置
// 1. 处理当前帧的接收
if (FFrameRecvSize < FFrameSize) then // FLackSize > 0 时 FFrameSize = 0
begin
RecvCount := GetContentSize(FBufSize);
UnMarkData(RecvCount); // 解码(服务端)
WriteStream(RecvCount); // 保存到流
IncBufferPos(RecvCount); // 前移
end;
// 2. 剩余的内容是下一消息的
if (FBufSize > 0) then
SaveRemainData;
end;
procedure TWSServerReceiver.SaveRemainData;
begin
// 保存剩余内容,下次接收(保留)
// 客户端发送完毕时稍微停顿,避免有剩余
end;
procedure TWSServerReceiver.UnMarkData(ASize: Cardinal);
var
i: Integer;
p: PByte;
begin
// 带掩码 -> xor 解码
if (ASize > 0) and FMaskExists then
begin
p := PByte(FBuffer);
for i := FFrameRecvSize to FFrameRecvSize + ASize - 1 do
begin
p^ := p^ xor FMask[i mod 4];
Inc(p);
end;
end;
end;
procedure TWSServerReceiver.WriteStream(ASize: Cardinal);
begin
// 保存数据到流
// 接收数+
IncRecvCount(ASize);
// 1. 写数据流
case FMsgType of
mtDefault: // 更新 mtDefault 的消息长度
Inc(TServerWebSocket(FOwner).FMsgSize, ASize);
mtJSON: // 扩展的 JSON 消息
FStream.Write(FBuffer^, ASize);
mtAttachment: // 附件流
if Assigned(FJSON.Attachment) then
FJSON.Attachment.Write(FBuffer^, ASize);
end;
// 2. 接收完毕
if FCompleted then
case FMsgType of
mtJSON: begin // JSON 消息
FJSON.Initialize(FStream, True); // 转换 JSON, 同时清除 FStream
if FJSON.HasAttachment then // 带附件
FMsgType := mtAttachment // 下次为附件流
else
FMsgType := mtDefault;
end;
mtAttachment: // 附件流
FMsgType := mtDefault; // 下次为 mtDefault
end;
end;
{ TWSClientReceiver }
destructor TWSClientReceiver.Destroy;
begin
if Assigned(FJSON) then
FJSON.Free;
inherited;
end;
procedure TWSClientReceiver.InitResources(ASize: Cardinal);
begin
// 准备数据流
// JSON、非扩展的数据均保存到数据流
if (Assigned(FStream) = False) then
FStream := TMemoryStream.Create;
end;
procedure TWSClientReceiver.InterReceiveData(ASize: Cardinal);
var
RecvCount: Cardinal;
begin
// 准备接收数据
RecvCount := GetContentSize(ASize); // 取有效长度
try
// 准备资源
InitResources(RecvCount);
// 保存到流
WriteStream(RecvCount);
finally
// 最后推进
if (RecvCount > 0) then
IncBufferPos(RecvCount);
end;
end;
procedure TWSClientReceiver.PostJSON(AOpCode: TWSOpCode;
AMsgType: TWSMsgType; AStream: TMemoryStream);
begin
// 投放 JSON 消息
with TJSONResultRef(FJSON) do
begin
FOpCode := AOpCode;
FMsgType := AMsgType;
FStream := AStream;
end;
try
FOnPost(FJSON); // 投放 FJSON
finally
FJSON := TJSONResult.Create(FOwner); // 新建
if Assigned(AStream) then // Stream 已经投放
FStream := TMemoryStream.Create; // 新建
if Assigned(FOnNewMsg) then
FOnNewMsg(FJSON); // 新消息事件
end;
end;
procedure TWSClientReceiver.Receive(const AData: PAnsiChar; const ASize: Cardinal);
var
RecvCount: Integer;
begin
// 接收后续数据
FBuffer := AData;
FBufSize := ASize;
// 1. 处理当前帧的接收
if (FFrameRecvSize < FFrameSize) then // FLackSize > 0 时 FFrameSize = 0
begin
RecvCount := GetContentSize(FBufSize);
WriteStream(RecvCount); // 保存到流
IncBufferPos(RecvCount); // 前移
end;
// 2. 处理剩余数据
// 2.1 处理帧描述折断问题
// 特殊:客户端接收到推算消息时,帧描述会被折断分块
if (FBufSize > 0) and (FLackSize > 0) then
begin
if (FLackSize = 9) then // 转义,填帧的第二字节
begin
FHeader[1] := FBuffer^;
FLackSize := GetFrameSize(Byte(FHeader[1])) - 2; // 重取
IncBufferPos(1);
end;
// 可能 ocClose、ocPing、ocPong -> RecvCount = 0
if (FBufSize < FLackSize) then
RecvCount := FBufSize
else
RecvCount := FLackSize;
if (RecvCount > 0) then
begin
System.Move(FBuffer^, FHeadAddr^, RecvCount);
IncBufferPos(RecvCount);
Inc(FHeadAddr, RecvCount);
Dec(FLackSize, RecvCount);
end;
end;
// 3. 帧描述完整,继续提取数据
if (FLackSize = 0) then
ScanRecvWSBuffers;
end;
procedure TWSClientReceiver.SaveRemainData;
var
i: Integer;
begin
// 描述长度至少 2 字节(ocClose、ocPing、ocPong)
// 不足时保存内容到 FHeader,下次拼接
if (FBufSize = 1) then
begin
FHeader[0] := FBuffer^;
FHeadAddr := @FHeader[2]; // 第3字节位置,见 TWSClientReceiver.Receive
FLackSize := 9; // 转义, 少第二字节
end else
begin
for i := 0 to FBufSize - 1 do
FHeader[i] := (FBuffer + i)^;
// 不足的长度
FLackSize := GetFrameSize(Byte(FHeader[1])) - FBufSize;
if (FLackSize > 0) then
FHeadAddr := @FHeader[FBufSize]
else begin // 帧描述完整,仅取信息
ExtractFrame(PAnsiChar(@FHeader[0]), FBufSize, False);
FCompleted := FFrameSize = 0; // ocClose、ocPing、 ocPong
end;
end;
if (FLackSize > 0) then
begin
FFrameSize := 0;
FFrameRecvSize := 0;
FCompleted := False;
end;
FBufSize := 0;
end;
procedure TWSClientReceiver.WriteStream(ASize: Cardinal);
begin
// 1. 接收数+
IncRecvCount(ASize);
// 2. 保存到流(FMsgType未知)
if (ASize > 0) then
if Assigned(FJSON.Attachment) then // 附件
begin
FJSON.Attachment.Write(FBuffer^, ASize);
FOnReceive(FJSON, mdtAttachment, ASize); // 附件的接收进程
end else // 文本消息(未知、InIOCP-JSON)
FStream.Write(FBuffer^, ASize);
// 5. 接收完毕
if FCompleted then
begin
// 清零
FFrameSize := 0;
FFrameRecvSize := 0;
// 检查数据类型
if (FMsgType <> mtAttachment) then
FMsgType := CheckInIOCPFlag(PAnsiChar(FStream.Memory), FStream.Size);
case FMsgType of
mtDefault:
if (FOpCode <= ocClose) then
PostJSON(FOpCode, mtDefault, FStream); // 同时投放 FStream
mtJSON: begin
FJSON.Initialize(FStream, True); // 转换 JSON, 同时清除 FStream
if FJSON.HasAttachment then // 同步
begin
FMsgType := mtAttachment; // 下次为附件流
if Assigned(FOnAttachment) then
FOnAttachment(FJSON); // 在其中判断是否接收文件流
end else // 直接投放
begin
FMsgType := mtDefault; // 下次为 mtDefault
PostJSON(FOpCode, mtJSON, nil);
end;
end;
mtAttachment: begin
FMsgType := mtDefault; // 下次为 mtDefault
if Assigned(FJSON.Attachment) then
FJSON.Attachment.Position := 0;
PostJSON(FOpCode, mtAttachment, nil); // 投放附件
end;
end;
end;
end;
end.
|
unit clOrdemServico;
interface
uses clConexao;
type
TOrdemServico = Class(TObject)
private
function getData: TDateTime;
function getEntregador: Integer;
function getExecutor: String;
function getHoraRetorno: String;
function getHoraSaida: String;
function getKmFinal: Integer;
function getKmInicial: Integer;
function getManutencao: TDateTime;
function getNumero: Integer;
function getRota: String;
function getValorDiaria: Double;
function getVeiculo: Integer;
procedure setData(const Value: TDateTime);
procedure setEntregador(const Value: Integer);
procedure setExecutor(const Value: String);
procedure setHoraRetorno(const Value: String);
procedure setHoraSaida(const Value: String);
procedure setKmFinal(const Value: Integer);
procedure setKmInicial(const Value: Integer);
procedure setManutencao(const Value: TDateTime);
procedure setNumero(const Value: Integer);
procedure setRota(const Value: String);
procedure setValorDiaria(const Value: Double);
procedure setVeiculo(const Value: Integer);
function getDescricao: String;
procedure setDescricao(const Value: String);
function getDataPago: TDateTime;
function getFechado: String;
procedure setDataPago(const Value: TDateTime);
procedure setFechado(const Value: String);
function getExtrato: String;
procedure setExtrato(const Value: String);
constructor Create;
destructor Destroy;
procedure SetID(val: Integer);
function getId: Integer;
function getCliente: Integer;
procedure setCliente(const Value: Integer);
protected
_numero: Integer;
_data: TDateTime;
_entregador: Integer;
_cliente : Integer;
_veiculo: Integer;
_rota: String;
_kminicial: Integer;
_kmfinal: Integer;
_horasaida: String;
_horaretorno: String;
_descricao: String;
_valordiaria: Double;
_fechado: String;
_datapago: TDateTime;
_executor: String;
_manutencao: TDateTime;
_extrato: String;
_id: Integer;
_conexao: TConexao;
public
property Numero: Integer read getNumero write setNumero;
property Data: TDateTime read getData write setData;
property Entregador: Integer read getEntregador write setEntregador;
property Cliente : Integer read getCliente write setCliente;
property Veiculo: Integer read getVeiculo write setVeiculo;
property Rota: String read getRota write setRota;
property KmInicial: Integer read getKmInicial write setKmInicial;
property KmFinal: Integer read getKmFinal write setKmFinal;
property HoraSaida: String read getHoraSaida write setHoraSaida;
property HoraRetorno: String read getHoraRetorno write setHoraRetorno;
property Descricao: String read getDescricao write setDescricao;
property ValorDiaria: Double read getValorDiaria write setValorDiaria;
property Fechado: String read getFechado write setFechado;
property DataPago: TDateTime read getDataPago write setDataPago;
property Executor: String read getExecutor write setExecutor;
property Manutencao: TDateTime read getManutencao write setManutencao;
property Extrato: String read getExtrato write setExtrato;
property Id: Integer read getId write SetID;
function Validar(): Boolean;
function Delete(filtro: String): Boolean;
function getObject(id, filtro: String): Boolean;
function getObjects(): Boolean;
function getField(campo, coluna: String): String;
function Insert(): Boolean;
function Update(): Boolean;
function Periodo(sdtInicial, sdtFinal, sEntregador: String): Boolean;
function Exist(): Boolean;
procedure MaxNumero;
procedure GeraNumeroExtrato;
end;
const
TABLENAME = 'TBORDEMSERVICO';
implementation
{ TOrdemServico }
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Math,
DateUtils;
constructor TOrdemServico.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TOrdemServico.Destroy;
begin
_conexao.Free;
end;
function TOrdemServico.getCliente: Integer;
begin
Result := _cliente;
end;
function TOrdemServico.getData: TDateTime;
begin
Result := _data;
end;
function TOrdemServico.getDataPago: TDateTime;
begin
Result := _datapago;
end;
function TOrdemServico.getEntregador: Integer;
begin
Result := _entregador;
end;
function TOrdemServico.getExecutor: String;
begin
Result := _executor;
end;
function TOrdemServico.getExtrato: String;
begin
Result := _extrato;
end;
function TOrdemServico.getHoraRetorno: String;
begin
Result := _horaretorno;
end;
function TOrdemServico.getHoraSaida: String;
begin
Result := _horasaida;
end;
function TOrdemServico.getKmFinal: Integer;
begin
Result := _kmfinal;
end;
function TOrdemServico.getKmInicial: Integer;
begin
Result := _kminicial;
end;
function TOrdemServico.getManutencao: TDateTime;
begin
Result := _manutencao;
end;
function TOrdemServico.getNumero: Integer;
begin
Result := _numero;
end;
function TOrdemServico.getRota: String;
begin
Result := _rota;
end;
function TOrdemServico.getValorDiaria: Double;
begin
Result := _valordiaria;
end;
function TOrdemServico.getVeiculo: Integer;
begin
Result := _veiculo;
end;
function TOrdemServico.getDescricao: String;
begin
Result := _descricao;
end;
function TOrdemServico.getId: Integer;
begin
Result := _id;
end;
function TOrdemServico.Validar(): Boolean;
begin
Result := False;
if Self.Entregador = 0 then
begin
MessageDlg('Informe o Entregador!', mtWarning, [mbOK], 0);
Exit;
end;
if Self.Veiculo = 0 then
begin
MessageDlg('Informe o Veiculo!', mtWarning, [mbOK], 0);
Exit;
end;
if Self.KmFinal > 0 then
begin
if Self.KmFinal < Self.KmInicial then
begin
MessageDlg('O KM Final não pode ser menor que o KM inicial!', mtWarning,
[mbOK], 0);
Exit;
end;
end;
if TUtil.Empty(Self.Descricao) then
begin
MessageDlg('Informe o(s) serviço(s)!', mtWarning, [mbOK], 0);
Exit;
end;
Result := True;
end;
function TOrdemServico.Delete(filtro: String): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'NUMERO' then
begin
SQL.Add('WHERE NUM_OS = :NUMERO');
ParamByName('NUMERO').AsInteger := Self.Numero;
end
else if filtro = 'DATA' then
begin
SQL.Add('WHERE DAT_OS = :DATA');
ParamByName('DATA').AsDate := Self.Data;
end;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.getObject(id, filtro: String): Boolean;
begin
try
Result := False;
With dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'NUMERO' then
begin
SQL.Add('WHERE NUM_OS = :NUMERO');
ParamByName('NUMERO').AsInteger := StrToInt(id);
end
else if filtro = 'DATA' then
begin
SQL.Add('WHERE DAT_OS = :DATA');
ParamByName('DATA').AsDate := StrToDate(id);
end
else if filtro = 'ENTREGADOR' then
begin
SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR');
ParamByName('ENTREGADOR').AsInteger := StrToInt(id);
end
else if filtro = 'CLIENTE' then
begin
SQL.Add('WHERE COD_CLIENTE = :CLIENTE');
ParamByName('CLIENTE').AsInteger := StrToInt(id);
end
else if filtro = 'VEICULO' then
begin
SQL.Add('WHERE COD_VEICULO = :VEICULO');
ParamByName('VEICULO').AsInteger := StrToInt(id);
end
else if filtro = 'ID' then
begin
SQL.Add('WHERE ID_CONTROLE = :ID');
ParamByName('ID').AsInteger := StrToInt(id);
end;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
First;
Self.Numero := FieldByName('NUM_OS').AsInteger;
Self.Data := FieldByName('DAT_OS').AsDateTime;
Self.Entregador := FieldByName('COD_ENTREGADOR').AsInteger;
Self.Cliente := FieldByName('COD_CLIENTE').AsInteger;
Self.Veiculo := FieldByName('COD_VEICULO').AsInteger;
Self.Rota := FieldByName('DES_ROTA').AsString;
Self.KmInicial := FieldByName('QTD_KM_INICIAL').AsInteger;
Self.KmFinal := FieldByName('QTD_KM_FINAL').AsInteger;
Self.HoraSaida := FieldByName('DES_HORA_SAIDA').AsString;
Self.HoraRetorno := FieldByName('DES_HORA_RETORNO').AsString;
Self.Descricao := FieldByName('DES_SERVICO').AsString;
Self.ValorDiaria := FieldByName('VAL_DIARIA').AsFloat;
Self.Executor := FieldByName('NOM_EXECUTOR').AsString;
Self.Manutencao := FieldByName('DAT_MANUTENCAO').AsDateTime;
Self.Fechado := FieldByName('DOM_FECHADO').AsString;
Self.DataPago := FieldByName('DAT_PAGO').AsDateTime;
Self.Extrato := FieldByName('NUM_EXTRATO').AsString;
Self.Id := FieldByName('ID_CONTROLE').AsInteger;
if RecordCount = 1 then
begin
Close;
SQL.Clear;
end;
end
else
begin
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.getObjects(): Boolean;
begin
try
Result := False;
With dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
dm.ZConn.PingServer;
Open;
if IsEmpty then
begin
MessageDlg('Nenhum registro encontrado!', mtWarning, [mbOK], 0);
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.getFechado: String;
begin
Result := _fechado;
end;
function TOrdemServico.getField(campo, coluna: String): String;
begin
try
Result := '';
with dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT :CAMPO FROM ' + TABLENAME);
ParamByName('CAMPO').AsString := campo;
if coluna = 'NUMERO' then
begin
SQL.Add('WHERE NUM_OS = :NUMERO');
ParamByName('NUMERO').AsInteger := Self.Numero;
end;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
First;
Result := FieldByName(campo).AsString;
end;
Close;
SQL.Clear;
end;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.Insert(): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + '(' +
'NUM_OS, ' +
'DAT_OS, ' +
'COD_ENTREGADOR, ' +
'COD_CLIENTE, ' +
'COD_VEICULO, ' +
'DES_ROTA, ' +
'QTD_KM_INICIAL, ' +
'QTD_KM_FINAL, ' +
'DES_HORA_SAIDA, ' +
'DES_HORA_RETORNO, ' +
'DES_SERVICO, ' +
'VAL_DIARIA, ' +
'DOM_FECHADO, ' +
'DAT_PAGO, ' +
'ID_CONTROLE, ' +
'NOM_EXECUTOR, ' +
'NUM_EXTRATO, ' +
'DAT_MANUTENCAO) ' +
'VALUES (' +
':NUMERO, ' +
':DATA, ' +
':ENTREGADOR, ' +
':CLIENTE, ' +
':VEICULO, ' +
':ROTA, ' +
':KMINICIAL, ' +
':KMFINAL, ' +
':HORASAIDA, ' +
':HORARETORNO, ' +
':SERVICO, ' +
':DIARIA, ' +
':FECHADO, ' +
':DATAPAGO, ' +
':ID, ' +
':EXECUTOR, ' +
':EXTRATO, ' +
':MANUTENCAO)';
MaxNumero;
ParamByName('NUMERO').AsInteger := Self.Numero;
ParamByName('DATA').AsDate := Self.Data;
ParamByName('ENTREGADOR').AsInteger := Self.Entregador;
ParamByName('CLIENTE').AsInteger := Self.Cliente;
ParamByName('VEICULO').AsInteger := Self.Veiculo;
ParamByName('ROTA').AsString := Self.Rota;
ParamByName('KMINICIAL').AsInteger := Self.KmInicial;
ParamByName('KMFINAL').AsInteger := Self.KmFinal;
ParamByName('HORASAIDA').AsString := Self.HoraSaida;
ParamByName('HORARETORNO').AsString := Self.HoraRetorno;
ParamByName('SERVICO').AsString := Self.Descricao;
ParamByName('DIARIA').AsFloat := Self.ValorDiaria;
ParamByName('FECHADO').AsString := Self.Fechado;
ParamByName('DATAPAGO').AsDateTime := Self.DataPago;
ParamByName('EXECUTOR').AsString := Self.Executor;
ParamByName('EXTRATO').AsString := Self.Extrato;
ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao;
ParamByName('ID').AsInteger := Self.Id;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.Update(): Boolean;
begin
try
Result := False;
with dm.qryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'DAT_OS = :DATA, ' +
'COD_ENTREGADOR = :ENTREGADOR, ' +
'COD_CLIENTE = :CLIENTE, ' +
'COD_VEICULO = :VEICULO, ' +
'DES_ROTA = :ROTA, ' +
'QTD_KM_INICIAL = :KMINICIAL, ' +
'QTD_KM_FINAL = :KMFINAL, ' +
'DES_HORA_SAIDA = :HORASAIDA, ' +
'DES_HORA_RETORNO = :HORARETORNO,' +
'DES_SERVICO = :SERVICO, ' +
'VAL_DIARIA = :DIARIA, ' +
'DOM_FECHADO = :FECHADO, ' +
'DAT_PAGO = :DATAPAGO, ' +
'ID_CONTROLE = :ID, ' +
'NOM_EXECUTOR = :EXECUTOR, ' +
'NUM_EXTRATO = :EXTRATO, ' +
'DAT_MANUTENCAO = :MANUTENCAO ' +
'WHERE NUM_OS = :NUMERO';
ParamByName('NUMERO').AsInteger := Self.Numero;
ParamByName('DATA').AsDate := Self.Data;
ParamByName('ENTREGADOR').AsInteger := Self.Entregador;
ParamByName('CLIENTE').AsInteger := Self.Cliente;
ParamByName('VEICULO').AsInteger := Self.Veiculo;
ParamByName('ROTA').AsString := Self.Rota;
ParamByName('KMINICIAL').AsInteger := Self.KmInicial;
ParamByName('KMFINAL').AsInteger := Self.KmFinal;
ParamByName('HORASAIDA').AsString := Self.HoraSaida;
ParamByName('HORARETORNO').AsString := Self.HoraRetorno;
ParamByName('SERVICO').AsString := Self.Descricao;
ParamByName('DIARIA').AsFloat := Self.ValorDiaria;
ParamByName('FECHADO').AsString := Self.Fechado;
ParamByName('DATAPAGO').AsDateTime := Self.DataPago;
ParamByName('ID').AsInteger := Self.Id;
ParamByName('EXECUTOR').AsString := Self.Executor;
ParamByName('EXTRATO').AsString := Self.Extrato;
ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao;
dm.ZConn.PingServer;
ExecSQL;
Close;
SQL.Clear;
end;
Result := True;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
procedure TOrdemServico.MaxNumero;
begin
try
with dm.qryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT MAX(NUM_OS) AS NUMERO FROM ' + TABLENAME);
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
Self.Numero := FieldByName('NUMERO').AsInteger + 1;
end
else
begin
Self.Numero := 1;
end;
Close;
SQL.Clear;
end;
Except
on E: Exception do
begin
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
end;
function TOrdemServico.Periodo(sdtInicial, sdtFinal,
sEntregador: String): Boolean;
var
iAgente: Integer;
begin
Try
Result := False;
if TUtil.Empty(sdtInicial) then
begin
Exit;
end;
if TUtil.Empty(sdtFinal) then
begin
Exit;
end;
with dm.qryGeral do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
SQL.Add(' WHERE DAT_OS BETWEEN :INICIO AND :TERMINO');
if StrToInt(sEntregador) > 0 then
begin
SQL.Add(' AND COD_CLIENTE = :CLIENTE');
end;
ParamByName('INICIO').AsDate := StrToDate(sdtInicial);
ParamByName('TERMINO').AsDate := StrToDate(sdtFinal);
if StrToInt(sEntregador) > 0 then
begin
ParamByName('CLIENTE').AsInteger := StrToInt(sEntregador);
end;
dm.ZConn.PingServer;
Open;
if IsEmpty then
begin
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TOrdemServico.GeraNumeroExtrato;
var
sNumero: String;
begin
try
sNumero := IntToStr(YearOf(Self.DataPago)) +
Format('%3.3d', [DayOfTheYear(Self.DataPago)]) +
Format('%6.6d', [Self.Entregador]);
Self.Extrato := sNumero;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TOrdemServico.Exist(): Boolean;
begin
Result := False;
With dm.qryPesquisa do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
SQL.Add('WHERE DAT_OS = :DATA ');
SQL.Add('AND COD_ENTREGADOR = :ENTREGADOR, ');
SQL.Add('AND COD_CLIENTE = :CLIENTE ');
SQL.Add('AND COD_VEICULO = :VEICULO ');
SQL.Add('AND QTD_KM_INICIAL = :KMINICIAL ' );
SQL.Add('AND QTD_KM_FINAL = :KMFINAL');
ParamByName('DATA').AsDate := Self.Data;
ParamByName('ENTREGADOR').AsInteger := Self.Entregador;
ParamByName('CLIENTE').AsInteger := Self.Cliente;
ParamByName('VEICULO').AsInteger := Self.Veiculo;
ParamByName('KMINICIAL').AsInteger := Self.KmInicial;
ParamByName('KMFINAL').AsInteger := Self.KmFinal;
dm.ZConn.PingServer;
Open;
if IsEmpty then
begin
Close;
SQL.Clear;
Exit;
end;
Close;
SQL.Clear;
end;
Result := True;
end;
procedure TOrdemServico.setCliente(const Value: Integer);
begin
_cliente := Value;
end;
procedure TOrdemServico.setData(const Value: TDateTime);
begin
_data := Value;
end;
procedure TOrdemServico.setDataPago(const Value: TDateTime);
begin
_datapago := Value;
end;
procedure TOrdemServico.setEntregador(const Value: Integer);
begin
_entregador := Value;
end;
procedure TOrdemServico.setExecutor(const Value: String);
begin
_executor := Value;
end;
procedure TOrdemServico.setExtrato(const Value: String);
begin
_extrato := Value;
end;
procedure TOrdemServico.setFechado(const Value: String);
begin
_fechado := Value;
end;
procedure TOrdemServico.setHoraRetorno(const Value: String);
begin
_horaretorno := Value;
end;
procedure TOrdemServico.setHoraSaida(const Value: String);
begin
_horasaida := Value;
end;
procedure TOrdemServico.setKmFinal(const Value: Integer);
begin
_kmfinal := Value;
end;
procedure TOrdemServico.setKmInicial(const Value: Integer);
begin
_kminicial := Value;
end;
procedure TOrdemServico.setManutencao(const Value: TDateTime);
begin
_manutencao := Value;
end;
procedure TOrdemServico.setNumero(const Value: Integer);
begin
_numero := Value;
end;
procedure TOrdemServico.setRota(const Value: String);
begin
_rota := Value;
end;
procedure TOrdemServico.setValorDiaria(const Value: Double);
begin
_valordiaria := Value;
end;
procedure TOrdemServico.setVeiculo(const Value: Integer);
begin
_veiculo := Value;
end;
procedure TOrdemServico.setDescricao(const Value: String);
begin
_descricao := Value;
end;
procedure TOrdemServico.SetID(val: Integer);
begin
_id := val;
end;
end.
|
unit dcInfoEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, ToolEdit, dcEdit;
type
TdcInfoEdit = class(TdcEdit)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent);
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcInfoEdit]);
end;
{ TdcInfoEdit }
constructor TdcInfoEdit.create(AOwner: TComponent);
begin
inherited create(AOwner);
CharCase := ecUpperCase;
end;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo;
type
TFormMain = class(TForm)
ButtonInfo: TButton;
Memo: TMemo;
procedure ButtonInfoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge,
Androidapi.JNI.GraphicsContentViewText, android.net.wifi;
{$R *.fmx}
procedure TFormMain.ButtonInfoClick(Sender: TObject);
var
Service: JObject;
WifiManager: JWifiManager;
ConnectionInfo: JWifiInfo;
ScanResults: JList;
ScanResult: JScanResult;
I: Integer;
begin
Memo.Lines.Clear;
Service := SharedActivity.getSystemService(TJContext.JavaClass.WIFI_SERVICE);
WifiManager := TJWifiManager.Wrap((Service as ILocalObject).GetObjectID);
if not WifiManager.isWifiEnabled then
Memo.Lines.Add('Wifi is disabled')
else
begin
ConnectionInfo := WifiManager.getConnectionInfo;
Memo.Lines.Add('Connection info');
Memo.Lines.Add(' SSID: ' + JStringToString(ConnectionInfo.getSSID));
Memo.Lines.Add(' BSSID: ' + JStringToString(ConnectionInfo.getBSSID));
Memo.Lines.Add(' MAC address: ' + JStringToString(ConnectionInfo.getMacAddress));
ScanResults := WifiManager.getScanResults;
for I := 0 to ScanResults.size - 1 do
begin
Memo.Lines.Add('');
Memo.Lines.Add('Detected access point ' + IntToStr(I));
ScanResult := TJScanResult.Wrap((ScanResults.get(I) as ILocalObject).GetObjectID);
Memo.Lines.Add(' SSID: ' + JStringToString(ScanResult.SSID));
Memo.Lines.Add(' BSSID: ' + JStringToString(ScanResult.BSSID));
Memo.Lines.Add(' Capabilities: ' + JStringToString(ScanResult.capabilities));
Memo.Lines.Add(' Frequency: ' + IntToStr(ScanResult.frequency) + 'MHz');
Memo.Lines.Add(' Signal level: ' + IntToStr(ScanResult.level) + 'dBm');
end
end
end;
end.
|
unit uGraph;
{$MODE OBJFPC}
interface
uses Classes;
type
TNode = class
strict private
FName: String;
FEdges: TList<TNode>;
function GetEdge(Index: Integer): TNode;
function GetEdgeCount: Integer;
function SetName(aName: String);
function GetName: String;
public
constructor Create(const AName: String);
procedure AddEdge(ANode: TNode);
procedure AddEdges(const ANodes: array of TNode);
property Edge[Index: Integer]: TNode read GetEdge;
property Count: Integer read GetEdgeCount;
property Name(s: String) write SetName;
property Name: String read GetName;
destructor Destroy; override;
end;
var
Nodes: TObjectList<TNode>;
function CreateNode(const AName: String): TNode;
implementation
function CreateNode(const AName: String): TNode;
begin
Result := TNode.Create(AName);
Nodes.Add(Result);
end;
{ TNode }
procedure TNode.AddEdge(ANode: TNode);
begin
FEdges.Add(ANode)
end;
procedure TNode.AddEdges(const ANodes: array of TNode);
var
Node: TNode;
begin
for Node in ANodes do
AddEdge(Node);
end;
constructor TNode.Create(const AName: String);
begin
FName := AName;
FEdges := TList<TNode>.Create;
end;
destructor TNode.Destroy;
begin
FEdges.Free;
inherited;
end;
procedure SetName(aName: String);
begin
FName := aName;
end;
function TNode.GetName: String;
begin
Result := FName;
end;
function TNode.GetEdgeCount: Integer;
begin
Result := FEdges.Count;
end;
function TNode.GetEdge(Index: Integer): TNode;
begin
Result := FEdges[Index];
end;
var NewYork,
London,
Paris,
Moscow: TNode;
BEGIN
Nodes := TObjectList<TNode>.Create(True{say})
NewYork := CreateNode('New York');
London := CreateNode('London');
Paris := CreateNode('Paris');
Moscow := CreateNode('Moscow');
NewYork.AddEdge(London);
London.AddEdges([NewYork, Paris, Moscow]);
Paris.AddEdges([London, Moscow]);
Moscow.AddEdge(NewYork);
London.Edge[2].Name('Mosscow');
WriteLn(Paris.Edge[1].Name)
END.
|
unit VSM.Rest.Auth;
interface
uses VSM.Rest.Enumeradores;
type
TSolucoesAuth = (VSMCard, VSMEcommerce, Orizon);
type TVSMRestAutentication = class
private
Furl: string;
Fuser: string;
Fpass: string;
FtimeOut: Integer;
FgrantType: string;
FToken: string;
FType_Authorizarion_API: TVSMRestTipoAutenticacao;
FEncode: string;
procedure Seturl(const Value: string);
procedure Setuser(const Value: string);
procedure Setpass(const Value: string);
procedure SettimeOut(const Value: Integer);
procedure SetgrantType(const Value: string);
procedure SetToken(const Value: string);
{ private declarations }
protected
{ protected declarations }
public
constructor Create;
{ public declarations }
published
property url: string read Furl write Seturl;
property user: string read Fuser write Setuser;
property pass: string read Fpass write Setpass;
property Token: string read FToken write SetToken;
property timeOut: Integer read FtimeOut write SettimeOut;
property grantType: string read FgrantType write SetgrantType;
property Type_Authorizarion_API : TVSMRestTipoAutenticacao read FType_Authorizarion_API write FType_Authorizarion_API;
property Encode : string read FEncode write FEncode;
{ published declarations }
end;
type
TVSMRestAuthFactory = class
private
{ private declarations }
protected
{ protected declarations }
public
class function GetRestAuth(solucao: TSolucoesAuth; bAutenticacaoToken : Boolean = False): TVSMRestAutentication;
{ public declarations }
published
{ published declarations }
end;
implementation
uses
Soap.EncdDecd, System.SysUtils;
{ TVSMRestAutentication }
constructor TVSMRestAutentication.Create;
begin
Self.FToken := '';
end;
procedure TVSMRestAutentication.SetgrantType(const Value: string);
begin
FgrantType := Value;
end;
procedure TVSMRestAutentication.Setpass(const Value: string);
begin
Fpass := Value;
end;
procedure TVSMRestAutentication.SettimeOut(const Value: Integer);
begin
FtimeOut := Value;
end;
procedure TVSMRestAutentication.SetToken(const Value: string);
begin
FToken := Value;
end;
procedure TVSMRestAutentication.Seturl(const Value: string);
begin
Furl := Value;
end;
procedure TVSMRestAutentication.Setuser(const Value: string);
begin
Fuser := Value;
end;
{ TVSMRestAuthFactory }
class function TVSMRestAuthFactory.GetRestAuth(solucao: TSolucoesAuth; bAutenticacaoToken : Boolean = False): TVSMRestAutentication;
var
restAuth: TVSMRestAutentication;
// wsWebService : TWebService;
begin
// try
restAuth := TVSMRestAutentication.Create();
// wsWebService := TWebService.Create;
// try
// case solucao of
// VSMCard : wsWebService := TVSMWebServiceUtils.GetWebService('OAC');
// VSMEcommerce : wsWebService := TVSMWebServiceUtils.GetWebService('OAT');
// Orizon : wsWebService := TVSMWebServiceUtils.GetWebService('ORZ');
// end;
// restAuth.Type_Authorizarion_API := TVSMRestTipoAutenticacao(wsWebService.Type_Authorizarion_API);
// case restAuth.Type_Authorizarion_API of
// tpBasicAuth :
// begin
// restAuth.Encode := 'Basic ' + EncodeString(TVSMConfigLojaService.getInstance.LerString('PBM_ORIZON_USER') +':'+TVSMConfigLojaService.getInstance.LerString('PBM_ORIZON_PASS'));
// restAuth.Token := TVSMConfigLojaService.getInstance.LerString('PBM_ORIZON_APIKEY') ;
// end;
// tpOAuth2 :
// begin
// restAuth.User := wsWebService.Usuario;
// restAuth.Pass := wsWebService.Senha;
// end;
// tpBearerToken :
// begin
//// restAuth.Token := 'Bearer ' + wsWebService.ApiKeyLoja;
// end;
// end;
// restAuth.Url := wsWebService.Url;
// restAuth.TimeOut := 10000;
// restAuth.grantType := 'grant_type=client_credentials';
// finally
// wsWebService.Free;
// end;
// Result := restAuth;
// except
// on E:Exception do
// begin
// TVSMLogUtils.GetInstance.LogE('TVSMRestAuthFactory.GetRestAuth - Ocorreu uma falha ao retornar o conte˙do do WebService. ' + E.Message);
// raise;
// end;
// end;
end;
end.
|
unit QueryForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, GridsEh, DBGridEh, ExtCtrls, Buttons,
FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, SynEditHighlighter,
SynHighlighterSQL, SynEdit, pFIBScripter, DBGridEhImpExp,
Menus, SynEditMiscClasses, SynEditSearch, ToolCtrlsEh,
DBGridEhToolCtrls, DBAxisGridsEh, PrjConst, EhLibVCL,
System.UITypes, DBGridEhGrouping, DynVarsEh;
type
TQueryForm = class(TForm)
Panel5: TPanel;
SpeedButton1: TSpeedButton;
SynSQLSyn1: TSynSQLSyn;
transaction: TpFIBTransaction;
SpeedButton2: TSpeedButton;
OpenDialog1: TOpenDialog;
SpeedButton3: TSpeedButton;
SaveDialog1: TSaveDialog;
FIBScript: TpFIBScripter;
pc: TPageControl;
tsResultScript: TTabSheet;
seScript: TSynEdit;
tsResultSelect: TTabSheet;
memResult: TMemo;
Splitter1: TSplitter;
DBGridEh1: TDBGridEh;
source: TDataSource;
DataSet: TpFIBDataSet;
gridPopUp: TPopupMenu;
ppmCopy: TMenuItem;
ppmSelectAll: TMenuItem;
MenuItem1: TMenuItem;
ppmSaveSelection: TMenuItem;
syndtsrch1: TSynEditSearch;
procedure SpeedButton1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure FIBScriptExecuteError(Sender: TObject; StatementNo, Line: Integer; Statement: TStrings; SQLCode: Integer;
const Msg: String; var doRollBack, Stop: Boolean);
procedure ppmSaveSelectionClick(Sender: TObject);
procedure ppmCopyClick(Sender: TObject);
procedure ppmSelectAllClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
QueryForm: TQueryForm;
implementation
uses DM, MAIN, atrStrUtils;
{$R *.dfm}
procedure TQueryForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if DataSet.Active
then
DataSet.Close;
Action := caFree;
QueryForm := nil;
end;
procedure TQueryForm.ppmCopyClick(Sender: TObject);
var
dbg: TDBGridEh;
begin
if (ActiveControl is TDBGridEh)
then begin
dbg := (ActiveControl as TDBGridEh);
if (geaCopyEh in dbg.EditActions)
then
if dbg.CheckCopyAction
then
DBGridEh_DoCopyAction(dbg, False)
else
StrToClipbrd(dbg.SelectedField.AsString);
end;
end;
procedure TQueryForm.ppmSaveSelectionClick(Sender: TObject);
var
ExpClass: TDBGridEhExportClass;
Ext: String;
begin
A4MainForm.SaveDialog.FileName := rsCaigin;
if (ActiveControl is TDBGridEh)
then
if A4MainForm.SaveDialog.Execute
then begin
case A4MainForm.SaveDialog.FilterIndex of
1: begin
ExpClass := TDBGridEhExportAsUnicodeText;
Ext := 'txt';
end;
2: begin
ExpClass := TDBGridEhExportAsCSV;
Ext := 'csv';
end;
3: begin
ExpClass := TDBGridEhExportAsHTML;
Ext := 'htm';
end;
4: begin
ExpClass := TDBGridEhExportAsRTF;
Ext := 'rtf';
end;
5: begin
ExpClass := TDBGridEhExportAsOLEXLS;
Ext := 'xls';
end;
else
ExpClass := nil;
Ext := '';
end;
if ExpClass <> nil
then begin
if AnsiUpperCase(Copy(A4MainForm.SaveDialog.FileName, Length(A4MainForm.SaveDialog.FileName) - 2, 3)) <> AnsiUpperCase(Ext)
then
A4MainForm.SaveDialog.FileName := A4MainForm.SaveDialog.FileName + '.' + Ext;
SaveDBGridEhToExportFile(ExpClass, TDBGridEh(ActiveControl), A4MainForm.SaveDialog.FileName, False);
end;
end;
end;
procedure TQueryForm.ppmSelectAllClick(Sender: TObject);
begin
if (ActiveControl is TDBGridEh)
then
with TDBGridEh(ActiveControl) do
if CheckSelectAllAction and (geaSelectAllEh in EditActions)
then
Selection.SelectAll;
end;
procedure TQueryForm.SpeedButton1Click(Sender: TObject);
var
crs: TCursor;
c: Boolean;
i: Integer;
itsSelect: Boolean;
begin
crs := Screen.Cursor;
Screen.Cursor := crHourGlass;
FIBScript.Script.Assign(seScript.Lines);
itsSelect := False;
FIBScript.Parse();
i := FIBScript.StatementsCount;
if i = 1
then
itsSelect := (Pos('SELECT', Trim(AnsiUpperCase(FIBScript.Script.Text))) = 1);
c := FIBScript.Database.Connected;
if not c
then
FIBScript.Database.Open;
if itsSelect
then begin
if DataSet.Active
then
DataSet.Close;
pc.ActivePage := tsResultSelect;
DataSet.SelectSQL.Text := FIBScript.Script.Text;
DataSet.Open;
end
else begin
pc.ActivePage := tsResultScript;
memResult.Lines.clear;
FIBScript.ExecuteScript(1);
if FIBScript.transaction.InTransaction
then
FIBScript.transaction.Commit;
memResult.Lines.Add(rsQueryCompite);
end;
Screen.Cursor := crs;
end;
procedure TQueryForm.SpeedButton2Click(Sender: TObject);
var
myEncoding : TEncoding;
begin
if OpenDialog1.Execute
then begin
//myEncoding := TEncoding.Default;
myEncoding := TEncoding.UTF8;
seScript.Lines.LoadFromFile(OpenDialog1.FileName, myEncoding);
end;
end;
procedure TQueryForm.SpeedButton3Click(Sender: TObject);
begin
if SaveDialog1.Execute
then
seScript.Lines.SaveToFile(SaveDialog1.FileName);
end;
procedure TQueryForm.FIBScriptExecuteError(Sender: TObject; StatementNo, Line: Integer; Statement: TStrings;
SQLCode: Integer; const Msg: String; var doRollBack, Stop: Boolean);
begin
memResult.Lines.Add(format(rsErrorInLine, [Line, Statement.Text]));
Stop := ((MessageDlg(Format(rsErrorQuestWT, [Statement.Text]), mtConfirmation, [mbYes, mbNo], 0) = mrNo));
end;
end.
|
unit udmPagParcela;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmPagParcela = class(TdmPadrao)
qryManutencaoIDPARC: TFloatField;
qryManutencaoIDPGTITULOPARC: TFloatField;
qryManutencaoNUM_PARCELA: TIntegerField;
qryManutencaoDT_VENCTO: TDateTimeField;
qryManutencaoVALOR_PARCELA: TFloatField;
qryLocalizacaoIDPARC: TFloatField;
qryLocalizacaoIDPGTITULOPARC: TFloatField;
qryLocalizacaoNUM_PARCELA: TIntegerField;
qryLocalizacaoDT_VENCTO: TDateTimeField;
qryLocalizacaoVALOR_PARCELA: TFloatField;
qryManutencaoFIL_ORIG: TStringField;
qryManutencaoAUTORIZACAO: TIntegerField;
qryManutencaoPARCELA: TIntegerField;
qryLocalizacaoFIL_ORIG: TStringField;
qryLocalizacaoAUTORIZACAO: TIntegerField;
qryLocalizacaoPARCELA: TIntegerField;
procedure qryManutencaoBeforePost(DataSet: TDataSet);
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FCodigoTitulo: real;
FNumParcela: real;
public
property CodigoTitulo: real read FCodigoTitulo write FCodigoTitulo;
property NumParcela: real read FNumParcela write FNumParcela;
function LocalizarPorNumParcela(DataSet: TDataSet = nil): Boolean;
end;
const
SQL_DEFAULT =
' SELECT ' +
' IDPARC, ' +
' IDPGTITULOPARC, ' +
' NUM_PARCELA, ' +
' DT_VENCTO, ' +
' VALOR_PARCELA, ' +
' FIL_ORIG, ' +
' AUTORIZACAO, ' +
' PARCELA ' +
' FROM PAG_PARCELA ';
var
dmPagParcela: TdmPagParcela;
implementation
uses
udmPrincipal;
{$R *.dfm}
{ TdmPagParcela }
function TdmPagParcela.LocalizarPorNumParcela(DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE IDPGTITULOPARC = :IDPGTITULOPARC');
SQL.Add(' AND NUM_PARCELA = :NUM_PARCELA');
Params[0].AsFloat := FCodigoTitulo;
Params[1].AsFloat := FNumParcela;
Open;
Result := not IsEmpty;
end;
end;
procedure TdmPagParcela.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE IDPGTITULOPARC = :IDPGTITULOPARC');
Params[0].AsFloat := FCodigoTitulo;
end;
end;
procedure TdmPagParcela.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY IDPGTITULOPARC, NUM_PARCELA');
end;
end;
procedure TdmPagParcela.qryManutencaoBeforePost(DataSet: TDataSet);
begin
inherited;
if (qryManutencaoIDPARC.isNull) or (qryManutencaoIDPARC.AsInteger = 0) then
qryManutencaoIDPARC.AsFloat := dmPrincipal.GeraGenerator('GEN_PAGPARCELA');
end;
end.
|
namespace Sugar.Threading;
interface
{$IF COOPER}
uses
java.util.concurrent;
{$ENDIF}
type
{$IF COOPER}
ThreadPool = public static class
private
var fExecutor: ThreadPoolExecutor := new ThreadPoolExecutor(4, 1000, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); readonly;
public
method QueueUserWorkItem(Callback: Runnable);
method Terminate; //must be called in Java
property MinThreads: Integer read fExecutor.CorePoolSize write fExecutor.CorePoolSize;
property MaxThreads: Integer read fExecutor.MaximumPoolSize write fExecutor.MaximumPoolSize;
property AvailableThreads: Integer read fExecutor.MaximumPoolSize - fExecutor.ActiveCount;
end;
{$ELSEIF ECHOES}
ThreadPool = public class mapped to System.Threading.ThreadPool
private
class method GetMinThreads: Integer;
class method GetMaxThreads: Integer;
class method SetMinThreads(Value: Integer);
class method SetMaxThreads(Value: Integer);
{$IF NOT WINDOWS_PHONE}
class method GetAvailableThreads: Integer;
{$ENDIF}
public
class method QueueUserWorkItem(Callback: System.Threading.WaitCallback); mapped to QueueUserWorkItem(Callback);
class property MinThreads: Integer read GetMinThreads write SetMinThreads;
class property MaxThreads: Integer read GetMaxThreads write SetMaxThreads;
{$IF NOT WINDOWS_PHONE}
class property AvailableThreads: Integer read GetAvailableThreads;
{$ENDIF}
end;
{$ENDIF}
{$IF TOFFEE}
ThreadPool = public static class
end;
{$ENDIF}
implementation
{$IF COOPER}
class method ThreadPool.QueueUserWorkItem(Callback: Runnable);
begin
fExecutor.execute(Callback);
end;
class method ThreadPool.Terminate;
begin
fExecutor.shutdown;
end;
{$ELSEIF ECHOES}
class method ThreadPool.GetMinThreads: Integer;
begin
var WorkerThreads: Integer;
var IOThreads: Integer;
System.Threading.ThreadPool.GetMinThreads(out WorkerThreads, out IOThreads);
exit WorkerThreads;
end;
class method ThreadPool.GetMaxThreads: Integer;
begin
var WorkerThreads: Integer;
var IOThreads: Integer;
System.Threading.ThreadPool.GetMaxThreads(out WorkerThreads, out IOThreads);
exit WorkerThreads;
end;
{$IF NOT WINDOWS_PHONE}
class method ThreadPool.GetAvailableThreads: Integer;
begin
var WorkerThreads: Integer;
var IOThreads: Integer;
System.Threading.ThreadPool.GetAvailableThreads(out WorkerThreads, out IOThreads);
exit WorkerThreads;
end;
{$ENDIF}
class method ThreadPool.SetMinThreads(Value: Integer);
begin
var WorkerThreads: Integer;
var IOThreads: Integer;
System.Threading.ThreadPool.GetMinThreads(out WorkerThreads, out IOThreads);
System.Threading.ThreadPool.SetMinThreads(Value, IOThreads);
end;
class method ThreadPool.SetMaxThreads(Value: Integer);
begin
var WorkerThreads: Integer;
var IOThreads: Integer;
System.Threading.ThreadPool.GetMaxThreads(out WorkerThreads, out IOThreads);
System.Threading.ThreadPool.SetMaxThreads(Value, IOThreads);
end;
{$ENDIF}
end. |
unit Rule_REF;
interface
uses
BaseRule,
BaseRuleData;
(*//
REF
含义:引用若干周期前的数据。
用法:REF(X,A),引用A周期前的X值。
例如:REF(CLOSE,1)表示上一周期的收盘价,在日线上就是昨收
//*)
type
TRule_REF = class(TBaseRule)
protected
fParamN: Word;
fInt64Ret: PArrayInt64;
fFloatRet: PArrayDouble;
function Get_REF_ValueF(AIndex: integer): double;
function Get_REF_ValueI(AIndex: integer): Int64;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
procedure ComputeInt64;
procedure ComputeFloat;
public
constructor Create(ADataType: TRuleDataType = dtDouble); override;
destructor Destroy; override;
procedure Execute; override;
procedure Clear; override;
property ValueF[AIndex: integer]: double read Get_REF_ValueF;
property ValueI[AIndex: integer]: int64 read Get_REF_ValueI;
property ParamN: Word read GetParamN write SetParamN;
end;
implementation
{ TRule_REF }
constructor TRule_REF.Create(ADataType: TRuleDataType = dtDouble);
begin
inherited;
fParamN := 20;
fFloatRet := nil;
fInt64Ret := nil;
end;
destructor TRule_REF.Destroy;
begin
Clear;
inherited;
end;
procedure TRule_REF.Execute;
begin
Clear;
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
if fBaseRuleData.DataLength > 0 then
begin
case fBaseRuleData.DataType of
dtInt64: begin
ComputeInt64;
end;
dtDouble: begin
ComputeFloat;
end;
end;
end;
end;
end;
procedure TRule_REF.Clear;
begin
CheckInArrayInt64(fInt64Ret);
CheckInArrayDouble(fFloatRet);
fBaseRuleData.DataLength := 0;
end;
procedure TRule_REF.ComputeInt64;
var
tmpInt64_Meta: array of Int64;
i: integer;
tmpCounter: integer;
tmpValue: Int64;
begin
if Assigned(OnGetDataI) then
begin
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
SetArrayInt64Length(fInt64Ret, fBaseRuleData.DataLength);
SetLength(tmpInt64_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpInt64_Meta[i] := OnGetDataI(i);
tmpValue := tmpInt64_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpValue := tmpValue + tmpInt64_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if 1 < fParamN then
begin
if i > fParamN - 1 then
begin
tmpValue := tmpValue div fParamN;
end else
begin
tmpValue := tmpValue div (i + 1);
end;
end;
SetArrayInt64Value(fInt64Ret, i, tmpValue);
end;
end;
end;
procedure TRule_REF.ComputeFloat;
var
tmpFloat_Meta: array of double;
i: integer;
tmpCounter: integer;
tmpDouble: Double;
begin
if Assigned(OnGetDataF) then
begin
if fFloatRet = nil then
fFloatRet := CheckOutArrayDouble;
SetArrayDoubleLength(fFloatRet, fBaseRuleData.DataLength);
SetLength(tmpFloat_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpFloat_Meta[i] := OnGetDataF(i);
tmpDouble := tmpFloat_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpDouble := tmpDouble + tmpFloat_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if fParamN > 1 then
begin
if i > fParamN - 1 then
begin
tmpDouble := tmpDouble / fParamN;
end else
begin
tmpDouble := tmpDouble / (i + 1);
end;
end;
SetArrayDoubleValue(fFloatRet, i, tmpDouble);
end;
end;
end;
function TRule_REF.GetParamN: Word;
begin
Result := fParamN;
end;
procedure TRule_REF.SetParamN(const Value: Word);
begin
if Value > 0 then
fParamN := Value;
end;
function TRule_REF.Get_REF_ValueF(AIndex: integer): double;
begin
Result := 0;
if fBaseRuleData.DataType = dtDouble then
begin
if fFloatRet <> nil then
begin
Result := GetArrayDoubleValue(fFloatRet, AIndex);
end;
end;
end;
function TRule_REF.Get_REF_ValueI(AIndex: integer): Int64;
begin
Result := 0;
if fBaseRuleData.DataType = dtInt64 then
begin
if fInt64Ret <> nil then
begin
Result := GetArrayInt64Value(fInt64Ret, AIndex);
end;
end;
end;
end.
|
unit periva;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
EnPngGr, Vcl.ExtCtrls, Vcl.StdCtrls,
cxDropDownEdit, cxCalc, cxDBEdit, cxTextEdit, cxMaskEdit, cxSpinEdit,
Vcl.Buttons, Vcl.ImgList, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox;
const
IVA = 767;
type
TFPerIVA = class(TForm)
cdsPerIVA: TClientDataSet;
cdsPerIVAcodigo: TIntegerField;
cdsPerIVAmonto: TFloatField;
ds: TDataSource;
Label1: TLabel;
Label3: TLabel;
cxMonto: TcxDBCalcEdit;
Memo1: TMemo;
Image1: TImage;
btnOK: TButton;
btnAnu: TButton;
img: TImageList;
dsCod: TDataSource;
cxCodigo: TcxDBLookupComboBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOKClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FPerIVA: TFPerIVA;
implementation
uses
DM;
{$R *.dfm}
procedure TFPerIVA.btnOKClick(Sender: TObject);
begin
try
if ( cdsPerIVAcodigo.Value = 0 ) then
raise Exception.Create('Debe ingresar un codigo de percepcion');
if ( cdsPerIVAmonto.Value <= 0 ) then
raise Exception.Create('Ingrese el monto de la percepcion');
except
modalResult := mrNone;
raise;
end;
end;
procedure TFPerIVA.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFPerIVA.FormCreate(Sender: TObject);
begin
cdsPerIVA.CreateDataSet;
cdsPerIVA.Append;
DMod.getTablaPer.Parameters.ParamByName('IMP').Value := IVA;
DMod.getTablaPer.Open;
end;
procedure TFPerIVA.FormDestroy(Sender: TObject);
begin
DMod.getTablaPer.Close;
end;
end.
|
unit DAO.ExpedicaoExpressas;
interface
uses
FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.ExpedicaoExpressas, System.DateUtils;
type
TExpedicaoExpressasDAO = class
private
FConexao : TConexao;
public
constructor Create;
function GetID(): Integer;
function Inserir(AExpedicao: TExpedicaoExpressas): Boolean;
function Alterar(AExpedicao: TExpedicaoExpressas): Boolean;
function Excluir(AExpedicao: TExpedicaoExpressas): Boolean;
function GeraNumeroContaiter(): Integer;
function GeraNumeroRomaneio(AExpedicao: TExpedicaoExpressas): Integer;
function NNExiste(sNN: String): Integer;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'expressas_expedicao';
implementation
{ TExpedicaoExpressasDAO }
uses Control.Sistema;
function TExpedicaoExpressasDAO.Alterar(AExpedicao: TExpedicaoExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set ' +
'dat_expedicao = :dat_expedicao, cod_ccep = :cod_ccep, cod_base = :cod_base, num_container = :num_container, ' +
'cod_unitizador = :cod_unitizador, num_nossonumero = :num_nossonumero, cod_embarcador = :cod_embarcador, ' +
'des_embarcador = :des_embarcador, qtd_volumes = :qtd_volumes, qtd_peso = :qtd_peso, des_executor = :des_executor, '+
'dat_execucao = :dat_execucao, des_conferente = :des_conferente, dat_conferencia = :dat_conferencia, ' +
'des_recebedor = :des_recebedor, dat_recebimento = :dat_recebimento, dom_ccep = :dom_ccep, num_romaneio = :num_romaneio ' +
'where id_expedicao = :id_expedicao;',
[AExpedicao.Data, AExpedicao.CCEP, AExpedicao.Base, AExpedicao.Container, AExpedicao.Unitizador, AExpedicao.NN,
AExpedicao.Embarcador, AExpedicao.NomeEmbarcador, AExpedicao.Volumes, AExpedicao.Peso, AExpedicao.Executor, AExpedicao.Execucao,
AExpedicao.Conferente, AExpedicao.Conferencia, AExpedicao.Recebedor, AExpedicao.Recebimento, AExpedicao.DomCCEP,
AExpedicao.Romaneio, AExpedicao.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TExpedicaoExpressasDAO.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TExpedicaoExpressasDAO.Excluir(AExpedicao: TExpedicaoExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_expedicao = :id_expedicao;', [AExpedicao.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TExpedicaoExpressasDAO.GeraNumeroContaiter: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(num_container),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressasDAO.GeraNumeroRomaneio(AExpedicao: TExpedicaoExpressas): Integer;
var
iDias: Integer;
sRomaneio: String;
begin
Result := 0;
iDias := DaysBetween(AExpedicao.Data, StrToDateDef('01/01/2000',0));
sRomaneio := iDias.ToString + AExpedicao.CCEP;
Result := StrToIntDef(sRomaneio, 0);
end;
function TExpedicaoExpressasDAO.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_expedicao),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressasDAO.Inserir(AExpedicao: TExpedicaoExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
AExpedicao.ID := GetID;
AExpedicao.Romaneio := GeraNumeroRomaneio(AExpedicao);
FDQuery.ExecSQL('insert into ' + TABLENAME +
'(id_expedicao, dat_expedicao, cod_ccep, cod_base, num_container, cod_unitizador, num_nossonumero, cod_embarcador, ' +
'des_embarcador, qtd_volumes, qtd_peso, des_executor, dat_execucao, des_conferente, dat_conferencia, des_recebedor, ' +
'dat_recebimento, dom_ccep, num_romaneio) ' +
'value ' +
'(:id_expedicao, :dat_expedicao, :cod_ccep, :cod_base, :num_container, :cod_unitizador, :num_nossonumero, :cod_embarcador, ' +
':des_embarcador, :qtd_volumes, :qtd_peso, :des_executor, :dat_execucao, :des_conferente, :dat_conferencia, :des_recebedor, ' +
':dat_recebimento, :dom_ccep, :num_romaneio)',
[AExpedicao.ID, AExpedicao.Data, AExpedicao.CCEP, AExpedicao.Base, AExpedicao.Container, AExpedicao.Unitizador, AExpedicao.NN,
AExpedicao.Embarcador, AExpedicao.NomeEmbarcador, AExpedicao.Volumes, AExpedicao.Peso, AExpedicao.Executor,
AExpedicao.Execucao, AExpedicao.Conferente, AExpedicao.Conferencia, AExpedicao.Recebedor, AExpedicao.Recebimento,
AExpedicao.DomCCEP, AExpedicao.Romaneio]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressasDAO.NNExiste(sNN: String): Integer;
var
FDQuery : TFDQuery;
begin
Result := 0;
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select num_container from ' + TABLENAME + ' where num_nossonumero = ' + QuotedStr(sNN));
FDQuery.Open;
if FDQuery.IsEmpty then Result := FDQuery.FieldByName('num_container').AsInteger;
FDQuery.Connection.Close;
FDQuery.Free;
end;
function TExpedicaoExpressasDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_expedicao = :id_expedicao');
FDQuery.ParamByName('id_expedicao').AsInteger := aParam[1];
end;
if aParam[0] = 'CCEP' then
begin
FDQuery.SQL.Add('where cod_ccep = :cod_ccep');
FDQuery.ParamByName('cod_ccep').AsString := aParam[1];
end;
if aParam[0] = 'BASE' then
begin
FDQuery.SQL.Add('where cod_base = :cod_base');
FDQuery.ParamByName('cod_base').AsInteger := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('where dat_expedicao = :dat_expedicao');
FDQuery.ParamByName('dat_expedicao').AsDateTime := aParam[1];
end;
if aParam[0] = 'CONTAINER' then
begin
FDQuery.SQL.Add('where num_container = :num_container');
FDQuery.ParamByName('num_container').AsInteger := aParam[1];
end;
if aParam[0] = 'NN' then
begin
FDQuery.SQL.Add('where num_nossonumero = :num_nossonumero');
FDQuery.ParamByName('num_nossonumero').AsString := aParam[1];
end;
if aParam[0] = 'ROMANEIO' then
begin
FDQuery.SQL.Add('where num_romaneio = :num_romaneio');
FDQuery.ParamByName('num_romaneio').AsString := aParam[1];
end;
if aParam[0] = 'EMBARCADOR' then
begin
FDQuery.SQL.Add('where cod_embarcador = :cod_embarcador');
FDQuery.ParamByName('cod_embarcador').AsInteger := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
Result := FDQuery;
end;
end.
|
unit evContentsNodeFilter;
{* фильтр оглваления документа }
// Модуль: "w:\common\components\gui\Garant\Everest\evContentsNodeFilter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevContentsNodeFilter" MUID: (4DFEF1DF009F)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, l3Base
, evInternalInterfaces
, l3Variant
, k2SimpleTagList
, nevTools
, nevBase
;
type
TevContentsNodeFilter = class(Tl3Base, InevContentsNodeFilter)
{* фильтр оглваления документа }
private
f_FilteredNodeFlag: Integer;
f_Document: Tl3Tag;
f_FilterTagList: Tk2SimpleTagList;
{* Список удаленных тегов. }
private
function NeedColor(const aNode: InevNode): Boolean;
function GetDocContentLevel: Integer;
protected
procedure ColorNode(const aNode: InevNode);
function pm_GetFilteredNodeFlag: Integer;
procedure pm_SetFilteredNodeFlag(aValue: Integer);
procedure CheckTagList;
procedure AddFilterTag(aTag: Tl3Variant);
procedure ChangeDocument(aDocument: Tl3Variant);
function NeedCreate(aTag: Tl3Variant): Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aDocument: Tl3Variant); reintroduce; virtual;
class function Make(aDocument: Tl3Variant): InevContentsNodeFilter;
end;//TevContentsNodeFilter
implementation
uses
l3ImplUses
, evdTypes
, l3TreeInterfaces
, SysUtils
, l3Bits
, l3Types
, l3MinMax
, k2Tags
, evContentsUtils
//#UC START# *4DFEF1DF009Fimpl_uses*
//#UC END# *4DFEF1DF009Fimpl_uses*
;
function TevContentsNodeFilter.NeedColor(const aNode: InevNode): Boolean;
//#UC START# *4ECA574B02DB_4DFEF1DF009F_var*
var
l_Part : IevDocumentPart;
l_Level : Integer;
l_CurLevel : Integer;
l_ParentNode : InevNode;
l_ContentsLevel : Integer;
//#UC END# *4ECA574B02DB_4DFEF1DF009F_var*
begin
//#UC START# *4ECA574B02DB_4DFEF1DF009F_impl*
Result := False;
l_ContentsLevel := GetDocContentLevel;
if (l_ContentsLevel > 0) then
begin
Inc(l_ContentsLevel);
l_CurLevel := aNode.GetLevel;
l_ParentNode := aNode;
l_Level := cnUndefLevel;
while l_ParentNode.GetLevel > 1 do
begin
if (l_ParentNode <> nil) and Supports(l_ParentNode, IevDocumentPart, l_Part) then
try
if (l_Part.ContentsRec.rLevel6 = 0) and (l_ParentNode <> aNode) then
begin
l_ContentsLevel := 0;
Break;
end // if l_Part.ContentsRec.rLevel6 = 0 then
else
if (l_Part.ContentsRec.rLevel6 < cnUndefLevel) then
begin
l_Level := l_ParentNode.GetLevel;
l_Level := l_Level + l_Part.ContentsRec.rLevel6;
end; // if (l_Part.ContentsRec.rLevel6 < Pred(High(Long))) then
finally
l_Part := nil;
end;//try..finally
if l_Level < cnUndefLevel then
begin
l_ContentsLevel := l_Level;
Break;
end; // if l_Level < cnUndefLevel then
l_ParentNode := l_ParentNode.ParentNode;
end; // while l_ParentNode.GetLevel > 1 do
if (l_ContentsLevel = 0) or (l_CurLevel > l_ContentsLevel) then
Result := True;
end // if l_ContentsLevel then
else
Result := True;
//#UC END# *4ECA574B02DB_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.NeedColor
function TevContentsNodeFilter.GetDocContentLevel: Integer;
//#UC START# *532BF0C70311_4DFEF1DF009F_var*
//#UC END# *532BF0C70311_4DFEF1DF009F_var*
begin
//#UC START# *532BF0C70311_4DFEF1DF009F_impl*
Result := EvGetContentLevel(f_Document.IntA[k2_tiContentsLevel6], True);
//#UC END# *532BF0C70311_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.GetDocContentLevel
constructor TevContentsNodeFilter.Create(aDocument: Tl3Variant);
//#UC START# *4DFEF2F303DD_4DFEF1DF009F_var*
//#UC END# *4DFEF2F303DD_4DFEF1DF009F_var*
begin
//#UC START# *4DFEF2F303DD_4DFEF1DF009F_impl*
f_FilteredNodeFlag := nfHidden;
aDocument.SetRef(f_Document);
f_FilterTagList := Tk2SimpleTagList.Make;
inherited Create;
//#UC END# *4DFEF2F303DD_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Create
class function TevContentsNodeFilter.Make(aDocument: Tl3Variant): InevContentsNodeFilter;
//#UC START# *4DFEF31A0273_4DFEF1DF009F_var*
var
l_Filter: TevContentsNodeFilter;
//#UC END# *4DFEF31A0273_4DFEF1DF009F_var*
begin
//#UC START# *4DFEF31A0273_4DFEF1DF009F_impl*
l_Filter := TevContentsNodeFilter.Create(aDocument);
try
Result := l_Filter;
finally
l3Free(l_Filter);
end;
//#UC END# *4DFEF31A0273_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Make
procedure TevContentsNodeFilter.ColorNode(const aNode: InevNode);
//#UC START# *4A2628130085_4DFEF1DF009F_var*
var
l_Flags : Integer;
//#UC END# *4A2628130085_4DFEF1DF009F_var*
begin
//#UC START# *4A2628130085_4DFEF1DF009F_impl*
if (aNode = nil) then
Exit;
l_Flags := aNode.Flags;
if NeedColor(aNode) then
l3SetMask(l_Flags, f_FilteredNodeFlag)
else
l3ClearMask(l_Flags, f_FilteredNodeFlag);
aNode.Flags := l_Flags;
//#UC END# *4A2628130085_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.ColorNode
function TevContentsNodeFilter.pm_GetFilteredNodeFlag: Integer;
//#UC START# *4A26284D0339_4DFEF1DF009Fget_var*
//#UC END# *4A26284D0339_4DFEF1DF009Fget_var*
begin
//#UC START# *4A26284D0339_4DFEF1DF009Fget_impl*
Result := f_FilteredNodeFlag;
//#UC END# *4A26284D0339_4DFEF1DF009Fget_impl*
end;//TevContentsNodeFilter.pm_GetFilteredNodeFlag
procedure TevContentsNodeFilter.pm_SetFilteredNodeFlag(aValue: Integer);
//#UC START# *4A26284D0339_4DFEF1DF009Fset_var*
//#UC END# *4A26284D0339_4DFEF1DF009Fset_var*
begin
//#UC START# *4A26284D0339_4DFEF1DF009Fset_impl*
f_FilteredNodeFlag := aValue;
//#UC END# *4A26284D0339_4DFEF1DF009Fset_impl*
end;//TevContentsNodeFilter.pm_SetFilteredNodeFlag
procedure TevContentsNodeFilter.CheckTagList;
//#UC START# *4E09B99A0384_4DFEF1DF009F_var*
//#UC END# *4E09B99A0384_4DFEF1DF009F_var*
begin
//#UC START# *4E09B99A0384_4DFEF1DF009F_impl*
if f_FilterTagList <> nil then
f_FilterTagList.Clear;
//#UC END# *4E09B99A0384_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.CheckTagList
procedure TevContentsNodeFilter.AddFilterTag(aTag: Tl3Variant);
//#UC START# *4E09BCEA0004_4DFEF1DF009F_var*
//#UC END# *4E09BCEA0004_4DFEF1DF009F_var*
begin
//#UC START# *4E09BCEA0004_4DFEF1DF009F_impl*
f_FilterTagList.Add(aTag);
//#UC END# *4E09BCEA0004_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.AddFilterTag
procedure TevContentsNodeFilter.ChangeDocument(aDocument: Tl3Variant);
//#UC START# *4EAE94530363_4DFEF1DF009F_var*
//#UC END# *4EAE94530363_4DFEF1DF009F_var*
begin
//#UC START# *4EAE94530363_4DFEF1DF009F_impl*
aDocument.SetRef(f_Document);
//#UC END# *4EAE94530363_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.ChangeDocument
function TevContentsNodeFilter.NeedCreate(aTag: Tl3Variant): Boolean;
//#UC START# *4ECA564903B7_4DFEF1DF009F_var*
//#UC END# *4ECA564903B7_4DFEF1DF009F_var*
begin
//#UC START# *4ECA564903B7_4DFEF1DF009F_impl*
if aTag = nil then
Result := True
else
Result := f_FilterTagList.IndexOf(aTag) < 0;
//#UC END# *4ECA564903B7_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.NeedCreate
procedure TevContentsNodeFilter.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4DFEF1DF009F_var*
//#UC END# *479731C50290_4DFEF1DF009F_var*
begin
//#UC START# *479731C50290_4DFEF1DF009F_impl*
FreeAndNil(f_Document);
CheckTagList;
l3Free(f_FilterTagList);
inherited;
//#UC END# *479731C50290_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Cleanup
end.
|
unit fClientForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
uROClient, uROClientIntf, uRORemoteService, uROJSONMessage, uROIndyTCPChannel;
type
TClientForm = class(TForm)
ROMessage: TROJSONMessage;
ROChannel: TROIndyTCPChannel;
RORemoteService: TRORemoteService;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ClientForm: TClientForm;
implementation
{
The unit NewLibrary_Intf.pas will be generated by the RemObjects preprocessor the first time you
compile your server application. Make sure to do that before trying to compile the client.
To invoke your server simply typecast your server to the name of the service interface like this:
(RORemoteService as INewService).Sum(1,2)
}
uses NewLibrary_Intf, uROWebsocketChannel;
{$R *.dfm}
procedure TClientForm.Button1Click(Sender: TObject);
var
i: Integer;
chn: TROWebsocketChannel;
begin
chn := TROWebsocketChannel.Create(Self);
try
chn.Host := 'localhost';
chn.Port := 7000;
RORemoteService.Channel := chn;
i := (RORemoteService as INewService).Sum(1,2);
finally
chn.Free;
end;
ShowMessage('Sum of 1 and 2 is: ' + IntToStr(i));
end;
procedure TClientForm.FormCreate(Sender: TObject);
begin
//
end;
end.
|
unit OverbyteIcsWinnls;
// From Winnls.h
{ Normalization requires Vista+ or XP SP2 with additional install of:
Microsoft Internationalized Domain Names (IDN) Mitigation APIs 1.1 }
{$ALIGN ON}
{$MINENUMSIZE 4}
{$WEAKPACKAGEUNIT}
{.$DEFINE CPP_WINHEADER_VISTA}
interface
uses
Windows;
type
//#if (WINVER >= 0x0600)
{$IFDEF CPP_WINHEADER_VISTA} {$EXTERNALSYM _NORM_FORM} {$ENDIF}
_NORM_FORM = (
NormalizationOther,
NormalizationC,
NormalizationD,
NormalizationKC = 5,
NormalizationKD);
{$IFDEF CPP_WINHEADER_VISTA} {$EXTERNALSYM NORM_FORM} {$ENDIF}
NORM_FORM = _NORM_FORM;
TNormForm = NORM_FORM;
{$IFDEF CPP_WINHEADER_VISTA} {$EXTERNALSYM IsNormalizedString} {$ENDIF}
function IsNormalizedString(NormForm: TNormForm; lpString: LPCWSTR;
cwLength: Integer): BOOL; stdcall;
{$IFDEF CPP_WINHEADER_VISTA} {$EXTERNALSYM NormalizeString} {$ENDIF}
function NormalizeString(NormForm: TNormForm; lpSrcString: LPCWSTR;
cwSrcLength: Integer; lpDstString: LPWSTR; cwDstLength: Integer): Integer; stdcall;
//#endif (WINVER >= 0x0600)
function LoadNormalizeLib: Boolean;
implementation
const
LibNormaliz = 'Normaliz.dll';
_IsNormalizedString : function (NormForm: TNormForm; lpString: LPCWSTR;
cwLength: Integer): BOOL; stdcall = nil;
_NormalizeString : function(NormForm: TNormForm; lpSrcString: LPCWSTR;
cwSrcLength: Integer; lpDstString: LPWSTR; cwDstLength: Integer): Integer; stdcall = nil;
var
hNormaliz: THandle = 0;
function LoadNormalizeLib: Boolean;
begin
if (@_IsNormalizedString = nil) or (@_NormalizeString = nil) then
begin
if hNormaliz = 0 then
hNormaliz := LoadLibrary(LibNormaliz);
if hNormaliz <> 0 then
begin
@_IsNormalizedString := GetProcAddress(hNormaliz, 'IsNormalizedString');
if @_IsNormalizedString <> nil then
@_NormalizeString := GetProcAddress(hNormaliz, 'NormalizeString');
end;
end;
Result := (@_IsNormalizedString <> nil) and (@_NormalizeString <> nil);
end;
function IsNormalizedString(NormForm: TNormForm; lpString: LPCWSTR;
cwLength: Integer): BOOL;
begin
if (@_IsNormalizedString = nil) then
LoadNormalizeLib;
Result := _IsNormalizedString(NormForm, lpString, cwLength);
end;
function NormalizeString(NormForm: TNormForm; lpSrcString: LPCWSTR;
cwSrcLength: Integer; lpDstString: LPWSTR;
cwDstLength: Integer): Integer;
begin
if (@_NormalizeString = nil) then
LoadNormalizeLib;
Result := _NormalizeString(NormForm, lpSrcString, cwSrcLength, lpDstString,
cwDstLength);
end;
end.
|
unit ExtAIDelphi;
interface
uses
System.SysUtils,
ExtAILog, ExtAIBaseDelphi;
type
// Here will be the main algorithm of the ExtAI
// It works just like dynamic scripts (it reacts to Events with Actions and States)
TExtAIDelphi = class(TExtAIBaseDelphi)
private
// Game variables and methods
procedure HuntUnit();
protected
// Game Events (only events which are used)
procedure OnMissionStart(); override;
procedure OnMissionEnd(); override;
procedure OnTick(aTick: Cardinal); override;
procedure OnPlayerVictory(aHandIndex: SmallInt); override;
public
constructor Create(aLog: TExtAILog = nil; aID: Word = 0);
destructor Destroy(); override;
end;
implementation
{ TExtAIDelphi }
constructor TExtAIDelphi.Create(aLog: TExtAILog = nil; aID: Word = 0);
const
AUTHOR: UnicodeString = 'Martin';
DESCRIPTION: UnicodeString = 'Testing ExtAI with WebSocket';
NAME: UnicodeString = 'Skynet';
VERSION: Cardinal = 20190625;
begin
Inherited Create(aLog, aID, AUTHOR, NAME, DESCRIPTION, VERSION);
end;
destructor TExtAIDelphi.Destroy();
begin
Inherited;
end;
procedure TExtAIDelphi.OnMissionStart();
begin
Log('TExtAIDelphi OnMissionStart');
end;
procedure TExtAIDelphi.OnMissionEnd();
begin
Log('TExtAIDelphi OnMissionEnd');
end;
procedure TExtAIDelphi.OnTick(aTick: Cardinal);
begin
Log('TExtAIDelphi Tick: %d', [aTick]);
//Actions.Log('This is message from ExtAI');
//Actions.GroupOrderWalk(11,5,5,22);
if (aTick = 1) AND (States.MapWidth > 0) then
Log('TExtAIDelphi Terrain was loaded');
HuntUnit();
end;
procedure TExtAIDelphi.OnPlayerVictory(aHandIndex: SmallInt);
begin
Log('TExtAIDelphi OnPlayerVictory');
end;
// Hello world of the ExtAI and KP
procedure TExtAIDelphi.HuntUnit();
{
var
Group: Integer;
HostileUnit: Integer;
}
begin
{
HostileUnit := States.GetUnit();
Group := States.GetGroup();
if (HostileUnit > 0) and (Group > 0) then
Actions.GroupOrderAttackUnit(Group,HostileUnit);
}
end;
end.
|
{-----------------------------------------------------------------------------
hpp_options (historypp project)
Version: 1.0
Created: 31.03.2003
Author: Oxygen
[ Description ]
Options module which has one global options variable and
manages all options throu all history windows
[ History ]
1.0 (31.03.2003) - Initial version
[ Modifications ]
[ Knows Inssues ]
None
Copyright (c) Art Fedorov, 2003
-----------------------------------------------------------------------------}
unit hpp_options;
interface
uses
Graphics, Classes, SysUtils, Windows,
m_globaldefs, m_api,
HistoryGrid, {OptionsForm, }PassForm, PassCheckForm,
hpp_global, hpp_contacts;
type
ThppIconsRec = record
name: PChar;
desc: PChar;
i: shortint;
handle: hIcon;
end;
ThppFontsRec = record
name: PChar;
nameColor: PChar;
mes: TMessageTypes;
style: byte;
size: longint;
color: TColor;
back: TColor;
end;
TCodePage = record
cp: Cardinal;
name: String;
end;
const
hppIcons : array[0..1] of ThppIconsRec = (
(name:'historypp_contact'; desc:'Contact history'; i:0; Handle:0),
(name:'historypp_search'; desc:'History search'; i:1; Handle:0)
);
hppFontItems: array[0..15] of ThppFontsRec = (
(name: 'Incoming nick'; nameColor: 'Divider'; Mes: []; style:DBFONTF_BOLD; size: -11; color: $6B3FC8; back: clGray),
(name: 'Outgoing nick'; nameColor: 'Selected text'; Mes: []; style:DBFONTF_BOLD; size: -11; color: $BD6008; back: clHighlightText),
(name: 'Timestamp'; nameColor: 'Selected background'; Mes: []; style:0; size: -11; color: $000000; back: clHighlight),
(name: 'Incoming message'; Mes: [mtMessage,mtIncoming]; style:0; size: -11; color: $000000; back: $DBDBDB),
(name: 'Outgoing message'; Mes: [mtMessage,mtOutgoing]; style:0; size: -11; color: $000000; back: $EEEEEE),
(name: 'Incoming file'; Mes: [mtFile,mtIncoming]; style:0; size: -11; color: $000000; back: $9BEEE3),
(name: 'Outgoing file'; Mes: [mtFile,mtOutgoing]; style:0; size: -11; color: $000000; back: $9BEEE3),
(name: 'Incoming url'; Mes: [mtUrl,mtIncoming]; style:0; size: -11; color: $000000; back: $F4D9CC),
(name: 'Outgoing url'; Mes: [mtUrl,mtOutgoing]; style:0; size: -11; color: $000000; back: $F4D9CC),
(name: 'Incoming SMS Message'; Mes: [mtSMS,mtIncoming]; style:0; size: -11; color: $000000; back: $CFF4FE),
(name: 'Outgoing SMS Message'; Mes: [mtSMS,mtOutgoing]; style:0; size: -11; color: $000000; back: $CFF4FE),
(name: 'Incoming contacts'; Mes: [mtContacts,mtIncoming]; style:0; size: -11; color: $000000; back: $FEF4CF),
(name: 'Outgoing contacts'; Mes: [mtContacts,mtOutgoing]; style:0; size: -11; color: $000000; back: $FEF4CF),
(name: 'System message'; Mes: [mtSystem,mtIncoming,mtOutgoing]; style:0; size: -11; color: $000000; back: $CFFEDC),
(name: 'Status change'; Mes: [mtStatus,mtIncoming,mtOutgoing]; style:0; size: -11; color: $000000; back: $F0F0F0),
(name: 'Other events'; Mes: [mtOther,mtIncoming,mtOutgoing]; style:0; size: -11; color: $000000; back: $FFFFFF)
);
cpTable: array[0..14] of TCodePage = (
(cp: 874; name: 'Thai' ),
(cp: 932; name: 'Japanese' ),
(cp: 936; name: 'Simplified Chinese' ),
(cp: 949; name: 'Korean' ),
(cp: 950; name: 'Traditional Chinese' ),
(cp: 1250; name: 'Central European' ),
(cp: 1251; name: 'Cyrillic' ),
(cp: 1252; name: 'Latin I' ),
(cp: 1253; name: 'Greek' ),
(cp: 1254; name: 'Turkish' ),
(cp: 1255; name: 'Hebrew' ),
(cp: 1256; name: 'Arabic' ),
(cp: 1257; name: 'Baltic' ),
(cp: 1258; name: 'Vietnamese' ),
(cp: 1361; name: 'Korean (Johab)' ));
var
GridOptions: TGridOptions;
PassFm: TfmPass;
PassCheckFm: TfmPassCheck;
IcoLibEnabled: Boolean;
FontServiceEnabled: Boolean;
SmileyAddEnabled: Boolean;
MathModuleEnabled: Boolean;
procedure LoadGridOptions;
procedure SaveGridOptions;
procedure LoadIcons;
procedure LoadIcons2;
procedure OnShowIcons;
//procedure LoadDefaultGridOptions;
procedure hppRegisterGridOptions;
implementation
uses hpp_database;
procedure RegisterFont(Name:PChar; Order:integer; defFont:FontSettings);
var
fid: FontID;
begin
fid.cbSize := sizeof(fid);
fid.group := hppName;
fid.dbSettingsGroup := hppDBName;
fid.flags := FIDF_DEFAULTVALID+FIDF_ALLOWEFFECTS;
fid.order := Order;
lstrcpy(fid.name,Name);
lstrcpy(fid.prefix,PChar('Font'+intToStr(Order)));
fid.deffontsettings := defFont;
fid.deffontsettings.size := hppFontItems[Order].size;
fid.deffontsettings.style := hppFontItems[Order].style;
fid.deffontsettings.colour := hppFontItems[Order].color;
PluginLink.CallService(MS_FONT_REGISTER,integer(@fid),0);
end;
procedure RegisterColor(Name:PChar; Order:integer; defColor:TColor);
var
cid: ColourID;
begin
cid.cbSize := sizeof(cid);
cid.group := hppName;
cid.dbSettingsGroup := hppDBName;
cid.order := Order;
lstrcpy(cid.name,Name);
lstrcpy(cid.setting,PChar('Color'+intToStr(Order)));
cid.defcolour := defColor;
PluginLink.CallService(MS_COLOUR_REGISTER,integer(@cid),0);
end;
procedure OnShowIcons;
begin
if GridOptions.ShowIcons then LoadIcons;
end;
function LoadIconFromDB(ID: Integer; Icon: TIcon): Boolean;
var
hic: HIcon;
begin
Result := False;
hic := LoadSkinnedIcon(ID);
if (hic <> 0) then begin
hic := CopyIcon(hic);
Icon.Handle := hic;
Result := True;
end;
end;
procedure LoadIcons;
begin
GridOptions.StartChange;
try
LoadIconFromDB(SKINICON_EVENT_MESSAGE,GridOptions.IconMessage);
LoadIconFromDB(SKINICON_EVENT_URL,GridOptions.IconUrl);
LoadIconFromDB(SKINICON_EVENT_FILE,GridOptions.IconFile);
LoadIconFromDB(SKINICON_OTHER_MIRANDA,GridOptions.IconOther);
finally
GridOptions.EndChange;
end;
end;
procedure LoadIcons2;
var
hic: HIcon;
i: integer;
begin
for i := 0 to High(hppIcons) do begin
if IcoLibEnabled then
hic := PluginLink.CallService(MS_SKIN2_GETICON,0,integer(hppIcons[i].name))
else
hic := LoadIcon(hInstance,hppIcons[i].name);
if (hic <> 0) then
hppIcons[i].handle := hic;
end;
end;
{procedure LoadDefaultGridOptions;
procedure LoadFont(Font: TFont; SettName: String);
var
fname: String;
fsize: Integer;
fcolor: TColor;
fset: TFontCharset;
fstyle: Byte;
fbold,fitalic: Boolean;
begin
fname := GetDBStr('SRMsg',SettName+'','');
if fname = '' then exit;
fsize := GetDBInt('SRMsg',PChar(SettName+'Size'),-11);
fcolor := GetDBInt('SRMsg',PChar(SettName+'Col'),clWindowText);
fstyle := GetDBInt('SRMsg',PChar(SettName+'Sty'),0);
if (fstyle = 1) or (fstyle=3) then
fbold := True
else
fbold := False;
if (fstyle = 2) or (fstyle=3) then
fitalic := True
else
fitalic := False;
fset := GetDBDWord('SRMsg',PChar(SettName+'Set'),DEFAULT_CHARSET);
Font.Name := fname;
Font.Height := fsize;
Font.Charset := fset;
Font.Color := fcolor;
Font.Style := [];
if fbold then
Font.Style := Font.Style + [fsBold];
if fitalic then
Font.Style := Font.Style + [fsItalic];
end;
begin
GridOptions.StartChange;
try
GridOptions.ShowIcons := GetDBBool('SRMsg','ShowLogIcons',True);
// Font 0 -- Outgoing Messages
// Font 1 -- Outgoing URL
// Font 2 -- Outgoing Files
// Font 3 -- Incoming Messages
// Font 4 -- Incoming Urls
// Font 5 -- Incoming Files
// Font 6 -- Profile Name
// Font 7 -- Profile Time
// Font 8 --
// Font 9 -- Contact Name
// Font 10 -- Contact Time
LoadFont(GridOptions.TextOutMes,'Font0');
LoadFont(GridOptions.TextOutUrl,'Font1');
LoadFont(GridOptions.TextOutFile,'Font2');
LoadFont(GridOptions.TextIncMes,'Font3');
LoadFont(GridOptions.TextIncUrl,'Font4');
LoadFont(GridOptions.TextIncFile,'Font5');
LoadFont(GridOptions.TextProfile,'Font6');
LoadFont(GridOptions.TextProfileDate,'Font7');
LoadFont(GridOptions.TextContact,'Font9');
LoadFont(GridOptions.TextContactDate,'Font10');
finally
GridOptions.EndChange;
end;
end;}
procedure LoadGridOptions;
function LoadColorDB(Order: integer): TColor;
begin
Result := GetDBInt(hppDBName,PChar('Color'+intToStr(Order)),ColorToRGB(hppFontItems[Order].back));
end;
function LoadFont(Order: integer): TFont;
const
size: integer = -11;
var
fid: FontID;
lf: TLogFont;
col: TColor;
fs: TFontStyles;
begin
Result := TFont.Create;
if FontServiceEnabled then begin
fid.cbSize := sizeof(fid);
fid.group := hppName;
lstrcpy(fid.name,Translate(hppFontItems[Order].name));
col := PluginLink.CallService(MS_FONT_GET,integer(@fid),integer(@lf));
Result.Handle := CreateFontIndirect(lf);
Result.Color := col;
end else begin
Result.Name := 'Tahoma';
Result.Height := size;
fs := [];
if (hppFontItems[Order].style and DBFONTF_BOLD) > 0 then include(fs,fsBold);
Result.Style := fs;
Result.Color := hppFontItems[Order].color;
end;
end;
var
i: integer;
begin
GridOptions.StartChange;
try
// load fonts
GridOptions.FontContact.Assign(LoadFont(0));
GridOptions.FontProfile.Assign(LoadFont(1));
GridOptions.FontTimestamp.Assign(LoadFont(2));
// load colors
GridOptions.ColorDivider := LoadColorDB(0);
GridOptions.ColorSelectedText := LoadColorDB(1);
GridOptions.ColorSelected := LoadColorDB(2);
// load mestype-related
for i := 3 to High(hppFontItems) do begin
if (i-3) > High(GridOptions.ItemOptions) then GridOptions.AddItemOptions;
GridOptions.ItemOptions[i-3].MessageType := hppFontItems[i].Mes;
GridOptions.ItemOptions[i-3].textFont.Assign(LoadFont(i));
GridOptions.ItemOptions[i-3].textColor := LoadColorDB(i);
end;
// load others
GridOptions.ShowIcons := GetDBBool(hppDBName,'ShowIcons',True);
GridOptions.RTLEnabled := GetContactRTLMode(0,'');
GridOptions.SmileysEnabled := GetDBBool(hppDBName,'Smileys',SmileyAddEnabled);
GridOptions.BBCodesEnabled := GetDBBool(hppDBName,'BBCodes',True);
GridOptions.MathModuleEnabled := GetDBBool(hppDBName,'MathModule',MathModuleEnabled);
GridOptions.UnderlineURLEnabled := GetDBBool(hppDBName,'UnderlineURL',True);
GridOptions.FindURLEnabled := GetDBBool(hppDBName,'FindURL',True);
finally
GridOptions.EndChange;
end;
end;
procedure SaveGridOptions;
begin
GridOptions.StartChange;
try
WriteDBBool(hppDBName,'ShowIcons',GridOptions.ShowIcons);
//WriteDBBool(hppDBName,'RTL',GridOptions.RTLEnabled);
WriteDBBool(hppDBName,'Smileys',GridOptions.SmileysEnabled);
WriteDBBool(hppDBName,'BBCodes',GridOptions.BBCodesEnabled);
WriteDBBool(hppDBName,'MathModule',GridOptions.MathModuleEnabled);
WriteDBBool(hppDBName,'UnderlineURL',GridOptions.UnderlineURLEnabled);
WriteDBBool(hppDBName,'FindURL',GridOptions.FindURLEnabled);
finally
GridOptions.EndChange;
end;
end;
procedure hppRegisterGridOptions;
var
sid: TSKINICONDESC;
defFont : FontSettings;
i: integer;
hppdll: string;
// upd: TUpdate;
begin
//
SmileyAddEnabled := Boolean(PluginLink.ServiceExists(MS_SMILEYADD_REPLACESMILEYS));
MathModuleEnabled := Boolean(PluginLink.ServiceExists(MATH_GET_STARTDELIMITER));
// Register in IcoLib
IcoLibEnabled := Boolean(PluginLink.ServiceExists(MS_SKIN2_ADDICON));
if IcoLibEnabled then begin
SetLength(hppdll, MAX_PATH);
SetLength(hppdll,GetModuleFileName(hInstance,PAnsiChar(hppdll),Length(hppdll)));
ZeroMemory(@sid,SizeOf(sid));
sid.cbSize := SizeOf(sid);
sid.pszSection := hppName;
sid.pszDefaultFile := PChar(hppdll);
for i := 0 to High(hppIcons) do begin
sid.pszName := hppIcons[i].name;
sid.pszDescription := translate(hppIcons[i].desc);
sid.iDefaultIndex := hppIcons[i].i;
PluginLink.CallService(MS_SKIN2_ADDICON,0,DWord(@sid));
end;
end;
// Register in FontService
FontServiceEnabled := Boolean(PluginLink.ServiceExists(MS_FONT_GET));
if FontServiceEnabled then begin
defFont.szFace := 'Tahoma';
defFont.charset := DEFAULT_CHARSET;
RegisterFont(Translate(hppFontItems[0].name),0,defFont);
RegisterFont(Translate(hppFontItems[1].name),1,defFont);
RegisterFont(Translate(hppFontItems[2].name),2,defFont);
RegisterColor(Translate(hppFontItems[0].nameColor),0,ColorToRGB(hppFontItems[0].back));
RegisterColor(Translate(hppFontItems[1].nameColor),1,ColorToRGB(hppFontItems[1].back));
RegisterColor(Translate(hppFontItems[2].nameColor),2,ColorToRGB(hppFontItems[2].back));
for i := 3 to High(hppFontItems) do begin
GridOptions.AddItemOptions;
RegisterFont(Translate(hppFontItems[i].name),i,defFont);
RegisterColor(Translate(hppFontItems[i].name),i,hppFontItems[i].back);
end;
end;
end;
initialization
GridOptions := TGridOptions.Create;
GridOptions.OnShowIcons := OnShowIcons;
finalization
GridOptions.Free;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品订单调整
*******************************************************************************}
unit UFormProductBillAdjust;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, UGridPainter, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, ExtCtrls, UImageButton, Grids, UGridExPainter;
type
TfFormProductBillAdjust = class(TSkinFormBase)
GridList: TDrawGridEx;
Panel1: TPanel;
BtnOK: TImageButton;
BtnExit: TImageButton;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
EditID: TcxTextEdit;
EditMan: TcxTextEdit;
EditTime: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Panel1Resize(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
private
{ Private declarations }
FOrderID: string;
//订单号
FPainter: TGridPainter;
//绘制对象
procedure LoadOrderDetail(const nOrderID: string);
//商品信息
procedure OnEditValueChanged(Sender: TObject);
//数据生效
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowProductBillAdjust(const nOrderID: string): Boolean;
//添加账户
implementation
{$R *.dfm}
uses
ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule, FZSale_Intf;
function ShowProductBillAdjust(const nOrderID: string): Boolean;
begin
with TfFormProductBillAdjust.Create(Application) do
begin
FOrderID := nOrderID;
LoadOrderDetail(nOrderID);
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormProductBillAdjust.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormProductBillAdjust.FormCreate(Sender: TObject);
var nIdx: Integer;
begin
for nIdx:=ComponentCount-1 downto 0 do
if Components[nIdx] is TImageButton then
LoadFixImageButton(TImageButton(Components[nIdx]));
//xxxxx
FPainter := TGridPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('品牌', 50);
AddHeader('商品名称', 50);
AddHeader('现有库存', 50);
AddHeader('原订货量', 50);
AddHeader('现调整为', 50);
end;
LoadFormConfig(Self);
LoadDrawGridConfig(Name, GridList);
end;
procedure TfFormProductBillAdjust.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveFormConfig(Self);
SaveDrawGridConfig(Name, GridList);
FPainter.Free;
end;
procedure TfFormProductBillAdjust.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 调整按钮位置
procedure TfFormProductBillAdjust.Panel1Resize(Sender: TObject);
var nW,nL: Integer;
begin
nW := BtnOK.Width + 65 + BtnExit.Width;
nL := Trunc((Panel1.Width - nW) / 2);
BtnOk.Left := nL;
BtnExit.Left := nL + BtnOK.Width + 65;
end;
//------------------------------------------------------------------------------
//Desc: 载入订单明细
procedure TfFormProductBillAdjust.LoadOrderDetail(const nOrderID: string);
var nStr,nHint: string;
nIdx,nInt: Integer;
nDS: TDataSet;
nEdit: TcxTextEdit;
nLabel: TLabel;
nData: TGridDataArray;
begin
nStr := 'Select dt.*,BrandName,StyleName,ColorName,SizeName,D_Number,' +
'P_Number,TerminalPrice,O_Man,O_Date From $DT dt ' +
' Left Join $PT pt On pt.ProductID=dt.D_Product ' +
' Left Join $ST st On st.StyleID=pt.StyleID ' +
' Left Join $SZ sz On sz.SizeID=pt.SizeID ' +
' Left Join $CR cr On cr.ColorID=pt.ColorID ' +
' Left Join $OD od On od.O_ID=dt.D_Order ' +
' Left Join $BR br On br.BrandID=pt.BrandID ' +
' Left Join $DP dp on dp.P_ID=dt.D_Product ' +
'Where D_Order=''$ID'' Order By StyleName,ColorName,SizeName';
//xxxxx
nStr := MacroValue(nStr, [MI('$DT', sTable_OrderDtl), MI('$ID', nOrderID),
MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size),
MI('$CR', sTable_DL_Color), MI('$OD', sTable_Order),
MI('$BR', sTable_DL_Brand), MI('$PT', sTable_DL_Product),
MI('$DP', sTable_Product)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
First;
nInt := 1;
EditID.Text := nOrderID;
EditMan.Text := FieldByName('O_Man').AsString;
EditTime.Text := DateTime2Str(FieldByName('O_Date').AsDateTime);
while not Eof do
begin
SetLength(nData, 9);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := FieldByName('BrandName').AsString;
nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString,
FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]);
nData[2].FText := nStr;
nData[3].FText := FieldByName('P_Number').AsString;
nData[4].FText := FieldByName('D_Number').AsString;
with nData[5] do
begin
FText := '';
FCtrls := TList.Create;
nEdit := TcxTextEdit.Create(Self);
FCtrls.Add(nEdit);
with nEdit do
begin
Width := 42;
Height := 18;
Text := nData[4].FText;
Properties.OnEditValueChanged := OnEditValueChanged;
end;
nLabel := TLabel.Create(Self);
nLabel.Transparent := True;
nLabel.Caption := '件';
FCtrls.Add(nLabel);
end;
nData[6].FText := FieldByName('D_Product').AsString;
nData[7].FText := Format('%.2f', [FieldByName('TerminalPrice').AsFloat]);
nData[8].FText := FieldByName('R_ID').AsString;
FPainter.AddData(nData);
Next;
end;
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 内容生效
procedure TfFormProductBillAdjust.OnEditValueChanged(Sender: TObject);
begin
with TcxTextEdit(Sender) do
begin
if (not IsNumber(Text, False)) or (StrToInt(Text) < 0) then
begin
SetFocus;
ShowMsg('请填写有效件数', sHint); Exit;
end;
end;
end;
//Desc: 保存
procedure TfFormProductBillAdjust.BtnOKClick(Sender: TObject);
var nStr,nHint: string;
nIdx,nNum: Integer;
nSQLList: SQLItems;
begin
ActiveControl := nil;
nSQLList := SQLItems.Create;
try
nNum := 0;
for nIdx:=0 to FPainter.DataCount - 1 do
begin
nStr := TcxTextEdit(FPainter.Data[nIdx][5].FCtrls[0]).Text;
if IsNumber(nStr, False) and (StrToInt(nStr) > 0) then
nNum := nNum + StrToInt(nStr);
//xxxxx
end;
if nNum < 1 then
begin
nSQLList.Free;
ShowMsg('订单件数为零', sHint); Exit;
end;
nStr := 'Update %s Set O_Number=%d Where O_ID=''%s''';
nStr := Format(nStr, [sTable_Order, nNum, FOrderID]);
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
for nIdx:=0 to FPainter.DataCount - 1 do
begin
nStr := TcxTextEdit(FPainter.Data[nIdx][5].FCtrls[0]).Text;
if (not IsNumber(nStr, False)) or (StrToInt(nStr) < 0) then Continue;
nNum := StrToInt(nStr);
if nNum = StrToInt(FPainter.Data[nIdx][4].FText) then Continue;
//下单量不变
nStr := 'Update %s Set D_Number=%d,D_Price=%s Where R_ID=%s';
nStr := Format(nStr, [sTable_OrderDtl, nNum, FPainter.Data[nIdx][7].FText,
FPainter.Data[nIdx][8].FText]);
//xxxxx
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
nStr := MakeSQLByStr([SF('A_Order', FOrderID),
SF('A_Product', FPainter.Data[nIdx][6].FText),
SF('A_Number', FPainter.Data[nIdx][4].FText, sfVal),
SF('A_NewNum', IntToStr(nNum), sfVal),
SF('A_Man', gSysParam.FUserID),
SF('A_Date', sField_SQLServer_Now, sfVal)
], sTable_OrderAdjust, '', True);
//insert sql
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
end;
if FDM.SQLUpdates(nSQLList, True, nHint) > -1 then
begin
ModalResult := mrOk;
end else ShowDlg(nHint, sWarn);
finally
//nSQLList.Free;
end;
end;
end.
|
unit qrpBaseCtrls;
interface
uses
Classes, QRCtrls, QRPrntr, Quickrpt;
type
TLabelSettings = class(TPersistent)
private
fFirstLabel : Longint;
fLabelCount : Longint;
protected
public
published
property FirstLabel: Longint Read fFirstLabel Write fFirstLabel;
property LabelCount: Longint Read fLabelCount Write fLabelCount;
end;
TQRPQuickrep = class(TQuickRep)
private
FLabelSettings : TLabelSettings;
FPrepareAutomatically : Boolean;
BandsHidden : Boolean;
protected
ReportPrintPrepared : Boolean;
SkipLabelsBand1 : TQRCustomBand;
SkipLabelsBand2 : TQRChildband;
SkipLabelsBand3 : TQRChildband;
public
DetailBand : TQRCustomBand;
TotalPageCount : Integer;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Print;
procedure Preview;
procedure Prepare;
procedure PrintBackground;
procedure ExportToFilter(AFilter: TQRExportFilter);
procedure PreviewModal;
procedure PreviewModeless;
function PrepareReportPrint: Boolean; virtual;
procedure DoneReportPrint; virtual;
published
property LabelSettings: TLabelSettings Read FLabelSettings Write FLabelSettings;
property PrepareAutomatically: Boolean Read FPrepareAutomatically Write FPrepareAutomatically;
end;
implementation
uses
Controls, Dialogs, Forms, QRPCtrls;
constructor TQRPQuickrep.Create(AOwner : TComponent);
begin
Inherited Create(AOwner);
FLabelSettings:=TLabelSettings.Create;
end;
destructor TQRPQuickrep.Destroy;
begin
FLabelSettings.Free;
Inherited Destroy;
end;
procedure TQRPQuickrep.Print;
begin
If PrepareReportPrint Then
begin
Inherited Print;
DoneReportPrint;
end;
end;
procedure TQRPQuickrep.Preview;
begin
If PrepareReportPrint Then
begin
Inherited Preview;
DoneReportPrint;
end;
end;
procedure TQRPQuickrep.Prepare;
begin
If PrepareReportPrint Then
begin
Inherited Prepare;
end;
end;
function TQRPQuickrep.PrepareReportPrint: Boolean;
var
DetailBand: TQRCustomBand;
RowSpaceBand: TQRCustomBand;
SkipLabels: Integer;
ColumnLabels: Integer;
begin
Result:=True;
If ReportPrintPrepared Then Exit;
ReportPrintPrepared:=True;
{--- create temporary label skip bands ---}
DetailBand:=TQRCustomBand(Owner.FindComponent('LabelBand'));
If DetailBand=NIL Then DetailBand:=TQRCustomBand(Owner.FindComponent('DetailBand'));
{$IFDEF QR3}
If (DetailBand is TQRLoopband) and (DetailBand.Name='LabelBand') Then
TQRLoopband(DetailBand).PrintCount:=LabelSettings.LabelCount;
{$ENDIF}
If (Labelsettings.FirstLabel>1) and (DetailBand<>NIL) Then
begin
SkipLabels:=Labelsettings.FirstLabel-1;
{$IFDEF QR3}
If DetailBand is TQRLoopband Then
begin
SkipLabelsBand1:=TQRLoopband.Create(Owner);
SkipLabelsBand1.Parent:=Self;
TQRLoopband(SkipLabelsBand1).Master:=Self;
TQRLoopband(SkipLabelsBand1).PrintCount:=1;
TQRLoopband(Detailband).Master:=SkiplabelsBand1;
end
else
{$ENDIF}
begin
SkipLabelsBand1:=TQRGroup.Create(Owner);
end;
SkipLabelsBand2:=TQRPChildband.Create(Owner);
SkipLabelsBand3:=TQRPChildband.Create(Owner);
SkipLabelsBand1.Parent:=Self;
SkipLabelsBand2.Parent:=Self;
SkipLabelsBand3.Parent:=Self;
SkipLabelsBand1.Height:=0;
SkipLabelsBand2.Height:=0;
SkipLabelsBand2.ParentBand:=SkipLabelsBand1;
SkipLabelsBand3.ParentBand:=SkipLabelsBand2;
RowSpaceBand:=TQRPChildBand(Owner.FindComponent('RowSpace'));
If DetailBand<>NIL Then
begin
If RowSpaceBand<>NIL Then
ColumnLabels:=Round((Page.Length-Page.TopMargin-Page.BottomMargin+RowSpaceBand.Size.Height)
/(DetailBand.Size.Height+RowSpaceband.Size.Height))
else
ColumnLabels:=Round((Page.Length-Page.TopMargin-Page.BottomMargin)
/DetailBand.Size.Height);
If SkipLabels>=ColumnLabels Then
begin
While SkipLabels>=ColumnLabels Do SkipLabels:=SkipLabels-ColumnLabels;
SkipLabelsBand2.ForceNewColumn:=True;
SkipLabelsBand3.ForceNewColumn:=True;
end;
If RowSpaceBand<>NIL Then
SkipLabelsBand3.Height:=(DetailBand.Height+RowSpaceBand.Height)*SkipLabels
else
SkipLabelsBand3.Height:=DetailBand.Height*SkipLabels;
end;
end;
If PrepareAutomatically Then
begin
BandsHidden:=HideBands;
Hidebands:=True;
try
Screen.Cursor:=crHourGlass;
Inherited Prepare;
finally
Screen.Cursor:=crDefault;
end;
TotalPageCount:=QRPrinter.PageCount;
end;
end;
procedure TQRPQuickrep.DoneReportPrint;
begin
If Not ReportPrintPrepared Then Exit;
ReportPrintPrepared:=False;
SkipLabelsBand1.Free;
SkipLabelsBand2.Free;
SkipLabelsBand3.Free;
SkipLabelsBand1:=NIL;
SkipLabelsBand2:=NIL;
SkipLabelsBand3:=NIL;
DetailBand:=NIL;
TotalPageCount:=0;
If PrepareAutomatically Then Hidebands:=BandsHidden;
end;
procedure TQRPQuickrep.PrintBackground;
begin
If PrepareReportPrint Then
begin
Inherited PrintBackground;
DoneReportPrint;
end;
end;
procedure TQRPQuickrep.ExportToFilter(AFilter: TQRExportFilter);
begin
If PrepareReportPrint Then
begin
Inherited ExportToFilter(AFilter);
DoneReportPrint;
end;
end;
procedure TQRPQuickrep.PreviewModal;
begin
If PrepareReportPrint Then
begin
//{$IFDEF QR3}
Inherited PreviewModal;
//{$ELSE}
//Inherited Preview;
//$ENDIF}
DoneReportPrint;
end;
end;
procedure TQRPQuickrep.PreviewModeless;
begin
If PrepareReportPrint Then
begin
//{$IFDEF QR3}
Inherited PreviewModeless;
//{$ELSE}
//Inherited Preview;
//{$ENDIF}
DoneReportPrint;
end;
end;
end.
|
{$mode objfpc}{$h+}
program demo;
uses classes, sysutils,
FPImage, FPCanvas, FPImgCanv,
FPWritePNG;
var canvas : TFPcustomCanvas;
image : TFPCustomImage;
writer : TFPCustomImageWriter;
{
Colors range from 0 to 65535 in each primary color.
They can also show as hexideciaml:
$FFFF = 65535, $0000 = 0
}
passionRed: TFPColor = (Red: 65535; Green: 0; Blue: 0; Alpha: 65535);
begin
image := TFPMemoryImage.Create (100,100);
Canvas := TFPImageCanvas.Create (image);
Writer := TFPWriterPNG.Create;
{ Set the pen styles }
with canvas do
begin
pen.mode := pmCopy;
pen.style := psSolid;
pen.width := 1;
pen.FPColor := passionRed;
end;
{ Draw a circle }
canvas.Ellipse (10,10, 90,90);
{ Save to file }
image.SaveToFile ('DrawTest.png', writer);
{ Clean up! }
Canvas.Free;
image.Free;
writer.Free;
end.
|
unit TM1638;
interface
uses
GlobalConfig,
GlobalConst,
Platform,
Threads,
SysUtils,
Classes,
Ultibo;
type
TShiftOrder = (soLsbFirst = 0, soMsbFirst = 1);
{ TTM1630 }
TTM1630 = class
private
strobe_: Integer;
clock_: Integer;
data_: Integer;
procedure Setup();
procedure Reset();
procedure ShiftOut(data, clock: LongWord; order: TShiftOrder; output: Byte);
function ShiftIn(data, clock: LongWord; order: TShiftOrder): Byte;
public
constructor Create; overload;
constructor Create(strobe, clock, data: Integer); overload;
procedure ShiftOut(order: TShiftOrder; output: Byte);
function ShiftIn(order: TShiftOrder): Byte;
procedure SendCommand(value: Byte);
function ReadButtons: Byte;
procedure SetLed(value, position: Byte);
procedure Start();
procedure Stop();
end;
implementation
const
strobePin = GPIO_PIN_23;
clockPin = GPIO_PIN_22;
dataPin = GPIO_PIN_17;
procedure TTM1630.ShiftOut(data, clock: LongWord; order: TShiftOrder; output: Byte);
var
i, mask: word;
begin
if order = soLsbFirst then
for i := 7 downto 0 do
begin
mask := 1 shl i; // calculate bitmask
GPIOOutputSet(clock, GPIO_LEVEL_LOW); // set clock to 0
// Send one bit on the data pin
if (output and mask) <> 0 then
GPIOOutputSet(data, GPIO_LEVEL_HIGH)
else
GPIOOutputSet(data, GPIO_LEVEL_LOW);
GPIOOutputSet(clock, GPIO_LEVEL_HIGH); // set clock to 1
end
else
for i := 0 to 7 do
begin
mask := 1 shl i; // calculate bitmask
GPIOOutputSet(clock, GPIO_LEVEL_LOW); // set clock to 0
// Send one bit on the data pin
if (output and mask) <> 0 then
GPIOOutputSet(data, GPIO_LEVEL_HIGH)
else
GPIOOutputSet(data, GPIO_LEVEL_LOW);
GPIOOutputSet(clock, GPIO_LEVEL_HIGH); // set clock to 1
end;
end;
function TTM1630.ShiftIn(data, clock: LongWord; order: TShiftOrder): Byte;
var
i, mask, v: word;
begin
Result := 0;
if order = soLsbFirst then
for i := 7 downto 0 do
begin
GPIOOutputSet(clock, GPIO_LEVEL_LOW); // set clock to 0
v := GPIOInputGet(data);
if v <> 0 then
begin
mask := 1 shl i; // calculate bitmask
Result := Result or mask;
end;
GPIOOutputSet(clock, GPIO_LEVEL_HIGH); // set clock to 1
end
else
for i := 0 to 7 do
begin
GPIOOutputSet(clock, GPIO_LEVEL_LOW); // set clock to 0
v := GPIOInputGet(data);
if v <> 0 then
begin
mask := 1 shl i; // calculate bitmask
Result := Result or mask;
end;
GPIOOutputSet(clock, GPIO_LEVEL_HIGH); // set clock to 1
end;
end;
procedure TTM1630.SendCommand(value: Byte);
begin
GPIOOutputSet(strobe_, GPIO_LEVEL_LOW);
ShiftOut(data_, clock_, soLsbFirst, value);
GPIOOutputSet(strobe_, GPIO_LEVEL_HIGH);
end;
procedure TTM1630.Reset();
var
i: Byte;
begin
SendCommand($40); // set auto increment mode
SendCommand($c0); // set starting address to 0
for i := 0 to 15 do
ShiftOut(data_, clock_, soLsbFirst, $00);
GPIOOutputSet(strobe_, GPIO_LEVEL_HIGH);
end;
constructor TTM1630.Create;
begin
inherited Create;
strobe_ := strobePin;
clock_ := clockPin;
data_ := dataPin;
end;
constructor TTM1630.Create(strobe, clock, data: Integer);
begin
inherited Create;
strobe_ := strobe;
clock_ := clock;
data_ := data;
end;
procedure TTM1630.ShiftOut(order: TShiftOrder; output: Byte);
begin
ShiftOut(data_, clock_, order, output);
end;
function TTM1630.ShiftIn(order: TShiftOrder): Byte;
begin
Result := ShiftIn(data_, clock_, order);
end;
procedure TTM1630.Setup();
begin
GPIOPullSelect(strobe_, GPIO_PULL_NONE);
GPIOFunctionSelect(strobe_, GPIO_FUNCTION_OUT);
GPIOPullSelect(clock_, GPIO_PULL_NONE);
GPIOFunctionSelect(clock_, GPIO_FUNCTION_OUT);
GPIOPullSelect(data_, GPIO_PULL_NONE);
GPIOFunctionSelect(data_, GPIO_FUNCTION_OUT);
SendCommand($40);
SendCommand($8f); // activate
Reset();
SendCommand($44); // set single address
end;
function TTM1630.ReadButtons: Byte;
var
i, v, buttons: Byte;
begin
buttons := 0;
GPIOOutputSet(strobe_, GPIO_LEVEL_LOW);
ShiftOut(data_, clock_, soLsbFirst, $42);
GPIOFunctionSelect(data_, GPIO_FUNCTION_IN);
for i := 0 to 3 do
begin
v := ShiftIn(data_, clock_, soLsbFirst) shl i;
buttons := buttons or v;
end;
GPIOFunctionSelect(data_, GPIO_FUNCTION_OUT);
GPIOOutputSet(strobe_, GPIO_LEVEL_HIGH);
Result := buttons;
end;
procedure TTM1630.SetLed(value, position: Byte);
begin
GPIOFunctionSelect(data_, GPIO_FUNCTION_OUT);
SendCommand($44);
GPIOOutputSet(strobe_, GPIO_LEVEL_LOW);
ShiftOut(data_, clock_, soLsbFirst, $C1 + (position shl 1));
ShiftOut(data_, clock_, soLsbFirst, value);
GPIOOutputSet(strobe_, GPIO_LEVEL_HIGH);
end;
procedure TTM1630.Start;
begin
GPIOOutputSet(strobe_, GPIO_LEVEL_LOW);
end;
procedure TTM1630.Stop;
begin
GPIOOutputSet(strobe_, GPIO_LEVEL_HIGH);
end;
end.
|
unit stDocumentPrintAndExportFontSizeItem;
{* Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" }
// Модуль: "w:\common\components\SandBox\VCM\View\Document\stDocumentPrintAndExportFontSizeItem.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TstDocumentPrintAndExportFontSizeItem" MUID: (1599BCBFE969)
{$Include w:\common\components\SandBox\VCM\sbDefine.inc}
interface
uses
l3IntfUses
, ddAppConfigTypes
;
type
TstDocumentPrintAndExportFontSizeItem = class(TddComboBoxConfigItem)
{* Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" }
public
constructor Create(aMasterItem: TddBaseConfigItem = nil); reintroduce;
end;//TstDocumentPrintAndExportFontSizeItem
implementation
uses
l3ImplUses
, DocumentPrintAndExportFontSizeSettingRes
, l3Base
, ddAppConfigConst
;
constructor TstDocumentPrintAndExportFontSizeItem.Create(aMasterItem: TddBaseConfigItem = nil);
var
l_Value : TddConfigValue;
begin
l3FillChar(l_Value, SizeOf(l_Value));
l_Value.Kind := dd_vkInteger;
l_Value.AsInteger := dv_Document_PrintAndExportFontSize;
inherited Create(pi_Document_PrintAndExportFontSize,
str_PrintAndExportFontSize.AsStr,
l_Value, TPrintAndExportFontSizeValuesMapImpl.Make, aMasterItem);
end;//TstDocumentPrintAndExportFontSizeItem.Create
end.
|
unit State.Model.Item;
interface
uses State.Model.Interfaces, State.Model.Item.Ativo, State.Model.Item.Vendido;
type
TModelItem = class(TInterfacedObject, iItem, iItemOperacoes, iState<iItemOperacoes>)
private
FState : iItemOperacoes;
public
constructor Create;
destructor Destroy; override;
class function New: iItem;
function Vender: iItemOperacoes;
function Cancelar: iItemOperacoes;
function Desconto: iItemOperacoes;
function Devolver: iItemOperacoes;
function SetState(Value : iItemOperacoes) : iItemOperacoes;
function State : iState<iItemOperacoes>;
function Operacoes : iItemOperacoes;
end;
implementation
{ TModelItem }
function TModelItem.Cancelar: iItemOperacoes;
begin
FState.Cancelar;
//implementa o codigo de cancelamento
FState := TModelItemAtivo.New;//Após realizar todos as operações de cancelamento retorna para ativo
Result := Self;
end;
constructor TModelItem.Create;
begin
FState := TModelItemAtivo.New;
end;
function TModelItem.Desconto: iItemOperacoes;
begin
FState.Desconto;
//implementa o codigo de cancelamento
Result := Self;
end;
destructor TModelItem.Destroy;
begin
inherited;
end;
function TModelItem.Devolver: iItemOperacoes;
begin
FState.Devolver;
//implementa o codigo de cancelamento
FState := TModelItemAtivo.New;//Após realizar todos as operações de devolução retorna para ativo
Result := Self;
end;
class function TModelItem.New: iItem;
begin
Result := Self.Create;
end;
function TModelItem.Operacoes: iItemOperacoes;
begin
Result := self;
end;
function TModelItem.SetState(Value: iItemOperacoes): iItemOperacoes;
begin
Result := Self;
FState := Value;
end;
function TModelItem.State: iState<iItemOperacoes>;
begin
Result := Self;
end;
function TModelItem.Vender: iItemOperacoes;
begin
FState.Vender;
//implementa o codigo de cancelamento
FState := TModelItemVendido.New;//Após realizar todos as operações de venda recebe o estado de vendido
Result := Self;
end;
end.
|
unit NLDTranslate;
{
:: NLDTranslate is a set components which make it easy to apply
:: runtime translation to an application. It uses the flexible XML
:: format to define language files.
:$
:$
:$ NLDTranslate is released under the zlib/libpng OSI-approved license.
:$ For more information: http://www.opensource.org/
:$ /n/n
:$ /n/n
:$ Copyright (c) 2002 M. van Renswoude
:$ /n/n
:$ 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.
:$ /n/n
:$ 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:
:$ /n/n
:$ 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.
:$ /n/n
:$ 2. Altered source versions must be plainly marked as such, and must not be
:$ misrepresented as being the original software.
:$ /n/n
:$ 3. This notice may not be removed or altered from any source distribution.
}
{$I NLDTDefines.inc}
{TODO Support Collection properties}
{TODO Implement Undo functionality}
{TODO Set Section to Owner name by default}
interface
uses
SysUtils,
Classes,
Contnrs,
XDOM_2_3,
NLDTInterfaces,
NLDTGlobal;
type
{
:$ Performs the translation on it's owner
:: TNLDTranslate hooks up to a manager and performs the actual translation.
}
TCustomNLDTranslate = class(TNLDTBaseComponent, INLDTranslate, INLDTEvent,
INLDTFileChangeEvent, INLDTTreeWalkEvent)
private
FManager: INLDTManager;
FSection: String;
FOnFileChange: TNotifyEvent;
FTreeStack: TStack;
FUndoDOM: TDomImplementation;
FUndoDocument: TDomDocument;
FUndoParent: TDomElement;
FUndoEmpty: Boolean;
FUndoAllow: Boolean;
procedure SetManagerInternal(const Value: INLDTManager);
procedure SetSection(const Value: String);
protected
procedure DoFileChange(); virtual;
function InternalQuerySection(const AItem: INLDTTreeItem;
const AStoreUndo: Boolean): Boolean; virtual; stdcall;
function InternalQueryTreeItem(const AItem: INLDTTreeItem;
const AStoreUndo: Boolean): Boolean; virtual; stdcall;
procedure InternalEndTreeItem(const AItem: INLDTTreeItem;
const AStoreUndo: Boolean); virtual; stdcall;
// INLDTranslate implementation
procedure SetManager(const Value: INLDTManager); virtual; stdcall;
// INLDTEvent implementation
procedure Detach(const ASender: INLDTInterface); virtual; stdcall;
// INLDTFileChangeEvent implementation
procedure FileChanged(const ASender: INLDTManager); virtual; stdcall;
// INLDTTreeWalkEvent implementation
function QuerySection(const AItem: INLDTTreeItem): Boolean; virtual; stdcall;
function QueryTreeItem(const AItem: INLDTTreeItem): Boolean; virtual; stdcall;
procedure EndTreeItem(const AItem: INLDTTreeItem); virtual; stdcall;
procedure ApplyProperties(const AObject: TObject;
const AItem: INLDTTreeItem;
const AStoreUndo: Boolean); virtual;
//:$ Gets or sets the manager
//:: Set the Manager property to an object supporting the INLDTManager
//:: interface (generally TNLDTManager).
property Manager: INLDTManager read FManager write SetManagerInternal;
//:$ Gets or sets the section
//:: The section specifies which second-level node is used to get
//:: translation data. Refer to the language file format specifications
//:: for more information about sections and nodes.
property Section: String read FSection write SetSection;
//:$ Raised when the manager's language file changes
property OnFileChange: TNotifyEvent read FOnFileChange write FOnFileChange;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
// INLDTranslate implementation
//:$ Reverts all language changes
//:: Undo reverts any changes made to the owner.
procedure Undo(); virtual; stdcall;
end;
TNLDTranslate = class(TCustomNLDTranslate)
published
property Manager;
property Section;
property OnFileChange;
end;
implementation
uses
Dialogs,
TypInfo,
Formatted_XDOM,
NLDTRTTIUtils,
NLDTXDOMUtils;
{******************* TCustomNLDTranslate
Con/destructor
****************************************}
constructor TCustomNLDTranslate.Create;
begin
inherited;
FTreeStack := TStack.Create();
FUndoDOM := TDomImplementation.Create(nil);
FUndoDocument := FUndoDOM.createDocument('language', nil);
FUndoEmpty := True;
FUndoAllow := True;
end;
destructor TCustomNLDTranslate.Destroy;
begin
FUndoDOM.freeDocument(FUndoDocument);
FreeAndNil(FUndoDOM);
FreeAndNil(FTreeStack);
inherited;
end;
{******************* TCustomNLDTranslate
INLDTEvent implementation
****************************************}
procedure TCustomNLDTranslate.Detach;
begin
if ASender = FManager then
FManager := nil;
end;
{******************* TCustomNLDTranslate
Undo
****************************************}
procedure TCustomNLDTranslate.Undo;
procedure InternalProcessSection(const ANode: TDomElement);
var
xmlNode: TDomElement;
ifItem: INLDTTreeItem;
begin
xmlNode := ANode.findFirstChildElement();
while Assigned(xmlNode) do begin
ifItem := TNLDTTreeItem.Create(xmlNode);
try
// Query
if InternalQueryTreeItem(ifItem, False) then begin
InternalProcessSection(xmlNode);
InternalEndTreeItem(ifItem, False);
end;
finally
ifItem := nil;
end;
xmlNode := xmlNode.findNextSiblingElement();
end;
end;
var
xmlRoot: TDomElement;
ifItem: INLDTTreeItem;
begin
xmlRoot := FUndoDocument.documentElement;
// Imitate NLDTManager.ProcessSection
ifItem := TNLDTTreeItem.Create(xmlRoot);
try
InternalQuerySection(ifItem, False);
InternalProcessSection(xmlRoot);
xmlRoot.clear();
FUndoEmpty := True;
finally
ifItem := nil;
end;
end;
procedure TCustomNLDTranslate.FileChanged;
begin
DoFileChange();
end;
function TCustomNLDTranslate.InternalQuerySection;
begin
Result := ((Length(FSection) > 0) and (FSection = AItem.GetName()));
if Result then begin
// New section comin' up, reset
while FTreeStack.Count > 0 do
FTreeStack.Pop();
FUndoParent := FUndoDocument.documentElement;
if AStoreUndo then
FUndoParent.clear();
// Check for owner to apply properties to
if Assigned(Self.Owner) then
ApplyProperties(Self.Owner, AItem, True);
end;
end;
function TCustomNLDTranslate.InternalQueryTreeItem;
var
sName: String;
pParent: TObject;
pDest: TObject;
pInfo: TNLDTRTTIInfo;
iComponent: Integer;
xmlTemp: TDomElement;
begin
// Get parent object
if FTreeStack.Count > 0 then
pParent := TObject(FTreeStack.Peek())
else
pParent := Self.Owner;
if not Assigned(pParent) then begin
Result := False;
exit;
end;
pDest := nil;
sName := AItem.GetName();
if (pParent is TCollection) and (sName = 'Item') then begin
// Destination is a TCollection's item
iComponent := StrToIntDef(AItem.GetAttributeValueByName('Index'), -1);
if (iComponent > -1) and (iComponent < TCollection(pParent).Count) then
pDest := TCollection(pParent).Items[iComponent];
end else begin
pInfo := TNLDTRTTIInfo.Create(pParent);
try
// Check if the object has a property with this name
if (pInfo.HasProperty(sName)) and
(pInfo.GetPropertyType(sName) = tkClass) then
// Class property exist
pDest := pInfo.GetPropertyAsObject(sName)
else begin
// Try to find owned object
if pParent is TComponent then
with TComponent(pParent) do
for iComponent := 0 to ComponentCount - 1 do
if CompareText(Components[iComponent].Name, sName) = 0 then begin
pDest := Components[iComponent];
break;
end;
end;
finally
FreeAndNil(pInfo);
end;
end;
// Add object to stack
Result := Assigned(pDest);
if not Result then
exit;
FTreeStack.Push(Pointer(pDest));
if AStoreUndo then begin
// Create new element
xmlTemp := FUndoDocument.createElement(sName);
FUndoParent.appendChild(xmlTemp);
FUndoParent := xmlTemp;
end;
// Apply properties
ApplyProperties(pDest, AItem, True);
end;
procedure TCustomNLDTranslate.InternalEndTreeItem;
begin
// We're done with the component, remove it from the stack
FTreeStack.Pop();
if AStoreUndo then
// ...and up one undo level we go!
FUndoParent := FUndoParent.findParentElement();
end;
function TCustomNLDTranslate.QuerySection;
begin
FUndoAllow := FUndoEmpty;
FUndoEmpty := False;
Result := InternalQuerySection(AItem, FUndoAllow);
end;
function TCustomNLDTranslate.QueryTreeItem;
begin
Result := InternalQueryTreeItem(AItem, FUndoAllow);
end;
procedure TCustomNLDTranslate.EndTreeItem;
begin
InternalEndTreeItem(AItem, FUndoAllow);
end;
procedure TCustomNLDTranslate.ApplyProperties;
var
pInfo: TNLDTRTTIInfo;
iAttr: Integer;
sName: String;
sValue: String;
bHasProp: Boolean;
bIsIndex: Boolean;
begin
pInfo := TNLDTRTTIInfo.Create(AObject);
try
for iAttr := 0 to AItem.GetAttributeCount() - 1 do begin
sName := AItem.GetAttributeName(iAttr);
bHasProp := pInfo.HasProperty(sName);
bIsIndex := ((AObject is TCollectionItem) and (sName = 'Index'));
if (AStoreUndo) and ((bHasProp) or (bIsIndex)) then begin
// Store property
if bIsIndex then
sValue := AItem.GetAttributeValue(iAttr)
else
sValue := pInfo.GetPropertyAsString(sName);
XDOMSetAttribute(FUndoParent, sName, sValue);
end;
if (bHasProp) and (not bIsIndex) then begin
// Apply property
sValue := AItem.GetAttributeValue(iAttr);
pInfo.SetPropertyAsString(sName, sValue);
end;
end;
finally
FreeAndNil(pInfo);
end;
end;
{******************* TCustomNLDTranslate
Properties
****************************************}
procedure TCustomNLDTranslate.SetManager;
begin
if FManager <> Value then begin
if Assigned(FManager) then
FManager.UnregisterEvent(Self);
FManager := Value;
if Assigned(FManager) then
FManager.RegisterEvent(Self);
end;
end;
procedure TCustomNLDTranslate.SetManagerInternal;
begin
SetManager(Value);
end;
procedure TCustomNLDTranslate.SetSection;
begin
if FSection <> Value then begin
FSection := Value;
end;
end;
{******************* TCustomNLDTranslate
Events
****************************************}
procedure TCustomNLDTranslate.DoFileChange;
begin
if Assigned(FOnFileChange) then
FOnFileChange(Self);
end;
end.
|
inherited dmMvtoAcertoContas: TdmMvtoAcertoContas
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWACRTMOV'
' (FIL_ORIGEM, LANCAMENTO, ANO, HISTORICO, VEICULO, MOTORISTA, D' +
'T_EVENTO, DESCRICAO, VL_EVENTO, DC, FIL_ORDEM, NR_ORDEM, DT_ORDE' +
'M, FIL_OS, NR_OR, DT_ALTERACAO, OPERADOR, CTO_FILIAL, CTO_NUMERO' +
', CTO_DOCUMENTO)'
'VALUES'
' (:FIL_ORIGEM, :LANCAMENTO, :ANO, :HISTORICO, :VEICULO, :MOTORI' +
'STA, :DT_EVENTO, :DESCRICAO, :VL_EVENTO, :DC, :FIL_ORDEM, :NR_OR' +
'DEM, :DT_ORDEM, :FIL_OS, :NR_OR, :DT_ALTERACAO, :OPERADOR, :CTO_' +
'FILIAL, :CTO_NUMERO, :CTO_DOCUMENTO)')
SQLDelete.Strings = (
'DELETE FROM STWACRTMOV'
'WHERE'
' FIL_ORIGEM = :Old_FIL_ORIGEM AND LANCAMENTO = :Old_LANCAMENTO ' +
'AND ANO = :Old_ANO')
SQLUpdate.Strings = (
'UPDATE STWACRTMOV'
'SET'
' FIL_ORIGEM = :FIL_ORIGEM, LANCAMENTO = :LANCAMENTO, ANO = :ANO' +
', HISTORICO = :HISTORICO, VEICULO = :VEICULO, MOTORISTA = :MOTOR' +
'ISTA, DT_EVENTO = :DT_EVENTO, DESCRICAO = :DESCRICAO, VL_EVENTO ' +
'= :VL_EVENTO, DC = :DC, FIL_ORDEM = :FIL_ORDEM, NR_ORDEM = :NR_O' +
'RDEM, DT_ORDEM = :DT_ORDEM, FIL_OS = :FIL_OS, NR_OR = :NR_OR, DT' +
'_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR'
'WHERE'
' FIL_ORIGEM = :Old_FIL_ORIGEM AND LANCAMENTO = :Old_LANCAMENTO ' +
'AND ANO = :Old_ANO')
SQLRefresh.Strings = (
'SELECT FIL_ORIGEM, LANCAMENTO, ANO, HISTORICO, VEICULO, MOTORIST' +
'A, DT_EVENTO, DESCRICAO, VL_EVENTO, DC, FIL_ORDEM, NR_ORDEM, DT_' +
'ORDEM, FIL_OS, NR_OR, DT_ALTERACAO, OPERADOR FROM STWACRTMOV'
'WHERE'
' FIL_ORIGEM = :Old_FIL_ORIGEM AND LANCAMENTO = :Old_LANCAMENTO ' +
'AND ANO = :Old_ANO')
SQLLock.Strings = (
'SELECT NULL FROM STWACRTMOV'
'WHERE'
'FIL_ORIGEM = :Old_FIL_ORIGEM AND LANCAMENTO = :Old_LANCAMENTO AN' +
'D ANO = :Old_ANO'
'FOR UPDATE WITH LOCK')
SQL.Strings = (
'SELECT'
' MOV.*,'
' HIS.DESCRICAO AS NM_HISTORICO,'
' MOT.NOME AS NM_MOTORISTA,'
' VEI.MARCA AS VEI_MARCA,'
' VEI.MODELO AS VEI_MODELO,'
' VEI.PLACA AS VEI_PLACA,'
' VEI.CGC_PRO AS PROPRIETARIO,'
' TPV.DESCRICAO AS TPO_VEICULO'
'FROM STWACRTMOV MOV'
'LEFT JOIN STWACRTHIS HIS on HIS.CODIGO = MOV.HISTORICO'
'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = MOV.MOTORISTA'
'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = MOV.VEICULO'
'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = VEI.TIPO')
object qryManutencaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Required = True
Size = 3
end
object qryManutencaoLANCAMENTO: TIntegerField
FieldName = 'LANCAMENTO'
Required = True
end
object qryManutencaoANO: TStringField
FieldName = 'ANO'
Required = True
Size = 2
end
object qryManutencaoHISTORICO: TStringField
FieldName = 'HISTORICO'
Size = 3
end
object qryManutencaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryManutencaoMOTORISTA: TStringField
FieldName = 'MOTORISTA'
Size = 18
end
object qryManutencaoDT_EVENTO: TDateTimeField
FieldName = 'DT_EVENTO'
end
object qryManutencaoDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Size = 120
end
object qryManutencaoVL_EVENTO: TFloatField
FieldName = 'VL_EVENTO'
end
object qryManutencaoDC: TStringField
FieldName = 'DC'
Size = 1
end
object qryManutencaoFIL_ORDEM: TStringField
FieldName = 'FIL_ORDEM'
Size = 3
end
object qryManutencaoNR_ORDEM: TIntegerField
FieldName = 'NR_ORDEM'
end
object qryManutencaoDT_ORDEM: TDateTimeField
FieldName = 'DT_ORDEM'
end
object qryManutencaoFIL_OS: TStringField
FieldName = 'FIL_OS'
Size = 3
end
object qryManutencaoNR_OR: TIntegerField
FieldName = 'NR_OR'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoNM_HISTORICO: TStringField
FieldName = 'NM_HISTORICO'
ProviderFlags = []
ReadOnly = True
Size = 40
end
object qryManutencaoNM_MOTORISTA: TStringField
FieldName = 'NM_MOTORISTA'
ProviderFlags = []
ReadOnly = True
Size = 40
end
object qryManutencaoVEI_MARCA: TStringField
FieldName = 'VEI_MARCA'
ProviderFlags = []
ReadOnly = True
Size = 15
end
object qryManutencaoVEI_MODELO: TStringField
FieldName = 'VEI_MODELO'
ProviderFlags = []
ReadOnly = True
Size = 15
end
object qryManutencaoVEI_PLACA: TStringField
FieldName = 'VEI_PLACA'
ProviderFlags = []
ReadOnly = True
Size = 8
end
object qryManutencaoPROPRIETARIO: TStringField
FieldName = 'PROPRIETARIO'
ProviderFlags = []
ReadOnly = True
Size = 18
end
object qryManutencaoTPO_VEICULO: TStringField
FieldName = 'TPO_VEICULO'
ProviderFlags = []
ReadOnly = True
end
object qryManutencaoCTO_FILIAL: TStringField
FieldName = 'CTO_FILIAL'
Size = 3
end
object qryManutencaoCTO_NUMERO: TFloatField
FieldName = 'CTO_NUMERO'
end
object qryManutencaoCTO_DOCUMENTO: TStringField
FieldName = 'CTO_DOCUMENTO'
Size = 2
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT'
' MOV.*,'
' HIS.DESCRICAO AS NM_HISTORICO,'
' MOT.NOME AS NM_MOTORISTA,'
' VEI.MARCA AS VEI_MARCA,'
' VEI.MODELO AS VEI_MODELO,'
' VEI.PLACA AS VEI_PLACA,'
' VEI.CGC_PRO AS PROPRIETARIO,'
' TPV.DESCRICAO AS TPO_VEICULO'
'FROM STWACRTMOV MOV'
'LEFT JOIN STWACRTHIS HIS on HIS.CODIGO = MOV.HISTORICO'
'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = MOV.MOTORISTA'
'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = MOV.VEICULO'
'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = VEI.TIPO')
object qryLocalizacaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Required = True
Size = 3
end
object qryLocalizacaoLANCAMENTO: TIntegerField
FieldName = 'LANCAMENTO'
Required = True
end
object qryLocalizacaoANO: TStringField
FieldName = 'ANO'
Required = True
Size = 2
end
object qryLocalizacaoHISTORICO: TStringField
FieldName = 'HISTORICO'
Size = 3
end
object qryLocalizacaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryLocalizacaoMOTORISTA: TStringField
FieldName = 'MOTORISTA'
Size = 18
end
object qryLocalizacaoDT_EVENTO: TDateTimeField
FieldName = 'DT_EVENTO'
end
object qryLocalizacaoDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Size = 120
end
object qryLocalizacaoVL_EVENTO: TFloatField
FieldName = 'VL_EVENTO'
end
object qryLocalizacaoDC: TStringField
FieldName = 'DC'
Size = 1
end
object qryLocalizacaoFIL_ORDEM: TStringField
FieldName = 'FIL_ORDEM'
Size = 3
end
object qryLocalizacaoNR_ORDEM: TIntegerField
FieldName = 'NR_ORDEM'
end
object qryLocalizacaoDT_ORDEM: TDateTimeField
FieldName = 'DT_ORDEM'
end
object qryLocalizacaoFIL_OS: TStringField
FieldName = 'FIL_OS'
Size = 3
end
object qryLocalizacaoNR_OR: TIntegerField
FieldName = 'NR_OR'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryLocalizacaoNM_HISTORICO: TStringField
FieldName = 'NM_HISTORICO'
ReadOnly = True
Size = 40
end
object qryLocalizacaoNM_MOTORISTA: TStringField
FieldName = 'NM_MOTORISTA'
ReadOnly = True
Size = 40
end
object qryLocalizacaoVEI_MARCA: TStringField
FieldName = 'VEI_MARCA'
ReadOnly = True
Size = 15
end
object qryLocalizacaoVEI_MODELO: TStringField
FieldName = 'VEI_MODELO'
ReadOnly = True
Size = 15
end
object qryLocalizacaoVEI_PLACA: TStringField
FieldName = 'VEI_PLACA'
ReadOnly = True
Size = 8
end
object qryLocalizacaoPROPRIETARIO: TStringField
FieldName = 'PROPRIETARIO'
ReadOnly = True
Size = 18
end
object qryLocalizacaoTPO_VEICULO: TStringField
FieldName = 'TPO_VEICULO'
ReadOnly = True
end
object qryLocalizacaoCTO_FILIAL: TStringField
FieldName = 'CTO_FILIAL'
Size = 3
end
object qryLocalizacaoCTO_NUMERO: TFloatField
FieldName = 'CTO_NUMERO'
end
object qryLocalizacaoCTO_DOCUMENTO: TStringField
FieldName = 'CTO_DOCUMENTO'
Size = 2
end
end
end
|
unit main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Data.DB,
Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
e_standard: TEdit;
l_n_standard: TLabel;
e_strength_class: TEdit;
l_n_strength_class: TLabel;
e_diameter_min: TEdit;
l_n_diameter_min: TLabel;
l_n_diameter_max: TLabel;
e_diameter_max: TEdit;
l_n_limit_min: TLabel;
e_limit_min: TEdit;
e_limit_max: TEdit;
l_n_limit_max: TLabel;
rb_yield_point: TRadioButton;
rb_rupture_strength: TRadioButton;
l_n_type: TLabel;
b_action: TButton;
cb_add_update_delete: TComboBox;
e_c_max: TEdit;
l_n_c_max: TLabel;
e_grade: TEdit;
l_n_grade: TLabel;
l_n_c_min: TLabel;
e_c_min: TEdit;
e_mn_max: TEdit;
l_n_mn_max: TLabel;
l_n_mn_min: TLabel;
e_mn_min: TEdit;
e_si_max: TEdit;
l_n_si_max: TLabel;
l_n_si_min: TLabel;
e_si_min: TEdit;
procedure FormCreate(Sender: TObject);
procedure DBGrid1CellClick(Column: TColumn);
procedure b_actionClick(Sender: TObject);
procedure e_standardClick(Sender: TObject);
procedure e_strength_classClick(Sender: TObject);
procedure e_diameter_minClick(Sender: TObject);
procedure e_diameter_maxClick(Sender: TObject);
procedure e_limit_minClick(Sender: TObject);
procedure e_limit_maxClick(Sender: TObject);
procedure rb_yield_pointClick(Sender: TObject);
procedure rb_rupture_strengthClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure e_gradeClick(Sender: TObject);
procedure e_c_minClick(Sender: TObject);
procedure e_c_maxClick(Sender: TObject);
procedure e_mn_minClick(Sender: TObject);
procedure e_mn_maxClick(Sender: TObject);
procedure e_si_minClick(Sender: TObject);
procedure e_si_maxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
CurrentDir: string;
HeadName: string = ' вид проката согласно инструкции технологических проб';
Version: string = ' v0.1';
DBFile: string = 'data.sdb';
function CheckAppRun: bool;
function ViewClear(InData: string): bool;
function DbGridColumnName: bool;
function EditColor(InData: integer): integer;
implementation
uses
settings, sql;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
//проверка 1 экземпляра программы
CheckAppRun;
Form1.Caption := HeadName+Version;
//заголовки к showmessage
Application.Title := HeadName+Version;
// текущая дириктория
CurrentDir := GetCurrentDir;
// точка вместо запятой при преобразовании в строку
FormatSettings.DecimalSeparator := '.';
//запрет на изменение формы
Form1.BorderStyle := bsToolWindow;
// Form1.BorderIcons := Form1.BorderIcons - [biMaximize];
ConfigSettings(true);
ConfigPostgresSetting(true);
ViewClear('');
DbGridColumnName;
SqlRead;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
ConfigPostgresSetting(false);
ConfigSettings(false);
end;
procedure TForm1.DBGrid1CellClick(Column: TColumn);
var
KeyValues : Variant;
begin
//отключаем управление
{ form1.DBGrid1.DataSource.DataSet.DisableControls;
try
//переменные по которым будет производиться поиск
KeyValues := VarArrayOf([SQuery.FieldByName('standard').AsString,
SQuery.FieldByName('strength_class').AsString,
SQuery.FieldByName('diameter_min').AsString]);
//поиск по ключивым полям
form1.DBGrid1.DataSource.DataSet.Locate('standard;strength_class;diameter_min', KeyValues, []);
finally
//включаем управление
form1.DBGrid1.DataSource.DataSet.EnableControls;
end;
//перемещение вверх
form1.DBGrid1.DataSource.DataSet.MoveBy(-1);
}
form1.e_grade.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('grade').AsString;
form1.e_standard.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('standard').AsString;
form1.e_strength_class.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('strength_class').AsString;
form1.e_c_min.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('c_min').AsString;
form1.e_c_max.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('c_max').AsString;
form1.e_mn_min.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('mn_min').AsString;
form1.e_mn_max.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('mn_max').AsString;
form1.e_si_min.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('si_min').AsString;
form1.e_si_max.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('si_max').AsString;
form1.e_diameter_min.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('diameter_min').AsString;
form1.e_diameter_max.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('diameter_max').AsString;
form1.e_limit_min.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('limit_min').AsString;
form1.e_limit_max.Text := Form1.DBGrid1.DataSource.DataSet.FieldByName('limit_max').AsString;
if Form1.DBGrid1.DataSource.DataSet.FieldByName('type').AsString = 'предел текучести' then
form1.rb_yield_point.Checked := true;
if Form1.DBGrid1.DataSource.DataSet.FieldByName('type').AsString = 'временное сопротивление' then
form1.rb_rupture_strength.Checked := true;
EditColor(2);
end;
function DbGridColumnName: bool;
begin
form1.DBGrid1.Columns.Items[0].Title.Caption := 'н/пп';
form1.DBGrid1.Columns.Items[1].Title.Caption := 'Марка стали';
form1.DBGrid1.Columns.Items[2].Title.Caption := 'Стандарт';
form1.DBGrid1.Columns.Items[3].Title.Caption := 'Класс прочности';
form1.DBGrid1.Columns.Items[4].Title.Caption := 'C min';
form1.DBGrid1.Columns.Items[5].Title.Caption := 'C max';
form1.DBGrid1.Columns.Items[6].Title.Caption := 'Mn min';
form1.DBGrid1.Columns.Items[7].Title.Caption := 'Mn max';
form1.DBGrid1.Columns.Items[8].Title.Caption := 'Si min';
form1.DBGrid1.Columns.Items[9].Title.Caption := 'Si max';
form1.DBGrid1.Columns.Items[10].Title.Caption := 'Диаметр min';
form1.DBGrid1.Columns.Items[11].Title.Caption := 'Диаметр max';
form1.DBGrid1.Columns.Items[12].Title.Caption := 'Предел min';
form1.DBGrid1.Columns.Items[13].Title.Caption := 'Предел max';
form1.DBGrid1.Columns.Items[14].Title.Caption := 'Тип';
DataSource.Enabled := true;
form1.DBGrid1.DataSource := DataSource;
end;
function ViewClear(InData: string): bool;
var
i: integer;
begin
if InData <> 'e' then
begin
for i:=0 to form1.ComponentCount - 1 do
begin
if (form1.Components[i] is Tlabel) then
if copy(form1.Components[i].Name,1,4) <> 'l_n_' then
Tlabel(Form1.FindComponent(form1.Components[i].Name)).Caption := '';
end;
form1.cb_add_update_delete.Items.Add('добавить');
form1.cb_add_update_delete.Items.Add('обновить');
form1.cb_add_update_delete.Items.Add('удалить');
form1.cb_add_update_delete.ItemIndex := 0;
end;
if InData = 'e' then
begin
for i:=0 to form1.ComponentCount - 1 do
begin
if (form1.Components[i] is TEdit) then
if copy(form1.Components[i].Name,1,2) = 'e_' then
Tlabel(Form1.FindComponent(form1.Components[i].Name)).Caption := '';
end;
form1.rb_yield_point.Checked := false;
form1.rb_rupture_strength.Checked := false;
end;
end;
procedure TForm1.b_actionClick(Sender: TObject);
var
ID, i, e: integer;
begin
ID := Form1.DBGrid1.DataSource.DataSet.FieldByName('id').AsInteger;
e := 0;
e := EditColor(1);
if (not form1.rb_yield_point.Checked) and (not form1.rb_rupture_strength.Checked) then
begin
b_action.Hint := ' не выбрано значение - Тип';
b_action.ShowHint := true;
inc(e);
end;
if e > 0 then
exit;
if form1.cb_add_update_delete.ItemIndex = 0 then
if MessageDlg('Добавить новую запись?', mtCustom, mbYesNo, 0) = mrYes then
SqlInsert;
if form1.cb_add_update_delete.ItemIndex = 1 then
if MessageDlg('Обновить запись?', mtCustom, mbYesNo, 0) = mrYes then
SqlUpdate(ID);
if form1.cb_add_update_delete.ItemIndex = 2 then
if MessageDlg('Удалить запись?', mtCustom, mbYesNo, 0) = mrYes then
SqlDelete(ID);
ViewClear('e');
end;
function EditColor(InData: integer): integer;
var
i, e: integer;
begin
for i:=0 to form1.ComponentCount - 1 do
begin
if (form1.Components[i] is TEdit) then
begin
if InData = 1 then
begin
if trim(TEdit(Form1.FindComponent(form1.Components[i].Name)).Text) = '' then
begin
TEdit(Form1.FindComponent(form1.Components[i].Name)).Color := clRed;
inc(e);
end;
end;
if InData = 2 then
begin
TEdit(Form1.FindComponent(form1.Components[i].Name)).Color := clWindow;
end;
end;
end;
Result := e;
end;
procedure TForm1.e_si_maxClick(Sender: TObject);
begin
e_si_max.Color := clWindow;
end;
procedure TForm1.e_si_minClick(Sender: TObject);
begin
e_si_min.Color := clWindow;
end;
procedure TForm1.e_standardClick(Sender: TObject);
begin
e_standard.Color := clWindow;
end;
procedure TForm1.e_strength_classClick(Sender: TObject);
begin
e_strength_class.Color := clWindow;
end;
procedure TForm1.e_diameter_minClick(Sender: TObject);
begin
e_diameter_min.Color := clWindow;
end;
procedure TForm1.e_gradeClick(Sender: TObject);
begin
e_grade.Color := clWindow;
end;
procedure TForm1.e_c_maxClick(Sender: TObject);
begin
e_c_max.Color := clWindow;
end;
procedure TForm1.e_c_minClick(Sender: TObject);
begin
e_c_min.Color := clWindow;
end;
procedure TForm1.e_diameter_maxClick(Sender: TObject);
begin
e_diameter_max.Color := clWindow;
end;
procedure TForm1.e_limit_minClick(Sender: TObject);
begin
e_limit_min.Color := clWindow;
end;
procedure TForm1.e_mn_maxClick(Sender: TObject);
begin
e_mn_max.Color := clWindow;
end;
procedure TForm1.e_mn_minClick(Sender: TObject);
begin
e_mn_min.Color := clWindow;
end;
procedure TForm1.e_limit_maxClick(Sender: TObject);
begin
e_limit_max.Color := clWindow;
end;
procedure TForm1.rb_yield_pointClick(Sender: TObject);
begin
b_action.ShowHint := false;
end;
procedure TForm1.rb_rupture_strengthClick(Sender: TObject);
begin
b_action.ShowHint := false;
end;
function CheckAppRun: bool;
var
hMutex : THandle;
begin
// закрытие 2 экземляра программы
hMutex := CreateMutex(0, true , 'AddTechnologicalSample');
if GetLastError = ERROR_ALREADY_EXISTS then
begin
Application.Title := HeadName+Version;
//прячим форму и выводим сообщение
Application.ShowMainForm:=false;
showmessage('Экземпляр программы уже запущен');
CloseHandle(hMutex);
TerminateProcess(GetCurrentProcess, 0);
end;
end;
end.
|
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
FMX.ListView, FMX.Edit, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.MultiView,
FMX.Controls.Presentation,
System.IniFiles, System.IOUtils, FMX.DialogService;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
SpeedButton1: TSpeedButton;
MultiView1: TMultiView;
ListView1: TListView;
Layout1: TLayout;
Button1: TButton;
Image1: TImage;
Edit1: TEdit;
Switch1: TSwitch;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure FormSaveState(Sender: TObject);
private
{ Private declarations }
FSettingsFilePath: String;
SwitchEnabled: Boolean;
EditText: String;
procedure SaveSettings;
procedure LoadSettings;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses Unit2;
procedure TForm1.Button1Click(Sender: TObject);
begin
TDialogService.ShowMessage('Settings Window');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{$IF DEFINED(MSWINDOWS)}
FSettingsFilePath := ExtractFilePath(ParamStr(0));
{$ELSE}
FSettingsFilePath := TPath.GetDocumentsPath + PathDelim;
{$ENDIF}
LoadSettings;
ListView1.Items.Add.Text := 'Item1';
ListView1.Items.Add.Text := 'Item2';
end;
procedure TForm1.FormSaveState(Sender: TObject);
begin
SaveSettings;
end;
procedure TForm1.ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
var
S: String;
begin
S := ListView1.Items[ListView1.ItemIndex].Text;
if S = 'Item1' then
Form2.Show;
end;
procedure TForm1.LoadSettings;
var
IniFile: TMemIniFile;
begin
IniFile := TMemIniFile.Create(FSettingsFilePath + 'Settings.ini');
try
SwitchEnabled := IniFile.ReadBool('Settings', 'SwitchEnabled', False);
EditText := IniFile.ReadString('Settings', 'EditText', '');
Switch1.IsChecked := SwitchEnabled;
Edit1.Text := EditText;
finally
IniFile.Free;
end;
end;
procedure TForm1.SaveSettings;
var
IniFile: TMemIniFile;
begin
IniFile := TMemIniFile.Create(FSettingsFilePath + 'Settings.ini');
try
SwitchEnabled := Switch1.IsChecked;
EditText := Edit1.Text;
IniFile.WriteString('Settings', 'EditText', EditText);
IniFile.WriteBool('Settings', 'SwitchEnabled', SwitchEnabled);
IniFile.UpdateFile;
finally
IniFile.Free;
end;
end;
end.
|
unit uEventAgg;
interface
uses SysUtils, Classes, Generics.Collections;
type
TEvent = class(TObject);
TEventClass = class of TEvent;
TCallbackProc = procedure(const aPublisher: TObject; const anEvent: TEventClass) of object;
TDispatch = record
private
FNotification: TCallbackProc;
FPublisher: TObject;
public
constructor Create(const aNotification: TCallbackProc; const aPublisher: TObject);
property Handle: TCallbackProc read FNotification write FNotification;
property Publisher: TObject read FPublisher write FPublisher;
end;
TDispatchList = class(TList<TDispatch>);
TDispatchTable = class(TDictionary<TEventClass, TDispatchList>);
TEventAggregator = class(TObject)
strict private
FDispatchTable: TDispatchTable;
function SameMethod(const aFirst, aSecond: TCallbackProc): Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Publish(const aPublisher: TObject; const anEvent: TEventClass);
procedure Subscribe(const aSubscriber: TCallbackProc; const anEvent: TEventClass; const aPublisher: TObject = nil);
procedure Unsubscribe(const aSubscriber: TCallbackProc); overload;
procedure Unsubscribe(const aSubscriber: TCallbackProc; const anEvent: TEventClass; const aPublisher: TObject = nil); overload;
end;
implementation
{ TEventAggregator }
procedure TEventAggregator.Subscribe(const aSubscriber: TCallbackProc; const anEvent: TEventClass; const aPublisher: TObject);
var
DispatchList: TDispatchList;
DispatchItem: TDispatch;
begin
DispatchItem := TDispatch.Create(aSubscriber, aPublisher);
if not FDispatchTable.TryGetValue(anEvent, DispatchList) then
begin
DispatchList := TDispatchList.Create;
FDispatchTable.Add(anEvent, DispatchList);
end;
if DispatchList.IndexOf(DispatchItem) < 0 then
DispatchList.Add(DispatchItem);
end;
constructor TEventAggregator.Create;
begin
inherited;
FDispatchTable := TDispatchTable.Create;
end;
destructor TEventAggregator.Destroy;
var
DispatchList: TDispatchList;
begin
for DispatchList in FDispatchTable.Values do
DispatchList.Free;
FDispatchTable.Free;
inherited;
end;
procedure TEventAggregator.Publish(const aPublisher: TObject; const anEvent: TEventClass);
var
Dispatcher: TDispatchList;
Dispatch: TDispatch;
Event: TEventClass;
begin
for Event in FDispatchTable.Keys do
if anEvent.InheritsFrom(Event) then
begin
Dispatcher := FDispatchTable.Items[Event];
for Dispatch in Dispatcher do
if (Dispatch.Publisher = nil) or (Dispatch.Publisher = aPublisher) then
Dispatch.Handle(aPublisher, anEvent);
end;
end;
procedure TEventAggregator.Unsubscribe(const aSubscriber: TCallbackProc);
begin
Unsubscribe(aSubscriber, nil, nil);
end;
procedure TEventAggregator.Unsubscribe(const aSubscriber: TCallbackProc; const anEvent: TEventClass; const aPublisher: TObject);
var
DispatchList: TDispatchList;
I: Integer;
begin
if Assigned(anEvent) then
begin
if FDispatchTable.TryGetValue(anEvent, DispatchList) then
begin
for I := DispatchList.Count - 1 downto 0 do
begin
if SameMethod(DispatchList[I].Handle, aSubscriber) and ((aPublisher = nil) or (DispatchList[I].Publisher = aPublisher)) then
DispatchList.Delete(I);
end;
end;
end
else
for DispatchList in FDispatchTable.Values do
begin
for I := DispatchList.Count - 1 downto 0 do
begin
if SameMethod(DispatchList[I].Handle, aSubscriber) and ((aPublisher = nil) or (DispatchList[I].Publisher = aPublisher)) then
DispatchList.Delete(I);
end;
end;
end;
function TEventAggregator.SameMethod(const aFirst, aSecond: TCallbackProc): Boolean;
begin
Result := (TMethod(aFirst).Code = TMethod(aSecond).Code) and (TMethod(aFirst).Data = TMethod(aSecond).Data);
end;
{ TDispatch }
constructor TDispatch.Create(const aNotification: TCallbackProc; const aPublisher: TObject);
begin
FNotification := aNotification;
FPublisher := aPublisher;
end;
end.
|
unit PicShopForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, FramedButton, StdCtrls, OpaquePanel, MarqueeCtrl, ComCtrls,
SocketComp, ExtDlgs, InternationalizerComponent;
const
PictureTransferPort = 6010;
BufferSize = 1024;
PhotoWidth = 150;
PhotoHeight = 200;
type
TPictureShopViewer = class(TForm)
Panel3: TPanel;
DestImage: TImage;
btnLoad: TFramedButton;
btnPreview: TFramedButton;
btnSend: TFramedButton;
btnCancel: TFramedButton;
SourcePanel: TOpaquePanel;
Panel1: TPanel;
ZoomIn: TFramedButton;
Panel4: TPanel;
ZoomOut: TFramedButton;
Marquee: TMarquee;
Timer: TTimer;
Shape1: TShape;
SourceImage: TImage;
OpenDialog: TOpenPictureDialog;
InternationalizerComponent1: TInternationalizerComponent;
procedure btnCancelClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnPreviewClick(Sender: TObject);
procedure SourcePanelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SourcePanelMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure ZoomInClick(Sender: TObject);
procedure ZoomOutClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
private
fUserImage : TBitmap;
fTempImage : TBitmap;
fRect : TRect;
fLastX : integer;
fLastY : integer;
fZoomLevel : byte;
fCanDrag : boolean;
fRepSource : boolean;
fProgress : integer;
fBusy : boolean;
fSocket : TClientSocket;
fStream : TMemoryStream;
fServerAddr : string;
fWorldName : string;
fUserName : string;
fCacheDir : string;
fCanSndData : boolean;
protected
procedure Paint; override;
public
procedure LoadImage(path : string);
function CenterImage(var Image : TBitmap) : boolean;
procedure SetImage;
procedure DragImage(deltaX, deltaY : integer);
procedure InvalidateImage;
procedure NotifyPerc(Sender : TObject; perc : integer);
procedure SendPicture;
procedure SocketRead(Sender : TObject; Socket : TCustomWinSocket);
procedure SocketConnect(Sender : TObject; Socket : TCustomWinSocket);
procedure SocketWrite(Sender : TObject; Socket : TCustomWinSocket);
procedure FinishSend(success : boolean; msg : string);
procedure HandleError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer);
private
procedure Message_WM_NCHITTEST(var Message : TMessage); message WM_NCHITTEST;
public
property ServerAddr : string read fServerAddr write fServerAddr;
property WorldName : string read fWorldName write fWorldName;
property UserName : string read fUserName write fUserName;
property CacheDir : string read fCacheDir write fCacheDir;
end;
var
PictureShopViewer: TPictureShopViewer;
implementation
uses
MathUtils, jpeg, Winsock, Literals;
{$R *.DFM}
type
TNotifyPerc = procedure(Sender : TObject; perc : integer) of object;
type
TRGBRec =
packed record
R : byte;
G : byte;
B : byte;
I : byte;
end;
PColorArray = ^TColorArray;
TColorArray = array[0..0] of TColor;
procedure CopyBitmap(Source, Dest : TBitmap);
var
srcLine : PColorArray;
dstLine : PColorArray;
lidx : integer;
cidx : integer;
theWidth : integer;
begin
theWidth := Source.Width;
Dest.Width := theWidth;
Dest.Height := Source.Height;
for lidx := 0 to pred(Source.Height) do
begin
srcLine := PColorArray(Source.ScanLine[lidx]);
dstLine := PColorArray(Dest.ScanLine[lidx]);
for cidx := 0 to pred(theWidth) do
srcLine[cidx] := dstLine[cidx];
//move(srcLine^, dstLine^, theWith*sizeof(TColor));
end;
end;
procedure ZoomBitmap(Source, Dest : TBitMap; level : byte; NotProc : TNotifyPerc);
var
R : TRect;
w : integer;
h : integer;
row : integer;
col : integer;
nr : integer;
nc : integer;
function AvrgPoint(pc, pr : integer; defColor : TColor) : TColor;
var
cnt : integer;
i : integer;
j : integer;
sR : integer;
sG : integer;
sB : integer;
begin
sR := 0;
sG := 0;
sB := 0;
cnt := 0;
for i := pr to pr + level do
for j := pc to pc + level do
if PtInRect(R, Point(j, i))
then
with TRGBRec(Source.Canvas.Pixels[j, i]) do
begin
inc(sR, R);
inc(sG, G);
inc(sB, B);
inc(cnt);
end;
result := defColor;
if cnt > 0
then
with TRGBRec(Result) do
begin
R := round(sR/cnt);
G := round(sG/cnt);
B := round(sB/cnt);
end;
end;
begin
R := Rect(0, 0, Source.Width, Source.Height);
w := Source.Width;
h := Source.Height;
Dest.Width := w div level;
Dest.Height := h div level;
if level = 1
then Dest.Canvas.CopyRect(R, Source.Canvas, R)
else
begin
row := 0;
nr := 0;
while row < h do
begin
col := 0;
nc := 0;
while col < w do
begin
Dest.Canvas.Pixels[nc, nr] := AvrgPoint(col, row, clBlack);
inc(col, level);
inc(nc);
end;
inc(row, level);
inc(nr);
if Assigned(NotProc)
then NotProc(nil, round(100*row/h));
end;
end;
end;
procedure MixImages(Dest, Source : TBitmap; NotProc : TNotifyPerc);
var
row : integer;
col : integer;
Color : TColor;
h : integer;
R : TRect;
begin
h := Dest.Height;
for row := 0 to pred(h) do
begin
for col := 0 to pred(Dest.Width) do
begin
Color := Dest.Canvas.Pixels[col, row];
with TRGBRec(Source.Canvas.Pixels[col, row]) do
begin
TRGBRec(Color).R := round((R/255)*TRGBRec(Color).R);//(R + TRGBRec(Color).R) div 2;
TRGBRec(Color).G := round((G/255)*TRGBRec(Color).G);//(G + TRGBRec(Color).G) div 2;
TRGBRec(Color).B := round((B/255)*TRGBRec(Color).B);//(G + TRGBRec(Color).B) div 2;
end;
Dest.Canvas.Pixels[col, row] := Color;
end;
if Assigned(NotProc)
then NotProc(nil, round(100*row/h));
end;
R := Rect(0, 0, Dest.Width, Dest.Height);
InflateRect(R, -5, -5);
Dest.Canvas.Brush.Style := bsClear;
Dest.Canvas.Pen.Color := $006A6A35;
Dest.Canvas.Pen.Width := 1;
Dest.Canvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom);
end;
procedure TPictureShopViewer.Paint;
begin
inherited;
if fRepSource
then
begin
SourceImage.Canvas.Brush.Style := bsSolid;
SourceImage.Canvas.Brush.Color := $003C3C1E;
SourceImage.Canvas.FillRect(Rect(0, 0, PhotoWidth, PhotoHeight));
SourceImage.Canvas.CopyRect(Rect(0, 0, PhotoWidth, PhotoHeight), fTempImage.Canvas, fRect);
end;
end;
procedure TPictureShopViewer.InvalidateImage;
var
R : TRect;
begin
fRepSource := true;
SourceImage.Refresh;
R := SourceImage.BoundsRect;
InvalidateRect(Handle, @R, false);
end;
procedure TPictureShopViewer.Message_WM_NCHITTEST(var Message : TMessage);
begin
if hi(Message.LParam) > Marquee.Height
then Message.Result := HTCAPTION
else inherited;
end;
procedure TPictureShopViewer.DragImage(deltaX, deltaY : integer);
var
tmpWidth : integer;
tmpHeight : integer;
begin
tmpWidth := fRect.Right - fRect.Left;
if deltaX + fRect.Left < 0
then
begin
fRect.Left := 0;
fRect.Right := tmpWidth;
end
else
if deltaX + fRect.Right > fTempImage.Width
then
begin
fRect.Right := fTempImage.Width;
fRect.Left := fRect.Right - tmpWidth;
end
else OffsetRect(fRect, deltaX, 0);
tmpHeight := fRect.Bottom - fRect.Top;
if deltaY + fRect.Top < 0
then
begin
fRect.Top := 0;
fRect.Bottom := tmpHeight;
end
else
if deltaY + fRect.Bottom > fTempImage.Height
then
begin
fRect.Bottom := fTempImage.Height;
fRect.Top := fRect.Bottom - tmpHeight;
end
else OffsetRect(fRect, 0, deltaY);
end;
function TPictureShopViewer.CenterImage(var Image : TBitmap) : boolean;
var
w : integer;
h : integer;
S : TRect;
D : TRect;
tmpImg : TBitmap;
begin
w := max(PhotoWidth, fTempImage.Width);
h := max(PhotoHeight, fTempImage.Height);
if (fTempImage.Width < PhotoWidth) or (fTempImage.Height < PhotoHeight)
then
begin
tmpImg := TBitmap.Create;
tmpImg.Width := w;
tmpImg.Height := h;
S := Rect(0, 0, Image.Width, Image.Height);
D := Rect(0, 0, w, h);
tmpImg.Canvas.Brush.Style := bsSolid;
tmpImg.Canvas.Brush.Color := $003C3C1E;
tmpImg.Canvas.FillRect(D);
D := S;
OffsetRect(D, max(0, (w - D.Right) div 2), max(0, (h - D.Bottom) div 2));
tmpImg.Canvas.CopyRect(D, Image.Canvas, S);
Image.Assign(tmpImg);
tmpImg.Free;
result := (fTempImage.Width > PhotoWidth) or (fTempImage.Height > PhotoHeight);
end
else result := true;
end;
procedure TPictureShopViewer.SetImage;
begin
fCanDrag := CenterImage(fTempImage);
fRect := Rect(0, 0, PhotoWidth, PhotoHeight);
OffsetRect(fRect, max(0, (fTempImage.Width - PhotoWidth) div 2), max(0, (fTempImage.Height - PhotoHeight) div 2));
fUserImage.Free;
fUserImage := TBitmap.Create;
fUserImage.Assign(fTempImage);
//DragImage(0, 0);
InvalidateImage;
SourcePanel.Cursor := crHandPoint;
ZoomIn.Enabled := true;
ZoomOut.Enabled := true;
end;
procedure TPictureShopViewer.LoadImage(path : string);
var
Stream : TStream;
jpgImg : TJPEGImage;
begin
try
Stream := TFileStream.Create(path, fmOpenRead);
try
if uppercase(ExtractFileExt(path)) = '.BMP'
then fTempImage.LoadFromStream(Stream)
else
if uppercase(ExtractFileExt(path)) = '.JPG'
then
begin
fTempImage.Free;
fTempImage := TBitmap.Create;
jpgImg := TJPEGImage.Create;
jpgImg.LoadFromStream(Stream);
fTempImage.Width := jpgImg.Width;
fTempImage.Height := jpgImg.Height;
fTempImage.Canvas.Draw(0, 0, jpgImg);
jpgImg.Free;
end;
SetImage;
btnPreview.Enabled := true;
finally
Stream.Free;
end;
except
end;
end;
procedure TPictureShopViewer.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
// close;
end;
procedure TPictureShopViewer.btnSendClick(Sender: TObject);
var
jpgImg : TJPEGImage;
begin
if btnSend.Text = GetLiteral('Literal49')
then FinishSend(false, GetLiteral('Literal50'))
else
if not fBusy
then
begin
fStream.Free;
fBusy := true;
jpgImg := TJPEGImage.Create;
jpgImg.Assign(DestImage.Picture.Bitmap);
fStream := TMemoryStream.Create;
jpgImg.SaveToStream(fStream);
jpgImg.Free;
btnSend.Text := GetLiteral('Literal51');
btnSend.Refresh;
SendPicture;
Marquee.Caption := GetLiteral('Literal52');
end;
end;
procedure TPictureShopViewer.btnLoadClick(Sender: TObject);
begin
if not fBusy and OpenDialog.Execute
then
begin
LoadImage(OpenDialog.FileName);
fZoomLevel := 1;
end;
end;
procedure TPictureShopViewer.FormCreate(Sender: TObject);
begin
fUserImage := TBitmap.Create;
fTempImage := TBitmap.Create;
fZoomLevel := 1;
fCacheDir := 'c:\work\five\release\cache\';
end;
procedure TPictureShopViewer.FormDestroy(Sender: TObject);
begin
fUserImage.Free;
fTempImage.Free;
if fSocket <> nil
then fSocket.Close;
fSocket.Free;
fStream.Free;
end;
procedure TPictureShopViewer.btnPreviewClick(Sender: TObject);
var
Vignette : TBitmap;
Stream : TStream;
begin
try
if not fBusy
then
begin
fBusy := true;
Vignette := TBitmap.Create;
try
Stream := TFileStream.Create(fCacheDir + 'OtherImages\photomask.bmp', fmOpenRead);
try
try
Vignette.LoadFromStream(Stream);
finally
Stream.Free;
end;
except
Vignette.Width := PhotoWidth;
Vignette.Height := PhotoHeight;
end;
MixImages(Vignette, SourceImage.Picture.Bitmap, NotifyPerc);
DestImage.Canvas.CopyRect(DestImage.ClientRect, Vignette.Canvas, DestImage.ClientRect);
DestImage.Refresh;
btnSend.Enabled := true;
Vignette.Free;
Marquee.Caption := GetLiteral('Literal53');
except
end;
fBusy := false;
end;
except
end;
end;
procedure TPictureShopViewer.SourcePanelMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if fCanDrag
then
begin
fLastX := X;
fLastY := Y;
end;
end;
procedure TPictureShopViewer.SourcePanelMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if fCanDrag and (ssLeft in Shift)
then
begin
DragImage(fLastX - X, fLastY - Y);
InvalidateImage;
fLastX := X;
fLastY := Y;
end;
end;
procedure TPictureShopViewer.ZoomInClick(Sender: TObject);
begin
if not fBusy
then
begin
if fZoomLevel > 1
then
begin
fBusy := true;
dec(fZoomLevel);
ZoomBitmap(fUserImage, fTempImage, fZoomLevel, NotifyPerc);
fCanDrag := CenterImage(fTempImage);
//DestImage.Picture.Bitmap.Assign(fTempImage);
DragImage(0, 0);
InvalidateImage;
fBusy := false;
end;
end;
end;
procedure TPictureShopViewer.ZoomOutClick(Sender: TObject);
begin
if not fBusy
then
begin
if fZoomLevel < 5
then
begin
fBusy := true;
inc(fZoomLevel);
ZoomBitmap(fUserImage, fTempImage, fZoomLevel, NotifyPerc);
fCanDrag := CenterImage(fTempImage);
//DestImage.Picture.Bitmap.Assign(fTempImage);
DragImage(0, 0);
InvalidateImage;
fBusy := false;
end;
end;
end;
procedure TPictureShopViewer.TimerTimer(Sender: TObject);
begin
Marquee.Tick;
end;
procedure TPictureShopViewer.NotifyPerc(Sender : TObject; perc : integer);
begin
if fProgress <> perc
then
begin
fProgress := perc;
Marquee.Caption := GetLiteral('Literal54') + IntToStr(perc) + '%';
Application.ProcessMessages;
end;
end;
procedure TPictureShopViewer.SocketConnect(Sender : TObject; Socket : TCustomWinSocket);
var
logText : string;
begin
logText := 'User=' + fUserName + ^M^J + 'World=' + fWorldName + ^M^J + 'Size=' + IntToStr(fStream.Size);
Socket.SendText(logText);
end;
procedure TPictureShopViewer.SocketRead(Sender : TObject; Socket : TCustomWinSocket);
var
text : string;
begin
text := Socket.ReceiveText;
if text = 'SEND'
then
begin
fCanSndData := true;
SocketWrite(Sender, Socket)
end
else
if text = 'OK'
then FinishSend(true, '')
else
if text = 'ERROR'
then FinishSend(false, GetLiteral('Literal55'))
else FinishSend(true, ''); // >> This should never happen...
end;
procedure TPictureShopViewer.SocketWrite(Sender : TObject; Socket : TCustomWinSocket);
var
buffer : array[0..BufferSize-1] of byte;
count : integer;
begin
if fCanSndData
then
begin
fStream.Seek(0, 0);
repeat
count := fStream.Read(buffer, BufferSize);
Socket.SendBuf(buffer, count);
until count < BufferSize;
Marquee.Caption := GetLiteral('Literal56');
end;
end;
procedure TPictureShopViewer.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer );
begin
case ErrorEvent of
eeGeneral, eeSend, eeReceive, eeConnect, eeDisconnect, eeAccept :
begin
ErrorCode := 0;
FinishSend(false, GetLiteral('Literal57'));
end;
end
end;
procedure TPictureShopViewer.FinishSend(success : boolean; msg : string);
begin
fCanSndData := false;
if msg <> ''
then Marquee.Caption := msg;
if success
then
begin
fSocket.Close;
fBusy := false;
btnSend.Text := GetLiteral('Literal58');
ModalResult := mrOk;
end
else
begin
fSocket.Close;
fBusy := false;
btnSend.Text := GetLiteral('Literal59');
end;
end;
procedure TPictureShopViewer.SendPicture;
begin
fCanSndData := false;
fSocket.Free;
fSocket := TClientSocket.Create(self);
fSocket.OnConnect := SocketConnect;
fSocket.OnRead := SocketRead;
fSocket.OnWrite := SocketWrite;
fSocket.Port := PictureTransferPort;
fSocket.OnError := HandleError;
if inet_addr(pchar(fServerAddr)) = u_long(INADDR_NONE)
then fSocket.Host := fServerAddr
else fSocket.Address := fServerAddr;
fSocket.Open;
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Custom edit control with the look and feel like TLabel
Copyright (C) 2017-2018 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit KASCDEdit;
{$mode delphi}
interface
uses
Classes, SysUtils, LResources, Controls, Graphics, Dialogs, Types,
Menus, CustomDrawnControls, CustomDrawnDrawers, CustomDrawn_Common;
type
{ TKASCDEdit }
TKASCDEdit = class(TCDEdit)
private
FEditMenu: TPopupMenu; static;
private
procedure CreatePopupMenu;
procedure ShowMenu(Data: PtrInt);
procedure MenuCopy(Sender: TObject);
procedure MenuSelectAll(Sender: TObject);
protected
procedure RealSetText(const Value: TCaption); override;
procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer;
WithThemeSpace: Boolean); override;
procedure CalculateSize(MaxWidth: Integer; var NeededWidth, NeededHeight: Integer);
procedure KeyDown(var Key: word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override;
public
procedure SelectAll;
procedure CopyToClipboard;
published
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
{ TKASCDDrawer }
TKASCDDrawer = class(TCDDrawerCommon)
public
function GetMeasures(AMeasureID: Integer): Integer; override;
procedure DrawEditBackground(ADest: TCanvas; ADestPos: TPoint; ASize: TSize;
AState: TCDControlState; AStateEx: TCDEditStateEx); override;
procedure DrawEdit(ADest: TCanvas; ASize: TSize;
AState: TCDControlState; AStateEx: TCDEditStateEx); override;
end;
procedure Register;
implementation
uses
Math, Forms, Clipbrd, LCLType, LCLIntf, LazUTF8;
resourcestring
rsMnuCopyToClipboard = 'Copy';
rsMnuSelectAll = 'Select &All';
procedure Register;
begin
RegisterComponents('KASComponents', [TKASCDEdit]);
end;
{ TKASCDDrawer }
function TKASCDDrawer.GetMeasures(AMeasureID: Integer): Integer;
begin
case AMeasureID of
TCDEDIT_LEFT_TEXT_SPACING: Result := 0;
TCDEDIT_RIGHT_TEXT_SPACING: Result := 0;
else Result:= inherited GetMeasures(AMeasureID);
end;
end;
procedure TKASCDDrawer.DrawEditBackground(ADest: TCanvas; ADestPos: TPoint;
ASize: TSize; AState: TCDControlState; AStateEx: TCDEditStateEx);
begin
// The background
ADest.Pen.Style := psSolid;
ADest.Pen.Color := AStateEx.RGBColor;
ADest.Brush.Style := bsSolid;
ADest.Brush.Color := AStateEx.RGBColor;
ADest.Rectangle(0, 0, ASize.cx, ASize.cy);
end;
procedure TKASCDDrawer.DrawEdit(ADest: TCanvas; ASize: TSize;
AState: TCDControlState; AStateEx: TCDEditStateEx);
var
lVisibleText, lControlText: TCaption;
lSelLeftPos, lSelLeftPixelPos, lSelLength, lSelRightPos: Integer;
lTextWidth, lLineHeight, lLineTop: Integer;
lControlTextLen: PtrInt;
lTextLeftSpacing, lTextTopSpacing, lTextBottomSpacing: Integer;
lTextColor: TColor;
i, lVisibleLinesCount: Integer;
begin
// Background
DrawEditBackground(ADest, Point(0, 0), ASize, AState, AStateEx);
// General text configurations which apply to all lines
// Configure the text color
if csfEnabled in AState then
lTextColor := AStateEx.Font.Color
else
lTextColor := clGrayText;
ADest.Brush.Style := bsClear;
ADest.Font.Assign(AStateEx.Font);
ADest.Font.Color := lTextColor;
lTextLeftSpacing := GetMeasures(TCDEDIT_LEFT_TEXT_SPACING);
//lTextRightSpacing := GetMeasures(TCDEDIT_RIGHT_TEXT_SPACING);
lTextTopSpacing := GetMeasures(TCDEDIT_TOP_TEXT_SPACING);
lTextBottomSpacing := GetMeasures(TCDEDIT_BOTTOM_TEXT_SPACING);
lLineHeight := ADest.TextHeight(cddTestStr)+2;
lLineHeight := Min(ASize.cy-lTextBottomSpacing, lLineHeight);
// Fill this to be used in other parts
AStateEx.LineHeight := lLineHeight;
AStateEx.FullyVisibleLinesCount := ASize.cy - lTextTopSpacing - lTextBottomSpacing;
AStateEx.FullyVisibleLinesCount := AStateEx.FullyVisibleLinesCount div lLineHeight;
AStateEx.FullyVisibleLinesCount := Min(AStateEx.FullyVisibleLinesCount, AStateEx.Lines.Count);
// Calculate how many lines to draw
if AStateEx.Multiline then
lVisibleLinesCount := AStateEx.FullyVisibleLinesCount + 1
else
lVisibleLinesCount := 1;
lVisibleLinesCount := Min(lVisibleLinesCount, AStateEx.Lines.Count);
// Now draw each line
for i := 0 to lVisibleLinesCount - 1 do
begin
lControlText := AStateEx.Lines.Strings[AStateEx.VisibleTextStart.Y+i];
lControlText := VisibleText(lControlText, AStateEx.PasswordChar);
lControlTextLen := UTF8Length(lControlText);
lLineTop := lTextTopSpacing + i * lLineHeight;
// The text
ADest.Pen.Style := psClear;
ADest.Brush.Style := bsClear;
// ToDo: Implement multi-line selection
if (AStateEx.SelLength = 0) or (AStateEx.SelStart.Y <> AStateEx.VisibleTextStart.Y+i) then
begin
lVisibleText := UTF8Copy(lControlText, AStateEx.VisibleTextStart.X, lControlTextLen);
ADest.TextOut(lTextLeftSpacing, lLineTop, lVisibleText);
end
// Text and Selection
else
begin
lSelLeftPos := AStateEx.SelStart.X;
if AStateEx.SelLength < 0 then lSelLeftPos := lSelLeftPos + AStateEx.SelLength;
lSelRightPos := AStateEx.SelStart.X;
if AStateEx.SelLength > 0 then lSelRightPos := lSelRightPos + AStateEx.SelLength;
lSelLength := AStateEx.SelLength;
if lSelLength < 0 then lSelLength := lSelLength * -1;
// Text left of the selection
lVisibleText := UTF8Copy(lControlText, AStateEx.VisibleTextStart.X, lSelLeftPos-AStateEx.VisibleTextStart.X+1);
ADest.TextOut(lTextLeftSpacing, lLineTop, lVisibleText);
lSelLeftPixelPos := ADest.TextWidth(lVisibleText)+lTextLeftSpacing;
// The selection background
lVisibleText := UTF8Copy(lControlText, lSelLeftPos+1, lSelLength);
lTextWidth := ADest.TextWidth(lVisibleText);
ADest.Brush.Color := clHighlight;
ADest.Brush.Style := bsSolid;
ADest.Rectangle(Bounds(lSelLeftPixelPos, lLineTop, lTextWidth, lLineHeight));
ADest.Brush.Style := bsClear;
// The selection text
ADest.Font.Color := clHighlightText;
ADest.TextOut(lSelLeftPixelPos, lLineTop, lVisibleText);
lSelLeftPixelPos := lSelLeftPixelPos + lTextWidth;
// Text right of the selection
ADest.Brush.Color := AStateEx.RGBColor;
ADest.Font.Color := lTextColor;
lVisibleText := UTF8Copy(lControlText, lSelLeftPos+lSelLength+1, lControlTextLen);
ADest.TextOut(lSelLeftPixelPos, lLineTop, lVisibleText);
end;
end;
// And the caret
DrawCaret(ADest, Point(0, 0), ASize, AState, AStateEx);
end;
{ TKASCDEdit }
procedure TKASCDEdit.CreatePopupMenu;
var
MenuItem: TMenuItem;
begin
if not Assigned(FEditMenu) then
begin
FEditMenu:= TPopupMenu.Create(Application);
MenuItem:= TMenuItem.Create(FEditMenu);
MenuItem.Caption:= rsMnuCopyToClipboard;
MenuItem.OnClick:= MenuCopy;
FEditMenu.Items.Add(MenuItem);
MenuItem:= TMenuItem.Create(FEditMenu);
MenuItem.Caption:= '-';
FEditMenu.Items.Add(MenuItem);
MenuItem:= TMenuItem.Create(FEditMenu);
MenuItem.Caption:= rsMnuSelectAll;
MenuItem.OnClick:= MenuSelectAll;
FEditMenu.Items.Add(MenuItem);
end;
end;
procedure TKASCDEdit.ShowMenu(Data: PtrInt);
begin
FEditMenu.Tag:= Data;
FEditMenu.PopUp;
end;
procedure TKASCDEdit.MenuCopy(Sender: TObject);
begin
TKASCDEdit(TMenuItem(Sender).Owner.Tag).CopyToClipboard;
end;
procedure TKASCDEdit.MenuSelectAll(Sender: TObject);
begin
TKASCDEdit(TMenuItem(Sender).Owner.Tag).SelectAll;
end;
procedure TKASCDEdit.RealSetText(const Value: TCaption);
begin
Lines.Text := Value;
inherited RealSetText(Value);
end;
procedure TKASCDEdit.CalculatePreferredSize(var PreferredWidth,
PreferredHeight: Integer; WithThemeSpace: Boolean);
var
AWidth: Integer;
begin
if (Parent = nil) or (not Parent.HandleAllocated) then Exit;
AWidth := Constraints.MinMaxWidth(10000);
CalculateSize(AWidth, PreferredWidth, PreferredHeight);
end;
procedure TKASCDEdit.CalculateSize(MaxWidth: Integer; var NeededWidth,
NeededHeight: Integer);
var
DC: HDC;
R: TRect;
Flags: Cardinal;
OldFont: HGDIOBJ;
LabelText: String;
lTextLeftSpacing, lTextTopSpacing,
lTextBottomSpacing, lTextRightSpacing: Integer;
begin
LabelText := Text;
if LabelText = '' then
begin
NeededWidth:= 1;
NeededHeight:= 1;
Exit;
end;
lTextLeftSpacing := FDrawer.GetMeasures(TCDEDIT_LEFT_TEXT_SPACING);
lTextTopSpacing := FDrawer.GetMeasures(TCDEDIT_TOP_TEXT_SPACING);
lTextRightSpacing := FDrawer.GetMeasures(TCDEDIT_RIGHT_TEXT_SPACING);
lTextBottomSpacing := FDrawer.GetMeasures(TCDEDIT_BOTTOM_TEXT_SPACING);
DC := GetDC(Parent.Handle);
try
R := Rect(0, 0, MaxWidth, 10000);
OldFont := SelectObject(DC, HGDIOBJ(Font.Reference.Handle));
Flags := DT_CALCRECT or DT_EXPANDTABS;
if not MultiLine then Flags := Flags or DT_SINGLELINE;
DrawText(DC, PAnsiChar(LabelText), Length(LabelText), R, Flags);
SelectObject(DC, OldFont);
NeededWidth := R.Right - R.Left + lTextLeftSpacing + lTextRightSpacing;
NeededHeight := R.Bottom - R.Top + lTextTopSpacing + lTextBottomSpacing;
finally
ReleaseDC(Parent.Handle, DC);
end;
end;
procedure TKASCDEdit.KeyDown(var Key: word; Shift: TShiftState);
begin
if (ssModifier in Shift) then
begin
case Key of
VK_A:
begin
SelectAll;
Key:= 0;
end;
VK_C:
begin
CopyToClipboard;
Key:= 0;
end;
end;
end;
inherited KeyDown(Key, Shift);
end;
constructor TKASCDEdit.Create(AOwner: TComponent);
begin
CreatePopupMenu;
inherited Create(AOwner);
Color:= clForm;
ReadOnly:= True;
Cursor:= crIBeam;
DrawStyle:= dsExtra1;
end;
procedure TKASCDEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) or (GetSelLength = 0) then
inherited MouseDown(Button, Shift, X, Y)
else if Assigned(OnMouseDown) then begin
OnMouseDown(Self, Button, Shift, X, Y);
end;
end;
procedure TKASCDEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
if Button = mbRight then begin
Application.QueueAsyncCall(ShowMenu, PtrInt(Self));
end;
end;
procedure TKASCDEdit.SelectAll;
begin
FEditState.SelStart.X:= 0;
FEditState.SelLength:= UTF8Length(Text);
Invalidate;
end;
procedure TKASCDEdit.CopyToClipboard;
begin
if (FEditState.SelLength >= 0) then
Clipboard.AsText:= UTF8Copy(Text, FEditState.SelStart.X + 1, FEditState.SelLength)
else begin
Clipboard.AsText:= UTF8Copy(Text, FEditState.SelStart.X + FEditState.SelLength + 1, -FEditState.SelLength);
end;
end;
initialization
RegisterDrawer(TKASCDDrawer.Create, dsExtra1);
end.
|
unit clServicosFuncionarios;
interface
uses clConexao;
type
TFuncionariosServicos = class(TObject)
private
constructor Create;
destructor Destroy;
function getCadastro: Integer;
function getCodigo: Integer;
procedure setCadastro(const Value: Integer);
procedure setCodigo(const Value: Integer);
protected
_codigo : Integer;
_cadastro : Integer;
_conexao: TConexao;
public
property Codigo : Integer read getCodigo write setCodigo;
property Cadastro : Integer read getCadastro write setCadastro;
function Validar(): Boolean;
function Delete(filtro: String): Boolean;
function getObject(id, filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
function getField(campo, coluna: String): String;
end;
const
TABLENAME = 'TBSERVICOSFUNCIONARIOS';
implementation
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
{ TFuncionariosServicos }
function TFuncionariosServicos.getCadastro: Integer;
begin
Result := _cadastro;
end;
function TFuncionariosServicos.getCodigo: Integer;
begin
Result := _codigo;
end;
constructor TFuncionariosServicos.Create;
begin
_conexao := TConexao.Create;
end;
destructor TFuncionariosServicos.Destroy;
begin
_conexao.Free;
end;
function TFuncionariosServicos.Validar(): Boolean;
begin
try
Result := False;
if Self.Codigo = 0 then
begin
MessageDlg('Informe o código do Serviço!', mtWarning, [mbOK], 0);
Exit;
end;
if Self.Cadastro = 0 then
begin
MessageDlg('Informe o código do Funcionário!', mtWarning, [mbOK], 0);
Exit;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TFuncionariosServicos.Delete(filtro: String): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_SERVCO = :CODIGO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if filtro = 'CADASTRO' then
begin
SQL.Add('WHERE COD_CADASTRO = :CADASTRO');
ParamByName('CADASTRO').AsInteger := Self.Cadastro;
end;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TFuncionariosServicos.getObject(id, filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(id) then begin
Exit;
end;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_SERVICO = :CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(id);
end
else if filtro = 'CADASTRO' then
begin
SQL.Add('WHERE COD_CADASTRO = :CADASTRO');
ParamByName('CADASTRO').AsInteger := StrToInt(id);
end;
dm.ZConn.PingServer;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
begin
Self.Codigo := dm.QryGetObject.FieldByName('COD_SERVICO').AsInteger;
Self.Cadastro := dm.QryGetObject.FieldByName('COD_CADASTRO').AsInteger;
Result := True;
end
else
begin
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TFuncionariosServicos.Insert(): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + '(' +
'COD_SERVICO, ' +
'COD_CADASTRO) ' +
'VALUES (' +
':CODIGO, ' +
':CADASTRO);';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('CADASTRO').AsInteger := Self.Cadastro;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TFuncionariosServicos.Update(): Boolean;
begin
try
Result := False;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'COD_CADASTRO = :CADASTRO ' +
'WHERE COD_CADASTRO = :CADASTRO';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('CADASTRO').AsInteger := Self.Cadastro;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TFuncionariosServicos.getField(campo, coluna: String): String;
begin
try
Result := '';
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME;
if coluna = 'CODIGO' then
begin
SQL.Add(' WHERE COD_SERVICO = :CODIGO ');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if coluna = 'CADASTRO' then
begin
SQL.Add(' WHERE COD_CADASTRO = :CADASTRO ');
ParamByName('CADASTRO').AsString := Self.Cadastro;
end;
dm.ZConn.PingServer;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
Result := dm.QryGetObject.FieldByName(campo).AsString;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TFuncionariosServicos.setCadastro(const Value: Integer);
begin
_cadastro := Value;
end;
procedure TFuncionariosServicos.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
end.
|
unit fmuEKLZ2;
interface
uses
// VCL
Windows, StdCtrls, Controls, Classes, Forms, Sysutils, ExtCtrls, Graphics,
// This
untPages, untDriver, TestManager, untUtil;
type
TfmEKLZ2 = class(TPage)
gbStatus: TGroupBox;
Memo: TMemo;
btnGetEKLZSerialNumber: TButton;
btnGetEKLZVersion: TButton;
btnGetEKLZCode2Status: TButton;
btnGetEKLZCode1Status: TButton;
lblResultCode: TLabel;
lblEKLZResultCode: TLabel;
edtEKLZResultCode: TEdit;
btnSetEKLZResultCode: TButton;
Label1: TLabel;
Bevel1: TBevel;
procedure btnGetEKLZSerialNumberClick(Sender: TObject);
procedure btnGetEKLZCode1StatusClick(Sender: TObject);
procedure btnGetEKLZCode2StatusClick(Sender: TObject);
procedure btnGetEKLZVersionClick(Sender: TObject);
procedure btnSetEKLZResultCodeClick(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure btnSetEKLZResultCodeMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
end;
implementation
{$R *.DFM}
{ TfmEKLZ2 }
procedure TfmEKLZ2.btnGetEKLZSerialNumberClick(Sender: TObject);
begin
EnableButtons(False);
try
Memo.Clear;
Driver.Password := DriverManager.Password;
if Driver.GetEKLZSerialNumber = 0 then
begin
Memo.Lines.Add('');
Memo.Lines.Add(' Заводской номер: ' + Driver.EKLZNumber);
end;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZ2.btnGetEKLZCode1StatusClick(Sender: TObject);
procedure EKLZFlagsToMemo;
const
DocType: array [0..3] of string = ('продажа', 'покупка', 'возврат продажи', 'возврат покупки');
BS: array [Boolean] of string = ('нет', 'да');
var
Flags: Integer;
begin
Flags := Driver.EKLZFlags;
with Memo do
begin
Lines.Add(' <T> Тип документа: ' + DocType[Flags and $3]);
Lines.Add(' <I> Открыт архив: ' + BS[Flags and $4=$4]);
Lines.Add(' <F> Выполнена активизация: ' + BS[Flags and $8=$8]);
Lines.Add(' <W> Режим отчета: ' + BS[Flags and $10=$10]);
Lines.Add(' <D> Открыт документ: ' + BS[Flags and $20=$20]);
Lines.Add(' <S> Открыта смена: ' + BS[Flags and $40=$40]);
Lines.Add(' <A> Ошибка устройства: ' + BS[Flags and $80=$80]);
end;
end;
begin
EnableButtons(False);
try
Memo.Clear;
Driver.Password := DriverManager.Password;
if Driver.GetEKLZCode1Report = 0 then
begin
with Memo do
begin
Lines.Add('');
Lines.Add(' Дата : ' + DateToStr(Driver.LastKPKDate));
Lines.Add(' Время : ' + TimeToStr(Driver.LastKPKTime));
Lines.Add(' Итог : ' + CurrToStr(Driver.LastKPKDocumentResult));
Lines.Add(' Номер КПК : ' + IntToStr(Driver.LastKPKNumber));
Lines.Add(' Заводской номер ЭКЛЗ : ' + Driver.EKLZNumber);
Lines.Add(' Флаги (' + IntToStr(Driver.EKLZFlags)+')');
end;
EKLZFlagsToMemo;
// Прокручиваем Memo на начало
Memo.SelStart := 0;
Memo.SelLength := 0;
end;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZ2.btnGetEKLZCode2StatusClick(Sender: TObject);
begin
EnableButtons(False);
try
Memo.Clear;
Driver.Password := DriverManager.Password;
if Driver.GetEKLZCode2Report = 0 then
begin
with Memo do
begin
Lines.Add('');
Lines.Add(' Номер смены : ' + IntToStr(Driver.SessionNumber));
Lines.Add(' Продажа : ' + CurrToStr(Driver.Summ1));
Lines.Add(' Покупка : ' + CurrToStr(Driver.Summ2));
Lines.Add(' Возврат продаж : ' + CurrToStr(Driver.Summ3));
Lines.Add(' Возврат покупок : ' + CurrToStr(Driver.Summ4));
end;
end;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZ2.btnGetEKLZVersionClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Memo.Clear;
if Driver.GetEKLZVersion = 0 then
begin
Memo.Lines.Add('');
Memo.Lines.Add(' Версия: ' + Driver.EKLZVersion);
end;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZ2.btnSetEKLZResultCodeClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.Password := DriverManager.Password;
Driver.EKLZResultCode := StrToInt(edtEKLZResultCode.Text);
Driver.SetEKLZResultCode;
UpdatePage;
finally
EnableButtons(True);
end;
end;
procedure TfmEKLZ2.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if HighLighting then
edtEKLZResultCode.Color := clWindow;
end;
procedure TfmEKLZ2.btnSetEKLZResultCodeMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if HighLighting then
edtEKLZResultCode.Color := InColor;
end;
end.
|
unit Migrator;
interface
uses
daTypes,
htInterfaces,
htDataProviderParams,
pgConnection,
pgDataProviderParams,
pgCommandExecutor
;
type
TReportCallback = procedure (const aStr: String; WriteToLog: Boolean) of object;
TMigrator = class(TObject)
private
f_CallBack: TReportCallback;
f_Connection: TpgConnection;
f_Executor: TpgCommandExecutor;
f_PostgresParams: TpgDataProviderParams;
f_Helper: IhtDataSchemeHelper;
f_StoredProcPath: String;
function Report(const aStr: String; WriteToLog: Boolean = False): String;
procedure InitHT;
procedure CloseHT;
procedure RecreateDataBase;
procedure RecreateSchema;
procedure LoadParams;
procedure SaveParams;
procedure MigrateTables;
procedure MigrateTable(aKind: TdaTables); overload;
function HTKey2SQL(aHTKey: Byte): string;
procedure MigrateForeignKeys;
procedure MigrateProcedures;
procedure CreateProcedure(const aProcName: String);
public
constructor Create; reintroduce;
destructor Destroy; override;
procedure Migrate;
property ReportCallBack: TReportCallback read f_CallBack write f_CallBack;
property PostrgesParams: TpgDataProviderParams read f_PostgresParams;
property StoredProcPath: String read f_StoredProcPath write f_StoredProcPath;
end;
implementation
uses
Windows,
SysUtils,
Classes,
l3Types,
l3Base,
l3StopWatch,
l3FileUtils,
l3Stream,
l3Tree_TLB,
l3TreeInterfaces,
l3Nodes,
l3IniFile,
Ht_Const,
Ht_DLL,
dt_Table,
dt_dictTree,
daInterfaces,
daScheme,
daDataProviderSuperFactory,
htDataSchemeHelper;
const
cPostgresSection = 'Postgres.Data';
cStoredProcPath = 'StoredProcPath';
{ TMigrator }
constructor TMigrator.Create;
begin
inherited Create;
f_Connection := TpgConnection.Create(nil);
f_Executor := TpgCommandExecutor.Create(f_Connection);
LoadParams;
end;
destructor TMigrator.Destroy;
begin
FreeAndNil(f_Executor);
FreeAndNil(f_Connection);
FreeAndNil(f_PostgresParams);
inherited;
end;
procedure TMigrator.RecreateDataBase;
begin
Report('Recreate database');
f_Connection.ConnectAs(PostrgesParams.Login, PostrgesParams.Password, 'postgres', PostrgesParams);
try
f_Executor.Execute(Format('DROP DATABASE IF EXISTS %s;', [cDefaultSchemeName]));
f_Executor.Execute(Format('CREATE DATABASE %s WITH TEMPLATE=template0 ENCODING=''WIN1251'' LC_COLLATE=''Russian_Russia.1251'' LC_CTYPE=''Russian_Russia.1251'';', [cDefaultSchemeName]));
finally
f_Connection.Disconnect;
end;
end;
procedure TMigrator.Migrate;
var
l_Watch: Tl3StopWatch;
l_WasError: Boolean;
begin
Report(Format('Start convertation at %s ', [FormatDateTime('dd.mm.yyyy hh:nn:ss', Now)]), True);
l_Watch.Reset;
l_Watch.Start;
try
l_WasError := False;
try
InitHT;
try
RecreateDataBase;
f_Connection.ConnectAs(PostrgesParams.Login, PostrgesParams.Password, cDefaultSchemeName, PostrgesParams);
try
Report('Connect to postgres');
RecreateSchema;
MigrateTables;
MigrateForeignKeys;
MigrateProcedures;
finally
f_Connection.Disconnect;
Report('Disconnect from postgres');
end;
finally
try
CloseHT;
except
end;
end;
SaveParams;
except
on E: Exception do
begin
Report(Format('ERROR!! %s', [E.Message]));
l3System.Exception2Log(E);
l_WasError := True;
end;
end;
finally
l_Watch.Stop;
if l_WasError then
Report(Format('FAILED. Elapsed %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
else
Report(Format('All done in %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True);
end;
end;
function TMigrator.Report(const aStr: String; WriteToLog: Boolean = False): String;
begin
Result := aStr;
if Assigned(f_CallBack) then
f_CallBack(aStr, WriteToLog);
end;
procedure TMigrator.SaveParams;
begin
TdaDataProviderSuperFactory.Instance.FindFactoryByParamType(TpgDataProviderParams.ParamsKey).SaveToConfig(f_PostgresParams);
StationConfig.Section := cPostgresSection;
StationConfig.WriteParamStr(cStoredProcPath, f_StoredProcPath);
end;
procedure TMigrator.RecreateSchema;
begin
f_Executor.Execute(Format('DROP SCHEMA IF EXISTS "%s" CASCADE;', [cDefaultSchemeName]));
f_Executor.Execute('VACUUM FULL');
f_Executor.Execute(Format('CREATE SCHEMA IF NOT EXISTS "%s" AUTHORIZATION postgres;', [cDefaultSchemeName]));
end;
procedure TMigrator.CloseHT;
begin
htShut;
htGlobalShut;
end;
procedure fn_OnIOError(fpFileName: PChar;
nIoCode: SmallInt;
nDosError: SmallInt); stdcall;
var
l_Buff220: array[0..220] of Char;
begin
htIOMessage(@l_Buff220);
raise Exception.Create(StrPas(l_Buff220) + StrPas(fpFileName));
end;
procedure fn_OnHtError(nMessID: SmallInt); stdcall;
var
l_Buff220: array[0..220] of Char;
begin
// игнорируемые ошибки
if nMessID in [
72, // "Таблица задействована в транзакциях" (это вовсе не ошибка)
25 // "Unique key doublet value found" - возникает при изменении записи,
// при этом дубликаты удаляются автоматически, так что можно не беспокоиться
] then
Exit;
htMessage(nMessID, @l_Buff220);
raise Exception.Create(StrPas(l_Buff220) + ' Код ошибки: ' + IntToStr(nMessID));
end;
procedure TMigrator.InitHT;
var
l_Init :Init;
begin
if not DirectoryExists(PostrgesParams.DocStoragePath) then
raise Exception.Create('Database not found');
if not DirectoryExists(ConcatDirName(PostrgesParams.DocStoragePath, 'MAIN')) then
raise Exception.Create('Database not found');
if not DirectoryExists(ConcatDirName(PostrgesParams.DocStoragePath, 'GARANT')) then
raise Exception.Create('Database not found');
l3FillChar(l_Init, SizeOf(l_Init));
with l_Init do
begin
nTableCnt := 50;
nTaskCnt := 20;
nHtCnt := 4 + 20 * 6 + 1;
nLockTimeOut := 40;
nPollDelay := 40;
nTransTimeOut := 40;
nTrsMode := TRS_HARD;
fpTmpPath := PChar(PostrgesParams.DocStoragePath);
fpNetPath := PChar(PostrgesParams.DocStoragePath);
fpTrtPath := PChar(PostrgesParams.DocStoragePath);
fpNetName := 'pgMigrate';
fpfInfo := Pointer(-1);
fpfIoMess := @fn_OnIOError;
fpfErrMess := @fn_OnHtError;
fpfPiStart := Pointer(-1);
fpfPiDraw := Pointer(-1);
fpfPiStop := Pointer(-1);
fpfYield := Pointer(-1);
gHeapCtrl := 10000000;
gHeapTask := 120000;
end;
htGlobalInit(HInstance);
htInit(@l_Init, SizeOf(l_Init));
end;
procedure TMigrator.MigrateTables;
var
l_IDX: TdaTables;
l_HitechParams: ThtDataProviderParams;
begin
l_HitechParams := TdaDataProviderSuperFactory.Instance.FindFactoryByParamType(ThtDataProviderParams.ParamsKey).MakeFromConfig as ThtDataProviderParams;
try
l_HitechParams.ChangeBasePath(f_PostgresParams.DocStoragePath);
f_Helper := ThtDataSchemeHelper.Make(l_HitechParams);
try
for l_IDX := Low(TdaTables) to High(TdaTables) do
MigrateTable(l_IDX);
finally
f_Helper := nil;
end;
finally
FreeAndNil(l_HitechParams);
end;
end;
function TMigrator.HTKey2SQL(aHTKey : Byte) : string;
begin
case aHTKey of
EK_NOTKEY: (* Элемент не ключ *)
Result := '';
EK_COMMON: (* Обычный ключ *)
Result := '';
EK_UNIQUE : (* Уникальный ключ *)
Result := 'UNIQUE';
end;
end;
procedure TMigrator.MigrateTable(aKind: TdaTables);
var
l_HTTable: String;
l_HTTableOut: String;
l_Table: TdtTable;
l_TableDesc: IdaTableDescription;
l_SQLString: String;
l_FullTableName: String;
l_IsFirst: Boolean;
l_CommandStr: String;
l_Watch: Tl3StopWatch;
l_TreeWatch: Tl3StopWatch;
l_IDX: Integer;
l_FldName: String;
procedure lp_AddToCommand(const aStr: String);
begin
if l_CommandStr <> '' then
l_CommandStr := l_CommandStr + #13#10;
l_CommandStr := l_CommandStr + aStr;
end;
function lp_HTType2SQL(const aField: IdaFieldDescription): String;
const
cMap: array [TdaDataType] of String = (
'varchar', //da_dtChar
'smallint', //da_dtByte
'int4', //da_dtDate
'int4', //da_dtTime
'int4', //da_dtDWord
'int2', //da_dtWord
'int4', //da_dtInteger
'bool', //da_dtBoolean
'int8' //da_dtQWord
);
begin
Result := cMap[aField.DataType];
if aField.DataType = da_dtChar then
Result := Format('%s(%d)', [Result, aField.Size]);
end;
function lp_BuildFields(aField: IdaFieldDescription): Boolean;
var
l_FldName: String;
const
cNullMap: array [Boolean] of String = ('NULL', 'NOT NULL');
begin
Result := True;
if l_SQLString <> '' then
l_SQLString := l_SQLString + ','#13#10;
l_FldName := aField.SQLName;
l_SQLString := l_SQLString + ' ' + l_FldName + ' ' + lp_HTType2SQL(aField) + ' ' + cNullMap[aField.Required];
end;
function lp_GetFieldsOfGroup(aElemIdx : word) : string;
var
I : Integer;
l_S: String;
begin
Result := '';
with l_Table, Element[aElemIdx] do
for I := 0 to Pred(wLength) do
begin
Result := Result + l_TableDesc.FieldByIndex(wOffset + I).SQLName;
if I < Pred(wLength) then
Result := Result + ','
end;
end;
procedure lp_ExportTreeToFile(const aHTTable : String);
var
lStream : Tl3TextStream;
lTreeStruct : TTreeStrorage;
lRootNode : Il3Node;
function IterHandler_MakeTreeInfo(const CurNode : Il3Node) : Boolean; far;
var
l_S: AnsiString;
begin
Result := False;
with CurNode, (CurNode as Il3HandleNode) do
begin
l_S := Format('%d'#9'%d'#9'%d'#13#10,[Handle, (Parent as Il3HandleNode).Handle, GetNumInParent(True)]);
lStream.Write(l_S[1], Length(l_S));
end;
end;
begin
lTreeStruct := TTreeStrorage.Create(ChangeFileExt(aHTTable, ''));
try
//lTreeStruct.ChildNodeClass:=fChildNodeClass;
lRootNode := Tl3UsualNode.Make;
try
lTreeStruct.Load(lRootNode);
lStream := Tl3TextStream.Create(ChangeFileExt(aHTTable, '.tree'), l3_fmCreateReadWrite);
try
lRootNode.IterateF(l3L2NA(@IterHandler_MakeTreeInfo), 0);
finally
lStream.Free;
end;
finally
lRootNode := nil;
end;
finally
l3Free(lTreeStruct);
end;
end;
const
cMap: array [Boolean] of Integer = (0, 2);
begin
if aKind in [da_mtControl, da_ftNone, da_ftControl, da_ftDocumentsDub1, da_ftDocumentsDub2] then
Exit;
l_HTTable := f_Helper.TableFullPath(aKind);
Report('Table : ' + l_HTTable, True);
if (aKind in [da_ftAutolinkDocumentsLocal, da_ftAutolinkEditionsLocal, da_ftAutolinkDocumentsRemote, da_ftAutolinkEditionsRemote]) and
not FileExists(ChangeFileExt(l_HTTable, '.htb')) then
begin
Report('Autolinker table not exists - skipping');
Exit;
end;
l_HTTableOut := ChangeFileExt(l_HTTable, '.txt');
l_Table := TdtTable.CreateWithOpen(ExtractFilePath(l_HTTable), f_Helper.TablePassword(aKind), ExtractOnlyFileName(l_HTTable), TAB_SHARE);
l_TableDesc := TdaScheme.Instance.Table(aKind);
try
l_FullTableName := Format('%s.%s', [cDefaultSchemeName, l_TableDesc.SQLName]);
l_CommandStr := '';
lp_AddToCommand(Report('CREATE TABLE ' + l_FullTableName + ' ('));
Assert(l_TableDesc.FieldsCountWithoutTree = l_Table.fldCount, 'Не совпадает структура таблиц');
l_SQLString := '';
l_TableDesc.IterateFieldsF(L2DaTableDescriptionIteratorIterateFieldsFAction(@lp_BuildFields));
l_SQLString := l_SQLString + #13#10');';
lp_AddToCommand(Report(l_SQLString));
l_Watch.Reset;
l_Watch.Start;
try
f_Executor.Execute(l_CommandStr);
finally
l_Watch.Stop;
Report(Format('ExecSQL time : %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end;
Report('ExportToFile');
l_Watch.Reset;
l_Watch.Start;
try
l_Table.ExportToFile(l_HTTableOut, #0, #9, cMap[l_TableDesc.IsTree]);
finally
l_Watch.Stop;
Report(Format('ExportToFile time : %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end;
l_Watch.Reset;
l_Watch.Start;
try
f_Executor.Execute(Report('COPY '+ l_FullTableName + ' FROM ''' + l_HTTableOut + ''' WITH (ENCODING ''Win1251'', NULL ''~~~NULL~~~'')'));
finally
l_Watch.Stop;
Report(Format('ExecSQL time : %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end;
// CREATE INDEX
l_Watch.Reset;
l_Watch.Start;
try
l_IsFirst := True;
l_CommandStr := '';
for l_IDX := 1 to l_Table.fldCount do
begin
l_FldName := l_TableDesc.FieldByIndex(l_IDX).SQLName;
if l_Table.ElementKeyKind[l_IDX] = EK_UNIQUE then
begin
if l_IsFirst then
begin
lp_AddToCommand(Report(Format('ALTER TABLE %s ADD PRIMARY KEY (%s);',[l_FullTableName, l_FldName])));
l_IsFirst := False;
end
else
lp_AddToCommand(Report(Format('ALTER TABLE %s ADD UNIQUE (%s);',[l_FullTableName, l_FldName])));
end
else
if l_Table.ElementKeyKind[l_IDX] = EK_COMMON then
lp_AddToCommand(Report(Format('CREATE INDEX %s_%s ON %s (%s);',[l_TableDesc.SQLName, l_FldName, l_FullTableName, l_FldName])));
end;
for l_IDX := (l_Table.fldCount + 1) to l_Table.ElementsCount do
begin
l_FldName := l_Table.ElementName[l_IDX];
if (l_Table.ElementKeyKind[l_IDX] = EK_UNIQUE) and (aKind <> da_ftPiblishedIn) then
lp_AddToCommand(Report(Format('CREATE UNIQUE INDEX %s_%s ON %s (%s);',[l_TableDesc.SQLName, l_FldName, l_FullTableName, lp_GetFieldsOfGroup(l_IDX)])))
else
lp_AddToCommand(Report(Format('CREATE INDEX %s_%s ON %s (%s);',[l_TableDesc.SQLName, l_FldName, l_FullTableName, lp_GetFieldsOfGroup(l_IDX)])));
end;
if l_CommandStr <> '' then
f_Executor.Execute(l_CommandStr);
finally
l_Watch.Stop;
Report(Format('Create index time : %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end; // CREATE INDEX
//Укладываем дерево в таблицу
if l_TableDesc.IsTree then
begin
l_TreeWatch.Reset;
l_TreeWatch.Start;
try
lp_ExportTreeToFile(l_HTTable);
l_CommandStr := '';
lp_AddToCommand(Report('DROP TABLE IF EXISTS TREE;'));
lp_AddToCommand(Report('CREATE TEMP TABLE TREE (ID int8, ParentID int8, OrderNum int8);'));
lp_AddToCommand(Report('COPY TREE FROM ''' + ChangeFileExt(l_HTTable, '.tree') + ''';'));
lp_AddToCommand(Report(Format('UPDATE %s d SET ParentID = t.ParentID, OrderNum = t.OrderNum FROM TREE t WHERE t.ID = d.ID;',[l_FullTableName])));
lp_AddToCommand(Report(Format('CREATE INDEX %s_order ON %s (ParentID, OrderNum);',[l_TableDesc.SQLName, l_FullTableName])));
l_Watch.Reset;
l_Watch.Start;
try
f_Executor.Execute(l_CommandStr);
finally
l_Watch.Stop;
Report(Format('ExecSQL time : %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end;
finally
l_TreeWatch.Stop;
Report(Format('Make tree data time : %s ms', [FormatFloat('#,###', l_TreeWatch.Time * 1000)]), True)
end;
end; //Укладываем дерево в таблицу
finally
l_TableDesc := nil;
l_Table.CloseTbl;
FreeAndNil(l_Table);
end;
end;
procedure TMigrator.MigrateForeignKeys;
begin
// Do nothing yet
end;
procedure TMigrator.MigrateProcedures;
var
l_IDX: Integer;
begin
for l_IDX := 0 to TdaScheme.Instance.StoredProcsCount - 1 do
CreateProcedure(TdaScheme.Instance.StoredProcName(l_IDX));
end;
procedure TMigrator.LoadParams;
begin
f_PostgresParams := TdaDataProviderSuperFactory.Instance.FindFactoryByParamType(TpgDataProviderParams.ParamsKey).MakeFromConfig as TpgDataProviderParams;
StationConfig.Section := cPostgresSection;
f_StoredProcPath := StationConfig.ReadParamStrDef(cStoredProcPath, '');
end;
procedure TMigrator.CreateProcedure(const aProcName: String);
var
l_Watch: Tl3StopWatch;
l_Name: String;
l_Text: TStringList;
begin
l_Watch.Reset;
l_Watch.Start;
try
Report('Create proc ' + aProcName, True);
l_Name := ConcatDirName(f_StoredProcPath, aProcName + '.sql');
if not FileExists(l_Name) then
raise Exception.CreateFmt('Source for stored proc %s not found (file %s)',[aProcName, l_Name]);
l_Text := TStringList.Create;
try
l_Text.LoadFromFile(l_Name);
f_Executor.Execute(Report(l_Text.Text, True));
finally
FreeAndNil(l_Text);
end;
finally
l_Watch.Stop;
Report(Format('ExecSQL %s ms', [FormatFloat('#,###', l_Watch.Time * 1000)]), True)
end;
end;
end.
|
unit tfwDictionaryEx;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwDictionaryEx.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TtfwDictionaryEx" MUID: (559E8B2E0385)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwDictionaryExPrim
, tfwScriptingInterfaces
, tfwDictionaryPtrList
, l3Interfaces
, tfwStreamFactory
, tfwInitCodeWord
, tfwDictionary
, tfwInitedDictionariesList
;
type
TtfwDictionaryEx = class(TtfwDictionaryExPrim)
private
f_UsedDictionaries: TtfwDictionaryPtrList;
f_FileName: Il3CString;
f_FileDateTime: TDateTime;
f_Stream: TtfwStreamFactory;
f_InitCode: TtfwInitCodeWord;
f_ExportedDictionaries: TtfwDictionaryPtrList;
protected
function FindInUsedDictionary(anOther: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord; virtual;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function DoCheckWord(const aName: Il3CString): TtfwKeyWord; override;
function DoGetDRbyCName(const aName: Il3CString): TtfwKeyWord; override;
procedure ClearFields; override;
public
procedure RunInitCode(aRunned: TtfwInitedDictionariesList;
const aCtx: TtfwContext); virtual;
procedure EnterCode(const aCtx: TtfwContext);
procedure LeaveCode(const aCtx: TtfwContext);
procedure UseDictionary(aDictionary: TtfwDictionaryEx);
constructor Create(aFile: TtfwStreamFactory;
const aUsed: array of TtfwDictionaryEx); reintroduce; overload;
procedure ExportDictionary(aDictionary: TtfwDictionaryEx);
constructor Create(const aFileName: Il3CString;
const aUsed: array of TtfwDictionaryEx); reintroduce; overload;
procedure AddCodePart(aWord: TtfwWord;
const aCtx: TtfwContext;
aSNI: TtfwSuppressNextImmediate);
{* Добавляет скомпилированный код к текущему компилируемуму слову }
function IsValidCode: Boolean; override;
function UsesDictionary(anOther: TtfwDictionaryExPrim): Boolean; override;
public
property UsedDictionaries: TtfwDictionaryPtrList
read f_UsedDictionaries;
property FileName: Il3CString
read f_FileName;
property FileDateTime: TDateTime
read f_FileDateTime;
property Stream: TtfwStreamFactory
read f_Stream;
property InitCode: TtfwInitCodeWord
read f_InitCode;
property ExportedDictionaries: TtfwDictionaryPtrList
read f_ExportedDictionaries;
end;//TtfwDictionaryEx
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, SysUtils
, Math
, tfwAutoregisteredDiction
, l3String
, tfwDictionaryExWordsPack
//#UC START# *559E8B2E0385impl_uses*
//#UC END# *559E8B2E0385impl_uses*
;
function TtfwDictionaryEx.FindInUsedDictionary(anOther: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
//#UC START# *55A3A1E7038F_559E8B2E0385_var*
//#UC END# *55A3A1E7038F_559E8B2E0385_var*
begin
//#UC START# *55A3A1E7038F_559E8B2E0385_impl*
Result := anOther.OwnDRbyCName(aName);
//#UC END# *55A3A1E7038F_559E8B2E0385_impl*
end;//TtfwDictionaryEx.FindInUsedDictionary
procedure TtfwDictionaryEx.RunInitCode(aRunned: TtfwInitedDictionariesList;
const aCtx: TtfwContext);
//#UC START# *55A3BF0502F8_559E8B2E0385_var*
var
l_Index : Integer;
l_D : TtfwDictionary;
l_KW : TtfwKeyWord;
l_W : TtfwWord;
//#UC END# *55A3BF0502F8_559E8B2E0385_var*
begin
//#UC START# *55A3BF0502F8_559E8B2E0385_impl*
if (aRunned.IndexOf(Self) < 0) then
begin
aCtx.rStoredValuesStack.StoreDictionary(Self, aCtx);
// - сохраняем значения переменных
aRunned.Add(Self);
// Сначала ЧИСТИМ СВОИ переменные
for l_Index := 0 to Pred(Self.Count) do
begin
l_KW := TtfwKeyWord(Self.Items[l_Index]);
if (l_KW.Dictionary = Self) then
begin
l_W := l_KW.Word;
if l_W.IsVarLike AND not l_W.IsGlobalVar then
l_W.InitValue(aCtx);
end;//l_KW.Dictionary = Self
end;//for l_Index
// Потом вызываем других
if (f_UsedDictionaries <> nil) then
for l_Index := 0 to Pred(f_UsedDictionaries.Count) do
begin
l_D := f_UsedDictionaries.Items[l_Index];
if (l_D Is TtfwDictionaryEx) then
TtfwDictionaryEx(l_D).RunInitCode(aRunned, aCtx);
end;//for l_Index
if (f_InitCode <> nil) then
f_InitCode.DoIt(aCtx);
end;//aRunned.IndexOf(Self) < 0
//#UC END# *55A3BF0502F8_559E8B2E0385_impl*
end;//TtfwDictionaryEx.RunInitCode
procedure TtfwDictionaryEx.EnterCode(const aCtx: TtfwContext);
//#UC START# *55A5294A01E9_559E8B2E0385_var*
//#UC END# *55A5294A01E9_559E8B2E0385_var*
begin
//#UC START# *55A5294A01E9_559E8B2E0385_impl*
Assert(false, 'Недоделано');
//#UC END# *55A5294A01E9_559E8B2E0385_impl*
end;//TtfwDictionaryEx.EnterCode
procedure TtfwDictionaryEx.LeaveCode(const aCtx: TtfwContext);
//#UC START# *55A5295C02AD_559E8B2E0385_var*
//#UC END# *55A5295C02AD_559E8B2E0385_var*
begin
//#UC START# *55A5295C02AD_559E8B2E0385_impl*
Assert(false, 'Недоделано');
//#UC END# *55A5295C02AD_559E8B2E0385_impl*
end;//TtfwDictionaryEx.LeaveCode
procedure TtfwDictionaryEx.UseDictionary(aDictionary: TtfwDictionaryEx);
//#UC START# *559F5EBA0249_559E8B2E0385_var*
var
l_Index : Integer;
l_D : TtfwDictionaryEx;
//#UC END# *559F5EBA0249_559E8B2E0385_var*
begin
//#UC START# *559F5EBA0249_559E8B2E0385_impl*
if (aDictionary = Self) then
Exit;
Assert(not aDictionary.IsMain);
if (f_UsedDictionaries = nil) then
f_UsedDictionaries := TtfwDictionaryPtrList.Create;
if (f_UsedDictionaries.IndexOf(aDictionary) < 0) then
f_UsedDictionaries.Add(aDictionary);
if (aDictionary.ExportedDictionaries <> nil) then
for l_Index := 0 to Pred(aDictionary.ExportedDictionaries.Count) do
begin
l_D := aDictionary.ExportedDictionaries.Items[l_Index] As TtfwDictionaryEx;
if (f_UsedDictionaries.IndexOf(l_D) < 0) then
f_UsedDictionaries.Add(l_D);
end;//for l_Index
//#UC END# *559F5EBA0249_559E8B2E0385_impl*
end;//TtfwDictionaryEx.UseDictionary
constructor TtfwDictionaryEx.Create(aFile: TtfwStreamFactory;
const aUsed: array of TtfwDictionaryEx);
//#UC START# *55A54B4C03BC_559E8B2E0385_var*
//#UC END# *55A54B4C03BC_559E8B2E0385_var*
begin
//#UC START# *55A54B4C03BC_559E8B2E0385_impl*
Assert(aFile <> nil);
aFile.SetRefTo(f_Stream);
Create(TtfwCStringFactory.C(f_Stream.FileName), aUsed);
if (f_Stream <> nil) then
f_FileDateTime := f_Stream.FileDateTime;
//#UC END# *55A54B4C03BC_559E8B2E0385_impl*
end;//TtfwDictionaryEx.Create
procedure TtfwDictionaryEx.ExportDictionary(aDictionary: TtfwDictionaryEx);
//#UC START# *55AE59580215_559E8B2E0385_var*
//#UC END# *55AE59580215_559E8B2E0385_var*
begin
//#UC START# *55AE59580215_559E8B2E0385_impl*
if (aDictionary = Self) then
Exit;
Assert(not aDictionary.IsMain);
if (f_ExportedDictionaries = nil) then
f_ExportedDictionaries := TtfwDictionaryPtrList.Create;
if (f_ExportedDictionaries.IndexOf(aDictionary) < 0) then
begin
f_ExportedDictionaries.Add(aDictionary);
end;//f_ExportedDictionaries.IndexOf(aDictionary) < 0
//#UC END# *55AE59580215_559E8B2E0385_impl*
end;//TtfwDictionaryEx.ExportDictionary
constructor TtfwDictionaryEx.Create(const aFileName: Il3CString;
const aUsed: array of TtfwDictionaryEx);
//#UC START# *55B0E69B0385_559E8B2E0385_var*
var
l_Index : Integer;
//#UC END# *55B0E69B0385_559E8B2E0385_var*
begin
//#UC START# *55B0E69B0385_559E8B2E0385_impl*
f_FileName := aFileName;
f_FileDateTime := 0;
for l_Index := Low(aUsed) to High(aUsed) do
UseDictionary(aUsed[l_Index]);
if (f_InitCode = nil) then
f_InitCode := TtfwInitCodeWord.Create(Self);
inherited Create;
//#UC END# *55B0E69B0385_559E8B2E0385_impl*
end;//TtfwDictionaryEx.Create
procedure TtfwDictionaryEx.AddCodePart(aWord: TtfwWord;
const aCtx: TtfwContext;
aSNI: TtfwSuppressNextImmediate);
{* Добавляет скомпилированный код к текущему компилируемуму слову }
//#UC START# *4DB6E3090290_559E8B2E0385_var*
//#UC END# *4DB6E3090290_559E8B2E0385_var*
begin
//#UC START# *4DB6E3090290_559E8B2E0385_impl*
if (f_InitCode = nil) then
f_InitCode := TtfwInitCodeWord.Create(Self);
f_InitCode.AddCodePart(aWord, aCtx, aSNI);
//#UC END# *4DB6E3090290_559E8B2E0385_impl*
end;//TtfwDictionaryEx.AddCodePart
procedure TtfwDictionaryEx.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_559E8B2E0385_var*
//#UC END# *479731C50290_559E8B2E0385_var*
begin
//#UC START# *479731C50290_559E8B2E0385_impl*
FreeAndNil(f_UsedDictionaries);
FreeAndNil(f_ExportedDictionaries);
FreeAndNil(f_InitCode);
FreeAndNil(f_Stream);
inherited;
//#UC END# *479731C50290_559E8B2E0385_impl*
end;//TtfwDictionaryEx.Cleanup
function TtfwDictionaryEx.DoCheckWord(const aName: Il3CString): TtfwKeyWord;
//#UC START# *4F465D580021_559E8B2E0385_var*
(*var
i : Integer;
l_KW : TTfwKeyWord;*)
//#UC END# *4F465D580021_559E8B2E0385_var*
begin
//#UC START# *4F465D580021_559E8B2E0385_impl*
(* if not IsAxiom then
begin
if TtfwAutoregisteredDiction.Instance.FindData(l3PCharLen(aName), i) then
begin
l_KW := TtfwAutoregisteredDiction.Instance.Items[i] As TTfwKeyWord;
Assert((l_KW.Word = nil) OR l_KW.Word.IsForwardDeclaration,
Format('Слово %s уже существует в базовой аксиоматике', [l3Str(aName)]));
end;//TtfwAutoregisteredDiction.Instance.FindData(l3PCharLen(aName), i)
end;//not IsAxiom*)
Result := inherited DoCheckWord(aName);
//#UC END# *4F465D580021_559E8B2E0385_impl*
end;//TtfwDictionaryEx.DoCheckWord
function TtfwDictionaryEx.DoGetDRbyCName(const aName: Il3CString): TtfwKeyWord;
//#UC START# *559FF0210296_559E8B2E0385_var*
var
l_Index : Integer;
//#UC END# *559FF0210296_559E8B2E0385_var*
begin
//#UC START# *559FF0210296_559E8B2E0385_impl*
Result := inherited DoGetDRbyCName(aName);
if (Result = nil) OR (Result.Word = nil) then
if (f_UsedDictionaries <> nil) then
for l_Index := Pred(f_UsedDictionaries.Count) downto 0 do
begin
Result := FindInUsedDictionary(f_UsedDictionaries.Items[l_Index], aName);
if (Result <> nil) then
Exit;
end;//for l_Index
//#UC END# *559FF0210296_559E8B2E0385_impl*
end;//TtfwDictionaryEx.DoGetDRbyCName
function TtfwDictionaryEx.IsValidCode: Boolean;
//#UC START# *55A3E53A00A8_559E8B2E0385_var*
//#UC END# *55A3E53A00A8_559E8B2E0385_var*
begin
//#UC START# *55A3E53A00A8_559E8B2E0385_impl*
Result := inherited IsValidCode;
if Result then
if (f_Stream <> nil) then
Result := SameValue(f_FileDateTime, f_Stream.FileDateTime);
//#UC END# *55A3E53A00A8_559E8B2E0385_impl*
end;//TtfwDictionaryEx.IsValidCode
function TtfwDictionaryEx.UsesDictionary(anOther: TtfwDictionaryExPrim): Boolean;
//#UC START# *55A4FD6401D3_559E8B2E0385_var*
var
l_Index : Integer;
//#UC END# *55A4FD6401D3_559E8B2E0385_var*
begin
//#UC START# *55A4FD6401D3_559E8B2E0385_impl*
Result := inherited UsesDictionary(anOther);
if not Result then
if (f_UsedDictionaries <> nil) then
for l_Index := 0 to Pred(f_UsedDictionaries.Count) do
if (anOther = f_UsedDictionaries[l_Index]) then
begin
Result := true;
Exit;
end;//anOther = f_UsedDictionaries[l_Index]
//#UC END# *55A4FD6401D3_559E8B2E0385_impl*
end;//TtfwDictionaryEx.UsesDictionary
procedure TtfwDictionaryEx.ClearFields;
begin
f_FileName := nil;
inherited;
end;//TtfwDictionaryEx.ClearFields
{$IfEnd} // NOT Defined(NoScripts)
end.
|
{ CSI 1101-X, Winter, 1999 }
{ Assignment 1-P }
{ Identification: Mark Sattolo, student# 428500 }
{ tutorial group DGD-4, t.a. = Manon Sanscartier }
program a1 (input,output) ;
label 170;
const
points_nowhere = nil ;
type
element = real ;
pointer = ^node ;
node = record
value: element ;
next: pointer
end ;
list = record
first: pointer ;
size: integer ;
end;
{ variable for the main program - NOT to be referenced anywhere else }
var YESorNO: char ;
{************************************************************}
procedure create_empty ( var L: list ) ; { sets list L to be empty. }
begin
L.first := points_nowhere ;
L.size := 0 ;
end ;
procedure write_list ( var L:list ) ;
var p: pointer ;
begin
if L.size = 0 then
writeln('empty list')
else
begin
p := L.first ;
while p <> points_nowhere do
begin
write( ' ', p^.value:7:2 ) ;
p := p^.next ;
end ; { while }
writeln;
writeln('Size of List is: ', L.size, '.') ;
end ; { else }
end ; { procedure }
procedure insert_at_front(var L:list; V: element) ;
var
p: pointer;
begin
New(p) ;
p^.value := V ;
p^.next := L.first ;
L.first := p ;
L.size := L.size + 1 ;
end; { procedure }
procedure insert_after_P(var L:list; V: element; P:pointer) ;
var
q, r : pointer ;
PointerCheck: boolean ;
begin
if (L.size = 0) then
begin
writeln('Error: The list provided is empty.') ;
goto 170 ; { halt }
end { if }
else
begin
r := L.first ;
PointerCheck := (p = r) ;
while (NOT PointerCheck) and (r^.next <> nil) do
begin
r := r^.next ;
PointerCheck := (p = r) ;
end ; { while }
if NOT PointerCheck then
begin
writeln('Error: Pointer provided does not point to an element in this list.') ;
goto 170 ; { halt }
end { if NOT PtrChk }
else
begin
New(q) ;
q^.value := V ;
q^.next := p^.next ;
p^.next := q ;
L.size := L.size + 1 ;
end ; { else }
end ; { else }
end; { procedure }
procedure pointer_to_Nth(var L:list; N: integer; var P:pointer);
var
counter: integer;
begin
if (N < 1) or (N > L.size) then
begin
writeln('Error: Position "', N, '" is outside the range [0 - ', L.size, '] of the list.');
goto 170; { halt }
end { if }
else
begin
p := L.first;
for counter := 1 to N-1 do
p := p^.next;
end; { else }
end; { procedure }
procedure assignment1 ;
var L:list ;
P: pointer ;
position: integer ;
val: element ;
done: boolean ;
begin
create_empty( L ) ;
repeat
writeln('enter a position (0 to ', L.size:0, ') and number (empty line to quit)' ) ;
done := eoln ;
if not done then
begin
readln(position, val) ;
if position = 0 then
insert_at_front(L, val)
else
begin
pointer_to_Nth(L, position, P);
insert_after_P(L, val, P)
end ; { else }
writeln;
writeln('here is the list after this insertion:');
write_list( L );
writeln;
end { if not done }
else readln { clear the empty line }
until done
end; { procedure }
{**** CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF ****}
procedure identify_myself ; { Writes who you are to the screen }
begin
writeln ;
writeln('CSI 1101-X (winter, 1999). Assignment #1-P.') ;
writeln('Mark Sattolo, student# 428500.') ;
writeln('tutorial section DGD-4, t.a. = Manon Sanscartier');
writeln
end ;
begin { main program }
identify_myself ;
repeat
assignment1 ;
170: writeln('Do you wish to continue (y or n) ?') ;
readln(YESorNO) ;
until (YESorNO <> 'y') ;
end.
|
unit ifelLotto;
interface
uses
Collection;
const
TICKET_LEN = 3;
TICKET_MAX = 20;
TICKET_PRICE = 100000000;
IFEL_PERC = 50;
TWO_WIN_PERC = 10;
type
TLottoTicket = class;
TLottoSystem = class;
TLottoTicket =
class
public
constructor Create(anOwner : TObject); overload;
constructor Create(anOwner : TObject; str : string); overload;
protected
procedure GenerateTicket;
procedure Sort;
private
fOwner : TObject;
fNumbers : array[0..TICKET_LEN-1] of byte;
private
function GetNumber(index : integer) : byte;
public
function HasNumber(num : byte) : boolean;
function NumbersMatched(other : TLottoTicket) : integer;
function AsText : string;
public
property Owner : TObject read fOwner write fOwner;
property Numbers[index : integer] : byte read GetNumber;
end;
TLottoFeedback = procedure(Winner : TObject; money : currency) of object;
TLottoSystem =
class
public
constructor Create;
destructor Destroy; override;
private
fTickets : TLockableCollection;
fPrevPot : currency;
fWinner : TLottoTicket;
public
procedure AddTicket(Ticket : TLottoTicket);
procedure RemTicketsFrom(Owner : TObject);
procedure Compute(Notify : TLottoFeedback);
private
function GetTicketCount : integer;
function GetTicket(index : integer) : TLottoTicket;
function GetJackpot : currency;
public
property Jackpot : currency read GetJackpot;
property TicketCount : integer read GetTicketCount;
property Tickets[index : integer] : TLottoTicket read GetTicket; default;
public
function GetTicketsOf(Owner : TObject) : string;
end;
implementation
uses
SysUtils, CompStringsParser;
// TLottoTicket
constructor TLottoTicket.Create(anOwner : TObject);
begin
inherited Create;
fOwner := anOwner;
GenerateTicket;
end;
constructor TLottoTicket.Create(anOwner : TObject; str : string);
var
aux : string;
p, i : integer;
begin
inherited Create;
fOwner := anOwner;
i := 0;
p := 1;
aux := CompStringsParser.GetNextStringUpTo(str, p, ',');
while (aux <> '') and (i < TICKET_LEN) do
begin
fNumbers[i] := StrToInt(aux);
inc(p);
inc(i);
aux := CompStringsParser.GetNextStringUpTo(str, p, ',');
end;
Sort;
end;
procedure TLottoTicket.GenerateTicket;
var
i : integer;
n : byte;
begin
for i := 0 to pred(TICKET_LEN) do
begin
n := random(TICKET_MAX) + 1;
while HasNumber(n) do
n := random(TICKET_MAX) + 1;
fNumbers[i] := n;
end;
Sort;
end;
procedure TLottoTicket.Sort;
var
i, j : integer;
tmp : byte;
begin
for i := 0 to pred(TICKET_LEN) do
for j := succ(i) to pred(TICKET_LEN) do
if fNumbers[i] > fNumbers[j]
then
begin
tmp := fNumbers[i];
fNumbers[i] := fNumbers[j];
fNumbers[j] := tmp;
end;
end;
function TLottoTicket.GetNumber(index : integer) : byte;
begin
if index < TICKET_LEN
then result := fNumbers[index]
else result := 0;
end;
function TLottoTicket.HasNumber(num : byte) : boolean;
var
j : integer;
begin
j := 0;
while (j < TICKET_LEN) and (num <> fNumbers[j]) do
inc(j);
result := j < TICKET_LEN;
end;
function TLottoTicket.NumbersMatched(other : TLottoTicket) : integer;
var
i : integer;
begin
result := 0;
for i := 0 to pred(TICKET_LEN) do
if other.HasNumber(fNumbers[i])
then inc(result);
end;
function TLottoTicket.AsText : string;
var
i : integer;
begin
result := '';
for i := 0 to pred(TICKET_LEN) do
if i <> 0
then result := result + ',' + IntToStr(fNumbers[i])
else result := IntToStr(fNumbers[i]);
end;
// TLottoSystem
constructor TLottoSystem.Create;
begin
inherited;
fTickets := TLockableCollection.Create(0, rkBelonguer);
end;
destructor TLottoSystem.Destroy;
begin
fTickets.Free;
inherited;
end;
procedure TLottoSystem.AddTicket(Ticket : TLottoTicket);
begin
fTickets.Insert(Ticket);
end;
function TLottoSystem.GetTicketCount : integer;
begin
result := fTickets.Count;
end;
function TLottoSystem.GetTicket(index : integer) : TLottoTicket;
begin
result := TLottoTicket(fTickets[index]);
end;
function TLottoSystem.GetJackpot : currency;
begin
result := TICKET_PRICE*fTickets.Count + fPrevPot;
end;
function TLottoSystem.GetTicketsOf(Owner : TObject) : string;
var
i : integer;
Ticket : TLottoTicket;
begin
result := '';
fTickets.Lock;
try
for i := pred(fTickets.Count) downto 0 do
begin
Ticket := TLottoTicket(fTickets[i]);
if Ticket.Owner = Owner
then result := Ticket.AsText + '|' + result;
end;
finally
fTickets.Unlock;
end;
end;
procedure TLottoSystem.RemTicketsFrom(Owner : TObject);
var
i : integer;
begin
fTickets.Lock;
try
for i := pred(fTickets.Count) downto 0 do
if TLottoTicket(fTickets[i]).Owner = Owner
then fTickets.AtDelete(i);
finally
fTickets.Unlock;
end;
end;
procedure TLottoSystem.Compute(Notify : TLottoFeedback);
var
totalPrize : currency;
jkpCount : integer;
win2of3 : integer;
i : integer;
jackpotWin : currency;
twoWinners : currency;
payJackpot : currency;
payTwoWin : currency;
Ticket : TLottoTicket;
begin
// Compute Total Prize
totalPrize := ((100 - IFEL_PERC)/100)*TICKET_PRICE*fTickets.Count + fPrevPot;
// Pick the winner
fWinner.Free;
fWinner := TLottoTicket.Create(nil);
// Compute winner tickets
jkpCount := 0;
win2of3 := 0;
fTickets.Lock;
try
for i := pred(fTickets.Count) downto 0 do
case fWinner.NumbersMatched(TLottoTicket(fTickets[i])) of
0, 1 : fTickets.AtDelete(i);
2 : inc(win2of3);
3 : inc(jkpCount);
end;
finally
fTickets.Unlock;
end;
// Compute Prizes
twoWinners := (TWO_WIN_PERC/100)*totalPrize;
jackpotWin := totalPrize - twoWinners;
if jkpCount > 0
then payJackpot := jackpotWin/jkpCount
else payJackpot := 0;
if win2of3 > 0
then payTwoWin := twoWinners/win2of3
else payTwoWin := 0;
// Compute Next Turn Jackpot
fPrevPot := totalPrize - twoWinners - jackpotWin;
if fPrevPot < 100
then fPrevPot := 0;
// Pay the tickets
try
for i := pred(fTickets.Count) downto 0 do
begin
Ticket := TLottoTicket(TLottoTicket(fTickets[i]));
case fWinner.NumbersMatched(Ticket) of
2 : Notify(Ticket.Owner, payTwoWin);
3 : Notify(Ticket.Owner, payJackpot);
end;
end;
finally
fTickets.Unlock;
end;
end;
begin
randomize;
end.
|
unit ChampionsLogic;
interface
uses
SysUtils, Dialogs;
type
TChampion = record
Name : String;
Role : String;
Health : Integer;
HealthRegen : Integer;
AbilityPower : Integer;
ResourceType : String;
ResourceRegen : Integer;
AttackType : String;
AttackDamage : Integer;
AttackSpeed : Extended;
AttackRange : Integer;
Armor : Integer;
MagicResist : Integer;
MovementSpeed : Integer;
end;
type
ChampionsArray = Array of TChampion;
function DoesChampionExists(ChampionName : String) : boolean;
function CreateChampion(Name, Role : String; Health, HealthRegen, AbilityPower : Integer; ResourceType : String;
ResourceRegen : Integer; AttackType : String; AttackDamage : Integer;
AttackSpeed : Extended; AttackRange, Armor, MagicResist, MovementSpeed : Integer) : TChampion;
function GetAllChampions() : ChampionsArray;
function GetChampion(ChampionName : String) : TChampion;
implementation
function DoesChampionExists(ChampionName : String) : boolean;
var
Arr : ChampionsArray;
x : Integer;
begin
Arr := GetAllChampions();
for x := Low(Arr) to High(Arr) do
begin
if CompareText(Trim(ChampionName), Arr[x].Name) = 0 then
begin
Result := True;
Exit;
end
else
Result := False;
end;
end;
function GetAllChampions() : ChampionsArray;
var
Arr : ChampionsArray;
begin
SetLength(Arr, 19);
Arr[0] := CreateChampion('Aatrox', 'Warrior', 3881, 59, 0, 'None', 0, 'Melee', 558, 1.40, 325, 178, 141, 415);
Arr[1] := CreateChampion('Ahri', 'Assassin', 2600, 37, 811, 'Mana', 21, 'Ranged', 100, 0.78, 400, 120, 103, 450);
Arr[2] := CreateChampion('Akali', 'Assassin', 2301, 45, 336, 'Energy', 10, 'Melee', 211, 1.15, 350, 100, 100, 395);
Arr[3] := CreateChampion('Alistar', 'Tank', 5353, 125, 0, 'Mana', 21, 'Melee', 107, 0.63, 325, 303, 286, 440);
Arr[4] := CreateChampion('Amumu', 'Tank', 4333, 57, 0, 'Mana', 17, 'Melee', 99, 0.70, 325, 332, 301, 400);
Arr[5] := CreateChampion('Anivia', 'Mage', 2250, 30, 591, 'Mana', 49, 'Ranged', 95, 0.61, 450, 105, 80, 430);
Arr[6] := CreateChampion('Annie', 'Mage', 2666, 66, 666, 'Mana', 66, 'Ranged', 101, 0.88, 450, 120, 100, 399);
Arr[7] := CreateChampion('Aphelios', 'Marksman', 1680, 13, 30, 'Mana', 11, 'Ranged', 711, 1.88, 475, 63, 39, 480);
Arr[8] := CreateChampion('Ashe', 'Marksman', 1533, 12, 0, 'Mana', 8, 'Ranged', 491, 2.35, 500, 50, 45, 400);
Arr[9] := CreateChampion('Aurelion Sol', 'Mage', 3696, 41, 806, 'Mana', 83, 'Ranged', 100, 0.70, 450, 130, 120, 444);
Arr[10] := CreateChampion('Azir', 'Mage', 3111, 35, 500, 'Mana', 40, 'Ranged', 99, 1.40, 450, 150, 140, 448);
Arr[11] := CreateChampion('Bard', 'Support', 4881, 85, 100, 'Mana', 50, 'Ranged', 86, 0.60, 400, 253, 191, 463);
Arr[12] := CreateChampion('Blitzcrank', 'Tank', 5001, 54, 50, 'Mana', 41, 'Melee', 103, 1.00, 320, 291, 200, 450);
Arr[13] := CreateChampion('Brand', 'Mage', 2310, 15, 758, 'Mana', 45, 'Ranged', 100, 0.88, 450, 133, 102, 441);
Arr[14] := CreateChampion('Nasus', 'Warrior', 6356, 217, 30, 'Mana', 150, 'Melee', 1851, 1.15, 350, 586, 411, 555);
Arr[15] := CreateChampion('Gnar', 'Warrior', 3631, 57, 30, 'Rage', 12, 'Melee / Ranged', 433, 1.44, 385, 233, 199, 427);
Arr[16] := CreateChampion('Rengar', 'Assassin', 2999, 43, 0, 'Ferocity', 1, 'Melee', 601, 1.15, 350, 150, 122, 500);
Arr[17] := CreateChampion('Kled', 'Warrior', 3136, 50, 50, 'Courage', 5, 'Meele', 333, 1.85, 325, 100, 100, 450);
Arr[18] := CreateChampion('Vladimir', 'Mage', 4000, 83, 991, 'Health', 83, 'Ranged', 115, 0.91, 400, 123, 101, 413);
Result := Arr;
end;
function GetChampion(ChampionName : String) : TChampion;
var
Arr : ChampionsArray;
Champion : TChampion;
x : Integer;
begin
Arr := GetAllChampions();
for x := Low(Arr) to High(Arr) do
begin
if CompareText(Trim(ChampionName), Arr[x].Name) = 0 then Champion := Arr[x];
end;
Result := Champion;
end;
function CreateChampion(Name, Role : String; Health, HealthRegen, AbilityPower : Integer; ResourceType : String;
ResourceRegen : Integer; AttackType : String; AttackDamage : Integer;
AttackSpeed : Extended; AttackRange, Armor, MagicResist, MovementSpeed : Integer) : TChampion;
var
Champion : TChampion;
begin
Champion.Name := Name;
Champion.Role := Role;
Champion.Health := Health;
Champion.HealthRegen := HealthRegen;
Champion.AbilityPower := AbilityPower;
Champion.ResourceType := ResourceType;
Champion.ResourceRegen := ResourceRegen;
Champion.AttackType := AttackType;
Champion.AttackDamage := AttackDamage;
Champion.AttackSpeed := AttackSpeed;
Champion.AttackRange := AttackRange;
Champion.Armor := Armor;
Champion.MagicResist := MagicResist;
Champion.MovementSpeed := MovementSpeed;
Result := Champion;
end;
end.
|
{
Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LogViewer.Settings;
{ Persistable application settings. }
interface
uses
System.Classes,
Spring,
DDuce.Settings.Form,
LogViewer.MessageList.Settings, LogViewer.Watches.Settings,
LogViewer.ComPort.Settings, LogViewer.WinODS.Settings,
LogViewer.WinIPC.Settings, LogViewer.ZeroMQ.Settings,
LogViewer.DisplayValues.Settings;
type
TLogViewerSettings = class(TPersistent)
private
FFormSettings : TFormSettings;
FFileName : string;
FMessageListSettings : TMessageListSettings;
FWinODSSettings : TWinODSSettings;
FWinIPCSettings : TWinIPCSettings;
FComPortSettings : TComPortSettings;
FZeroMQSettings : TZeroMQSettings;
FWatchSettings : TWatchSettings;
FDisplayValuesSettings : TDisplayValuesSettings;
FOnChanged : Event<TNotifyEvent>;
procedure FormSettingsChanged(Sender: TObject);
protected
function GetOnChanged: IEvent<TNotifyEvent>;
function GetFileName: string;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure Changed;
procedure Load;
procedure Save;
property FormSettings: TFormSettings
read FFormSettings;
property WinODSSettings: TWinODSSettings
read FWinODSSettings;
property WinIPCSettings: TWinIPCSettings
read FWinIPCSettings;
property ComPortSettings: TComPortSettings
read FComPortSettings;
property ZeroMQSettings: TZeroMQSettings
read FZeroMQSettings;
property WatchSettings: TWatchSettings
read FWatchSettings;
property MessageListSettings: TMessageListSettings
read FMessageListSettings;
property DisplayValuesSettings: TDisplayValuesSettings
read FDisplayValuesSettings;
property OnChanged: IEvent<TNotifyEvent>
read GetOnChanged;
property FileName: string
read GetFileName;
end;
implementation
uses
System.SysUtils,
JsonDataObjects;
{$REGION 'construction and destruction'}
procedure TLogViewerSettings.AfterConstruction;
begin
inherited AfterConstruction;
FFileName := 'settings.json';
FFormSettings := TFormSettings.Create;
FFormSettings.OnChanged.Add(FormSettingsChanged);
FMessageListSettings := TMessageListSettings.Create;
FWinODSSettings := TWinODSSettings.Create;
FWinIPCSettings := TWinIPCSettings.Create;
FComPortSettings := TComPortSettings.Create;
FZeroMQSettings := TZeroMQSettings.Create;
FWatchSettings := TWatchSettings.Create;
FDisplayValuesSettings := TDisplayValuesSettings.Create;
end;
procedure TLogViewerSettings.BeforeDestruction;
begin
FreeAndNil(FDisplayValuesSettings);
FreeAndNil(FWatchSettings);
FreeAndNil(FZeroMQSettings);
FreeAndNil(FComPortSettings);
FreeAndNil(FWinIPCSettings);
FreeAndNil(FWinODSSettings);
FreeAndNil(FMessageListSettings);
FFormSettings.OnChanged.Remove(FormSettingsChanged);
FreeAndNil(FFormSettings);
inherited BeforeDestruction;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TLogViewerSettings.GetFileName: string;
begin
Result := FFileName;
end;
function TLogViewerSettings.GetOnChanged: IEvent<TNotifyEvent>;
begin
Result := FOnChanged;
end;
{$ENDREGION}
{$REGION 'event dispatch methods'}
procedure TLogViewerSettings.Changed;
begin
FOnChanged.Invoke(Self);
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TLogViewerSettings.FormSettingsChanged(Sender: TObject);
begin
Changed;
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TLogViewerSettings.Load;
var
JO : TJsonObject;
begin
if FileExists(FFileName) then
begin
JO := TJsonObject.Create;
try
JO.LoadFromFile(FFileName);
JO['FormSettings'].ObjectValue.ToSimpleObject(FFormSettings);
JO['MessageListSettings'].ObjectValue.ToSimpleObject(FMessageListSettings);
JO['WinODSSettings'].ObjectValue.ToSimpleObject(FWinODSSettings);
JO['WinIPCSettings'].ObjectValue.ToSimpleObject(FWinIPCSettings);
JO['ZeroMQSettings'].ObjectValue.ToSimpleObject(FZeroMQSettings);
FZeroMQSettings.Endpoints.Text :=
JO['ZeroMQSettings'].ObjectValue['Endpoints'].Value;
JO['DisplayValueSettings'].ObjectValue['Id'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Id);
JO['DisplayValueSettings'].ObjectValue['Info'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Info);
JO['DisplayValueSettings'].ObjectValue['Warning'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Warning);
JO['DisplayValueSettings'].ObjectValue['Error'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Error);
JO['DisplayValueSettings'].ObjectValue['TimeStamp'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.TimeStamp);
JO['DisplayValueSettings'].ObjectValue['ValueName'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.ValueName);
JO['DisplayValueSettings'].ObjectValue['ValueType'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.ValueType);
JO['DisplayValueSettings'].ObjectValue['Value'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Value);
JO['DisplayValueSettings'].ObjectValue['CheckPoint'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.CheckPoint);
JO['DisplayValueSettings'].ObjectValue['Counter'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Counter);
JO['DisplayValueSettings'].ObjectValue['Tracing'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Tracing);
JO['DisplayValueSettings'].ObjectValue['Conditional'].ObjectValue
.ToSimpleObject(FDisplayValuesSettings.Conditional);
JO.ToSimpleObject(Self);
finally
JO.Free;
end;
end;
end;
procedure TLogViewerSettings.Save;
var
JO : TJsonObject;
begin
JO := TJsonObject.Create;
try
JO.FromSimpleObject(Self);
JO['FormSettings'].ObjectValue.FromSimpleObject(FFormSettings);
JO['MessageListSettings'].ObjectValue.FromSimpleObject(FMessageListSettings);
JO['WinODSSettings'].ObjectValue.FromSimpleObject(FWinODSSettings);
JO['WinIPCSettings'].ObjectValue.FromSimpleObject(FWinIPCSettings);
JO['ZeroMQSettings'].ObjectValue.FromSimpleObject(FZeroMQSettings);
JO['ZeroMQSettings'].ObjectValue['Endpoints'].Value :=
FZeroMQSettings.Endpoints.Text;
JO['DisplayValueSettings'].ObjectValue['Id'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Id);
JO['DisplayValueSettings'].ObjectValue['Info'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Info);
JO['DisplayValueSettings'].ObjectValue['Warning'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Warning);
JO['DisplayValueSettings'].ObjectValue['Error'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Error);
JO['DisplayValueSettings'].ObjectValue['TimeStamp'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.TimeStamp);
JO['DisplayValueSettings'].ObjectValue['ValueName'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.ValueName);
JO['DisplayValueSettings'].ObjectValue['ValueType'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.ValueType);
JO['DisplayValueSettings'].ObjectValue['Value'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Value);
JO['DisplayValueSettings'].ObjectValue['CheckPoint'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.CheckPoint);
JO['DisplayValueSettings'].ObjectValue['Counter'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Counter);
JO['DisplayValueSettings'].ObjectValue['Tracing'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Tracing);
JO['DisplayValueSettings'].ObjectValue['Conditional'].ObjectValue
.FromSimpleObject(FDisplayValuesSettings.Conditional);
JO.SaveToFile(FFileName, False);
finally
JO.Free;
end;
end;
{$ENDREGION}
end.
|
unit NtUtils.WinStation;
interface
uses
Winapi.winsta, NtUtils.Exceptions;
type
TSessionIdW = Winapi.winsta.TSessionIdW;
// Enumerate all session on the server for which we have Query access
function WsxEnumerateSessions(out Sessions: TArray<TSessionIdW>;
hServer: TWinStaHandle = SERVER_CURRENT): TNtxStatus;
// Query basic information about a session
function WsxQueryInformation(out Info: TWinStationInformation;
SessionId: Cardinal; hServer: TWinStaHandle = SERVER_CURRENT): TNtxStatus;
// Format a name of a session, always succeeds with at least an ID
function WsxQueryName(SessionId: Cardinal;
hServer: TWinStaHandle = SERVER_CURRENT): String;
// Open session token
function WsxQueryToken(out hToken: THandle; SessionId: Cardinal;
hServer: TWinStaHandle = SERVER_CURRENT): TNtxStatus;
// Send a message to a session
function WsxSendMessage(SessionId: Cardinal; Title, MessageStr: String;
Style: Cardinal; Timeout: Cardinal; WaitForResponse: Boolean = False;
pResponse: PCardinal = nil; ServerHandle: TWinStaHandle = SERVER_CURRENT):
TNtxStatus;
implementation
uses
System.SysUtils;
function WsxEnumerateSessions(out Sessions: TArray<TSessionIdW>;
hServer: TWinStaHandle = SERVER_CURRENT): TNtxStatus;
var
Buffer: PSessionIdArrayW;
Count, i: Integer;
begin
Result.Location := 'WinStationEnumerateW';
Result.Win32Result := WinStationEnumerateW(hServer, Buffer, Count);
if Result.IsSuccess then
begin
SetLength(Sessions, Count);
for i := 0 to High(Sessions) do
Sessions[i] := Buffer{$R-}[i]{$R+};
WinStationFreeMemory(Buffer);
end;
end;
function WsxQueryInformation(out Info: TWinStationInformation;
SessionId: Cardinal; hServer: TWinStaHandle): TNtxStatus;
var
Rerurned: Cardinal;
begin
Result.Location := 'WinStationQueryInformationW';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(WinStationInformation);
Result.LastCall.InfoClassType := TypeInfo(TWinStationInfoClass);
Result.Win32Result := WinStationQueryInformationW(hServer, SessionId,
WinStationInformation, @Info, SizeOf(Info), Rerurned);
end;
function WsxQueryName(SessionId: Cardinal;
hServer: TWinStaHandle = SERVER_CURRENT): String;
var
Info: TWinStationInformation;
begin
Result := IntToStr(SessionId);
if WsxQueryInformation(Info, SessionId, hServer).IsSuccess then
begin
if Info.WinStationName <> '' then
Result := Result + ': ' + String(Info.WinStationName);
Result := Result + ' (' + Info.FullUserName + ')';
end;
end;
function WsxQueryToken(out hToken: THandle; SessionId: Cardinal;
hServer: TWinStaHandle = SERVER_CURRENT): TNtxStatus;
var
UserToken: TWinStationUserToken;
Returned: Cardinal;
begin
FillChar(UserToken, SizeOf(UserToken), 0);
// TODO: fall back to WTS Api to workaround a bug with Sandboxie where this
// call inserts a handle to SbieSvc.exe's handle table and not into ours
Result.Location := 'WinStationQueryInformationW';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(WinStationUserToken);
Result.LastCall.InfoClassType := TypeInfo(TWinStationInfoClass);
Result.Win32Result := WinStationQueryInformationW(hServer, SessionId,
WinStationUserToken, @UserToken, SizeOf(UserToken), Returned);
if Result.IsSuccess then
hToken := UserToken.UserToken;
end;
function WsxSendMessage(SessionId: Cardinal; Title, MessageStr: String;
Style: Cardinal; Timeout: Cardinal; WaitForResponse: Boolean;
pResponse: PCardinal; ServerHandle: TWinStaHandle): TNtxStatus;
var
Response: Cardinal;
begin
Result.Location := 'WinStationSendMessageW';
Result.Win32Result := WinStationSendMessageW(ServerHandle, SessionId,
PWideChar(Title), Length(Title) * SizeOf(WideChar),
PWideChar(MessageStr), Length(MessageStr) * SizeOf(WideChar),
Style, Timeout, Response, WaitForResponse);
if Result.IsSuccess and Assigned(pResponse) then
pResponse^ := Response;
end;
end.
|
namespace RemObjects.Train;
interface
uses
System.Collections.Generic,
System.IO,
System.Reflection;
type
SharedSettings = public sealed class
private
class var defaultInstance: SharedSettings;
//var fValues: Dictionary<String, String>;
//method get_MachineName: System.String;
//method get_Values(aValue: String): String;
//method get_OptionalValues(aValue: String): String;
class method get_DefaultInstance: SharedSettings;
constructor;
public
class method FixFolder(aFolder: String): String;
class property &Default: SharedSettings read get_DefaultInstance;
//class property SettingsData: String;
//property Values[aValue: String]: String read get_Values; default;
//property OptionalValues[aValue: String]: String read get_OptionalValues;
property Filename: String read private write;
//property MachineName: String read get_MachineName;
property PlatformName: String read case RemObjects.Elements.RTL.Environment.OS of
RemObjects.Elements.RTL.OperatingSystem.Windows: "Windows";
RemObjects.Elements.RTL.OperatingSystem.macOS: "Mac";
RemObjects.Elements.RTL.OperatingSystem.Linux: "Linux";
end;
end;
implementation
{ SharedSettings }
constructor SharedSettings;
begin
inherited constructor;
var lBaseName := Path.Combine(Path.GetDirectoryName(&Assembly.GetEntryAssembly.Location),
Path.GetFileNameWithoutExtension(&Assembly.GetEntryAssembly.Location));
var lMachineName := System.Environment.MachineName.Trim();
if lMachineName.EndsWith('.local') then
lMachineName := lMachineName.Substring(0, lMachineName.Length-6);
//if assigned(SettingsData) then begin
//Console.WriteLine('Using configured data, not loading ini');
//fValues := Helpers.ReadIniFileData(SettingsData)
//end else
begin
Console.WriteLine('Considering ini file '+lBaseName+'.'+lMachineName+'.ini');
if File.Exists(lBaseName+'.'+lMachineName+'.ini') then begin
Console.WriteLine('Loading ini file '+lBaseName+'.'+lMachineName+'.ini');
//fValues := Helpers.ReadIniFile(lBaseName+'.'+lMachineName+'.ini')
Filename := lBaseName+'.'+lMachineName+'.ini';
end
else begin
Console.WriteLine('Considering ini file '+lBaseName+'.'+PlatformName+'.ini');
if File.Exists(lBaseName+'.'+PlatformName+'.ini') then begin
Console.WriteLine('Loading ini file '+lBaseName+'.'+PlatformName+'.ini');
//fValues := Helpers.ReadIniFile(lBaseName+'.'+PlatformName+'.ini')
Filename := lBaseName+'.'+PlatformName+'.ini';
end
else begin
Console.WriteLine('Considering ini file '+lBaseName+'.ini');
if File.Exists(lBaseName+'.ini') then begin
Console.WriteLine('Loading ini file '+lBaseName+'.ini');
//fValues := Helpers.ReadIniFile(lBaseName+'.ini');
Filename := lBaseName+'.ini';
end
else begin
Console.WriteLine('No config file found.');
//raise new Exception('No config file found.');
end;
end;
end;
end;
end;
//method SharedSettings.get_MachineName: System.String;
//begin
//if fValues:ContainsKey('MachineName') then
//result := fValues['MachineName'] as System.String;
//var lPhysicalMachineName := System.Environment.MachineName;
//if lPhysicalMachineName.EndsWith('.local') then
//lPhysicalMachineName := lPhysicalMachineName.Substring(0, lPhysicalMachineName.Length-6);
//if fValues:ContainsKey('MachineName-'+lPhysicalMachineName) then
//result := fValues['MachineName-'+lPhysicalMachineName] as System.String;
//if length(result) = 0 then
//result := System.Environment.GetEnvironmentVariable("CI2_MACHINE_NAME");
//if length(result) = 0 then
//result := lPhysicalMachineName;
//end;
//method SharedSettings.get_Values(aValue: String): String;
//begin
//if fValues:ContainsKey(aValue) then
//exit (fValues[aValue] as System.String):Trim
//else
//raise new Exception('Value '+aValue+' not found in server .ini');
//end;
//method SharedSettings.get_OptionalValues(aValue: String): String;
//begin
//if fValues.ContainsKey(aValue) then
//exit (fValues[aValue] as System.String).Trim
//else
//exit nil;
//end;
class method SharedSettings.get_DefaultInstance: SharedSettings;
begin
if not assigned(defaultInstance) then
defaultInstance := new SharedSettings;
result := defaultInstance;
end;
class method SharedSettings.FixFolder(aFolder: String): String;
begin
result := aFolder;
if result.StartsWith("~/") or result.StartsWith("~\") then begin
var lHome := System.Environment.GetEnvironmentVariable("HOME");
if length(lHome) > 0 then
result := lHome+result.Substring(1);
end;
end;
end. |
{*************************************************}
{* *}
{* Generics unit *}
{* *}
{*************************************************}
unit Generics;
interface
{$IFDEF DEBUGSTATE}
var DebugOutput: Text;
{$ENDIF}
type
PString = ^string;
PPGeneric = ^PGeneric;
PGeneric = ^TGeneric;
TGeneric = object
public
constructor Create;
destructor Destroy; virtual;
procedure Free; virtual;
end;
PError = ^TError;
TError = object( TGeneric)
end;
PMessageError = ^TMessageError;
TMessageError = object( TError)
private
Message: PString;
public
constructor Create( AMessage: string);
destructor Destroy; virtual;
function GetMessage: string;
end;
PErrGeneric = ^TErrGeneric;
TErrGeneric = object( TGeneric)
private
Owner: PErrGeneric;
public
constructor Create( AOwner: PErrGeneric);
function AddError( AError: PError): Boolean; virtual;
function AnyError: Boolean; virtual;
function GetErrorsCount: Word; virtual;
function GetError( AErrorIndex: Word): PError; virtual;
end;
PItemLink = ^TItemLink;
TItemLink = record
Item : PGeneric;
Next : PItemLink;
Prev : PItemLink;
end;
PCollection = ^TCollection;
TCollection = object( TGeneric)
private
First, Last, Current: PItemLink;
public
constructor Create;
destructor Destroy; virtual;
procedure Clear;
procedure WhenFreeCollectionItem( AItem: PGeneric); virtual;
function GetItemsCount: Word;
procedure PushLast( AItem: PGeneric);
function PopLast: PGeneric;
procedure PushFirst( AItem: PGeneric);
function PopFirst: PGeneric;
function RemoveFromCollection( AItem: PGeneric): Boolean;
function GetFirst: PGeneric;
function GetLast: PGeneric;
function GetNext: PGeneric;
function GetPrev: PGeneric;
function GetByIndex( AIndex: Integer): PGeneric;
function GetAfter( AItem: PGeneric): PGeneric;
function GetBefore( AItem: PGeneric): PGeneric;
function InsertAfter( AItem, NewItem: PGeneric): Boolean;
function InsertBefore( AItem, NewItem: PGeneric): Boolean;
end;
PContainerCollection = ^TContainerCollection;
TContainerCollection = object( TCollection)
public
procedure WhenFreeCollectionItem( AItem: PGeneric); virtual;
end;
PTopErrGeneric = ^TTopErrGeneric;
TTopErrGeneric = object( TErrGeneric)
private
Errors: PContainerCollection;
public
constructor Create;
destructor Destroy; virtual;
function AddError( AError: PError): Boolean; virtual;
function AnyError: Boolean; virtual;
function GetErrorsCount: Word; virtual;
function GetError( AErrorIndex: Word): PError; virtual;
end;
function AllocateString( AString: string): PString;
procedure FreeString( AString: PString);
implementation
function AllocateString( AString: string): PString;
var NewString: PString;
begin
if ( Length( AString) > 0)
then begin
GetMem( NewString, Length( AString) + 1);
NewString^ := AString;
AllocateString := NewString;
end
else AllocateString := nil;
end;
procedure FreeString( AString: PString);
begin
if ( AString <> nil)
then FreeMem( AString, Length( AString^) + 1);
end;
constructor TGeneric.Create;
begin
end;
destructor TGeneric.Destroy;
begin
end;
procedure TGeneric.Free;
var TempGeneric : PGeneric;
begin
TemPGeneric := @Self;
Dispose( TempGeneric, Destroy);
end;
constructor TMessageError.Create( AMessage: string);
begin
inherited Create;
Message := AllocateString( AMessage);
end;
destructor TMessageError.Destroy;
begin
FreeString( Message);
inherited Destroy;
end;
function TMessageError.GetMessage: string;
begin
if ( Message <> nil)
then GetMessage := Message^
else GetMessage := '';
end;
constructor TErrGeneric.Create( AOwner: PErrGeneric);
begin
inherited Create;
Owner := AOwner;
end;
function TErrGeneric.AddError( AError: PError): Boolean;
begin
if ( Owner <> nil)
then AddError := Owner^.AddError( AError)
else begin
AError^.Free;
AddError := False;
end;
end;
function TErrGeneric.AnyError: Boolean;
begin
if ( Owner <> nil)
then begin
AnyError := Owner^.AnyError;
end
else AnyError := False;
end;
function TErrGeneric.GetErrorsCount: Word;
begin
if ( Owner <> nil)
then GetErrorsCount := Owner^.GetErrorsCount
else GetErrorsCount := 0;
end;
function TErrGeneric.GetError( AErrorIndex: Word): PError;
begin
if ( Owner <> nil)
then GetError := Owner^.GetError( AErrorIndex)
else GetError := nil;
end;
constructor TCollection.Create;
begin
inherited Create;
First := nil;
Last := nil;
Current := nil;
end;
destructor TCollection.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TCollection.Clear;
begin
Current := First;
while ( Current <> nil)
do begin
WhenFreeCollectionItem( Current^.Item);
First := Current^.Next;
Dispose( Current);
Current := First;
end;
Current := nil;
First := nil;
Last := nil;
end;
procedure TCollection.WhenFreeCollectionItem( AItem: PGeneric);
begin
end;
function TCollection.GetItemsCount: Word;
var C: Word;
TempItem: PItemLink;
begin
TempItem := First;
C := 0;
while ( TempItem <> nil)
do begin
C := C + 1;
TempItem := TempItem^.Next;
end;
GetItemsCount := C;
end;
procedure TCollection.PushLast( AItem: PGeneric);
var NewItem: PItemLink;
begin
if ( AItem <> nil)
then begin
New( NewItem);
NewItem^.Next := nil;
NewItem^.Prev := Last;
NewItem^.Item := AItem;
Current := NewItem;
if ( First <> nil)
then Last^.Next := NewItem
else First := NewItem;
Last := NewItem;
end;
end;
function TCollection.PopLast: PGeneric;
var TempItem: PItemLink;
begin
if ( First <> nil)
then begin
TempItem := Last;
Last := Last^.Prev;
Current := Last;
if ( Last = nil)
then First := nil;
PopLast := TempItem^.Item;
Dispose( TempItem);
end
else PopLast := nil;
end;
procedure TCollection.PushFirst( AItem: PGeneric);
var NewItem: PItemLink;
begin
New( NewItem);
NewItem^.Next := First;
NewItem^.Prev := nil;
NewItem^.Item := AItem;
Current := NewItem;
if ( First <> nil)
then begin
First^.Prev := NewItem;
First := NewItem;
end
else begin
First := NewItem;
Last := NewItem;
end;
end;
function TCollection.PopFirst: PGeneric;
var TempItem: PItemLink;
begin
if ( First <> nil)
then begin
TempItem := First;
First := First^.Next;
Current := First;
if ( First = nil)
then Last := nil;
PopFirst := TempItem^.Item;
Dispose( TempItem);
end
else PopFirst := nil;
end;
function TCollection.RemoveFromCollection( AItem: PGeneric): Boolean;
var TempItem: PItemLink;
begin
TempItem := First;
while ( TempItem <> nil)
do if ( TempItem^.Item <> AItem)
then TempItem := TempItem^.Next
else begin
if ( TempItem^.Next <> nil)
then TempItem^.Next^.Prev := TempItem^.Prev
else Last := TempItem^.Prev;
if ( TempItem^.Prev <> nil)
then TempItem^.Prev^.Next := TempItem^.Next
else First := TempItem^.Next;
Current := First;
Dispose( TempItem);
RemoveFromCollection := True;
exit;
end;
RemoveFromCollection := False;
end;
function TCollection.GetFirst: PGeneric;
begin
if ( First <> nil)
then begin
Current := First;
GetFirst := Current^.Item;
end
else begin
Current := nil;
GetFirst := nil;
end;
end;
function TCollection.GetLast: PGeneric;
begin
if ( Last <> nil)
then begin
Current := Last;
GetLast := Current^.Item;
end
else begin
Current := nil;
GetLast := nil;
end;
end;
function TCollection.GetNext: PGeneric;
begin
if (( Current <> nil) and ( Current <> Last))
then begin
Current := Current^.Next;
GetNext := Current^.Item;
end
else begin
Current := nil;
GetNext := nil;
end;
end;
function TCollection.GetPrev: PGeneric;
begin
if (( Current <> nil) and ( Current <> First))
then begin
Current := Current^.Prev;
GetPrev := Current^.Item;
end
else begin
Current := nil;
GetPrev := nil;
end;
end;
function TCollection.GetByIndex( AIndex: Integer): PGeneric;
var C: Word;
TempItem: PItemLink;
begin
TempItem := First;
C := 1;
while ( TempItem <> nil)
do if (C <> AIndex)
then begin
C := C + 1;
TempItem := TempItem^.Next;
end
else begin
Current := TempItem;
GetByIndex := TempItem^.Item;
exit;
end;
GetByIndex := nil;
end;
function TCollection.GetAfter( AItem: PGeneric): PGeneric;
var TempCurrent: PItemLink;
begin
TempCurrent := First;
while ( TempCurrent <> nil)
do begin
if ( TempCurrent^.Item = AItem)
then if ( TempCurrent^.Next <> nil)
then begin
Current := TempCurrent^.Next;
GetAfter := TempCurrent^.Next^.Item;
exit;
end;
TempCurrent := TempCurrent^.Next;
end;
GetAfter := nil;
end;
function TCollection.GetBefore( AItem: PGeneric): PGeneric;
var TempCurrent: PItemLink;
begin
TempCurrent := First;
while ( TempCurrent <> nil)
do begin
if ( TempCurrent^.Item = AItem)
then begin
if ( TempCurrent^.Prev <> nil)
then begin
Current := TempCurrent^.Prev;
GetBefore := TempCurrent^.Prev^.Item;
exit;
end
else begin
GetBefore := nil;
exit;
end;
end;
TempCurrent := TempCurrent^.Next;
end;
GetBefore := nil;
end;
function TCollection.InsertAfter( AItem, NewItem: PGeneric): Boolean;
var TempCurrent: PItemLink;
NewLink: PItemLink;
begin
if (( AItem <> nil) and ( NewItem <> nil))
then begin
TempCurrent := First;
while ( TempCurrent <> nil)
do if ( TempCurrent^.Item = AItem)
then begin
New( NewLink);
NewLink^.Item := NewItem;
NewLink^.Prev := TempCurrent;
if ( TempCurrent^.Next <> nil)
then begin
TempCurrent^.Next^.Prev := NewLink;
NewLink^.Next := TempCurrent^.Next;
end
else begin
Last := NewLink;
NewLink^.Next := nil;
end;
TempCurrent^.Next := NewLink;
Current := NewLink;
InsertAfter := True;
Exit;
end
else TempCurrent := TempCurrent^.Next;
end;
InsertAfter := False;
end;
function TCollection.InsertBefore( AItem, NewItem: PGeneric): Boolean;
var TempCurrent: PItemLink;
NewLink: PItemLink;
begin
if (( AItem <> nil) and ( NewItem <> nil))
then begin
TempCurrent := First;
while ( TempCurrent <> nil)
do if ( TempCurrent^.Item = AItem)
then begin
New( NewLink);
NewLink^.Item := NewItem;
NewLink^.Next := TempCurrent;
if ( TempCurrent^.Prev <> nil)
then begin
TempCurrent^.Prev^.Next := NewLink;
NewLink^.Prev := TempCurrent^.Prev;
end
else begin
First := NewLink;
NewLink^.Prev := nil;
end;
TempCurrent^.Prev := NewLink;
Current := NewLink;
InsertBefore := True;
Exit;
end
else TempCurrent := TempCurrent^.Next;
end;
InsertBefore := False;
end;
procedure TContainerCollection.WhenFreeCollectionItem( AItem: PGeneric);
begin
if ( AItem <> nil)
then AItem^.Free;
end;
constructor TTopErrGeneric.Create;
begin
inherited Create( nil);
Errors := New( PContainerCollection, Create);
end;
destructor TTopErrGeneric.Destroy;
begin
Errors^.Free;
inherited Destroy;
end;
function TTopErrGeneric.AddError( AError: PError): Boolean;
begin
{$IFDEF DEBUGSTATE}
WriteLn( DebugOutput, 'An error aded . . . .');
{$ENDIF}
Errors^.PushLast( AError);
AddError := true;
end;
function TTopErrGeneric.AnyError: Boolean;
begin
AnyError := ( Errors^.GetItemsCount > 0);
end;
function TTopErrGeneric.GetErrorsCount: Word;
begin
GetErrorsCount := Errors^.GetItemsCount;
end;
function TTopErrGeneric.GetError( AErrorIndex: Word): PError;
begin
GetError := PError( Errors^.GetByIndex( AErrorIndex));
end;
end.
|
unit DW.OSDevice;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.SysUtils,
{$IF CompilerVersion < 33}
// DW
DW.PermissionsTypes,
{$ENDIF}
// RTL
System.Types;
type
TOSPlatform = TOSVersion.TPlatform;
TLocaleInfo = record
CountryCode: string;
CountryDisplayName: string;
CurrencySymbol: string;
LanguageCode: string;
LanguageDisplayName: string;
function Culture: string;
end;
/// <summary>
/// Operating System specific functions that operate below FMX
/// </summary>
/// <remarks>
/// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS
/// </remarks>
TOSDevice = record
public
{$IF CompilerVersion < 33}
/// <summary>
/// Checks whether or not a single permissions has been granted
/// </summary>
class function CheckPermission(const APermission: string; const ALog: Boolean = False): Boolean; static;
/// <summary>
/// Checks whether or not a set of permissions have been granted
/// </summary>
class function CheckPermissions(const APermissions: array of string): Boolean; overload; static;
class function CheckPermissions(const APermissions: array of string; var AResults: TPermissionResults): Boolean; overload; static;
{$ENDIF}
class function GetCurrentLocaleInfo: TLocaleInfo; static;
/// <summary>
/// Returns the name of the device, whether it is mobile or desktop
/// </summary>
class function GetDeviceName: string; static;
/// <summary>
/// Returns a summary of information about the device/application, including Package ID, Version, Device Name and Device ID
/// </summary>
class function GetDeviceSummary: string; static;
/// <summary>
/// Returns build for the application package, if any exists
/// </summary>
class function GetPackageBuild: string; static;
/// <summary>
/// Returns id for the application package, if any exists
/// </summary>
class function GetPackageID: string; static;
/// <summary>
/// Returns version for the application package, if any exists
/// </summary>
class function GetPackageVersion: string; static;
/// <summary>
/// Returns the unique id for the device, if any exists
/// </summary>
class function GetUniqueDeviceID: string; static;
class function GetUsername: string; static;
/// <summary>
/// Returns whether the application is a beta version
/// </summary>
class function IsBeta: Boolean; static;
/// <summary>
/// Returns whether the device is a mobile device
/// </summary>
class function IsMobile: Boolean; static;
/// <summary>
/// Returns whether the screen is locked
/// </summary>
class function IsScreenLocked: Boolean; static;
/// <summary>
/// Returns whether the device has touch capability
/// </summary>
class function IsTouchDevice: Boolean; static;
/// <summary>
/// Returns whether the platform matches
/// </summary>
class function IsPlatform(const APlatform: TOSPlatform): Boolean; static;
/// <summary>
/// Shows the folder that contains the nominated files
/// </summary>
class procedure ShowFilesInFolder(const AFileNames: array of string); static;
end;
implementation
uses
// DW
DW.OSLog,
{$IF Defined(ANDROID)}
DW.OSDevice.Android;
{$ELSEIF Defined(IOS)}
DW.OSDevice.iOS;
{$ELSEIF Defined(MACOS)}
DW.OSDevice.Mac;
{$ELSEIF Defined(MSWINDOWS)}
DW.OSDevice.Win;
{$ELSEIF Defined(LINUX)}
DW.OSDevice.Linux;
{$ENDIF}
{ TOSDevice }
{$IF CompilerVersion < 33}
class function TOSDevice.CheckPermission(const APermission: string; const ALog: Boolean = False): Boolean;
begin
{$IF Defined(ANDROID)}
Result := TPlatformOSDevice.CheckPermission(APermission);
if ALog then
begin
if Result then
TOSLog.d('%s granted', [APermission])
else
TOSLog.d('%s denied', [APermission]);
end;
{$ELSE}
Result := True;
{$ENDIF}
end;
class function TOSDevice.CheckPermissions(const APermissions: array of string; var AResults: TPermissionResults): Boolean;
var
I: Integer;
begin
SetLength(AResults, Length(APermissions));
for I := 0 to AResults.Count - 1 do
begin
AResults[I].Permission := APermissions[I];
AResults[I].Granted := CheckPermission(AResults[I].Permission);
end;
Result := AResults.AreAllGranted;
end;
class function TOSDevice.CheckPermissions(const APermissions: array of string): Boolean;
var
LResults: TPermissionResults;
begin
Result := CheckPermissions(APermissions, LResults);
end;
{$ENDIF}
class function TOSDevice.GetCurrentLocaleInfo: TLocaleInfo;
begin
Result := TPlatformOSDevice.GetCurrentLocaleInfo;
end;
class function TOSDevice.GetDeviceName: string;
begin
Result := TPlatformOSDevice.GetDeviceName;
end;
class function TOSDevice.GetDeviceSummary: string;
begin
Result := Format('%s Version: %s, Device: %s (%s)', [GetPackageID, GetPackageVersion, GetDeviceName, GetUniqueDeviceID]);
end;
class function TOSDevice.GetPackageBuild: string;
begin
{$IF Defined(MSWINDOWS)}
Result := TPlatformOSDevice.GetPackageBuild;
{$ELSE}
Result := '';
{$ENDIF}
end;
class function TOSDevice.GetPackageID: string;
begin
Result := TPlatformOSDevice.GetPackageID;
end;
class function TOSDevice.GetPackageVersion: string;
begin
Result := TPlatformOSDevice.GetPackageVersion;
end;
class function TOSDevice.GetUniqueDeviceID: string;
begin
Result := TPlatformOSDevice.GetUniqueDeviceID;
end;
class function TOSDevice.GetUsername: string;
begin
{$IF Defined(MSWINDOWS) or Defined(OSX)}
Result := TPlatformOSDevice.GetUsername;
{$ELSE}
Result := '';
{$ENDIF}
end;
class function TOSDevice.IsBeta: Boolean;
begin
{$IF Defined(MSWINDOWS)}
Result := TPlatformOSDevice.IsBeta;
{$ELSE}
Result := False;
{$ENDIF}
end;
class function TOSDevice.IsMobile: Boolean;
begin
Result := TOSVersion.Platform in [TOSVersion.TPlatform.pfiOS, TOSVersion.TPlatform.pfAndroid];
end;
class function TOSDevice.IsPlatform(const APlatform: TOSPlatform): Boolean;
begin
Result := TOSVersion.Platform = APlatform;
end;
class function TOSDevice.IsScreenLocked: Boolean;
begin
{$IF Defined(IOS) or Defined(ANDROID)}
Result := TPlatformOSDevice.IsScreenLocked;
{$ELSE}
Result := False;
{$ENDIF}
end;
class function TOSDevice.IsTouchDevice: Boolean;
begin
Result := TPlatformOSDevice.IsTouchDevice;
end;
class procedure TOSDevice.ShowFilesInFolder(const AFileNames: array of string);
begin
{$IF Defined(MSWINDOWS) or Defined(OSX)}
TPlatformOSDevice.ShowFilesInFolder(AFileNames);
{$ENDIF}
end;
{ TLocaleInfo }
function TLocaleInfo.Culture: string;
begin
Result := ''; // WIP
end;
end.
|
unit PyramidalModifier;
interface
uses
Windows, Surfaces;
type
TPyramidalModifier =
class( TSurfaceModifier )
protected
function GetValueAt( x, y : integer ) : TSurfaceValue; override;
function GetArea : TRect; override;
procedure SetArea( anArea : TRect ); override;
procedure Update; override;
private
fRadius : single;
fHeight : single;
fPositive : boolean;
end;
procedure RegisterBackup;
implementation
uses
Classes, Math, MathUtils, BackupInterfaces;
function TPyramidalModifier.GetValueAt( x, y : integer ) : TSurfaceValue;
var
xrel, yrel : integer;
begin
if Strength > 0
then
begin
xrel := x - Origin.x;
yrel := y - Origin.y;
if fPositive
then result := realmax( 0, fHeight - sqrt(sqr(xrel) + sqr(yrel))/Strength )
else result := realmin( 0, sqrt(sqr(xrel) + sqr(yrel))/Strength - fHeight)
end
else result := 0
end;
function TPyramidalModifier.GetArea : TRect;
begin
result := Classes.Bounds( Origin.x - round(fRadius), Origin.y - round(fRadius), round(2*fRadius), round(2*fRadius) );
end;
procedure TPyramidalModifier.SetArea( anArea : TRect );
begin
fRadius := abs(anArea.Right - anArea.Left)/2;
if fRadius > 0
then fHeight := 3*Value/sqr(fRadius)
else fHeight := 0;
end;
procedure TPyramidalModifier.Update;
begin
if (Value <> 0) and (Strength > 0)
then
begin
fPositive := Value >= 0;
if not FixedArea
then fRadius := power( 3*abs(Value)*Strength/pi, 1/3 )
else
if (fRadius > 0) and (Value <> 0)
then Strength := (fRadius*fRadius*fRadius)*pi/(3*abs(Value))
else Strength := 0;
if Strength > 0
then fHeight := fRadius/Strength
else fHeight := 0;
end
else
begin
fPositive := true;
fRadius := 0;
fHeight := 0;
end;
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TPyramidalModifier );
end;
end.
|
unit system16b_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine,
sound_engine,ym_2151,dialogs,upd7759,mcs51,sega_315_5195;
function iniciar_system16b:boolean;
implementation
const
//Altered Beast
altbeast_rom:array[0..1] of tipo_roms=(
(n:'epr-11907.a7';l:$20000;p:0;crc:$29e0c3ad),(n:'epr-11906.a5';l:$20000;p:$1;crc:$4c9e9cd8));
altbeast_sound:array[0..2] of tipo_roms=(
(n:'epr-11671.a10';l:$8000;p:0;crc:$2b71343b),(n:'opr-11672.a11';l:$20000;p:$8000;crc:$bbd7f460),
(n:'opr-11673.a12';l:$20000;p:$28000;crc:$400c4a36));
altbeast_mcu:tipo_roms=(n:'317-0078.c2';l:$1000;p:0;crc:$8101925f);
altbeast_tiles:array[0..2] of tipo_roms=(
(n:'opr-11674.a14';l:$20000;p:0;crc:$a57a66d5),(n:'opr-11675.a15';l:$20000;p:$20000;crc:$2ef2f144),
(n:'opr-11676.a16';l:$20000;p:$40000;crc:$0c04acac));
altbeast_sprites:array[0..7] of tipo_roms=(
(n:'epr-11677.b1';l:$20000;p:1;crc:$a01425cd),(n:'epr-11681.b5';l:$20000;p:$0;crc:$d9e03363),
(n:'epr-11678.b2';l:$20000;p:$40001;crc:$17a9fc53),(n:'epr-11682.b6';l:$20000;p:$40000;crc:$e3f77c5e),
(n:'epr-11679.b3';l:$20000;p:$80001;crc:$14dcc245),(n:'epr-11683.b7';l:$20000;p:$80000;crc:$f9a60f06),
(n:'epr-11680.b4';l:$20000;p:$c0001;crc:$f43dcdec),(n:'epr-11684.b8';l:$20000;p:$c0000;crc:$b20c0edb));
//Golden Axe
goldnaxe_rom:array[0..1] of tipo_roms=(
(n:'epr-12545.ic2';l:$40000;p:0;crc:$a97c4e4d),(n:'epr-12544.ic1';l:$40000;p:$1;crc:$5e38f668));
goldnaxe_sound:array[0..1] of tipo_roms=(
(n:'epr-12390.ic8';l:$8000;p:0;crc:$399fc5f5),(n:'mpr-12384.ic6';l:$20000;p:$8000;crc:$6218d8e7));
goldnaxe_mcu:tipo_roms=(n:'317-0123a.c2';l:$1000;p:0;crc:$cf19e7d4);
goldnaxe_tiles:array[0..2] of tipo_roms=(
(n:'epr-12385.ic19';l:$20000;p:0;crc:$b8a4e7e0),(n:'epr-12386.ic20';l:$20000;p:$20000;crc:$25d7d779),
(n:'epr-12387.ic21';l:$20000;p:$40000;crc:$c7fcadf3));
goldnaxe_sprites:array[0..5] of tipo_roms=(
(n:'mpr-12378.ic9';l:$40000;p:1;crc:$119e5a82),(n:'mpr-12379.ic12';l:$40000;p:$0;crc:$1a0e8c57),
(n:'mpr-12380.ic10';l:$40000;p:$80001;crc:$bb2c0853),(n:'mpr-12381.ic13';l:$40000;p:$80000;crc:$81ba6ecc),
(n:'mpr-12382.ic11';l:$40000;p:$100001;crc:$81601c6f),(n:'mpr-12383.ic14';l:$40000;p:$100000;crc:$5dbacf7a));
//Dinamite Dux
ddux_rom:array[0..3] of tipo_roms=(
(n:'epr-12189.a7';l:$20000;p:0;crc:$558e9b5d),(n:'epr-12188.a5';l:$20000;p:$1;crc:$802a240f),
(n:'epr-11915.a8';l:$20000;p:$40000;crc:$d8ed3132),(n:'epr-11913.a6';l:$20000;p:$40001;crc:$30c6cb92));
ddux_sound:tipo_roms=(n:'epr-11916.a10';l:$8000;p:0;crc:$7ab541cf);
ddux_mcu:tipo_roms=(n:'317-0095.c2';l:$1000;p:0;crc:$b06b4ca7);
ddux_tiles:array[0..2] of tipo_roms=(
(n:'mpr-11917.a14';l:$10000;p:0;crc:$6f772190),(n:'mpr-11918.a15';l:$10000;p:$10000;crc:$c731db95),
(n:'mpr-11919.a16';l:$10000;p:$20000;crc:$64d5a491));
ddux_sprites:array[0..3] of tipo_roms=(
(n:'mpr-11920.b1';l:$20000;p:$1;crc:$e5d1e3cd),(n:'mpr-11922.b5';l:$20000;p:$0;crc:$70b0c4dd),
(n:'mpr-11921.b2';l:$20000;p:$40001;crc:$61d2358c),(n:'mpr-11923.b6';l:$20000;p:$40000;crc:$c9ffe47d));
//E-Swat
eswat_rom:array[0..1] of tipo_roms=(
(n:'bootleg_epr-12659.a2';l:$40000;p:0;crc:$3157f69d),(n:'bootleg_epr-12658.a1';l:$40000;p:$1;crc:$0feb544b));
eswat_sound:array[0..1] of tipo_roms=(
(n:'epr-12617.a13';l:$8000;p:0;crc:$7efecf23),(n:'mpr-12616.a11';l:$40000;p:$8000;crc:$254347c2));
eswat_tiles:array[0..2] of tipo_roms=(
(n:'mpr-12624.b11';l:$40000;p:0;crc:$375a5ec4),(n:'mpr-12625.b12';l:$40000;p:$40000;crc:$3b8c757e),
(n:'mpr-12626.b13';l:$40000;p:$80000;crc:$3efca25c));
eswat_sprites:array[0..5] of tipo_roms=(
(n:'mpr-12618.b1';l:$40000;p:1;crc:$0d1530bf),(n:'mpr-12621.b4';l:$40000;p:$0;crc:$18ff0799),
(n:'mpr-12619.b2';l:$40000;p:$80001;crc:$32069246),(n:'mpr-12622.b5';l:$40000;p:$80000;crc:$a3dfe436),
(n:'mpr-12620.b3';l:$40000;p:$100001;crc:$f6b096e0),(n:'mpr-12623.b6';l:$40000;p:$100000;crc:$6773fef6));
//Passing Shot
passsht_rom:array[0..1] of tipo_roms=(
(n:'bootleg_epr-11871.a4';l:$10000;p:0;crc:$f009c017),(n:'bootleg_epr-11870.a1';l:$10000;p:$1;crc:$9cd5f12f));
passsht_sound:array[0..4] of tipo_roms=(
(n:'epr-11857.a7';l:$8000;p:0;crc:$789edc06),(n:'epr-11858.a8';l:$8000;p:$8000;crc:$08ab0018),
(n:'epr-11859.a9';l:$8000;p:$18000;crc:$8673e01b),(n:'epr-11860.a10';l:$8000;p:$28000;crc:$10263746),
(n:'epr-11861.a11';l:$8000;p:$38000;crc:$38b54a71));
passsht_tiles:array[0..2] of tipo_roms=(
(n:'opr-11854.b9';l:$10000;p:0;crc:$d31c0b6c),(n:'opr-11855.b10';l:$10000;p:$10000;crc:$b78762b4),
(n:'opr-11856.b11';l:$10000;p:$20000;crc:$ea49f666));
passsht_sprites:array[0..5] of tipo_roms=(
(n:'opr-11862.b1';l:$10000;p:1;crc:$b6e94727),(n:'opr-11865.b5';l:$10000;p:$0;crc:$17e8d5d5),
(n:'opr-11863.b2';l:$10000;p:$20001;crc:$3e670098),(n:'opr-11866.b6';l:$10000;p:$20000;crc:$50eb71cc),
(n:'opr-11864.b3';l:$10000;p:$40001;crc:$05733ca8),(n:'opr-11867.b7';l:$10000;p:$40000;crc:$81e49697));
//Aurail
aurail_rom:array[0..3] of tipo_roms=(
(n:'epr-13577.a7';l:$20000;p:0;crc:$6701b686),(n:'epr-13576.a5';l:$20000;p:$1;crc:$1e428d94),
(n:'epr-13447.a8';l:$20000;p:$40000;crc:$70a52167),(n:'epr-13445.a6';l:$20000;p:$40001;crc:$28dfc3dd));
aurail_sound:array[0..1] of tipo_roms=(
(n:'epr-13448.a10';l:$8000;p:0;crc:$b5183fb9),(n:'mpr-13449.a11';l:$20000;p:$8000;crc:$d3d9aaf9));
aurail_tiles:array[0..5] of tipo_roms=(
(n:'mpr-13450.a14';l:$20000;p:0;crc:$0fc4a7a8),(n:'mpr-13465.b14';l:$20000;p:$20000;crc:$e08135e0),
(n:'mpr-13451.a15';l:$20000;p:$40000;crc:$1c49852f),(n:'mpr-13466.b15';l:$20000;p:$60000;crc:$e14c6684),
(n:'mpr-13452.a16';l:$20000;p:$80000;crc:$047bde5e),(n:'mpr-13467.b16';l:$20000;p:$a0000;crc:$6309fec4));
aurail_sprites:array[0..15] of tipo_roms=(
(n:'mpr-13453.b1';l:$20000;p:1;crc:$5fa0a9f8),(n:'mpr-13457.b5';l:$20000;p:$0;crc:$0d1b54da),
(n:'mpr-13454.b2';l:$20000;p:$40001;crc:$5f6b33b1),(n:'mpr-13458.b6';l:$20000;p:$40000;crc:$bad340c3),
(n:'mpr-13455.b3';l:$20000;p:$80001;crc:$4e80520b),(n:'mpr-13459.b7';l:$20000;p:$80000;crc:$7e9165ac),
(n:'mpr-13456.b4';l:$20000;p:$c0001;crc:$5733c428),(n:'mpr-13460.b8';l:$20000;p:$c0000;crc:$66b8f9b3),
(n:'mpr-13440.a1';l:$20000;p:$100001;crc:$4f370b2b),(n:'mpr-13461.b10';l:$20000;p:$100000;crc:$f76014bf),
(n:'mpr-13441.a2';l:$20000;p:$140001;crc:$37cf9cb4),(n:'mpr-13462.b11';l:$20000;p:$140000;crc:$1061e7da),
(n:'mpr-13442.a3';l:$20000;p:$180001;crc:$049698ef),(n:'mpr-13463.b12';l:$20000;p:$180000;crc:$7dbcfbf1),
(n:'mpr-13443.a4';l:$20000;p:$1c0001;crc:$77a8989e),(n:'mpr-13464.b13';l:$20000;p:$1c0000;crc:$551df422));
//Dip
system16b_dip_a:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';number:16;dip:((dip_val:$7;dip_name:'4C/1C'),(dip_val:$8;dip_name:'3C/1C'),(dip_val:$9;dip_name:'2C/1C'),(dip_val:$5;dip_name:'2C/1C 5C/3C 6C/4C'),(dip_val:$4;dip_name:'2C/1C 4C/3C'),(dip_val:$f;dip_name:'1C/1C'),(dip_val:$3;dip_name:'1C/1C 5C/6C'),(dip_val:$2;dip_name:'1C/1C 4C/5C'),(dip_val:$1;dip_name:'1C/1C 2C/3C'),(dip_val:$6;dip_name:'2C/3C'),(dip_val:$e;dip_name:'1C/2C'),(dip_val:$d;dip_name:'1C/3C'),(dip_val:$c;dip_name:'1C/4C'),(dip_val:$b;dip_name:'1C/5C'),(dip_val:$a;dip_name:'1C/6C'),(dip_val:$0;dip_name:'Free Play (if Coin B too) or 1C/1C'))),
(mask:$f0;name:'Coin B';number:16;dip:((dip_val:$70;dip_name:'4C/1C'),(dip_val:$80;dip_name:'3C/1C'),(dip_val:$90;dip_name:'2C/1C'),(dip_val:$50;dip_name:'2C/1C 5C/3C 6C/4C'),(dip_val:$40;dip_name:'2C/1C 4C/3C'),(dip_val:$f0;dip_name:'1C/1C'),(dip_val:$30;dip_name:'1C/1C 5C/6C'),(dip_val:$20;dip_name:'1C/1C 4C/5C'),(dip_val:$10;dip_name:'1C/1C 2C/3C'),(dip_val:$60;dip_name:'2C/3C'),(dip_val:$e0;dip_name:'1C/2C'),(dip_val:$d0;dip_name:'1C/3C'),(dip_val:$c0;dip_name:'1C/4C'),(dip_val:$b0;dip_name:'1C/5C'),(dip_val:$a0;dip_name:'1C/6C'),(dip_val:$00;dip_name:'Free Play (if Coin A too) or 1C/1C'))),());
altbeast_dip_b:array [0..5] of def_dip=(
(mask:$1;name:'Credits Needed';number:2;dip:((dip_val:$1;dip_name:'1 Credit To Start'),(dip_val:$0;dip_name:'2 Credit To Start'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Lives';number:4;dip:((dip_val:$8;dip_name:'2'),(dip_val:$c;dip_name:'3'),(dip_val:$4;dip_name:'4'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Player Meter';number:4;dip:((dip_val:$20;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$80;dip_name:'Easy'),(dip_val:$c0;dip_name:'Normal'),(dip_val:$40;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),());
goldnaxe_dip_b:array [0..3] of def_dip=(
(mask:$1;name:'Credits Needed';number:2;dip:((dip_val:$1;dip_name:'1 Credit To Start'),(dip_val:$0;dip_name:'2 Credit To Start'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$3c;name:'Difficulty';number:8;dip:((dip_val:$0;dip_name:'Special'),(dip_val:$14;dip_name:'Easiest'),(dip_val:$1c;dip_name:'Easier'),(dip_val:$34;dip_name:'Easy'),(dip_val:$3c;dip_name:'Normal'),(dip_val:$38;dip_name:'Hard'),(dip_val:$2c;dip_name:'Harder'),(dip_val:$28;dip_name:'Hardest'),(),(),(),(),(),(),(),())),());
ddux_dip_b:array [0..4] of def_dip=(
(mask:$1;name:'Demo Sounds';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$6;name:'Difficulty';number:4;dip:((dip_val:$4;dip_name:'Easy'),(dip_val:$6;dip_name:'Normal'),(dip_val:$2;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Lives';number:4;dip:((dip_val:$10;dip_name:'2'),(dip_val:$18;dip_name:'3'),(dip_val:$8;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Bonus Life';number:4;dip:((dip_val:$40;dip_name:'150K'),(dip_val:$60;dip_name:'200K'),(dip_val:$20;dip_name:'300K'),(dip_val:$0;dip_name:'400K'),(),(),(),(),(),(),(),(),(),(),(),())),());
eswat_dip_b:array [0..6] of def_dip=(
(mask:$1;name:'Credits Needed';number:2;dip:((dip_val:$1;dip_name:'1 Credit To Start'),(dip_val:$0;dip_name:'2 Credit To Start'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Flip Screen';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Timer';number:2;dip:((dip_val:$8;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Difficulty';number:4;dip:((dip_val:$20;dip_name:'Easy'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'1'),(dip_val:$40;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$80;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),());
passsht_dip_b:array [0..4] of def_dip=(
(mask:$1;name:'Demo Sounds';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$e;name:'Initial Point';number:4;dip:((dip_val:$6;dip_name:'2000'),(dip_val:$a;dip_name:'3000'),(dip_val:$c;dip_name:'4000'),(dip_val:$e;dip_name:'5000'),(dip_val:$8;dip_name:'6000'),(dip_val:$4;dip_name:'7000'),(dip_val:$2;dip_name:'8000'),(dip_val:$0;dip_name:'9000'),(),(),(),(),(),(),(),())),
(mask:$30;name:'Point Table';number:4;dip:((dip_val:$20;dip_name:'Easy'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$80;dip_name:'Easy'),(dip_val:$c0;dip_name:'Normal'),(dip_val:$40;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),());
aurail_dip_b:array [0..7] of def_dip=(
(mask:$1;name:'Cabinet';number:2;dip:((dip_val:$1;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'2'),(dip_val:$c;dip_name:'3'),(dip_val:$8;dip_name:'4'),(dip_val:$4;dip_name:'5'),(dip_val:$8;dip_name:'6000'),(dip_val:$4;dip_name:'7000'),(dip_val:$2;dip_name:'8000'),(dip_val:$0;dip_name:'9000'),(),(),(),(),(),(),(),())),
(mask:$10;name:'Bonus Life';number:2;dip:((dip_val:$10;dip_name:'80K/200K/500K/1000K'),(dip_val:$0;dip_name:'100K/300K/700K/1000K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Difficulty';number:2;dip:((dip_val:$20;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Controller';number:2;dip:((dip_val:$40;dip_name:'1 Player Side'),(dip_val:$0;dip_name:'2 Players Side'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Special Function Mode';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
type
tsystem16_info=record
normal,shadow,hilight:array[0..31] of byte;
s_banks,t_banks:byte;
mb_type:byte;
screen:array[0..7] of byte;
screen_enabled:boolean;
tile_bank:array[0..1] of byte;
tile_buffer:array[0..7,0..$7ff] of boolean;
end;
var
rom:array[0..$3ffff] of word;
rom2:array[0..$1ffff] of word;
ram:array[0..$ffff] of word;
tile_ram:array[0..$7fff] of word;
char_ram:array[0..$7ff] of word;
sprite_ram:array[0..$3ff] of word;
sprite_rom:array[0..$fffff] of word;
sprite_bank:array[0..$f] of byte;
s16_info:tsystem16_info;
sound_bank:array[0..$f,0..$3fff] of byte;
sound_bank_num:byte;
sound_latch:byte;
s315_5248_regs:array[0..1] of word;
s315_5250_regs:array[0..$f] of word;
s315_5250_bit:byte;
region0_read:function(direccion:dword):word;
region1_read:function(direccion:dword):word;
region2_read:function(direccion:dword):word;
region1_write:procedure(direccion:dword;valor:word);
region2_write:procedure(direccion:dword;valor:word);
sound_bank_calc:function(valor:byte):byte;
procedure update_video_system16b;
procedure draw_sprites(pri:byte);
var
g,f,sprpri,vzoom,hzoom:byte;
bottom,top,xacc,addr,bank,y,pix,data_7,pixels,color:word;
x,xpos,pitch:integer;
spritedata:dword;
hide,flip:boolean;
procedure system16b_draw_pixel(x:integer;y,pix:word);
var
punt,punt2,temp1,temp2,temp3:word;
begin
//only draw if onscreen, not 0 or 15
if ((x>=0) and (x<320) and ((pix and $f)<>0) and ((pix and $f)<>15)) then begin
if (pix and $3f0)=$3f0 then begin //Shadow
punt:=getpixel(x+ADD_SPRITE,y+ADD_SPRITE,7);
punt2:=paleta[$800];
temp1:=(((punt and $f800)+(punt2 and $f800)) shr 1) and $f800;
temp2:=(((punt and $7e0)+(punt2 and $7e0)) shr 1) and $7e0;
temp3:=(((punt and $1f)+(punt2 and $1f)) shr 1) and $1f;
punt:=temp1 or temp2 or temp3;
end else punt:=paleta[pix+$400]; //Normal
putpixel(x+ADD_SPRITE,y+ADD_SPRITE,1,@punt,7);
end;
end;
begin
for f:=0 to $7f do begin
sprpri:=(sprite_ram[(f*8)+4] and $ff) shr 6;
if sprpri<>pri then continue;
addr:=sprite_ram[(f*8)+3];
sprite_ram[(f*8)+7]:=addr;
if (sprite_ram[(f*8)+2] and $8000)<>0 then exit;
bottom:=(sprite_ram[f*8] shr 8);
top:=sprite_ram[f*8] and $ff;
hide:=(sprite_ram[(f*8)+2] and $4000)<>0;
bank:=sprite_bank[(sprite_ram[(f*8)+4] shr 8) and $f];
// if hidden, or top greater than/equal to bottom, or invalid bank, punt
if (hide or (top>=bottom) or (bank=255)) then continue;
xpos:=(sprite_ram[(f*8)+1] and $1ff)-$b7; //-$bd+6
pitch:=shortint(sprite_ram[(f*8)+2] and $ff);
color:=(sprite_ram[(f*8)+4] and $3f) shl 4;
flip:=(sprite_ram[(f*8)+2] and $100)<>0;
vzoom:=(sprite_ram[(f*8)+5] shr 5) and $1f;
hzoom:=sprite_ram[(f*8)+5] and $1f;
// clamp to within the memory region size
spritedata:=$10000*(bank mod s16_info.s_banks);
// reset the yzoom counter
sprite_ram[(f*8)+5]:=sprite_ram[(f*8)+5] and $3ff;
// loop from top to bottom
for y:=top to (bottom-1) do begin
// advance a row
addr:=addr+pitch;
// accumulate zoom factors; if we carry into the high bit, skip an extra row
sprite_ram[(f*8)+5]:=sprite_ram[(f*8)+5]+(vzoom shl 10);
if (sprite_ram[(f*8)+5] and $8000)<>0 then begin
addr:=addr+pitch;
sprite_ram[(f*8)+5]:=sprite_ram[(f*8)+5] and $7fff;
end;
// skip drawing if not within the cliprect
if (y<256) then begin
xacc:=4*hzoom;
if not(flip) then begin
data_7:=addr;
x:=xpos;
while (x<512) do begin
pixels:=sprite_rom[spritedata+data_7];
// draw four pixels
for g:=3 downto 0 do begin
xacc:=(xacc and $3f)+hzoom;
if xacc<$40 then begin
pix:=(pixels shr (g*4)) and $f;
system16b_draw_pixel(x,y,pix or color);
x:=x+1;
end;
end;
// stop if the last pixel in the group was 0xf
if (((pixels shr 0) and $f)=15) then begin
sprite_ram[(f*8)+7]:=data_7;
break;
end else data_7:=data_7+1;
end;
end else begin
// flipped case
data_7:=addr;
x:=xpos;
while (x<512) do begin
pixels:=sprite_rom[spritedata+data_7];
// draw four pixels
for g:=0 to 3 do begin
xacc:=(xacc and $3f)+hzoom;
if xacc<$40 then begin
pix:=(pixels shr (g*4)) and $f;
system16b_draw_pixel(x,y,pix or color);
x:=x+1;
end;
end;
// stop if the last pixel in the group was 0xf
if (((pixels shr 12) and $f)=15) then begin
sprite_ram[(f*8)+7]:=data_7;
break;
end else data_7:=data_7-1;
end;
end;
end;
end;
end;
end;
procedure draw_tiles(num:byte;px,py:word;scr:byte;trans:boolean);
var
pos,f,nchar,color,data,x,y:word;
begin
pos:=s16_info.screen[num]*$800;
for f:=$0 to $7ff do begin
data:=tile_ram[pos+f];
color:=(data shr 6) and $7f;
if (s16_info.tile_buffer[num,f] or buffer_color[color]) then begin
x:=((f and $3f) shl 3)+px;
y:=((f shr 6) shl 3)+py;
nchar:=data and $1fff;
nchar:=s16_info.tile_bank[nchar div $1000]*$1000+(nchar mod $1000);
if trans then put_gfx_trans(x,y,nchar,color shl 3,scr,0)
else put_gfx(x,y,nchar,color shl 3,scr,0);
if (data and $8000)<>0 then put_gfx_trans(x,y,nchar,color shl 3,scr+1,0)
else put_gfx_block_trans(x,y,scr+1,8,8);
s16_info.tile_buffer[num,f]:=false;
end;
end;
end;
var
f,nchar,color,scroll_x1,scroll_x2,x,y,atrib,scroll_y1,scroll_y2:word;
begin
if not(s16_info.screen_enabled) then begin
fill_full_screen(7,$1000);
actualiza_trozo_final(0,0,320,224,7);
exit;
end;
//Background
draw_tiles(0,0,256,3,false);
draw_tiles(1,512,256,3,false);
draw_tiles(2,0,0,3,false);
draw_tiles(3,512,0,3,false);
scroll_x1:=char_ram[$74d] and $3ff;
scroll_x1:=(704-scroll_x1) and $3ff;
scroll_y1:=char_ram[$749] and $1ff;
//Foreground
draw_tiles(4,0,256,5,true);
draw_tiles(5,512,256,5,true);
draw_tiles(6,0,0,5,true);
draw_tiles(7,512,0,5,true);
scroll_x2:=char_ram[$74c] and $3ff;
scroll_x2:=(704-scroll_x2) and $3ff;
scroll_y2:=char_ram[$748] and $1ff;
//text
for f:=$0 to $6ff do begin
atrib:=char_ram[f];
color:=(atrib shr 9) and $7;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
x:=(f and $3f) shl 3;
y:=(f shr 6) shl 3;
nchar:=s16_info.tile_bank[0]*$1000+(atrib and $1ff);
put_gfx_trans(x,y,nchar,color shl 3,1,0);
if (atrib and $8000)<>0 then put_gfx_trans(x,y,nchar,color shl 3,2,0)
else put_gfx_block_trans(x,y,2,8,8);
gfx[0].buffer[f]:=false;
end;
end;
//Lo pongo todo con prioridades, falta scrollrow y scrollcol!!
scroll_x_y(3,7,scroll_x1,scroll_y1); //B0
draw_sprites(0);
scroll_x_y(4,7,scroll_x1,scroll_y1); //B1
draw_sprites(1);
scroll_x_y(5,7,scroll_x2,scroll_y2); //F0
draw_sprites(2);
scroll_x_y(6,7,scroll_x2,scroll_y2); //F1
actualiza_trozo(192,0,320,224,1,0,0,320,224,7); //T0
draw_sprites(3);
actualiza_trozo(192,0,320,224,2,0,0,320,224,7); //T1
//Y lo pinto a la pantalla principal
actualiza_trozo_final(0,0,320,224,7);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_system16b;
begin
if event.arcade then begin
//P1
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.but3[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or $8);
//P2
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $ffdf) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $ffef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $ff7f) else marcade.in2:=(marcade.in2 or $80);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $ffbf) else marcade.in2:=(marcade.in2 or $40);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $fffb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $fffd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $fffe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.but3[1] then marcade.in2:=(marcade.in2 and $fff7) else marcade.in2:=(marcade.in2 or $8);
//Service
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2);
end;
end;
procedure system16b_principal_mcu;
var
frame_m,frame_s,frame_mcu:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
frame_mcu:=mcs51_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 261 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
//MCU
mcs51_0.run(frame_mcu);
frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador;
if f=223 then begin
mcs51_0.change_irq0(HOLD_LINE);
update_video_system16b;
end;
end;
eventos_system16b;
video_sync;
end;
end;
procedure system16b_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 261 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=223 then begin
m68000_0.irq[4]:=HOLD_LINE;
update_video_system16b;
end;
end;
eventos_system16b;
video_sync;
end;
end;
function standar_s16_io_r(direccion:word):word;
var
res:word;
begin
res:=$ff;
case (direccion and $1800) of
$800:case (direccion and 3) of
0:res:=marcade.in0; //SERVICE
1:res:=marcade.in1; //P1
2:; //UNUSED
3:res:=marcade.in2; //P2
end;
$1000:case (direccion and $1) of
0:res:=marcade.dswb; //DSW2
1:res:=marcade.dswa; //DSW1
end;
end;
standar_s16_io_r:=res;
end;
procedure change_pal(direccion,valor:word);
var
r,g,b:byte;
color:tcolor;
begin
// byte 0 byte 1
// sBGR BBBB GGGG RRRR
// x000 4321 4321 4321
r:=((valor shr 12) and $01) or ((valor shl 1) and $1e);
g:=((valor shr 13) and $01) or ((valor shr 3) and $1e);
b:=((valor shr 14) and $01) or ((valor shr 7) and $1e);
//normal
color.r:=s16_info.normal[r];
color.g:=s16_info.normal[g];
color.b:=s16_info.normal[b];
set_pal_color(color,direccion);
//shadow
if (valor and $8000)<>0 then begin
color.r:=s16_info.shadow[r];
color.g:=s16_info.shadow[g];
color.b:=s16_info.shadow[b];
end else begin
//hilight
color.r:=s16_info.hilight[r];
color.g:=s16_info.hilight[g];
color.b:=s16_info.hilight[b];
end;
set_pal_color(color,direccion+$800);
buffer_color[(direccion shr 3) and $7f]:=true;
end;
procedure test_screen_change(direccion:word);
var
tmp:byte;
begin
if direccion=$740 then begin
//Foreground
tmp:=(char_ram[$740] shr 12) and $f;
if tmp<>s16_info.screen[4] then begin
s16_info.screen[4]:=tmp;
fillchar(s16_info.tile_buffer[4,0],$800,1);
end;
tmp:=(char_ram[$740] shr 8) and $f;
if tmp<>s16_info.screen[5] then begin
s16_info.screen[5]:=tmp;
fillchar(s16_info.tile_buffer[5,0],$800,1);
end;
tmp:=(char_ram[$740] shr 4) and $f;
if tmp<>s16_info.screen[6] then begin
s16_info.screen[6]:=tmp;
fillchar(s16_info.tile_buffer[6,0],$800,1);
end;
tmp:=char_ram[$740] and $f;
if tmp<>s16_info.screen[7] then begin
s16_info.screen[7]:=tmp;
fillchar(s16_info.tile_buffer[7,0],$800,1);
end;
end;
if direccion=$741 then begin
//Background
tmp:=(char_ram[$741] shr 12) and $f;
if tmp<>s16_info.screen[0] then begin
s16_info.screen[0]:=tmp;
fillchar(s16_info.tile_buffer[0,0],$800,1);
end;
tmp:=(char_ram[$741] shr 8) and $f;
if tmp<>s16_info.screen[1] then begin
s16_info.screen[1]:=tmp;
fillchar(s16_info.tile_buffer[1,0],$800,1);
end;
tmp:=(char_ram[$741] shr 4) and $f;
if tmp<>s16_info.screen[2] then begin
s16_info.screen[2]:=tmp;
fillchar(s16_info.tile_buffer[2,0],$800,1);
end;
tmp:=char_ram[$741] and $f;
if tmp<>s16_info.screen[3] then begin
s16_info.screen[3]:=tmp;
fillchar(s16_info.tile_buffer[3,0],$800,1);
end;
end;
end;
function region0_5704_read(direccion:dword):word;
begin
direccion:=(direccion and $3ffff) shr 1;
region0_5704_read:=rom[direccion];
end;
function region0_5797_read(direccion:dword):word;
begin
direccion:=(direccion and $7ffff) shr 1;
region0_5797_read:=rom[direccion];
end;
function region0_5358_read(direccion:dword):word;
begin
direccion:=(direccion and $1ffff) shr 1;
region0_5358_read:=rom[direccion];
end;
function region1_5704_read(direccion:dword):word;
begin
direccion:=(direccion and $3ffff) shr 1;
region1_5704_read:=rom2[direccion];
end;
function region1_5797_read(direccion:dword):word;
begin
direccion:=(direccion shr 1) and $1fff;
case (direccion and $1800) of
0:case (direccion and 3) of
0:region1_5797_read:=s315_5248_regs[0];
1:region1_5797_read:=s315_5248_regs[1];
2:region1_5797_read:=(smallint(s315_5248_regs[0])*smallint(s315_5248_regs[1])) shr 16;
3:region1_5797_read:=(smallint(s315_5248_regs[0])*smallint(s315_5248_regs[1])) and $ffff;
end;
$800:case (direccion and $f) of
0..7:region1_5797_read:=s315_5250_regs[direccion and $f];
else region1_5797_read:=$ffff;
end;
end;
end;
procedure region1_5797_write(direccion:dword;valor:word);
procedure exec(history:boolean=false);
var
min,max,bound1,bound2,value:smallint;
begin
bound1:= smallint(s315_5250_regs[0]);
bound2:= smallint(s315_5250_regs[1]);
value:= smallint(s315_5250_regs[2]);
if (bound1<bound2) then min:=bound1
else min:=bound2;
if (bound1>bound2) then max:=bound1
else max:=bound2;
if (value<min) then begin
s315_5250_regs[7]:=min;
s315_5250_regs[3]:=$8000;
end else if (value>max) then begin
s315_5250_regs[7]:=max;
s315_5250_regs[3]:=$4000;
end else begin
s315_5250_regs[7]:=value;
s315_5250_regs[3]:=0;
end;
if (history) then begin
s315_5250_regs[4]:=s315_5250_regs[4] or (byte(s315_5250_regs[3]=0) shl s315_5250_bit);
s315_5250_bit:=s315_5250_bit+1;
end;
end;
begin
direccion:=(direccion shr 1) and $1fff;
case (direccion and $1800) of
0:s315_5248_regs[direccion and 1]:=valor;
$800:case direccion and 15 of
0..1:begin
s315_5250_regs[direccion and $f]:=valor;
exec;
end;
2:begin
s315_5250_regs[2]:=valor;
exec(true);
end;
4:begin
s315_5250_regs[4]:=0;
s315_5250_bit:=0;
end;
6:begin
s315_5250_regs[2]:=valor;
exec;
end;
8,$c:s315_5250_regs[8]:=valor;
9,$d:; //irq ack
$a,$e:s315_5250_regs[10]:=valor;
$b,$f:s315_5250_regs[11]:=valor; //write to sound
end;
$1000:begin
s16_info.tile_bank[direccion and 1]:=(valor and 7) and s16_info.t_banks; //Tile bank!
fillchar(s16_info.tile_buffer,$4000,1);
end;
end;
end;
procedure region2_5704_write(direccion:dword;valor:word);
begin
if s16_info.tile_bank[(direccion and 3) shr 1]<>(valor and 7) then begin//Tile bank!
s16_info.tile_bank[(direccion and 3) shr 1]:=(valor and 7) and s16_info.t_banks;
fillchar(s16_info.tile_buffer,$4000,1);
end;
end;
function system16b_getword(direccion:dword):word;
var
zona:boolean;
begin
zona:=false;
if ((direccion>=s315_5195_0.dirs_start[0]) and (direccion<s315_5195_0.dirs_end[0])) then begin
//Esta zona no se puede solapar!!!!
system16b_getword:=region0_read(direccion);
exit;
end;
if ((direccion>=s315_5195_0.dirs_start[1]) and (direccion<s315_5195_0.dirs_end[1])) then begin
if @region1_read<>nil then system16b_getword:=region1_read(direccion);
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[2]) and (direccion<s315_5195_0.dirs_end[2])) then begin
if @region2_read<>nil then system16b_getword:=region2_read(direccion);
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[3]) and (direccion<s315_5195_0.dirs_end[3])) then begin
system16b_getword:=ram[(direccion and $ffff) shr 1]; //RAM
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[4]) and (direccion<s315_5195_0.dirs_end[4])) then begin
system16b_getword:=sprite_ram[(direccion and $7ff) shr 1]; //Object RAM
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[5]) and (direccion<s315_5195_0.dirs_end[5])) then begin
case direccion and $1ffff of //Text/Tile RAM
0..$ffff:system16b_getword:=tile_ram[(direccion and $ffff) shr 1];
$10000..$1ffff:system16b_getword:=char_ram[(direccion and $fff) shr 1];
end;
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[6]) and (direccion<s315_5195_0.dirs_end[6])) then begin
system16b_getword:=buffer_paleta[(direccion and $fff) shr 1]; //Color RAM
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[7]) and (direccion<s315_5195_0.dirs_end[7])) then begin
system16b_getword:=standar_s16_io_r((direccion shr 1) and $1fff); //IO Read
zona:=true;
end;
if not(zona) then system16b_getword:=s315_5195_0.read_reg((direccion shr 1) and $1f);
end;
procedure test_tile_buffer(direccion:word);
var
num_scr,f:byte;
pos:word;
begin
num_scr:=direccion shr 11;
pos:=direccion and $7ff;
for f:=0 to 7 do
if s16_info.screen[f]=num_scr then s16_info.tile_buffer[f,pos]:=true;
end;
procedure system16b_putword(direccion:dword;valor:word);
var
zona:boolean;
tempd:dword;
begin
{Region 0 - Program ROM
Region 3 - 68000 work RAM
Region 4 - Object RAM
Region 5 - Text/tile RAM
Region 6 - Color RAM
Region 7 - I/O area
Si tiene una region mapeada hace lo que toca, pero si no tiene nada mapeado
rellena los registros del 315-5195 y mapea
Se pueden solapar las zonas (excepto la 0), tiene prioridad la mas alta (por ejemplo ESwat)
}
zona:=false;
if ((direccion>=s315_5195_0.dirs_start[0]) and (direccion<s315_5195_0.dirs_end[0])) then begin
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[1]) and (direccion<s315_5195_0.dirs_end[1])) then begin
if @region1_write<>nil then region1_write(direccion,valor);
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[2]) and (direccion<s315_5195_0.dirs_end[2])) then begin
if @region2_write<>nil then region2_write(direccion,valor);
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[3]) and (direccion<s315_5195_0.dirs_end[3])) then begin
ram[(direccion and $ffff) shr 1]:=valor; //RAM
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[4]) and (direccion<s315_5195_0.dirs_end[4])) then begin
sprite_ram[(direccion and $7ff) shr 1]:=valor; //Object RAM
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[5]) and (direccion<s315_5195_0.dirs_end[5])) then begin
case direccion and $1ffff of
0..$ffff:begin
direccion:=(direccion and $ffff) shr 1;
if tile_ram[direccion]<>valor then begin
tile_ram[direccion]:=valor;
test_tile_buffer(direccion);
end;
end;
$10000..$1ffff:begin
direccion:=(direccion and $fff) shr 1;
if char_ram[direccion]<>valor then begin
char_ram[direccion]:=valor;
gfx[0].buffer[direccion]:=true;
end;
test_screen_change(direccion);
end;
end;
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[6]) and (direccion<s315_5195_0.dirs_end[6])) then begin
direccion:=(direccion and $fff) shr 1;
if buffer_paleta[direccion]<>valor then begin
buffer_paleta[direccion]:=valor;
change_pal(direccion,valor);
end;
zona:=true;
end;
if ((direccion>=s315_5195_0.dirs_start[7]) and (direccion<s315_5195_0.dirs_end[7])) then begin
case ((direccion and $1fff) shr 1) of //IO
0:s16_info.screen_enabled:=(valor and $20)<>0;
end;
zona:=true;
end;
if not(zona) then begin
tempd:=s315_5195_0.dirs_start[5];
s315_5195_0.write_reg((direccion shr 1) and $1f,valor and $ff);
if tempd<>s315_5195_0.dirs_start[5] then fillchar(s16_info.tile_buffer,$4000,0);
end;
end;
procedure system16b_putword_mcu(direccion:dword;valor:word);
begin
//Cuando hay un i8751 el M68000 no tiene acceso directo al 315-5195!!
//Por ejemplo GoldenAxe solo espera que el i8751 toque el direccionamiento o se vuelve loco!
if ((direccion>=s315_5195_0.dirs_start[0]) and (direccion<s315_5195_0.dirs_end[0])) then begin
end;
if ((direccion>=s315_5195_0.dirs_start[1]) and (direccion<s315_5195_0.dirs_end[1])) then begin
if @region1_write<>nil then region1_write(direccion,valor);
end;
if ((direccion>=s315_5195_0.dirs_start[2]) and (direccion<s315_5195_0.dirs_end[2])) then begin
if @region2_write<>nil then region2_write(direccion,valor);
end;
if ((direccion>=s315_5195_0.dirs_start[3]) and (direccion<s315_5195_0.dirs_end[3])) then begin
ram[(direccion and $ffff) shr 1]:=valor; //RAM
end;
if ((direccion>=s315_5195_0.dirs_start[4]) and (direccion<s315_5195_0.dirs_end[4])) then begin
sprite_ram[(direccion and $7ff) shr 1]:=valor; //Object RAM
end;
if ((direccion>=s315_5195_0.dirs_start[5]) and (direccion<s315_5195_0.dirs_end[5])) then begin
case direccion and $1ffff of
0..$ffff:begin
direccion:=(direccion and $ffff) shr 1;
if tile_ram[direccion]<>valor then begin
tile_ram[direccion]:=valor;
test_tile_buffer(direccion);
end;
end;
$10000..$1ffff:begin
direccion:=(direccion and $fff) shr 1;
if char_ram[direccion]<>valor then begin
char_ram[direccion]:=valor;
gfx[0].buffer[direccion]:=true;
end;
test_screen_change(direccion);
end;
end;
end;
if ((direccion>=s315_5195_0.dirs_start[6]) and (direccion<s315_5195_0.dirs_end[6])) then begin
direccion:=(direccion and $fff) shr 1;
if buffer_paleta[direccion]<>valor then begin
buffer_paleta[direccion]:=valor;
change_pal(direccion,valor);
end;
end;
if ((direccion>=s315_5195_0.dirs_start[7]) and (direccion<s315_5195_0.dirs_end[7])) then begin
case ((direccion and $1fff) shr 1) of //IO
0:s16_info.screen_enabled:=(valor and $20)<>0;
end;
end;
end;
function system16b_snd_getbyte(direccion:word):byte;
var
res:byte;
begin
res:=$ff;
case direccion of
0..$7fff:res:=mem_snd[direccion];
$8000..$dfff:res:=sound_bank[sound_bank_num,direccion and $3fff];
$e800:begin
res:=sound_latch;
z80_0.change_irq(CLEAR_LINE);
end;
$f800..$ffff:res:=mem_snd[direccion];
end;
system16b_snd_getbyte:=res;
end;
procedure system16b_snd_putbyte(direccion:word;valor:byte);
begin
if direccion>$f7ff then mem_snd[direccion]:=valor;
end;
function system16b_snd_inbyte(puerto:word):byte;
var
res:byte;
begin
res:=$ff;
case (puerto and $ff) of
$00..$3f:if (puerto and 1)<>0 then res:=ym2151_0.status;
$80..$bf:res:=upd7759_0.busy_r shl 7;
$c0..$ff:begin
res:=sound_latch;
z80_0.change_irq(CLEAR_LINE);
end;
end;
system16b_snd_inbyte:=res;
end;
procedure system16b_snd_irq(valor:byte);
begin
sound_latch:=valor;
z80_0.change_irq(ASSERT_LINE);
end;
function system16b_sound_5704(valor:byte):byte;
begin
system16b_sound_5704:=valor and $f;
end;
function system16b_sound_5797(valor:byte):byte;
begin
//De momento el maximo de bancos es de 16!
system16b_sound_5797:=(valor and $7) or ((valor and $10) shr 1);// or ((valor and 8) shl 1);
end;
function system16b_sound_5358(valor:byte):byte;
begin
system16b_sound_5358:=(valor and $3)+((not(valor) and $38) shr 1);
end;
procedure system16b_snd_outbyte(puerto:word;valor:byte);
begin
case (puerto and $ff) of
$00..$3f:case (puerto and 1) of
0:ym2151_0.reg(valor);
1:ym2151_0.write(valor);
end;
$40..$7f:begin
upd7759_0.start_w((valor shr 7) and 1);
upd7759_0.reset_w((valor shr 6) and 1);
sound_bank_num:=sound_bank_calc(valor);
end;
$80..$bf:upd7759_0.port_w(valor);
end;
end;
function system16b_mcu_getbyte(direccion:word):byte;
begin
system16b_mcu_getbyte:=s315_5195_0.read_reg(direccion and $1f);
end;
procedure system16b_mcu_putbyte(direccion:word;valor:byte);
var
tempd:dword;
begin
tempd:=s315_5195_0.dirs_start[5];
s315_5195_0.write_reg(direccion and $1f,valor);
if tempd<>s315_5195_0.dirs_start[5] then fillchar(s16_info.tile_buffer,$4000,0);
end;
function in_port1:byte;
begin
in_port1:=marcade.in0;
end;
procedure system16b_sound_act;
begin
ym2151_0.update;
upd7759_0.update;
end;
procedure upd7759_drq(valor:byte);
begin
if (valor and 1)<>0 then z80_0.change_nmi(PULSE_LINE);
end;
//Main
procedure reset_system16b;
var
f:byte;
begin
//Debo poner el direccionamiento antes del reset de la CPU!!!
s315_5195_0.reset;
m68000_0.reset;
z80_0.reset;
mcs51_0.reset;
upd7759_0.reset;
ym2151_0.reset;
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$ffff;
marcade.in2:=$ffff;
if s16_info.mb_type=1 then begin
for f:=0 to $f do sprite_bank[f]:=$ff;
sprite_bank[0]:=0;
sprite_bank[7]:=3;
sprite_bank[11]:=2;
sprite_bank[13]:=1;
sprite_bank[14]:=0;
end else for f:=0 to $f do sprite_bank[f]:=f;
s16_info.screen_enabled:=false;
fillchar(s16_info.tile_buffer,$4000,1);
s16_info.tile_bank[0]:=0;
s16_info.tile_bank[1]:=1;
sound_bank_num:=0;
sound_latch:=0;
s315_5250_bit:=0;
end;
function iniciar_system16b:boolean;
var
f:word;
memoria_temp:pbyte;
memoria_temp2,ptemp:pword;
weights:array[0..1,0..5] of single;
i0,i1,i2,i3,i4:integer;
const
resistances_normal:array[0..5] of integer=(3900, 2000, 1000, 1000 div 2,1000 div 4, 0);
resistances_sh:array[0..5] of integer=(3900, 2000, 1000, 1000 div 2, 1000 div 4, 470);
procedure convert_chars(n:byte);
const
pt_x:array[0..7] of dword=(0, 1, 2, 3, 4, 5, 6, 7 );
pt_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8);
begin
init_gfx(0,8,8,n*$1000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(3,0,8*8,n*$10000*8,n*$8000*8,0);
convert_gfx(0,0,memoria_temp,@pt_x,@pt_y,false,false);
end;
begin
case main_vars.tipo_maquina of
292,293,294:llamadas_maquina.bucle_general:=system16b_principal_mcu;
295,296,297:llamadas_maquina.bucle_general:=system16b_principal;
end;
llamadas_maquina.reset:=reset_system16b;
llamadas_maquina.fps_max:=60.05439;
iniciar_system16b:=false;
iniciar_audio(false);
//text
screen_init(1,512,256,true);
screen_init(2,512,256,true);
//Background
screen_init(3,1024,512);
screen_mod_scroll(3,1024,512,1023,512,256,511);
screen_init(4,1024,512,true);
screen_mod_scroll(4,1024,512,1023,512,256,511);
//Foreground
screen_init(5,1024,512,true);
screen_mod_scroll(5,1024,512,1023,512,256,511);
screen_init(6,1024,512,true);
screen_mod_scroll(6,1024,512,1023,512,256,511);
//Final
screen_init(7,512,256,false,true);
if main_vars.tipo_maquina=296 then main_screen.rot270_screen:=true;
iniciar_video(320,224);
//Main CPU
m68000_0:=cpu_m68000.create(10000000,262);
//Sound CPU
z80_0:=cpu_z80.create(5000000,262);
z80_0.change_ram_calls(system16b_snd_getbyte,system16b_snd_putbyte);
z80_0.change_io_calls(system16b_snd_inbyte,system16b_snd_outbyte);
z80_0.init_sound(system16b_sound_act);
//Memory Mapper
s315_5195_0:=t315_5195.create(m68000_0,z80_0,system16b_snd_irq);
//MCU
mcs51_0:=cpu_mcs51.create(8000000,262);
mcs51_0.change_ram_calls(system16b_mcu_getbyte,system16b_mcu_putbyte);
mcs51_0.change_io_calls(nil,in_port1,nil,nil,nil,nil{out_port1},nil,nil);
//Sound
ym2151_0:=ym2151_chip.create(4000000);
upd7759_0:=upd7759_chip.create(0.9,0,upd7759_drq);
//DIP
marcade.dswa:=$ff;
marcade.dswa_val:=@system16b_dip_a;
region1_read:=nil;
region1_write:=nil;
region2_read:=nil;
region2_write:=nil;
getmem(memoria_temp,$100000);
s16_info.mb_type:=0;
case main_vars.tipo_maquina of
292:begin //Altered Beast
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword_mcu);
if not(roms_load16w(@rom,altbeast_rom)) then exit;
region0_read:=region0_5704_read;
region2_write:=region2_5704_write;
//Sound CPU
if not(roms_load(memoria_temp,altbeast_sound)) then exit;
copymemory(@mem_snd,@memoria_temp[0],$8000);
for f:=0 to $f do copymemory(@sound_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
sound_bank_calc:=system16b_sound_5704;
//MCU
if not(roms_load(mcs51_0.get_rom_addr,altbeast_mcu)) then exit;
//tiles
if not(roms_load(memoria_temp,altbeast_tiles)) then exit;
convert_chars(4);
s16_info.t_banks:=3;
//Sprite ROM
if not(roms_load16w(@sprite_rom,altbeast_sprites)) then exit;
s16_info.s_banks:=8;
marcade.dswb:=$fd;
marcade.dswb_val:=@altbeast_dip_b;
end;
293:begin //Golden Axe
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword_mcu);
if not(roms_load16w(@rom,goldnaxe_rom)) then exit;
region0_read:=region0_5797_read;
region1_read:=region1_5797_read;
region1_write:=region1_5797_write;
//Sound CPU
if not(roms_load(memoria_temp,goldnaxe_sound)) then exit;
copymemory(@mem_snd,@memoria_temp[0],$8000);
for f:=0 to 7 do copymemory(@sound_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
sound_bank_calc:=system16b_sound_5797;
//MCU
if not(roms_load(mcs51_0.get_rom_addr,goldnaxe_mcu)) then exit;
//tiles
if not(roms_load(memoria_temp,goldnaxe_tiles)) then exit;
convert_chars(4);
s16_info.t_banks:=3;
//Sprite ROM
getmem(memoria_temp2,$200000);
ptemp:=memoria_temp2;
if not(roms_load16w(memoria_temp2,goldnaxe_sprites)) then exit;
copymemory(@sprite_rom,ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$100000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$40000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$140000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$80000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$180000 shr 1],ptemp,$40000);
freemem(memoria_temp2);
s16_info.s_banks:=16;
marcade.dswb:=$fd;
marcade.dswb_val:=@goldnaxe_dip_b;
end;
294:begin //Dynamite Dux
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword_mcu);
if not(roms_load16w(@rom,ddux_rom)) then exit;
region0_read:=region0_5704_read;
region1_read:=region1_5704_read;
region2_write:=region2_5704_write;
copymemory(@rom2,@rom[$40000 shr 1],$40000);
//Sound CPU
if not(roms_load(@mem_snd,ddux_sound)) then exit;
sound_bank_calc:=system16b_sound_5704;
//MCU
if not(roms_load(mcs51_0.get_rom_addr,ddux_mcu)) then exit;
//tiles
if not(roms_load(memoria_temp,ddux_tiles)) then exit;
convert_chars(2);
s16_info.t_banks:=1;
//Sprite ROM
if not(roms_load16w(@sprite_rom,ddux_sprites)) then exit;
s16_info.s_banks:=4;
marcade.dswb:=$fe;
marcade.dswb_val:=@ddux_dip_b;
end;
295:begin //Eswat
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword);
if not(roms_load16w(@rom,eswat_rom)) then exit;
region0_read:=region0_5797_read;
region1_read:=region1_5797_read;
region1_write:=region1_5797_write;
//Sound CPU
if not(roms_load(memoria_temp,eswat_sound)) then exit;
copymemory(@mem_snd,@memoria_temp[0],$8000);
for f:=0 to $f do copymemory(@sound_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
sound_bank_calc:=system16b_sound_5797;
//tiles
if not(roms_load(memoria_temp,eswat_tiles)) then exit;
convert_chars(8);
s16_info.t_banks:=7;
//Sprite ROM
getmem(memoria_temp2,$200000);
ptemp:=memoria_temp2;
if not(roms_load16w(memoria_temp2,eswat_sprites)) then exit;
copymemory(@sprite_rom,ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$100000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$40000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$140000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$80000 shr 1],ptemp,$40000);
inc(ptemp,$20000);
copymemory(@sprite_rom[$180000 shr 1],ptemp,$40000);
freemem(memoria_temp2);
s16_info.s_banks:=16;
marcade.dswb:=$fd;
marcade.dswb_val:=@eswat_dip_b;
end;
296:begin //Passing Shot
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword);
if not(roms_load16w(@rom,passsht_rom)) then exit;
region0_read:=region0_5358_read;
//Sound CPU
fillchar(memoria_temp^,$30000,0);
if not(roms_load(memoria_temp,passsht_sound)) then exit;
copymemory(@mem_snd,@memoria_temp[0],$8000);
for f:=0 to 7 do copymemory(@sound_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
sound_bank_calc:=system16b_sound_5358;
//tiles
if not(roms_load(memoria_temp,passsht_tiles)) then exit;
convert_chars(2);
s16_info.t_banks:=1;
//Sprite ROM
if not(roms_load16w(@sprite_rom,passsht_sprites)) then exit;
s16_info.s_banks:=3;
marcade.dswb:=$fe;
marcade.dswb_val:=@passsht_dip_b;
//La placa 5358 usa un tipo diferente de banco de sprites!!
s16_info.mb_type:=1;
end;
297:begin //Aurail
//Main CPU
m68000_0.change_ram16_calls(system16b_getword,system16b_putword);
if not(roms_load16w(@rom,aurail_rom)) then exit;
region0_read:=region0_5704_read;
region1_read:=region1_5704_read;
region2_write:=region2_5704_write;
copymemory(@rom2,@rom[$40000 shr 1],$40000);
//Sound CPU
if not(roms_load(memoria_temp,aurail_sound)) then exit;
copymemory(@mem_snd,@memoria_temp[0],$8000);
for f:=0 to 7 do copymemory(@sound_bank[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
sound_bank_calc:=system16b_sound_5704;
//tiles
if not(roms_load(memoria_temp,aurail_tiles)) then exit;
convert_chars(8);
s16_info.t_banks:=7;
//Sprite ROM
if not(roms_load16w(@sprite_rom,aurail_sprites)) then exit;
s16_info.s_banks:=16;
marcade.dswb:=$fd;
marcade.dswb_val:=@aurail_dip_b;
end;
end;
freemem(memoria_temp);
//poner la paleta
compute_resistor_weights(0,255,-1.0,
6,@resistances_normal[0],@weights[0],0,0,
0,nil,nil,0,0,
0,nil,nil,0,0);
compute_resistor_weights(0,255,-1.0,
6,@resistances_sh[0],@weights[1],0,0,
0,nil,nil,0,0,
0,nil,nil,0,0);
for f:=0 to 31 do begin
i4:=(f shr 4) and 1;
i3:=(f shr 3) and 1;
i2:=(f shr 2) and 1;
i1:=(f shr 1) and 1;
i0:=(f shr 0) and 1;
s16_info.normal[f]:=combine_6_weights(@weights[0],i0,i1,i2,i3,i4,0);
s16_info.shadow[f]:=combine_6_weights(@weights[1],i0,i1,i2,i3,i4,0);
s16_info.hilight[f]:=combine_6_weights(@weights[1],i0,i1,i2,i3,i4,1);
end;
//final
reset_system16b;
iniciar_system16b:=true;
end;
end.
|
unit HGM.Mail.ServerOptions;
interface
uses Classes, System.Types, Generics.Collections, HGM.Common.Settings,
System.SysUtils, IdPOP3, IdSSLOpenSSL, IdIMAP4;
type
TServerType = (stIMAP, stPOP, stSMTP);
TSocketType = (sSSL, sSTARTTLS, sPlain);
TUserName = (unAddress, unLocalPart, unDomain);
TPassType = (ptClearText, ptCRAMMD5, ptOther);
TServerOptions = class
private
FServerType:TServerType;
FSocketType:TSocketType;
FPort:Cardinal;
FHostName:string;
FUserName:TUserName;
FAuthentication:TPassType;
public
constructor Create(AServerType:TServerType; ASocketType:TSocketType; APort:Cardinal; AHostName:string; AUserName:TUserName; AAuthentication:TPassType); overload;
constructor Create; overload;
destructor Destroy; override;
function Save(Settings:TSettings; RelativePath:string):Boolean;
function Load(Settings:TSettings; RelativePath:string):Boolean;
procedure Assign(Source:TServerOptions);
procedure SetSettingsTo(POP3:TIdPOP3); overload;
procedure SetSettingsTo(IOSSL:TIdSSLIOHandlerSocketOpenSSL); overload;
procedure SetSettingsTo(IMAP:TIdIMAP4); overload;
property Authentication:TPassType read FAuthentication write FAuthentication;
property HostName:string read FHostName write FHostName;
property UserName:TUserName read FUserName write FUserName;
property ServerType:TServerType read FServerType write FServerType;
property SocketType:TSocketType read FSocketType write FSocketType;
property Port:Cardinal read FPort write FPort;
end;
TServerOptionList = TList<TServerOptions>;
TISPDB = class
private
FServers:TServerOptionList;
function GET(const URL:string; AResponse:TStringStream):Integer;
function MX(const AEmail:string; AResponse:TStringList):Boolean;
procedure Parse(AXMLResponse:TStringStream);
public
constructor Create;
destructor Destroy; override;
function GetDomain(const AEmail:string):string;
function GetUser(const AEmail: string): string;
function FindOptions(const AEmail:string):Boolean;
function FindServer(AServerType:TServerType; var ASocketType:TSocketType):TServerOptions; overload;
function FindServer(AServerType:TServerType):TServerOptions; overload;
property Servers:TServerOptionList read FServers;
end;
EServerOptionException = class(Exception);
ESettingsNotAssign = class(EServerOptionException);
EUnknownError = class(EServerOptionException);
const
cBaseURL = 'https://autoconfig.thunderbird.net/v1.1/';
cDefaultDNS = '8.8.8.8';
resourcestring
rsWrongEmailAddress = 'Неверно задан адрес почты. Домен не определен';
rsEmptyXML = 'В ответе ISPDB получен пустой XML';
function GetMailServers(const DNSHost, Domain:AnsiString; const Servers:TStrings):Boolean;
implementation
uses StrUtils, IdDNSResolver, IdHTTP, Xml.XMLDoc, Xml.XMLIntf;
function GetMailServers(const DNSHost, Domain:AnsiString; const Servers:TStrings):Boolean;
var i:integer;
begin
Result:=False;
with TIdDNSResolver.Create(nil) do
begin
QueryType:=[qtMX];
Host:=DNSHost;
WaitingTime:=5000;
try
Resolve(Domain);
if QueryResult.Count > 0 then
begin
for i:= 0 to QueryResult.Count-1 do Servers.Append(TMXRecord(QueryResult.Items[i]).ExchangeServer);
Result:=True;
end //ssageDlg('There is no response from the DNS server !', mtInformation, [mbOK], 0);
else Result:=False;
except //ssageDlg('Error resolving domain: ' + e.message, mtInformation, [mbOK], 0);
on E:Exception do Result:=False;
end;
Free;
end;
end;
{ TServerOptions }
procedure TServerOptions.Assign(Source: TServerOptions);
begin
Self.FServerType:=Source.ServerType;
Self.FSocketType:=Source.SocketType;
Self.FPort:=Source.Port;
Self.FHostName:=Source.HostName;
Self.FUserName:=Source.UserName;
Self.FAuthentication:=Source.Authentication;
end;
procedure TServerOptions.SetSettingsTo(POP3:TIdPOP3);
begin
POP3.Host:=FHostName;
POP3.Port:=FPort;
end;
constructor TServerOptions.Create;
begin
inherited Create;
end;
constructor TServerOptions.Create(AServerType:TServerType; ASocketType:TSocketType; APort:Cardinal; AHostName:string; AUserName:TUserName; AAuthentication:TPassType);
begin
Create;
FServerType:=AServerType;
FSocketType:=ASocketType;
FPort:=APort;
FHostName:=AHostName;
FUserName:=AUserName;
FAuthentication:=AAuthentication;
end;
destructor TServerOptions.Destroy;
begin
inherited;
end;
function TServerOptions.Load(Settings: TSettings; RelativePath: string): Boolean;
begin
Result:=False;
if not Assigned(Settings) then raise ESettingsNotAssign.Create('Класс параметров "TSettings" не инициализирован');
try
FServerType:=TServerType(Settings.GetInt(RelativePath, 'ServerType', Ord(TServerType.stSMTP)));
FSocketType:=TSocketType(Settings.GetInt(RelativePath, 'SocketType', Ord(TSocketType.sPlain)));
FPort:=Settings.GetInt(RelativePath, 'Port', 0);
FHostName:=Settings.GetStr(RelativePath, 'HostName', '');
FUserName:=TUserName(Settings.GetInt(RelativePath, 'UserName', Ord(TUserName.unLocalPart)));
FAuthentication:=TPassType(Settings.GetInt(RelativePath, 'Authentication', Ord(TPassType.ptClearText)));
Result:=True;
except
raise EServerOptionException.Create('Ошибка при загрузке параметров');
end;
end;
function TServerOptions.Save(Settings: TSettings; RelativePath: string): Boolean;
begin
Result:=False;
if not Assigned(Settings) then raise ESettingsNotAssign.Create('Класс параметров "TSettings" не инициализирован');
try
Settings.SetInt(RelativePath, 'ServerType', Ord(FServerType));
Settings.SetInt(RelativePath, 'SocketType', Ord(FSocketType));
Settings.SetInt(RelativePath, 'Port', FPort);
Settings.SetStr(RelativePath, 'HostName', FHostName);
Settings.SetInt(RelativePath, 'UserName', Ord(FUserName));
Settings.SetInt(RelativePath, 'Authentication', Ord(FAuthentication));
Result:=True;
except
raise EServerOptionException.Create('Ошибка при сохранении параметров');
end;
end;
procedure TServerOptions.SetSettingsTo(IMAP: TIdIMAP4);
begin
IMAP.Host:=FHostName;
IMAP.Port:=FPort;
end;
procedure TServerOptions.SetSettingsTo(IOSSL: TIdSSLIOHandlerSocketOpenSSL);
begin
IOSSL.Destination:=FHostName+':'+IntToStr(FPort);
IOSSL.Host:=FHostName;
IOSSL.Port:=FPort;
IOSSL.DefaultPort:=0;
IOSSL.SSLOptions.Method:=sslvTLSv1;
IOSSL.SSLOptions.Mode:=sslmUnassigned;
end;
{ TISPDB }
constructor TISPDB.Create;
begin
inherited;
FServers:=TServerOptionList.Create;
end;
destructor TISPDB.Destroy;
begin
FServers.Free;
inherited;
end;
function TISPDB.FindOptions(const AEmail:string):Boolean;
var AStream:TStringStream;
AMX:TStringList;
Str:TStringDynArray;
Domain:string;
begin
FServers.Clear;
Domain:=GetDomain(AEmail);
if Domain.IsEmpty then raise Exception.Create(rsWrongEmailAddress);
AStream:=TStringStream.Create;
try
Result:=GET(cBaseURL + Domain, AStream) = 200;
if Result then Parse(AStream) else
begin
AMX:=TStringList.Create;
try
if MX(AEmail, AMX) then
begin
Str:=SplitString(AMX[0], '.');
AStream.Clear;
Result:=GET(cBaseURL + LowerCase(Str[High(Str) - 1] + '.' + Str[High(Str)]), AStream) = 200;
if Result then Parse(AStream);
end;
finally
AMX.Free;
end;
end;
finally
AStream.Free
end;
end;
function TISPDB.FindServer(AServerType:TServerType):TServerOptions;
var i:Integer;
begin
for i:= 0 to Pred(FServers.Count) do
if (FServers[i].ServerType = AServerType) then Exit(FServers[i]);
Result:=nil;
end;
function TISPDB.FindServer(AServerType:TServerType; var ASocketType:TSocketType):TServerOptions;
var i:Integer;
begin
for i:= 0 to Pred(FServers.Count) do
if (FServers[i].ServerType = AServerType) and (FServers[i].SocketType = ASocketType) then Exit(FServers[i]);
Result:=FindServer(AServerType);
if Assigned(Result) then ASocketType:=Result.SocketType;
end;
function TISPDB.GET(const URL:string; AResponse:TStringStream):Integer;
var HTTP:TIdHTTP;
IdSSLIOHandlerSocketOpenSSL:TIdSSLIOHandlerSocketOpenSSL;
begin
HTTP:=TIdHTTP.Create;
IdSSLIOHandlerSocketOpenSSL:=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
HTTP.IOHandler:=IdSSLIOHandlerSocketOpenSSL;
try
HTTP.HandleRedirects:=True;
HTTP.HTTPOptions:=HTTP.HTTPOptions+[hoNoProtocolErrorException];
HTTP.Get(URL, AResponse);
Result:=HTTP.ResponseCode;
finally
begin
IdSSLIOHandlerSocketOpenSSL.Free;
HTTP.Free;
end;
end;
end;
function TISPDB.GetDomain(const AEmail:string):string;
var i:integer;
begin
Result:=EmptyStr;
i:=Pos('@', AEmail);
if i > 0 then Result:=Trim(Copy(AEmail, i + 1, Length(AEmail) - i));
end;
function TISPDB.GetUser(const AEmail:string):string;
var i:integer;
begin
Result:=EmptyStr;
i:=Pos('@', AEmail);
if i > 0 then Result:=Trim(Copy(AEmail, 1, i-1));
end;
function TISPDB.MX(const AEmail:string; AResponse:TStringList):Boolean;
begin
Result:=GetMailServers(cDefaultDNS, GetDomain(AEmail), AResponse);
end;
procedure TISPDB.Parse(AXMLResponse: TStringStream);
const cServerNodes: array[0..4] of string = ('hostname', 'port', 'socketType', 'username', 'authentication');
var XMLDoc:IXMLDocument;
SOption:TServerOptions;
Node, ServerNode:IXMLNode;
ServerStr:string;
begin
if not Assigned(AXMLResponse) then raise Exception.Create(rsEmptyXML);
XMLDoc:=TXMLDocument.Create(nil);
try
XMLDoc.LoadFromStream(AXMLResponse);
Node:=XMLDoc.DocumentElement.ChildNodes.FindNode('emailProvider');
if Assigned(Node) then Node:=Node.ChildNodes.First;
while Assigned(Node) do
begin
if SameText(Node.NodeName, 'incomingServer') or SameText(Node.NodeName, 'outgoingServer') then
begin
SOption:=TServerOptions.Create;
ServerStr:=Node.Attributes['type'];
// определяем тип сервера
if SameText(ServerStr, 'imap') then SOption.ServerType:=TServerType.stIMAP else
if SameText(ServerStr, 'pop3') then SOption.ServerType:=TServerType.stPOP
else SOption.ServerType:=TServerType.stSMTP;
// читаем настройки сервера
ServerNode:=Node.ChildNodes.First;
while Assigned(ServerNode) do
begin
case AnsiIndexStr(ServerNode.NodeName, cServerNodes) of
0: SOption.HostName:=ServerNode.Text; // hostname
1: SOption.Port:=StrToInt(ServerNode.Text); // port
2: begin // socketType
if SameText(ServerNode.Text, 'SSL') then SOption.SocketType:=TSocketType.sSSL else
if SameText(ServerNode.Text, 'STARTTLS') then SOption.SocketType:=TSocketType.sSTARTTLS
else SOption.SocketType:=TSocketType.sPlain;
end;
3: begin // username
if SameText(ServerNode.Text, '%EMAILADDRESS%')
then SOption.UserName:=unAddress
else SOption.UserName:=unLocalPart;
end;
4: begin // authentication
if SameText(ServerNode.Text, 'password-cleartext') then SOption.Authentication:=ptClearText else
if SameText(ServerNode.Text, 'password-encrypted') then SOption.Authentication:=ptCRAMMD5
else SOption.Authentication:=ptOther;
end;
end;
ServerNode:=ServerNode.NextSibling;
end;
FServers.Add(SOption);
end;
Node:=Node.NextSibling;
end;
finally
XMLDoc:=nil;
end;
end;
end.
|
unit nsThreadNotifier;
{ Автор: Тучнин Д.А. © }
{ Модуль: nsThreadNotifier - объект для синхронизации нотификаций, приходящих с сервера в другой триаде}
{ Начат: 25.10.2005 13:00 }
{ $Id: nsThreadNotifier.pas,v 1.10 2016/03/31 11:52:55 lulin Exp $ }
//$Log: nsThreadNotifier.pas,v $
//Revision 1.10 2016/03/31 11:52:55 lulin
//- перегенерация.
//
//Revision 1.9 2015/01/15 14:17:12 lulin
//{RequestLink:585926571}. Используем Interlocked.
//
//Revision 1.8 2012/08/03 13:17:23 kostitsin
//[$380616604]
// - nsThreadNotifier
//
//Revision 1.7 2008/08/05 06:31:07 lulin
//- переименовываем в рамках <K>: 93264761.
//
//Revision 1.6 2008/02/14 17:08:45 lulin
//- cleanup.
//
//Revision 1.5 2008/01/10 07:23:30 oman
//Переход на новый адаптер
//
//Revision 1.4.22.4 2007/12/11 07:02:38 oman
//Перепиливаем на новый адаптер
//
//Revision 1.4.22.3 2007/12/10 09:39:34 oman
//Перепиливаем на новый адаптер
//
//Revision 1.4.22.2 2007/12/10 09:23:56 oman
//Перепиливаем на новый адаптер
//
//Revision 1.4.22.1 2007/11/16 14:03:50 oman
//Перепиливаем на новый адаптер
//
//Revision 1.4 2005/11/30 16:56:20 lulin
//- при синхронизации посылаем объект, а не буфер.
//
//Revision 1.3 2005/11/21 14:11:01 lulin
//- нотификатор выделен в шаблон.
//
//Revision 1.2 2005/11/15 11:31:27 migel
//- fix: при выходе из оболочки ожидаем полного цикла прохождения нотификации (CQ: 17910).
//
//Revision 1.1 2005/10/25 09:18:34 demon
//- new behavior: выделен отдельный объект (и модуль) TnsThreadNotifier для обработки нотификаций не в основной триаде
//
interface
uses
Classes,
Windows,
Messages,
l3Base,
l3CProtoObject,
l3CacheableBase,
vcmBase,
FoldersUnit
;
type
_ThreadNotifierParent_ = TvcmCacheableBase;
{$Include l3ThreadNotifier.int.pas}
TnsThreadNotifier = class(_ThreadNotifier_)
end;//TnsThreadNotifier
TnsDoneNotifierThread = class(TThread)
private
f_DoneNotifier: IDoneNotifier;
protected
procedure Execute;
override;
{-}
public
constructor Create(aDoneNotifier: IDoneNotifier);
reintroduce;
{-}
end;//TnsDoneNotifierThread
implementation
uses
l3Interlocked,
afwFacade,
SysUtils
;
{$Include l3ThreadNotifier.int.pas}
// Start class TnsDoneNotifierThread
procedure TnsDoneNotifierThread.Execute;
begin
try
try
f_DoneNotifier.Done;
finally
f_DoneNotifier := nil;
end;
except
on E: Exception do
l3System.Exception2Log(E);
end;
end;
constructor TnsDoneNotifierThread.Create(aDoneNotifier: IDoneNotifier);
begin
inherited Create(True);
//
f_DoneNotifier := aDoneNotifier;
end;
end.
|
unit NoticeStdSetup;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, dcCheckBox, dcLabel, ExtCtrls, DataController, ComCtrls,
WPDefs, WPPrint, WpWinCtr, WPRich, editlist, FFSMemo2, Placemnt, Mask,
ToolEdit, CurrEdit, dcCalcEdit, Grids, AdvGrid, RXCtrls, dcCalcEditBtn,
sCheckBox;
type
TfrmNoticeStdSetup = class(TForm)
Panel1: TPanel;
Panel4: TPanel;
Label1: TLabel;
Panel5: TPanel;
BitBtn4: TBitBtn;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
Panel6: TPanel;
FieldList: TAdvStringGrid;
Panel2: TPanel;
dc1: TDataController;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
memHeader: TMemo;
memAddr: TMemo;
memFooter: TMemo;
memBody: TMemo;
rich: TMemo;
lblCategory: TLabel;
lblCat: TdcLabel;
lblCatDesc: TLabel;
lblNotice: TLabel;
lblStage: TdcLabel;
lblLapseDays: TLabel;
edtLapseDays: TdcCalcEditBtn;
cbxCustomer: TdcCheckBox;
cbxCoMaker: TdcCheckBox;
procedure FormCreate(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
procedure FieldListDblClick(Sender: TObject);
procedure memHeaderEnter(Sender: TObject);
procedure memBodyEnter(Sender: TObject);
procedure memFooterEnter(Sender: TObject);
procedure memAddrEnter(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
CurrentEditor : TMemo;
procedure SetNotice(const Value: string);
procedure InsertField;
function GetNotice: string;
{ Private declarations }
public
{ Public declarations }
procedure clear;
property Notice:string read GetNotice write SetNotice;
end;
var
frmNoticeStdSetup: TfrmNoticeStdSetup;
implementation
uses StrUtils, TicklerTypes, TicklerGlobals, categorySetup, ffsutils,
datamod, MergeFields;
const maxHeader = 6;
maxBody = 13;
maxFooter = 7;
{$R *.DFM}
procedure TfrmNoticeStdSetup.clear;
begin
memHeader.Clear;
memBody.clear;
memFooter.clear;
memAddr.Clear;
end;
procedure TfrmNoticeStdSetup.FormCreate(Sender: TObject);
var x : integer;
s : string;
lLoan,
lLend,
lBorr : string;
sl : TStringList;
begin
sl := TStringList.Create;
for x := 0 to MergeFieldMax(CurrentLend)-1 do sl.Add(MergeFieldName(x)+'='+MergeFieldDesc(x));
// remove flood options
// perhaps we could extend the mergefields unit to allow this kinda thing
if not CurrentLend.FloodEnabled then begin
x := 0;
while x<sl.Count do begin
if (sl[x]='FZ=Flood Zone') or
(sl[x]='CV2=Collateral Value 2') or
(sl[x]='MP=Map/Panel') or
(sl[x]='MED=Map Effective Date') then begin
sl.Delete(x);
Continue;
end;
Inc(x);
end;
end;
// remove comaker options
if not CurrentLend.CoMakerEnabled then begin
x := 0;
while x<sl.Count do begin
if (sl[x]='C1=Co-Maker Name') or
(sl[x]='C2=Co-Maker Address 1') or
(sl[x]='C3=Co-Maker Address 2') or
(sl[x]='C4=Co-Maker Address 3') then begin
sl.Delete(x);
Continue;
end;
Inc(x);
end;
end;
// remove Agent options
if not CurrentLend.AgentEnabled then begin
x := 0;
while x < sl.Count do begin
if (sl[x]='AGC=Agent Code') or
(sl[x]='AGN=Agent Name') or
(sl[x]='AG1=Agent Address 1') or
(sl[x]='AG3=Agent Address 3') or
(sl[x]='AGP=Agent Phone') or
(sl[x]='AGE=Agent Email') or
(sl[x]='AG2=Agent Address 2') then begin
sl.Delete(x);
Continue;
end;
Inc(x);
end;
end;
lLoan := CurrentLend.capLoan;
lLend := CurrentLend.capLender;
lBorr := CurrentLend.capBorrower;
FieldList.Clear;
FieldList.RowCount := sl.Count;
for x := 0 to sl.Count-1 do begin
s := Copy(sl[x],Pos('=',sl[x])+1,MAXINT);
s := FindReplace(s, 'Loan', lLoan);
s := FindReplace(s, 'Lender', lLend);
s := FindReplace(s, 'Borrower', lBorr);
fieldlist.Cells[0,x] := Copy(sl[x],1,Pos('=',sl[x])-1);
fieldlist.cells[1,x] := s;
end;
cbxCoMaker.Caption := CurrentLend.capCoMaker;
cbxCoMaker.Visible := CurrentLend.CoMakerEnabled;
CurrentEditor := MemBody;
sl.Free;
end;
procedure TfrmNoticestdSetup.InsertField;
var
s : string;
i : integer;
cp : integer;
lineNo : integer;
begin
i := fieldlist.row;
if CurrentEditor.lines.Count > 0 then
begin
lineNo := CurrentEditor.Caretpos.y;
s := CurrentEditor.lines[lineNo];
insert('<<'+MergeFieldName(i)+'>>', s, CurrentEditor.Caretpos.x+1);
CurrentEditor.Lines[lineNo] := s;
end
else CurrentEditor.Lines.Add('<<'+MergeFieldName(i)+'>>');
CurrentEditor.Refresh;
if CurrentEditor.CanFocus then CurrentEditor.Setfocus;
end;
procedure TfrmNoticeStdSetup.SetNotice(const Value: string);
var x : integer;
rc : integer;
s1,s2 : string;
lcount : integer;
begin
rich.Lines.Text := value;
lcount := rich.lines.count;
rich.Refresh;
Clear;
rc := 3;
for x := 1 to maxHeader do if lcount >= (rc + x) then memHeader.Lines.Add(rich.Lines[rc+x-1]);
rc := 9;
for x := 1 to maxBody do if lcount >= (rc + x) then memBody.Lines.Add(rich.Lines[rc+x-1]);
rc := 23;
for x := 1 to maxFooter do if lcount >= (rc + x) then
begin
s1 := rich.Lines[rc+x-1];
s2 := TrimRight(copy(s1,41,length(s1)-40));
s1 := TrimRight(copy(s1,1,40));
memFooter.Lines.Add(s1);
memAddr.Lines.Add(s2);
end;
end;
procedure TfrmNoticeStdSetup.BitBtn4Click(Sender: TObject);
begin
InsertField;
end;
procedure TfrmNoticeStdSetup.FieldListDblClick(Sender: TObject);
begin
InsertField;
end;
procedure TfrmNoticeStdSetup.memHeaderEnter(Sender: TObject);
begin
CurrentEditor := MemHeader;
end;
procedure TfrmNoticeStdSetup.memBodyEnter(Sender: TObject);
begin
CurrentEditor := MemBody;
end;
procedure TfrmNoticeStdSetup.memFooterEnter(Sender: TObject);
begin
CurrentEditor := MemFooter;
end;
procedure TfrmNoticeStdSetup.memAddrEnter(Sender: TObject);
begin
CurrentEditor := MemAddr;
end;
function TfrmNoticeStdSetup.GetNotice: string;
begin
result := rich.Lines.Text;
end;
procedure TfrmNoticeStdSetup.BitBtn1Click(Sender: TObject);
var x : integer;
s : string;
begin
rich.lines.clear;
for x := 1 to 3 do rich.lines.add('');
// header
for x := 1 to maxHeader do
begin
if memHeader.lines.count >= x then rich.lines.add(memheader.lines[x-1])
else rich.lines.add('');
end;
// body
for x := 1 to maxBody do
begin
if memBody.lines.count >= x then rich.lines.add(membody.lines[x-1])
else rich.lines.add('');
end;
rich.lines.add('');// blank line divider
// footer
for x := 1 to maxFooter do
begin
s := '';
if memFooter.lines.count >= x then s := memFooter.lines[x-1];
s := copy(LeftStr(s,40),1,40);
if memAddr.Lines.count >= x then s := s + memAddr.lines[x-1];
rich.lines.add(s);
end;
for x := 1 to 3 do rich.lines.add('');
modalresult := mrOk;
end;
procedure TfrmNoticeStdSetup.FormShow(Sender: TObject);
begin
cbxCoMaker.Caption := 'Send to '+CurrentLend.capCoMaker;
end;
end.
|
unit deco_16ic;
interface
uses main_engine,gfx_engine;
type
tipo_deco16ic_bank=function(direccion:word):word;
type_pf=class
constructor create(pant:byte;col_bank:byte;call_bank:tipo_deco16ic_bank);
destructor free;
public
data,rowscroll:array[0..$7ff] of word;
buffer_color:array[0..$3f] of boolean;
buffer:array[0..$7ff] of boolean;
procedure reset;
private
pant,color_bank:byte;
bank:word;
call_bank:tipo_deco16ic_bank;
is_8x8:boolean;
end;
chip_16ic=class
constructor create(pant1,pant2:byte;color_base1,color_base2,tmask1,tmask2:word;gfx_plane8,gfx_plane16,col_bank1,col_bank2:byte;call_bank1,call_bank2:tipo_deco16ic_bank);
destructor free;
public
pf1,pf2:type_pf;
color_mask:array[1..2] of word;
gfx_plane:array[1..2] of byte;
procedure reset;
procedure control_w(pos,valor:word);
function control_r(pos:word):word;
procedure update_pf_1(screen:byte;trans:boolean);
procedure update_pf_2(screen:byte;trans:boolean);
private
control:array[0..7] of word;
color_base:array[1..2] of word;
procedure update_plane_1(screen:byte;trans:boolean);
procedure update_plane_2(screen:byte;trans:boolean);
end;
var
deco16ic_0,deco16ic_1:chip_16ic;
implementation
constructor type_pf.create(pant:byte;col_bank:byte;call_bank:tipo_deco16ic_bank);
begin
self.pant:=pant;
screen_init(pant,1024,512,true);
screen_mod_scroll(pant,1024,1024,1023,512,512,511);
self.color_bank:=col_bank;
self.call_bank:=call_bank;
end;
destructor type_pf.free;
begin
end;
procedure type_pf.reset;
begin
fillchar(self.data[0],$800*2,0);
fillchar(self.rowscroll[0],$800*2,0);
fillchar(self.buffer[0],$800,1);
fillchar(self.buffer_color[0],$40,1);
self.bank:=0;
self.is_8x8:=true;
end;
constructor chip_16ic.create(pant1,pant2:byte;color_base1,color_base2,tmask1,tmask2:word;gfx_plane8,gfx_plane16,col_bank1,col_bank2:byte;call_bank1,call_bank2:tipo_deco16ic_bank);
begin
self.pf1:=type_pf.create(pant1,col_bank1,call_bank1);
self.pf2:=type_pf.create(pant2,col_bank2,call_bank2);
self.color_mask[1]:=tmask1;
self.color_mask[2]:=tmask2;
self.color_base[1]:=color_base1;
self.color_base[2]:=color_base2;
self.gfx_plane[1]:=gfx_plane8;
self.gfx_plane[2]:=gfx_plane16;
end;
destructor chip_16ic.free;
begin
end;
procedure chip_16ic.reset;
begin
fillchar(self.control[0],8*2,0);
self.pf1.reset;
self.pf2.reset;
end;
function chip_16ic.control_r(pos:word):word;
begin
control_r:=self.control[pos];
end;
procedure chip_16ic.control_w(pos,valor:word);
begin
if pos=6 then begin
//żes de 8x8?
if (self.control[6] and $80)<>(valor and $80) then fillchar(self.pf1.buffer[0],$800,1);
if (self.control[6] and $8000)<>(valor and $8000) then fillchar(self.pf2.buffer[0],$800,1);
if (valor and $80)<>0 then begin //8x8
screen_mod_scroll(self.pf1.pant,512,512,511,256,256,255);
self.pf1.is_8x8:=true;
end else begin //16x16
screen_mod_scroll(self.pf1.pant,1024,1024,1023,512,512,511);
self.pf1.is_8x8:=false;
end;
if (valor and $8000)<>0 then begin //8x8
screen_mod_scroll(self.pf2.pant,512,512,511,256,256,255);
self.pf2.is_8x8:=true;
end else begin //16x16
screen_mod_scroll(self.pf2.pant,1024,1024,1023,512,512,511);
self.pf2.is_8x8:=false;
end;
end;
self.control[pos]:=valor;
end;
procedure chip_16ic.update_plane_1(screen:byte;trans:boolean);
var
f,x,y,atrib,nchar,pos,rows,cols:word;
color,color_mask:byte;
flipx,flipy:boolean;
begin
for f:=0 to $7ff do begin
x:=f mod 64;
y:=f div 64;
if self.pf1.is_8x8 then pos:=f
else pos:=(x and $1f)+((y and $1f) shl 5)+((x and $20) shl 5)+((y and $20) shl 6);
atrib:=self.pf1.data[pos];
flipx:=false;
flipy:=false;
if self.pf1.is_8x8 then color_mask:=self.color_mask[1]
else color_mask:=self.color_mask[2];
if (atrib and $8000)<>0 then begin
if (self.control[6] and 1)<>0 then begin
flipx:=true;
color_mask:=color_mask shr 1;
end;
if (self.control[6] and 2)<>0 then begin
flipy:=true;
color_mask:=color_mask shr 1;
end;
end;
color:=(atrib shr 12) and color_mask;
if ((self.pf1.buffer[pos]) or (self.pf1.buffer_color[color])) then begin
nchar:=(atrib and $fff) or self.pf1.bank;
if self.pf1.is_8x8 then begin //8x8
if trans then put_gfx_trans_flip(x*8,y*8,nchar,((color+self.pf1.color_bank) shl 4)+self.color_base[1],self.pf1.pant,self.gfx_plane[1],flipx,flipy)
else put_gfx_flip(x*8,y*8,nchar,((color+self.pf1.color_bank) shl 4)+self.color_base[1],self.pf1.pant,self.gfx_plane[1],flipx,flipy);
end else begin //16x16
if trans then put_gfx_trans_flip(x*16,y*16,nchar,((color+self.pf1.color_bank) shl 4)+self.color_base[2],self.pf1.pant,self.gfx_plane[2],flipx,flipy)
else put_gfx_flip(x*16,y*16,nchar,((color+self.pf1.color_bank) shl 4)+self.color_base[2],self.pf1.pant,self.gfx_plane[2],flipx,flipy);
end;
self.pf1.buffer[pos]:=false;
end;
end;
case (self.control[6] and $60) of
$00:scroll_x_y(self.pf1.pant,screen,self.control[1],self.control[2]);
$20:begin //col_scroll
//scroll_x_y(self.pf1.pant,screen,self.control[1],self.control[2]);
cols:=8 shl (self.control[5] and $7);
atrib:=1024 div cols;
scroll__y_part2(self.pf1.pant,screen,atrib,@self.pf1.rowscroll[$200],self.control[1],self.control[2]);
end;
$40:begin //row_scroll
rows:=512 shr ((self.control[5] shr 3) and $f);
if self.pf1.is_8x8 then begin
rows:=rows shr 1;
atrib:=256 div rows;
end else atrib:=512 div rows;
scroll__x_part2(self.pf1.pant,screen,atrib,@self.pf1.rowscroll[0],self.control[1],self.control[2]);
end;
$60:halt(0); //col & row scroll
end;
end;
procedure chip_16ic.update_plane_2(screen:byte;trans:boolean);
var
f,x,y,atrib,nchar,pos,rows,cols:word;
color,color_mask:byte;
flipx,flipy:boolean;
begin
for f:=0 to $7ff do begin
x:=f mod 64;
y:=f div 64;
if self.pf2.is_8x8 then pos:=f
else pos:=(x and $1f)+((y and $1f) shl 5)+((x and $20) shl 5)+((y and $20) shl 6);
atrib:=self.pf2.data[pos];
flipx:=false;
flipy:=false;
if self.pf2.is_8x8 then color_mask:=self.color_mask[1]
else color_mask:=self.color_mask[2];
if (atrib and $8000)<>0 then begin
if (self.control[6] and $100)<>0 then begin
flipx:=true;
color_mask:=color_mask shr 1;
end;
if (self.control[6] and $200)<>0 then begin
flipy:=true;
color_mask:=color_mask shr 1;
end;
end;
color:=(atrib shr 12) and color_mask;
if ((self.pf2.buffer[pos]) or (self.pf2.buffer_color[color])) then begin
nchar:=(atrib and $fff) or self.pf2.bank;
if self.pf2.is_8x8 then begin //8x8
if trans then put_gfx_trans_flip(x*8,y*8,nchar,((color+self.pf2.color_bank) shl 4)+self.color_base[1],self.pf2.pant,self.gfx_plane[1],flipx,flipy)
else put_gfx_flip(x*8,y*8,nchar,((color+self.pf2.color_bank) shl 4)+self.color_base[1],self.pf2.pant,self.gfx_plane[1],flipx,flipy);
end else begin //16x16
if trans then put_gfx_trans_flip(x*16,y*16,nchar,((color+self.pf2.color_bank) shl 4)+self.color_base[2],self.pf2.pant,self.gfx_plane[2],flipx,flipy)
else put_gfx_flip(x*16,y*16,nchar,((color+self.pf2.color_bank) shl 4)+self.color_base[2],self.pf2.pant,self.gfx_plane[2],flipx,flipy);
end;
self.pf2.buffer[pos]:=false;
end;
end;
case ((self.control[6] shr 8) and $60) of
$00:scroll_x_y(self.pf2.pant,screen,self.control[3],self.control[4]);
$20:begin //col_scroll
cols:=8 shl ((self.control[5] shr 8) and $7);
atrib:=1024 div cols;
scroll__y_part2(self.pf2.pant,screen,atrib,@self.pf2.rowscroll[$200],self.control[3],self.control[4]);
end;
$40:begin //row_scroll
rows:=512 shr (((self.control[5] shr 8) shr 3) and $f);
if self.pf2.is_8x8 then begin
rows:=rows shr 1;
atrib:=256 div rows;
end else atrib:=512 div rows;
scroll__x_part2(self.pf2.pant,screen,atrib,@self.pf2.rowscroll[0],self.control[3],self.control[4]);
end;
$60:halt(0); //col & row scroll
end;
end;
procedure chip_16ic.update_pf_1(screen:byte;trans:boolean);
var
bank:word;
begin
if @self.pf1.call_bank<>nil then begin
bank:=self.pf1.call_bank(self.control[7] and $ff);
if bank<>self.pf1.bank then begin
self.pf1.bank:=bank;
fillchar(self.pf1.buffer[0],$800,1);
end;
end;
if (self.control[5] and $80)<>0 then self.update_plane_1(screen,trans);
fillchar(self.pf1.buffer_color[0],$40,0);
end;
procedure chip_16ic.update_pf_2(screen:byte;trans:boolean);
var
bank:word;
begin
if @self.pf2.call_bank<>nil then begin
bank:=self.pf2.call_bank((self.control[7] shr 8) and $ff);
if bank<>self.pf2.bank then begin
self.pf2.bank:=bank;
fillchar(self.pf2.buffer[0],$800,1);
end;
end;
if (self.control[5] and $8000)<>0 then self.update_plane_2(screen,trans);
fillchar(self.pf2.buffer_color[0],$40,0);
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.UITypes;
type
TRegExpForm = class(TForm)
Input: TLabeledEdit;
procedure InputChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
end;
var
RegExpForm: TRegExpForm;
implementation
{$R *.dfm}
uses
System.RegularExpressions;
function IsValid(S: string): Boolean;
begin
Result := TRegEx.IsMatch(S, '^[10]{3,4}([^10]+.*|[^10]*)$');
end;
procedure TRegExpForm.FormCreate(Sender: TObject);
begin
InputChange(Input);
end;
procedure TRegExpForm.InputChange(Sender: TObject);
begin
if IsValid(TEdit(Sender).Text) then
TEdit(Sender).Color := TColors.Lightgreen
else
TEdit(Sender).Color := TColors.Lightcoral;
end;
end.
|
unit sql;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ZConnection, ZDataset, ZDbcIntfs, IBConnection, sqldb,
mssqlconn, sqldblib, DateUtils, FileUtil;
type
TMeltingCharacteristics = Record
tid_ : string[50];
heat_ : string[50];
grade_ : string[50];
StrengthClass_ : string[50];
section_ : string[50];
standard_ : string[50];
rolling_mill_ : string[1];
temperature_ : string[50];
side_ : string[1];
recordid_ : string[50];
end;
var
FConnectOld: TIBConnection;
FTransactionOld: TSQLTransaction;
FQueryOld: TSQLQuery;
FConnect: TZConnection;
FQuery: TZQuery;
// {$DEFINE DEBUG}
function ConfigFirebirdSettingToOldIB(InData: boolean): boolean;
function ConfigFirebirdSetting(InData: boolean; InRollingMill: integer): boolean;
// function ConfigFirebirdSetting(InData: boolean): boolean;
// function ConfigMsSetting(InData: boolean): boolean;
function ReadSql(InRollingMill: integer): boolean;
procedure ReadSqlOld;
function MSSqlWrite(InData: TMeltingCharacteristics): boolean;
implementation
uses
settings, thread_main;
function ConfigFirebirdSettingToOldIB(InData: boolean): boolean;
begin
if InData then
begin
try
FConnectOld := TIBConnection.Create(nil);
FTransactionOld := TSQLTransaction.Create(nil);
FQueryOld := TSQLQuery.Create(nil);
FTransactionOld.Database := FConnectOld;
FTransactionOld.Params.Append('isc_tpb_read_committed');
FTransactionOld.Params.Append('isc_tpb_concurrency');
FTransactionOld.Params.Append('isc_tpb_nowait');
FTransactionOld.Action := caCommit;
FQueryOld.Database := FConnectOld;
FQueryOld.Transaction := FTransactionOld;
FConnectOld.Connected := false;
FConnectOld.DatabaseName := FbSqlSettings[1].db_name;
FConnectOld.Dialect := strtoint(FbSqlSettings[1].dialect);
FConnectOld.HostName := FbSqlSettings[1].ip;
FConnectOld.UserName := FbSqlSettings[1].user;
FConnectOld.Password := FbSqlSettings[1].password;
FConnectOld.LoginPrompt := false;
FConnectOld.Transaction := FTransactionOld;
FConnectOld.Connected := true;
FbSqlSettings[1].configured := true;
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
end
else
begin
FreeAndNil(FTransactionOld);
FreeAndNil(FQueryOld);
FreeAndNil(FConnectOld);
end;
end;
function ConfigFirebirdSetting(InData: boolean; InRollingMill: integer): boolean;
begin
if InData then
begin
try
FConnect := TZConnection.Create(nil);
FQuery := TZQuery.Create(nil);
FConnect.LibraryLocation := '.\fbclient.dll';// отказался от полных путей не читает
FConnect.Protocol := 'firebird-2.5';
FConnect.Database := FbSqlSettings[InRollingMill].db_name;
FConnect.HostName := FbSqlSettings[InRollingMill].ip;
FConnect.User := FbSqlSettings[InRollingMill].user;
FConnect.Password := FbSqlSettings[InRollingMill].password;
FConnect.ReadOnly := True;
FConnect.LoginPrompt := false;
FConnect.Port := 3050;
FConnect.AutoCommit := False;
FConnect.TransactIsolationLevel := tiReadCommitted;
with FConnect.Properties do
begin
Add('Dialect='+FbSqlSettings[InRollingMill].dialect);
Add('isc_tpb_read_committed');
Add('isc_tpb_concurrency'); // Needed for multiuser environments
Add('isc_tpb_nowait'); // Needed for multiuser environments
Add('timeout=3');
// Add('codepage=NONE');
// Add('controls_cp=CP_UTF8');
// Add('AutoEncodeStrings=ON');
// Add('codepage=win1251');
// Add('client_encoding=UTF8');
end;
FConnect.Connect;
FbSqlSettings[InRollingMill].configured := true;
FQuery.Connection := FConnect;
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
end
else
begin
FreeAndNil(FQuery);
FreeAndNil(FConnect);
end;
end;
function ReadSql(InRollingMill: integer): boolean;
var
heat, recordid, table_name: string;
tid, heat_local, grade, standard, StrengthClassLeft, StrengthClassRight,
SectionLeft, SectionRight: string;
timestamp: TDateTime;
TempLeft, TempRight: integer;
OutToSql: TMeltingCharacteristics;
str: TStringList;
begin
try
if FConnect <> nil then begin
if not FConnect.Ping then
FConnect.Reconnect;
end;
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
try
FQuery.Close;
FQuery.SQL.Clear;
FQuery.SQL.Add('select FIRST 1 begindt, NOPLAV as heat,');
FQuery.SQL.Add('MARKA as grade, STANDART as standard');
FQuery.SQL.Add('FROM melts where state=1 order by begindt desc');
FQuery.Open;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
try
heat := FQuery.FieldByName('heat').AsString;
grade := FQuery.FieldByName('grade').AsString;
standard := FQuery.FieldByName('standard').AsString;
heat_local := StringReplace(heat,'-','_', [rfReplaceAll]);
timestamp := FQuery.FieldByName('begindt').AsDateTime;
table_name := 'P'+FormatDateTime('yymmdd', timestamp)+'N'+heat_local
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
try
FQuery.Close;
FQuery.SQL.Clear;
FQuery.SQL.Add('select *');
FQuery.SQL.Add('FROM '+table_name);
FQuery.SQL.Add('where recordid=(select max(recordid)');
FQuery.SQL.Add('FROM '+table_name+')');
FQuery.Open;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
try
tid := inttostr(DateTimeToUnix(timestamp));
str := TStringList.Create;
recordid := FQuery.FieldByName('recordid').AsString;
str.Text := StringReplace(FQuery.FieldByName('SECL').AsString, '_', #13#10, [rfReplaceAll]);
SectionLeft := str.Strings[0];
StrengthClassLeft := UpperCase(str.Strings[1]);
str.Free;
str := TStringList.Create;
str.Text := StringReplace(FQuery.FieldByName('SECR').AsString, '_', #13#10, [rfReplaceAll]);
SectionRight := str.Strings[0];
StrengthClassRight := UpperCase(str.Strings[1]);
str.Free;
TempLeft := FQuery.FieldByName('TMOUTL').AsInteger;
TempRight := FQuery.FieldByName('TMOUTR').AsInteger;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
{$IFDEF DEBUG}
SaveLog.Log(etDebug, 'tid -> '+tid);
SaveLog.Log(etDebug, 'heat -> '+heat);
SaveLog.Log(etDebug, 'grade -> '+grade);
SaveLog.Log(etDebug, 'standard -> '+standard);
SaveLog.Log(etDebug, 'recordid -> '+recordid);
SaveLog.Log(etDebug, 'SectionLeft -> '+SectionLeft);
SaveLog.Log(etDebug, 'StrengthClassLeft -> '+StrengthClassLeft);
SaveLog.Log(etDebug, 'TempLeft -> '+inttostr(TempLeft));
SaveLog.Log(etDebug, 'SectionRight -> '+SectionRight);
SaveLog.Log(etDebug, 'StrengthClassRight -> '+StrengthClassRight);
SaveLog.Log(etDebug, 'TempRight -> '+inttostr(TempRight));
SaveLog.Log(etDebug, 'rolling mill -> '+inttostr(InRollingMill));
{$ENDIF}
if 250 < TempLeft then begin
with OutToSql do begin
tid_ := tid;
heat_ := heat;
grade_ := grade;
StrengthClass_ := StrengthClassLeft;
section_ := SectionLeft;
standard_ := standard;
rolling_mill_ := inttostr(InRollingMill);
temperature_ := inttostr(TempLeft);
side_ := '0';
recordid_ := recordid;
end;
MSSqlWrite(OutToSql);
//free memory
Finalize(OutToSql);
FillChar(OutToSql,sizeof(OutToSql),0);
end;
if 250 < TempRight then begin
with OutToSql do begin
tid_ := tid;
heat_ := heat;
grade_ := grade;
StrengthClass_ := StrengthClassRight;
section_ := SectionRight;
standard_ := standard;
rolling_mill_ := inttostr(InRollingMill);
temperature_ := inttostr(TempRight);
side_ := '1';
recordid_ := recordid;
end;
MSSqlWrite(OutToSql);
//free memory
Finalize(OutToSql);
FillChar(OutToSql,sizeof(OutToSql),0);
end;
end;
procedure ReadSqlOld;
var
heat, recordid, table_name: string;
tid, heat_local, grade, standard, StrengthClassLeft, StrengthClassRight,
SectionLeft, SectionRight: string;
timestamp: TDateTime;
TempLeft, TempRight: integer;
OutToSql: TMeltingCharacteristics;
str: TStringList;
begin
try
if FConnectOld <> nil then begin
if not FConnectOld.Connected then
FConnectOld.Connected := true;
end;
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
{$IFDEF DEBUG}
SaveLog.Log(etDebug, 'configured -> '+booltostr(FbSqlSettings[1].configured));
{$ENDIF}
try
FTransactionOld.Active:=false;
FQueryOld.Close;
FQueryOld.SQL.Clear;
FQueryOld.SQL.Add('select BEGINDT, NOPLAV as heat,');
FQueryOld.SQL.Add('MARKA as grade, KLASS as standard');
FQueryOld.SQL.Add('FROM melts where state=1');
FQueryOld.Open;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
try
heat := FQueryOld.FieldByName('heat').AsString;
grade := FQueryOld.FieldByName('grade').AsString;
standard := FQueryOld.FieldByName('standard').AsString;
heat_local := StringReplace(heat,'-','_', [rfReplaceAll]);
timestamp := FQueryOld.FieldByName('begindt').AsDateTime;
table_name := 'PARAMS'+heat_local;
except
on E: Exception do
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
end;
try
FTransactionOld.Active:=false;
FQueryOld.Close;
FQueryOld.SQL.Clear;
FQueryOld.SQL.Add('select *');
FQueryOld.SQL.Add('FROM '+table_name);
FQueryOld.SQL.Add('where recordid=(select max(recordid)');
FQueryOld.SQL.Add('FROM '+table_name+')');
FQueryOld.Open;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
try
tid := inttostr(DateTimeToUnix(timestamp));
str := TStringList.Create;
recordid := FQueryOld.FieldByName('recordid').AsString;
str.Text := StringReplace(FQueryOld.FieldByName('SECTIONL').AsString, '_', #13#10, [rfReplaceAll]);
SectionLeft := str.Strings[0];
StrengthClassLeft := UpperCase(str.Strings[1]);
str.Free;
str := TStringList.Create;
str.Text := StringReplace(FQueryOld.FieldByName('SECTIONR').AsString, '_', #13#10, [rfReplaceAll]);
SectionRight := str.Strings[0];
StrengthClassRight := UpperCase(str.Strings[1]);
str.Free;
TempLeft := FQueryOld.FieldByName('TOTPL').AsInteger;
TempRight := FQueryOld.FieldByName('TOTPP').AsInteger;
except
on E: Exception do begin
SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message);
exit;
end;
end;
{$IFDEF DEBUG}
SaveLog.Log(etDebug, 'tid -> '+tid);
SaveLog.Log(etDebug, 'heat -> '+heat);
SaveLog.Log(etDebug, 'grade -> '+grade);
SaveLog.Log(etDebug, 'standard -> '+standard);
SaveLog.Log(etDebug, 'recordid -> '+recordid);
SaveLog.Log(etDebug, 'SectionLeft -> '+SectionLeft);
SaveLog.Log(etDebug, 'StrengthClassLeft -> '+StrengthClassLeft);
SaveLog.Log(etDebug, 'TempLeft -> '+inttostr(TempLeft));
SaveLog.Log(etDebug, 'SectionRight -> '+SectionRight);
SaveLog.Log(etDebug, 'StrengthClassRight -> '+StrengthClassRight);
SaveLog.Log(etDebug, 'TempRight -> '+inttostr(TempRight));
SaveLog.Log(etDebug, 'rolling mill -> 1');//+inttostr(InRollingMill));
{$ENDIF}
if 250 < TempLeft then begin
with OutToSql do begin
tid_ := tid;
heat_ := heat;
grade_ := grade;
StrengthClass_ := StrengthClassLeft;
section_ := SectionLeft;
standard_ := standard;
rolling_mill_ := '1';
temperature_ := inttostr(TempLeft);
side_ := '0';
recordid_ := recordid;
end;
MSSqlWrite(OutToSql);
//free memory
Finalize(OutToSql);
FillChar(OutToSql,sizeof(OutToSql),0);
end;
if 250 < TempRight then begin
with OutToSql do begin
tid_ := tid;
heat_ := heat;
grade_ := grade;
StrengthClass_ := StrengthClassRight;
section_ := SectionRight;
standard_ := standard;
rolling_mill_ := '1';
temperature_ := inttostr(TempRight);
side_ := '1';
recordid_ := recordid;
end;
MSSqlWrite(OutToSql);
//free memory
Finalize(OutToSql);
FillChar(OutToSql,sizeof(OutToSql),0);
end;
end;
function MSSqlWrite(InData: TMeltingCharacteristics): boolean;
var
MSDBLibraryLoader: TSQLDBLibraryLoader;
MSConnection: TMSSQLConnection;
MSQuery: TSQLQuery;
MSTransaction: TSQLTransaction;
begin
{$IFDEF DEBUG}
SaveLog.Log(etDebug, 'ms tid -> '+InData.tid_);
SaveLog.Log(etDebug, 'ms heat -> '+InData.heat_);
SaveLog.Log(etDebug, 'ms grade -> '+InData.grade_);
SaveLog.Log(etDebug, 'ms StrengthClass -> '+InData.StrengthClass_);
SaveLog.Log(etDebug, 'ms recordid -> '+InData.recordid_);
SaveLog.Log(etDebug, 'ms section -> '+InData.section_);
SaveLog.Log(etDebug, 'ms standard -> '+InData.standard_);
SaveLog.Log(etDebug, 'ms temperature -> '+InData.temperature_);
SaveLog.Log(etDebug, 'ms side -> '+InData.side_);
SaveLog.Log(etDebug, 'ms rolling_mill -> '+InData.rolling_mill_);
{$ENDIF}
{ MSConnect := TZConnection.Create(nil);
MSQuery := TZQuery.Create(nil);}
MSDBLibraryLoader := TSQLDBLibraryLoader.Create(nil);
MSConnection := TMSSQLConnection.Create(nil);
MSQuery := TSQLQuery.Create(nil);
MSTransaction := TSQLTransaction.Create(nil);
try
MSDBLibraryLoader.ConnectionType := 'MSSQLServer';
MSDBLibraryLoader.LibraryName := '.\'+MsSqlSettings.lib;
MSConnection.DatabaseName := MsSqlSettings.db_name;
MSConnection.HostName := MsSqlSettings.ip;
MSConnection.Transaction := MSTransaction;
MSTransaction.DataBase := MSConnection;
MSTransaction.Action := caCommit;
MSQuery.DataBase := MSConnection;
MSQuery.Transaction := MSTransaction;
{ MSConnect.LibraryLocation := '.\'+MsSqlSettings.lib;
MSConnect.Protocol := 'FreeTDS_MsSQL>=2005';
//BD надо перевести в кодировку Cyrillic_General_CI_AS для отображения кирилицы
{ ALTER DATABASE [KRR-PA-MGT-QCRollingMill] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE [KRR-PA-MGT-QCRollingMill] COLLATE Cyrillic_General_CI_AS
ALTER DATABASE [KRR-PA-MGT-QCRollingMill] SET MULTI_USER}
// MSConnect.ControlsCodePage := cCP_UTF8;//cCP_UTF8;
// MSConnect.AutoEncodeStrings := False;
// MSConnect.ClientCodePage := 'CP866';//'WIN1251';
MSConnect.HostName := MsSqlSettings.ip;
MSConnect.Port := MsSqlSettings.port;
MSConnect.User := MsSqlSettings.user;
MSConnect.Password := MsSqlSettings.password;
MSConnect.Database := MsSqlSettings.db_name;
MSConnect.Connect;
MSQuery.Connection := MSConnect;}
except
on E : Exception do
SaveLog.Log(etError, E.ClassName+', с сообщением: '+E.Message);
end;
try
MSDBLibraryLoader.Enabled := true;
MSConnection.Connected := true;
MSQuery.Close;
MSQuery.SQL.Clear;
MSQuery.SQL.Add('UPDATE temperature_current SET temperature='+InData.temperature_+'');
MSQuery.SQL.Add('where tid='+InData.tid_+' and rolling_mill='+InData.rolling_mill_+' and side='+InData.side_+'');
MSQuery.SQL.Add('IF @@ROWCOUNT=0');
MSQuery.SQL.Add('INSERT INTO temperature_current (tid, [timestamp], ');
MSQuery.SQL.Add('rolling_mill, heat, grade, strength_class, section, ');
MSQuery.SQL.Add('standard, side, temperature) values ( ');
MSQuery.SQL.Add(''+InData.tid_+', datediff(ss, ''1970/01/01'', GETDATE()),');
MSQuery.SQL.Add(''+InData.rolling_mill_+', '''+UTF8Encode(InData.heat_)+''', ');
MSQuery.SQL.Add(''''+UTF8Encode(InData.grade_)+''', '''+UTF8Encode(InData.StrengthClass_)+''', ');
MSQuery.SQL.Add(''+InData.section_+', '''+UTF8Encode(InData.standard_)+''', ');
MSQuery.SQL.Add(''+InData.side_+', '+InData.temperature_+' ) ');
{{$IFDEF DEBUG}
SaveLog.Log(etDebug, 'MSQuery.SQL.Text -> '+MSQuery.SQL.Text);
{$ENDIF}}
MSQuery.ExecSQL;
except
on E : Exception do
SaveLog.Log(etError, E.ClassName+', с сообщением: '+E.Message);
end;
FreeAndNil(MSDBLibraryLoader);
FreeAndNil(MSConnection);
FreeAndNil(MSQuery);
FreeAndNil(MSTransaction);
//free memory
Finalize(InData);
FillChar(InData,sizeof(InData),0);
end;
end.
|
unit vtSaveDialog;
{------------------------------------------------------------------------------}
{ Библиоткека : VT }
{ Автор : М. Морозов }
{ Создан : 25.05.2006 г. }
{ Назначение : Диалог сохранения решающий проблему смену расширения файла в }
{ строке FileName диалога при выборе другого расширение в списке }
{ Filters. }
{------------------------------------------------------------------------------}
// $Id: vtSaveDialog.pas,v 1.15 2016/04/21 08:19:40 morozov Exp $
// $Log: vtSaveDialog.pas,v $
// Revision 1.15 2016/04/21 08:19:40 morozov
// {RequestLink: 621277863}
//
// Revision 1.14 2016/04/19 08:47:20 morozov
// {RequestLink: 621277863}
//
// Revision 1.13 2013/04/24 09:35:37 lulin
// - портируем.
//
// Revision 1.12 2013/04/17 14:20:20 lulin
// - портируем.
//
// Revision 1.11 2007/08/14 19:31:40 lulin
// - оптимизируем очистку памяти.
//
// Revision 1.10 2007/04/03 13:34:17 oman
// - new: Запрещаем поле ввода при записи в разные файлы (cq24791)
//
// Revision 1.9 2007/03/20 13:10:24 lulin
// - не ищем адрес процедуры каждый раз.
//
// Revision 1.8 2007/03/20 13:04:57 lulin
// - cleanup.
//
// Revision 1.7 2007/03/20 13:01:31 lulin
// - bug fix: не там отрезали звездочки.
//
// Revision 1.6 2007/03/20 12:28:48 lulin
// - используем родной список строк.
//
// Revision 1.5 2007/03/20 12:17:30 lulin
// - cleanup.
//
// Revision 1.4 2006/07/24 15:02:19 mmorozov
// - new behaviour: устанавливаем расширение файла, если у пользователя стоит режим показывать расширение для известных файлов;
// - new: не путаем имя с точками, которые задал пользовать с фильтрами, для корректной смены расширения при смене фильтра;
//
// Revision 1.3 2006/06/26 12:52:12 mmorozov
// - optimization: список фильтров формируется только один раз;
//
// Revision 1.2 2006/05/30 07:49:34 mmorozov
// - bugfix: отрезаем расширение у имени файла, если оно определено, и пользователь меняет тип файла, с включенной настройкой не показывать расширения (CQ: OIT500020954);
//
// Revision 1.1 2006/05/25 14:25:18 mmorozov
// - new: диалог сохранения;
//
interface
uses
Classes,
Types,
Dialogs,
ShlObj,
l3VCLStrings
;
type
TvtSaveDialog = class(TSaveDialog)
{* Диалог сохранения. }
private
// internal fields
f_CurrentFilter : String;
f_Filters : Tl3Strings;
f_NeedSkipSelChanged : Boolean;
private
// internal methods
function DefineCurrentFilter: String;
{* - получить текущий фильтр. }
procedure ChangeExtension;
{-}
function DialogHandle: THandle;
{-}
private
// property methods
function pm_GetFilters: Tl3Strings;
{* - список фильтров в формате '.txt'. }
protected
// properties
property Filters: Tl3Strings
read pm_GetFilters;
{* - список фильтров в формате '.txt'. }
protected
// protected methods
function GetFileNameEditHandle: THandle;
{-}
function GetFileNameForAdjust: AnsiString;
virtual;
{* - Получить имя файла для корректировки расширения }
procedure SetAdjustedFileName(const aFileName: AnsiString);
virtual;
{* - Установить откорректированное имя файла}
procedure FirstCorrectFileName;
virtual;
{-}
procedure DoTypeChange;
override;
{* - меняем тип файла при смене фильтра. }
procedure DoSelectionChange;
override;
{-}
procedure DoShow;
override;
{-}
public
// methods
destructor Destroy;
override;
{-}
end;//TvtSaveDialog
function vtNeedShowExtentions: Boolean;
{* - определяет нужно ли показывать расширения для известных системе файлов. }
implementation
uses
Windows,
SysUtils,
StrUtils,
l3Base
;
const
c_fnSHGetSettings = 'SHGetSettings';
c_shell32 = 'shell32.dll';
var
g_GetSettingsProc: Pointer = nil;
procedure vtSHGetSettings(var lpss: TShellFlagState; dwMask: DWORD); stdcall;
begin
if (g_GetSettingsProc = nil) then
g_GetSettingsProc := GetProcAddress(GetModuleHandle(c_shell32), c_fnSHGetSettings);
if (g_GetSettingsProc <> nil) then
asm
mov esp, ebp
pop ebp
jmp [g_GetSettingsProc]
end//asm
else
l3FillChar(lpss, SizeOf(lpss), 0);
end;//vtSHGetSettings
function vtNeedShowExtentions: Boolean;
{* - определяет нужно ли показывать расширения для известных системе файлов. }
var
l_ShellFlag: TShellFlagState;
begin
vtSHGetSettings(l_ShellFlag, SSF_SHOWEXTENSIONS);
Result := l_ShellFlag.Data > 0;
end;//vtNeedShowExtentions
var
g_FileNameDlgCtlId: Integer = 0;
// - идентификатор поля "Имя файла" в диалоге сохранения, определяется при
// первом обращении;
function FindFileNameDlgCtlId(aCtrl: HWND; aParam: LPARAM): Bool; stdcall;
{* - aParam - указатель на Integer, в котором нужно вернуть результат. }
const
c_BufferSize = 80;
c_FileNameClass = 'EDIT';
var
l_ClassName : array [0..80] of Char;
l_Temp : String;
begin
Result := True;
// Получим имя класса:
Windows.GetClassName(aCtrl, l_ClassName, c_BufferSize);
l_Temp := l_ClassName;
// Это поле имя файла:
if AnsiUpperCase(l_Temp) = c_FileNameClass then
begin
PInteger(aParam)^ := Windows.GetDlgCtrlID(aCtrl);
// Дальше итерировать не нужно:
Result := False;
end;//if AnsiUpperCase(l_Temp) = c_FileNameClass then
end;//EnumChildProc
function vtFileNameDlgCtlId(const aHandle: HWND): Integer;
{* - см. g_FileNameDlgCtlId. }
begin
if g_FileNameDlgCtlId = 0 then
EnumChildWindows(Windows.GetParent(aHandle), @FindFileNameDlgCtlId,
Integer(@g_FileNameDlgCtlId));
Assert(g_FileNameDlgCtlId <> 0, 'FileName dialog control id wasn`t define.');
Result := g_FileNameDlgCtlId;
end;//vtFileNameDlgCtlId
{ TvtSaveDialog }
function TvtSaveDialog.pm_GetFilters: Tl3Strings;
{* - список фильтров в формате '.txt'. }
begin
if (f_Filters = nil) then
f_Filters := Tl3Strings.Create;
Result := f_Filters;
end;
function TvtSaveDialog.DefineCurrentFilter: String;
const
cFilterSeparator = '|';
cAsterisk = '*';
var
l_Pos: Integer;
function lp_GetToken(const aStr: String; out aToken: String): Boolean;
var
l_Begin: Integer;
l_End: Integer;
begin
Result := False;
l_Begin := l_Pos;
while (l_Pos <= Length(aStr)) do
begin
Result := True;
if (aStr[l_Pos] = cFilterSeparator) or (l_Pos > Length(aStr)) then
begin
l_End := l_Pos;
Inc(l_Pos);
Break;
end
else
Inc(l_Pos);
end;
aToken := Copy(aStr, l_Begin, l_End - l_Begin);
end;
procedure DoAdd(const aStr: String);
begin
f_Filters.Add(AnsiReplaceStr(aStr, cAsterisk, ''))
end;
var
l_Index : Integer;
l_DisplayName : Boolean;
l_Temp : String;
begin
Result := DefaultExt;
if (Filter <> '') and (Filters.Count = 0) then
begin
l_Pos := 1;
l_DisplayName := True;
while lp_GetToken(Filter, l_Temp) do
begin
if (not l_DisplayName) then
DoAdd(l_Temp);
// DisplayName - первый блок, сам фильтр - второй и т.д.
l_DisplayName := not l_DisplayName;
end;
end;//if Filter <> '' then
if (FilterIndex < Filters.Count) then
Result := Filters[Pred(FilterIndex)].AsString
else
Result := '';
// - последним в списке идёт фильтр "Все файлы"
end;//DefineCurrentFilter
destructor TvtSaveDialog.Destroy;
// override;
{-}
begin
FreeAndNil(f_Filters);
inherited;
end;
procedure TvtSaveDialog.DoShow;
// override;
{-}
begin
f_NeedSkipSelChanged := True;
inherited;
end;
procedure TvtSaveDialog.DoSelectionChange;
// override;
{-}
begin
// Зададим расширение в имени, если у пользователя стоит режим показывать
// расширения для известных файлов:
if not f_NeedSkipSelChanged then
FirstCorrectFileName;
f_NeedSkipSelChanged := False;
inherited;
end;
procedure TvtSaveDialog.ChangeExtension;
{-}
var
l_FileName: String;
function lp_IsValidExtension: Boolean;
{-}
var
l_FileExt: String;
l_Index: Integer;
begin//lp_IsValidExtension
Result := False;
l_FileExt := ExtractFileExt(l_FileName);
for l_Index := 0 to Pred(f_Filters.Count) do
begin
// http://mdp.garant.ru/pages/viewpage.action?pageId=621277863
Result := AnsiSameText(f_Filters[l_Index].AsString, l_FileExt);
if Result then
Exit;
end;
end;//lp_IsValidExtension
var
l_Temp: String;
begin
f_CurrentFilter := DefineCurrentFilter;
if (f_CurrentFilter <> '') then
begin
l_FileName := GetFileNameForAdjust;
if vtNeedShowExtentions then
// У пользователя может быть задано имя с точками (например "ЧЕРТЕЖ 13.
// СХЕМА УСТАНОВКИ СВЕТОВОЗВРАЩАЮЩЕЙ ПЛЕНКИ") не будем путать его с
// фильтрами:
if lp_IsValidExtension then
l_Temp := ChangeFileExt(l_FileName, f_CurrentFilter)
else
l_Temp := l_FileName + f_CurrentFilter
else
begin
// У пользователя может быть задано имя с точками (например "ЧЕРТЕЖ 13.
// СХЕМА УСТАНОВКИ СВЕТОВОЗВРАЩАЮЩЕЙ ПЛЕНКИ") не будем путать его с
// фильтрами:
if lp_IsValidExtension then
l_Temp := ChangeFileExt(l_FileName, '')
else
l_Temp := l_FileName;
end;
SetAdjustedFileName(l_Temp);
end;//if f_CurrentFilter <> '' then
end;
procedure TvtSaveDialog.DoTypeChange;
begin
ChangeExtension;
inherited;
end;
procedure TvtSaveDialog.FirstCorrectFileName;
begin
ChangeExtension;
end;
function TvtSaveDialog.GetFileNameEditHandle: THandle;
begin
Result := Windows.GetDlgItem(DialogHandle, vtFileNameDlgCtlId(Handle));
end;
function TvtSaveDialog.GetFileNameForAdjust: AnsiString;
const
c_BufferSize = 255;
var
l_FileName : array [0..c_BufferSize] of AnsiChar;
begin
l3FillChar(l_FileName, SizeOf(l_FileName));
Windows.GetDlgItemTextA(DialogHandle, vtFileNameDlgCtlId(Handle), l_FileName, c_BufferSize);
Result := StrPas(l_FileName);
end;
procedure TvtSaveDialog.SetAdjustedFileName(const aFileName: AnsiString);
begin
Windows.SetDlgItemTextA(DialogHandle, vtFileNameDlgCtlId(Handle), PAnsiChar(aFileName));
end;
function TvtSaveDialog.DialogHandle: THandle;
begin
Result := Windows.GetParent(Handle);
end;
end.
|
unit udmHabilidade;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmHabilidade = class(TdmPadrao)
protected
private
FRegistro: Double;
FCurso: String;
public
property Registro: Double read FRegistro write FRegistro;
property Curso: String read FCurso write FCurso;
function LocalizarHabilidade(DataSet: TDataSet): Boolean;
end;
const
SQL_DEFAULT =
' SELECT ' +
' REGISTRO, ' +
' DESCRICAO_CURSO, ' +
' DATA_REALIZACAO, ' +
' CARGA_HORARIA, ' +
' LOCAL_DO_EVENTO, ' +
' OPERADOR, ' +
' DT_ALTERACAO ' +
' FROM STWCPGTFUN4 ';
var
dmHabilidade: TdmHabilidade;
implementation
{$R *.dfm}
{ TdmHabilidade }
function TdmHabilidade.LocalizarHabilidade(DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE REGISTRO = :REGISTRO ');
SQL.Add(' AND DESCRICAO_CURSO = :DESCRICAO_CURSO ');
Params[0].AsFloat := FRegistro;
Params[1].AsString := FCurso;
Open;
Result := not IsEmpty;
end;
end;
end.
|
uses DrugDealData,DOS;
{$V-}
function fileExist(var s : string) : boolean;
begin
fileExist := fSearch(s, '') <> '';
end;
procedure Update;
begin
writeln;
writeln(' You are in: ',City[Dealer.CurCity].Name,'.');
writeln(' Your weapon is: ',GunName[Dealer.Gun],'.');
writeln('Your mode of travel is: ',TransName[Dealer.Trans],'.');
end;
procedure SaveGame;
var
fn : string[30];
f : file;
begin
writeln;
write('Save game to filename> ');
readln(fn);
if fileexist(fn) then
write('Overwriting file...')
else
write('Saving File...');
assign(f,fn);
rewrite(f,1);
blockwrite(f,dealer,sizeof(dealerinfotype));
write('....');
blockwrite(f,city,sizeof(cityarray));
write('........');
blockwrite(f,drug,sizeof(drugarray));
writeln('......');
close(f);
writeln('Done!');
end;
procedure LoadGame;
var
fn : string[30];
f : file;
begin
writeln;
write('Load game from filename> ');
readln(fn);
if not fileexist(fn) then
writeln('File not found.')
else begin
write('Loading File...');
assign(f,fn);
reset(f,1);
blockread(f,dealer,sizeof(dealerinfotype));
write('....');
blockread(f,city,sizeof(cityarray));
write('........');
blockread(f,drug,sizeof(drugarray));
writeln('......');
close(f);
writeln('Done!');
end;
end;
begin
writeln('Kingston and Windsor: ',
Distance[Kingston,Windsor],' ',Distance[Windsor,Kingston]);
writeln('Windsor and Cornwall: ',Distance[Windsor,Cornwall]);
writeln('Ottawa and Windsor: ',Distance[Ottawa,Windsor]);
writeln(Distance[Hamilton,Hamilton]);
Update;
Dealer.CurCity:=CornWall;
Dealer.Gun:=FullAuto;
Dealer.Trans := BadCar;
Update;
SaveGame;
Dealer.CurCity := Toronto;
Dealer.Gun:=SemiAuto;
Dealer.Trans:=GoodCar;
Update;
LoadGame;
Update;
end.
|
unit PolUnit;
interface
const
// Точность сравнения с нулем чисел с плавающей запятой
POL_UNIT_EPSILON = 0.0001;
type
// Линейный односвязный список, в каждом элементе списка 3 поля:
// Coef - Коэффициент при члене степени Degree
// Degree - Степень члена
// Next - Указатель на следующий элемент списка
TPtr = ^TList;
TList = record
Coef: Double;
Degree: Integer;
Next: TPtr;
end;
// Указатель на заглавный элемент списка с многочленом
TPolynomial = TPtr;
// Функция попытки преобразования строки stringWithPol в многочлен pol
// Возвращает True, если преобразование удалось
// Возвращает False в обратном случае
function TryStrToPol(stringWithPol: string; var pol: TPolynomial): Boolean;
// Функция преобразования многочлена pol в строку
// Возвращает строку с многочленом
function PolToStr(pol: TPolynomial): string;
// Функция копирования списка с многочленом polToCopy
// Возвращает указатель на заглавный элемент списка со скопированным многочленом
function PolCopy(polToCopy: TPolynomial): TPolynomial;
// Процедура полного удаления списка с многочленом polToDestroy
procedure PolDestroy(var polToDestroy: TPolynomial);
// Все последующие функции возвращают указатель на заглавный элемент списка с результирующим многочленом
// Функция умножения многочлена pol на число number
function PolMultByNumber(pol: TPolynomial; number: Double): TPolynomial;
// Функция сложения полиномов p1 и p2
function PolSum(p1, p2: TPolynomial): TPolynomial;
// Функция вычитания полинома p2 из полинома p1
function PolSub(p1, p2: TPolynomial): TPolynomial;
// Функция произведения полиномов p1 и p2
function PolMult(p1, p2: TPolynomial): TPolynomial;
// Функция деления многочлена pol на число number
function PolDivByNumber(pol: TPolynomial; number: Double): TPolynomial;
// Функция деления полинома p1 на полином p2 с остатком remainder
function PolDiv(p1, p2: TPolynomial; var remainder: TPolynomial): TPolynomial;
implementation
uses
SysUtils, StrUtils;
// Функция вставки элемента с заданным коэффициентом cf и степенью dg в список
// p - указатель на следующий элемент списка после вставляемого
// Возвращает указатель на вставленный элемент списка
function AddNode(var p: TPtr; cf: Double; dg: Integer): TPtr;
begin
New(Result);
Result^.Coef := cf;
Result^.Degree := dg;
Result^.Next := p;
p := Result;
end;
// Процедура удаления элемента из списка
// p - указатель на удаляемый элемент списка
// Перенаправляет указатель p на следующий за удаляемым элемент списка
procedure DelNode(var p: TPtr);
var
del: TPtr;
begin
del := p;
p := p^.Next;
Dispose(del);
end;
// Процедура очистки списка polToClear
// (удаление всех элементов, кроме заглавного)
procedure PolClear(var polToClear: TPolynomial);
begin
while polToClear^.Next <> nil do
DelNode(polToClear^.Next);
end;
// Процедура полного удаления списка polToDestroy из памяти
procedure PolDestroy(var polToDestroy: TPolynomial);
begin
PolClear(polToDestroy);
Dispose(polToDestroy);
polToDestroy := nil;
end;
// Функция инициализации списка polToInit
// Возвращает указатель на заглавный элемент списка с коэффициентом cf и степенью dg
function PolInit(var polToInit: TPolynomial; cf: Double = 0; dg: Integer = 0): TPolynomial;
begin
New(polToInit);
polToInit^.Coef := cf;
polToInit^.Degree := dg;
polToInit^.Next := nil;
Result := polToInit;
end;
// Функция преобразования строки stringWithPol в многочлен pol
// Возвращает True, если преобразование удалось
// Возвращает False в обратном случае
function TryStrToPol(stringWithPol: string; var pol: TPolynomial): Boolean;
var
spaceIndex, dg, i: Integer;
cf: Double;
t: TPtr;
begin
Result := True;
stringWithPol := Trim(stringWithPol);
// Если передана пустая строка, возвращаем нулевой многочлен
if Length(stringWithPol) = 0 then
PolInit(pol)
else
begin
dg := -1;
i := 1;
// Считаем степень многочлена dg по количеству символов, разделенных пробелами
while i <> 0 do
if stringWithPol[i] = ' ' then
i := i + 1
else
begin
Inc(dg);
i := PosEx(' ', stringWithPol, i);
end;
t := PolInit(pol);
// Пока нет ошибок в вводе и не считали все коэффициенты
while Result and (Length(stringWithPol) <> 0) do
begin
// Находим индекс в строке,
// соответствующий первому символу после очередного коэффициента
spaceIndex := Pos(' ', stringWithPol);
if spaceIndex = 0 then
spaceIndex := Length(stringWithPol);
// Пытаемся преобразовать очередной коэффициент к числу с плавающей точкой
Result := TryStrToFloat(Copy(stringWithPol, 1, spaceIndex), cf);
if Result then
begin
// Если попытка успешная - проверяем на равенство считанного числа нулю
if Abs(cf) > POL_UNIT_EPSILON then
t := AddNode(t^.next, cf, dg);
// Уменьшаем степень члена для следующего коэффициента
dg := dg - 1;
// Удаляем считанный коэффициент из строки
Delete(stringWithPol, 1, spaceIndex);
stringWithPol := Trim(stringWithPol);
end;
end;
if not Result then
PolDestroy(pol)
else
// Удаление первого, нулевого элемента списка
if pol^.Next <> nil then
DelNode(pol)
end;
end;
// Функция преобразования многочлена pol в строку
// Возвращает строку с многочленом
function PolToStr(pol: TPolynomial): string;
var
p: Integer;
begin
Result := '';
// Преобразуем многочлен в строку без форматирования
while pol^.next <> nil do
begin
Result := Result + FloatToStrF(pol^.Coef, ffGeneral, 3, 5) + 'x^' + IntToStr(pol^.Degree) + ' + ';
pol := pol^.Next;
end;
Result := Result + FloatToStrF(pol^.Coef, ffGeneral, 3, 5) + 'x^' + IntToStr(pol^.Degree);
// Приводим полученную строку с многочленом к привычному формату
Result := StringReplace(Result, '+ -', '– ', [rfReplaceAll]);
if AnsiEndsStr('x^0', Result) then
Delete(Result, Length(Result) - 2, 3);
p := LastDelimiter('^', Result);
if (p <> 0) and (Result[p + 1] = '1') and ((p + 1 = Length(Result)) or (Result[p + 2] = ' ')) then
Delete(Result, p, 2);
Result := StringReplace(Result, ' 1x', ' x', [rfReplaceAll]);
if AnsiStartsStr('1x', Result) then
Delete(Result, 1, 1);
if AnsiStartsStr('-1x', Result) then
Delete(Result, 2, 1);
if AnsiStartsStr('-', Result) then
Result := StringReplace(Result, '-', '– ', []);
end;
// Функция копирования списка с многочленом polToCopy
// Возвращает указатель на заглавный элемент списка со скопированным многочленом
function PolCopy(polToCopy: TPolynomial): TPolynomial;
var
t: TPtr;
begin
t := PolInit(Result, polToCopy^.Coef, polToCopy^.Degree);
polToCopy := polToCopy^.Next;
while polToCopy <> nil do
begin
t := AddNode(t^.Next, polToCopy^.Coef, polToCopy^.Degree);
polToCopy := polToCopy^.Next;
end;
end;
// Вспомогательная функция сложения многочленов p1 и p2, sign отвечает за сложение/вычитание
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolSumHelp(p1, p2: TPolynomial; sign: Integer = 1): TPolynomial;
var
t: TPtr;
cf: Double;
begin
t := PolInit(Result);
// Пока не закончился один из полиномов, осуществляем складывание почленно
while (p1 <> nil) and (p2 <> nil) do
if p1^.Degree = p2^.Degree then
begin
cf := p1^.Coef + sign * p2^.Coef;
if Abs(cf) > POL_UNIT_EPSILON then
t := AddNode(t^.Next, cf, p1^.Degree);
p1 := p1^.Next;
p2 := p2^.Next;
end
else
if p1^.Degree > p2^.Degree then
begin
t := AddNode(t^.Next, p1^.Coef, p1^.Degree);
p1 := p1^.Next;
end
else
begin
t := AddNode(t^.Next, sign * p2^.Coef, p2^.Degree);
p2 := p2^.Next;
end;
// Когда кончился один из многочленов, дописываем остаток другого
while p1 <> nil do
begin
t := AddNode(t^.Next, p1^.Coef, p1^.Degree);
p1 := p1^.Next;
end;
while p2 <> nil do
begin
t := AddNode(t^.Next, sign * p2^.Coef, p2^.Degree);
p2 := p2^.Next;
end;
// Удаление первого, нулевого элемента списка
if Result^.next <> nil then
DelNode(Result);
end;
// Функция умножения многочлена pol на число number
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolMultByNumber(pol: TPolynomial; number: Double): TPolynomial;
var
t: TPtr;
begin
if Abs(number) < POL_UNIT_EPSILON then
PolInit(Result)
else
begin
Result := PolCopy(pol);
if Abs(Number - 1) > POL_UNIT_EPSILON then
begin
t := Result;
while t <> nil do
begin
t^.Coef := t^.Coef * Number;
t := t^.Next;
end;
end;
end;
end;
// Функция сложения полиномов p1 и p2
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolSum(p1, p2: TPolynomial): TPolynomial;
begin
if Abs(p1^.Coef) < POL_UNIT_EPSILON then
Result := p2
else
if Abs(p2^.Coef) < POL_UNIT_EPSILON then
Result := p1
else
Result := PolSumHelp(p1, p2);
end;
// Функция вычитания полинома p2 из полинома p1
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolSub(p1, p2: TPolynomial): TPolynomial;
begin
if Abs(p1^.Coef) < POL_UNIT_EPSILON then
Result := PolMultByNumber(p2, -1)
else
if Abs(p2^.Coef) < POL_UNIT_EPSILON then
Result := p1
else
Result := PolSumHelp(p1, p2, -1);
end;
// Функция умножения многочлена pol на одночлен с коэффициентом cf и степенью dg
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolMultByMonomial(pol: TPolynomial; cf: Double; dg: Integer): TPolynomial;
var
t: TPtr;
begin
Result := PolMultByNumber(pol, cf);
if dg <> 0 then
begin
t := Result;
while t <> nil do
begin
t^.Degree := t^.Degree + dg;
t := t^.Next;
end;
end;
end;
// Функция произведения полиномов p1 и p2
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolMult(p1, p2: TPolynomial): TPolynomial;
begin
Result := PolMultByMonomial(p1, p2^.Coef, p2^.Degree);
p2 := p2^.Next;
while p2 <> nil do
begin
Result := PolSum(Result, PolMultByMonomial(p1, p2^.Coef, p2^.Degree));
p2 := p2^.Next;
end;
end;
// Функция деления многочлена pol на число number
function PolDivByNumber(pol: TPolynomial; number: Double): TPolynomial;
var
t: TPtr;
begin
if Abs(number) < POL_UNIT_EPSILON then
Result := nil
else
begin
Result := PolCopy(pol);
if Abs(Number - 1) > POL_UNIT_EPSILON then
begin
t := Result;
while t <> nil do
begin
t^.Coef := t^.Coef / Number;
t := t^.Next;
end;
end;
end;
end;
// Функция деления полинома p1 на полином p2 с остатком remainder
// Возвращает указатель на заглавный элемент списка с результирующим многочленом
function PolDiv(p1, p2: TPolynomial; var remainder: TPolynomial): TPolynomial;
var
numerator, t: TPtr;
cf: Double;
dg: Integer;
begin
// Проверка деления на ноль
if Abs(p2^.Coef) < POL_UNIT_EPSILON then
begin
remainder := nil;
Result := nil;
end
else
// Проверка деления нуля
if Abs(p1^.Coef) < POL_UNIT_EPSILON then
begin
remainder := nil;
PolInit(Result);
end
else
// Проверка деления многочлена с меньшей степенью на многочлен с большей
if p1^.Degree < p2^.Degree then
begin
remainder := PolCopy(p1);
PolInit(Result);
end
else
// Проверка деления многочлена на число
if p2.Degree = 0 then
begin
remainder := nil;
Result := PolDivByNumber(p1, p2.Coef)
end
else
begin
numerator := PolCopy(p1);
t := PolInit(Result);
// Пока не получим 0 в остатке либо пока не получим в остатке многочлен со степенью меньшей, чем у делителя
while (Abs(numerator^.Coef) > POL_UNIT_EPSILON) and (numerator^.Degree >= p2^.Degree) do
begin
// Делим заглавный член делимого на заглавный член делителя
cf := numerator^.Coef / p2^.Coef;
dg := numerator^.Degree - p2^.Degree;
// Добавляем получившийся одночлен к результирующему многочлену
t := AddNode(t^.next, cf, dg);
// Вычитаем из делимого делитель, умноженный на найденный одночлен
numerator := PolSub(numerator, PolMultByMonomial(p2, cf, dg));
end;
// Удаление первого, нулевого элемента списка
DelNode(Result);
remainder := numerator;
end;
end;
end.
|
unit Sample.Platform.iOS;
{$INCLUDE 'Sample.inc'}
interface
uses
System.TypInfo,
Macapi.ObjectiveC,
iOSapi.UIKit,
iOSapi.Foundation,
iOSapi.QuartzCore,
iOSapi.CoreGraphics,
iOSapi.OpenGLES,
Sample.Platform;
type
id = Pointer;
SEL = Pointer;
type
{ We create our own view derived from UIView. It uses an OpenGLES layer for
rendering. Also, it intercepts certain view events. }
IGLView = interface(UIView)
['{87AA45F0-2EA1-490B-8517-4BEA610E562A}']
{ From UIView }
{ Is called when the dimensions of the view have changed, usually as the
result of rotating the device. We use this to update the size of the
render surface accordingly. }
procedure layoutSubviews; cdecl;
{ Is called when the user starts touching the screen. We do not support
multi-touch in the sample apps. Instead, the first touch is converted to
a mouse-move event and a left-mouse-button-pressed event. }
procedure touchesBegan(touches: NSSet; withEvent: UIEvent); cdecl;
{ Is called when the user cancelled a screen touch.
Is converted to a left-mouse-button-released event. }
procedure touchesCancelled(touches: NSSet; withEvent: UIEvent); cdecl;
{ Is called when the user finished touching the screen.
Is converted to a left-mouse-button-released event. }
procedure touchesEnded(touches: NSSet; withEvent: UIEvent); cdecl;
{ Is called when the user moved one or more fingers on the screen.
Is converted to a mouse-move event. }
procedure touchesMoved(touches: NSSet; withEvent: UIEvent); cdecl;
{ New }
{ Is called by the display link when the screen needs to be updated. }
procedure RenderFrame(Sender: Pointer); cdecl;
end;
type
{ Implementation of IGLView }
TGLView = class(TOCLocal)
{$REGION 'Internal Declarations'}
private
FDisplayLink: CADisplayLink;
FContext: EAGLContext;
FFramebuffer: GLuint;
FColorRenderbuffer: GLuint;
FDepthRenderbuffer: GLuint;
FWidth: GLint;
FHeight: GLint;
FSizeChanged: Boolean;
private
function GetNativeView: UIView; inline;
private
class function LayerClass(Self: Pointer; Cmd: SEL): Pointer; cdecl; static;
public
class procedure Setup; static;
private
procedure CreateContext;
procedure CreateBuffers;
{$ENDREGION 'Internal Declarations'}
public
{ UIView }
procedure layoutSubviews; cdecl;
procedure touchesBegan(touches: NSSet; withEvent: UIEvent); cdecl;
procedure touchesCancelled(touches: NSSet; withEvent: UIEvent); cdecl;
procedure touchesEnded(touches: NSSet; withEvent: UIEvent); cdecl;
procedure touchesMoved(touches: NSSet; withEvent: UIEvent); cdecl;
public
{ IGLView }
procedure RenderFrame(Sender: Pointer); cdecl;
public
{ Creates the view and OpenGL context }
constructor Create(const ABounds: CGRect);
destructor Destroy; override;
{ Starts the render loop for the view. Creates a display link that will call
the RenderFrame method at the refresh rate of the device. }
procedure Start;
{ Stops the render loop. Destroys the display link. }
procedure Stop;
{ To let Delphi know this class implements IGLView }
function GetObjectiveCClass: PTypeInfo; override;
{ The parent Objective-C UIView class }
property NativeView: UIView read GetNativeView;
end;
type
{ We create our own view controller derived from UIViewController. We use it
to control some settings for our application (main view) }
IGLViewController = interface(UIViewController)
['{A632D30F-FC6A-431A-B5EC-4A3CDE6142B4}']
{ From UIViewController }
{ Is called when iOS wants to know if it should display a status bar.
We return True to hide the status bar. }
function prefersStatusBarHidden: Boolean; cdecl;
{ Is called when iOS wants to know if the view should be rotated when the
user rotates the device. We return True to support rotation. }
function shouldAutorotate: Boolean; cdecl;
end;
type
{ Implementation of IGLViewController }
TGLViewController = class(TOCLocal)
{$REGION 'Internal Declarations'}
private
function GetNativeViewController: UIViewController; inline;
{$ENDREGION 'Internal Declarations'}
public
{ UIViewController }
function prefersStatusBarHidden: Boolean; cdecl;
function shouldAutorotate: Boolean; cdecl;
public
{ To let Delphi know this class implementss IGLViewController }
function GetObjectiveCClass: PTypeInfo; override;
{ The parent Objective-C UIViewController class }
property NativeViewController: UIViewController read GetNativeViewController;
end;
type
{ Implements the iOS UIApplicationDelegate protocol to get notified of
certain application events. Note that unlike the previous classes, this
class does not derive from TOCLocal. Instead, we use the Objective-C runtime
to manually define the class (see Setup). }
TAppDelegate = class sealed
{$REGION 'Internal Declarations'}
private class var
FWindow: UIWindow;
FView: TGLView;
FViewController: TGLViewController;
public const
DelegateName = 'AppDelegate';
private
{ Is called when the application has booted up. This is our main entry
point. We create the main window (UIWindow), view (IGLView) and view
controller (IGLViewController) here. }
class function applicationDidFinishLaunchingWithOptions(self: id; _cmd: SEL;
application: PUIApplication; options: PNSDictionary): Boolean; cdecl; static;
{ Is called when the application has completely entered the background. }
class procedure applicationDidEnterBackground(self: id; _cmd: SEL;
application: PUIApplication); cdecl; static;
{ Is called when the application first activated or resumes from the
background. We kick of the render loop here by calling TGLView.Start. }
class procedure applicationDidBecomeActive(self: id; _cmd: SEL;
application: PUIApplication); cdecl; static;
{ Is called when the application is about to resume from the background. }
class procedure applicationWillEnterForeground(self: id; _cmd: SEL;
application: PUIApplication); cdecl; static;
{ Is called when the application is about to be terminated.
We stop the render loop here by calling TGLView.Stop }
class procedure applicationWillTerminate(self: id; _cmd: SEL;
application: PUIApplication); cdecl; static;
{ Is called when the application is about to enter the background.
We stop the render loop here by calling TGLView.Stop }
class procedure applicationWillResignActive(self: id; _cmd: SEL;
application: PUIApplication); cdecl; static;
{$ENDREGION 'Internal Declarations'}
public
{ Uses the Objective-C runtime to register a class that implements
UIApplicationDelegate. }
class procedure Setup; static;
{ Disposes of the window, view and view controller }
class procedure Shutdown; static;
end;
type
{ Implements iOS-specific functionality. }
TPlatformIOS = class(TPlatformBase)
{$REGION 'Internal Declarations'}
private
class procedure RunLoop; static;
{$ENDREGION 'Internal Declarations'}
protected
class procedure DoRun; override;
end;
implementation
uses
System.Classes,
System.SysUtils,
System.UITypes,
Macapi.Helpers,
Macapi.ObjCRuntime,
Neslib.Ooogles;
{$WARN SYMBOL_PLATFORM OFF}
{ This should be in Macapi.ObjCRuntime }
function objc_getMetaClass(const name: MarshaledAString): Pointer; cdecl;
external libobjc name _PU + 'objc_getMetaClass';
{ This should be in iOSapi.QuartzCore }
type
TCAEAGLLayer = class (TOCGenericImport<CAEAGLLayerClass, CAEAGLLayer>) end;
{ TPlatformIOS }
class procedure TPlatformIOS.DoRun;
begin
TGLView.Setup;
TAppDelegate.Setup;
RunLoop;
App.Shutdown;
TAppDelegate.Shutdown;
end;
class procedure TPlatformIOS.RunLoop;
var
Pool: NSAutoreleasePool;
begin
{ This is the main entry point of the application.
On iOS, an app is started by calling UIApplicationMain, passing the name
of the application delegate class to create (TAppDelegate.DelegateName).
So UIApplicationMain will eventually call
TAppDelegate.applicationDidFinishLaunchingWithOptions, which in turn will
kick of the rest. }
StartClock;
Pool := TNSAutoreleasePool.Create;
try
UIApplicationMain(ArgCount, ArgValues, nil, StringToID(TAppDelegate.DelegateName));
finally
Pool.release;
end;
end;
{ TGLView }
constructor TGLView.Create(const ABounds: CGRect);
var
V: Pointer;
View: UIView;
Screen: UIScreen;
EAGLLayer: CAEAGLLayer;
begin
inherited Create;
{ Call the "inherited" constructor of UIView }
View := NativeView;
V := View.initWithFrame(ABounds);
if (GetObjectID <> V) then
UpdateObjectID(V);
{ On iOS8 and later we use the native scale of the screen as our content scale
factor. This allows us to render to the exact pixel resolution of the screen
which avoids additional scaling and GPU rendering work.
For example the iPhone 6 Plus appears to UIKit as a 736 x 414 pt screen with
a 3x scale factor (2208 x 1242 virtual pixels). But the native pixel
dimensions are actually 1920 x 1080. Since we are streaming 1080p buffers
from the camera we can render to the iPhone 6 Plus screen at 1:1 with no
additional scaling if we set everything up correctly. Using the native scale
of the screen also allows us to render at full quality when using the
display zoom feature on iPhone 6/6 Plus. }
Screen := TUIScreen.Wrap(TUIScreen.OCClass.mainScreen);
if (TOSVersion.Check(8)) then
TPlatformIOS.ScreenScale := Screen.nativeScale
else
TPlatformIOS.ScreenScale := Screen.scale;
View.setContentScaleFactor(TPlatformIOS.ScreenScale);
{ Make view layer opaque }
EAGLLayer := TCAEAGLLayer.Wrap((View.layer as ILocalObject).GetObjectID);
EAGLLayer.setOpaque(True);
{ Create OpenGL context, framebuffer and renderbuffer }
CreateContext;
CreateBuffers;
TPlatformIOS.App.Initialize;
FSizeChanged := True;
end;
procedure TGLView.CreateBuffers;
begin
glDisable(GL_DEPTH_TEST);
glGenFramebuffers(1, @FFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, FFramebuffer);
glGenRenderbuffers(1, @FColorRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, FColorRenderbuffer);
FContext.renderbufferStorage(GL_RENDERBUFFER, (NativeView.layer as ILocalObject).GetObjectID);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, @FWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, @FHeight);
glGenRenderbuffers(1, @FDepthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, FDepthRenderbuffer);
if (TPlatformIOS.App.NeedStencilBuffer) then
begin
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, FWidth, FHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, FDepthRenderbuffer);
end
else
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, FWidth, FHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, FColorRenderbuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, FDepthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, FColorRenderbuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) <> GL_FRAMEBUFFER_COMPLETE) then
raise Exception.Create('Unable to attach framebuffer to renderbuffer');
end;
procedure TGLView.CreateContext;
begin
FContext := TEAGLContext.Wrap(TEAGLContext.Alloc.initWithAPI(kEAGLRenderingAPIOpenGLES2));
TEAGLContext.OCClass.setCurrentContext(FContext);
InitOoogles;
end;
destructor TGLView.Destroy;
begin
TEAGLContext.OCClass.setCurrentContext(FContext);
if (FFramebuffer <> 0) then
glDeleteFramebuffers(1, @FFramebuffer);
if (FColorRenderbuffer <> 0) then
glDeleteRenderbuffers(1, @FColorRenderbuffer);
if (FDepthRenderbuffer <> 0) then
glDeleteRenderbuffers(1, @FDepthRenderbuffer);
if (FContext <> nil) then
FContext.release;
inherited;
end;
function TGLView.GetNativeView: UIView;
begin
Result := UIView(Super);
end;
function TGLView.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(IGLView);
end;
class function TGLView.LayerClass(Self: Pointer; Cmd: SEL): Pointer;
begin
{ This method overrides the class method UIView.layerClass. It should return
the layer class that is used for rendering. Since we use hardware
accelerated OpenGLES for rendering, we need to return the CAEAGLLayer class }
Result := objc_getClass('CAEAGLLayer');
end;
procedure TGLView.layoutSubviews;
begin
FSizeChanged := True;
end;
procedure TGLView.RenderFrame(Sender: Pointer);
begin
{ This method is called at regular intervals by the display link to update the
display. }
if (FSizeChanged) then
begin
{ Size of framebuffer has changed (probably because user rotated device).
Update render buffer storage and retrieve new dimensions. }
glBindRenderbuffer(GL_RENDERBUFFER, FColorRenderbuffer);
FContext.renderbufferStorage(GL_RENDERBUFFER, (NativeView.layer as ILocalObject).GetObjectID);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, @FWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, @FHeight);
glBindRenderbuffer(GL_RENDERBUFFER, FDepthRenderbuffer);
if (TPlatformIOS.App.NeedStencilBuffer) then
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, FWidth, FHeight)
else
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, FWidth, FHeight);
TPlatformIOS.App.Resize(FWidth, FHeight);
FSizeChanged := False;
end;
{ Update app and render frame to back buffer }
glBindFramebuffer(GL_FRAMEBUFFER, FFramebuffer);
TPlatformIOS.Update;
{ Swap backbuffer to front to display it }
glBindRenderbuffer(GL_RENDERBUFFER, FColorRenderbuffer);
FContext.presentRenderbuffer(GL_RENDERBUFFER);
end;
class procedure TGLView.Setup;
var
MetaClass: Pointer;
Selector: SEL;
begin
{ We need to override the class method UIView.layerClass. We need to do this
*before* an object of this type is created. To do that, we need to manually
register our Objective-C class first, and override the "layerClass" method
of the meta-class. }
RegisterObjectiveCClass(TGLView, TypeInfo(IGLView));
MetaClass := objc_getMetaClass('IGLView');
Assert(Assigned(MetaClass));
{ Override the UIView.layerClass method and forward it to TGLView.LayerClass }
Selector := sel_getUid('layerClass');
if (class_addMethod(MetaClass, Selector, @LayerClass, '#@:') = 0) then
Assert(False);
end;
procedure TGLView.Start;
var
RunLoop: NSRunLoop;
begin
if (FDisplayLink = nil) then
begin
{ Create a display link to render the view at regular intervals (the screen
refresh rate). The display link will call our RenderFrame method at those
intervals. }
FDisplayLink := NativeView.window.screen.displayLinkWithTarget(GetObjectID,
sel_getUid('RenderFrame:'));
{ Add the display link to the run loop so it gets processed }
RunLoop := TNSRunLoop.Wrap(TNSRunLoop.OCClass.currentRunLoop);
FDisplayLink.addToRunLoop(RunLoop, NSDefaultRunLoopMode);
end;
end;
procedure TGLView.Stop;
begin
if (FDisplayLink <> nil) then
begin
FDisplayLink.invalidate;
FDisplayLink := nil;
end;
end;
procedure TGLView.touchesBegan(touches: NSSet; withEvent: UIEvent);
var
View: UIView;
Touch: UITouch;
Location: CGPoint;
begin
{ Call "inherited" version first }
View := NativeView;
View.touchesBegan(touches, withEvent);
{ Convert to mouse-move and left-mouse-button-pressed events }
Touch := TUITouch.Wrap(withEvent.allTouches.anyObject);
Location := Touch.locationInView(View);
TPlatformIOS.App.MouseMove([ssTouch], Location.x, Location.y);
TPlatformIOS.App.MouseDown(TMouseButton.mbLeft, [ssTouch], Location.x, Location.y);
end;
procedure TGLView.touchesCancelled(touches: NSSet; withEvent: UIEvent);
var
View: UIView;
Touch: UITouch;
Location: CGPoint;
begin
{ Call "inherited" version first }
View := NativeView;
View.touchesCancelled(touches, withEvent);
{ Convert to left-mouse-button-released event }
Touch := TUITouch.Wrap(withEvent.allTouches.anyObject);
Location := Touch.locationInView(View);
TPlatformIOS.App.MouseUp(TMouseButton.mbLeft, [ssTouch], Location.x, Location.y);
end;
procedure TGLView.touchesEnded(touches: NSSet; withEvent: UIEvent);
var
View: UIView;
Touch: UITouch;
Location: CGPoint;
begin
{ Call "inherited" version first }
View := NativeView;
View.touchesCancelled(touches, withEvent);
{ Convert to left-mouse-button-released event }
Touch := TUITouch.Wrap(withEvent.allTouches.anyObject);
Location := Touch.locationInView(View);
TPlatformIOS.App.MouseUp(TMouseButton.mbLeft, [ssTouch], Location.x, Location.y);
end;
procedure TGLView.touchesMoved(touches: NSSet; withEvent: UIEvent);
var
View: UIView;
Touch: UITouch;
Location: CGPoint;
begin
{ Call "inherited" version first }
View := NativeView;
View.touchesMoved(touches, withEvent);
{ Convert to mouse-move event }
Touch := TUITouch.Wrap(withEvent.allTouches.anyObject);
Location := Touch.locationInView(View);
TPlatformIOS.App.MouseMove([ssTouch], Location.x, Location.y);
end;
{ TGLViewController }
function TGLViewController.GetNativeViewController: UIViewController;
begin
Result := UIViewController(Super);
end;
function TGLViewController.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(IGLViewController);
end;
function TGLViewController.prefersStatusBarHidden: Boolean;
begin
Result := True;
end;
function TGLViewController.shouldAutorotate: Boolean;
begin
Result := True;
end;
{ TAppDelegate }
class procedure TAppDelegate.applicationDidBecomeActive(self: id; _cmd: SEL;
application: PUIApplication);
begin
FView.Start;
end;
class procedure TAppDelegate.applicationDidEnterBackground(self: id; _cmd: SEL;
application: PUIApplication);
begin
{ TODO }
end;
class function TAppDelegate.applicationDidFinishLaunchingWithOptions(self: id;
_cmd: SEL; application: PUIApplication; options: PNSDictionary): Boolean;
var
Screen: UIScreen;
Rect: CGRect;
begin
{ Create a UIWindow and TGLView that take up the entire screen. Add the
view to the window. }
Screen := TUIScreen.Wrap(TUIScreen.OCClass.mainScreen);
Rect := Screen.bounds;
FWindow := TUIWindow.Wrap(TUIWindow.Alloc.initWithFrame(Rect));
FView := TGLView.Create(Rect);
FWindow.addSubview(FView.NativeView);
{ Create a TGLViewController for our view, and assign it to the window }
FViewController := TGLViewController.Create;
FViewController.NativeViewController.setView(FView.NativeView);
FWindow.setRootViewController(FViewController.NativeViewController);
FWindow.makeKeyAndVisible;
Result := True;
end;
class procedure TAppDelegate.applicationWillEnterForeground(self: id; _cmd: SEL;
application: PUIApplication);
begin
{ TODO }
end;
class procedure TAppDelegate.applicationWillResignActive(self: id; _cmd: SEL;
application: PUIApplication);
begin
FView.Stop;
end;
class procedure TAppDelegate.applicationWillTerminate(self: id; _cmd: SEL;
application: PUIApplication);
begin
FView.Stop;
end;
class procedure TAppDelegate.Setup;
{ This method manually uses the Objective-C runtime to define and register a
class that implements UIApplicationDelegate. If forwards the methods of
UIApplicationDelegate to static methods of this TAppDelegate class. }
var
DelegateClass: Pointer;
begin
{ Define a new class called AppDelegate, derived from NSObject }
DelegateClass := objc_allocateClassPair(objc_getClass('NSObject'), DelegateName, 0);
{ Implement the UIApplicationDelegate in our class }
class_addProtocol(DelegateClass, objc_getProtocol('UIApplicationDelegate'));
{ Add the methods from UIApplicationDelegate to our class. Note that the
UIApplicationDelegate methods are optional, so we only implement those we
are interested in.
Each UIApplicationDelegate method will be forwarded to a static method in
this class }
class_addMethod(DelegateClass, sel_getUid('application:didFinishLaunchingWithOptions:'),
@applicationDidFinishLaunchingWithOptions, 'B@:@@');
class_addMethod(DelegateClass, sel_getUid('applicationDidEnterBackground:'),
@applicationDidEnterBackground, 'v@:@');
class_addMethod(DelegateClass, sel_getUid('applicationDidBecomeActive:'),
@applicationDidBecomeActive, 'v@:@');
class_addMethod(DelegateClass, sel_getUid('applicationWillEnterForeground:'),
@applicationWillEnterForeground, 'v@:@');
class_addMethod(DelegateClass, sel_getUid('applicationWillTerminate:'),
@applicationWillTerminate, 'v@:@');
class_addMethod(DelegateClass, sel_getUid('applicationWillResignActive:'),
@applicationWillResignActive, 'v@:@');
{ Register our class, so the UIApplicationMain call can create an instance
of it. }
objc_registerClassPair(DelegateClass);
end;
class procedure TAppDelegate.Shutdown;
begin
if Assigned(FWindow) then
begin
FWindow.release;
FWindow := nil;
end;
FView.DisposeOf;
FView := nil;
FViewController.DisposeOf;
FViewController := nil;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
{ Rev 1.2 10/26/2004 9:55:58 PM JPMugaas
{ Updated refs.
}
{
Rev 1.1 6/11/2004 9:38:48 AM DSiders
Added "Do not Localize" comments.
}
{
{ Rev 1.0 6/7/2004 7:46:26 PM JPMugaas
{ FTP List parser for TSX+. This is based on:
{
{ http://www.gweep.net/~shifty/music/miragehack/gcc/xasm/cug292.lst
}
unit IdFTPListParseTSXPlus;
interface
uses
IdFTPList, IdFTPListParseBase, IdFTPListTypes, IdObjs;
type
TIdTSXPlusFTPListItem = class(TIdMinimalFTPListItem)
protected
FNumberBlocks : Integer;
public
property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks;
end;
TIdFTPLPTSXPlus = class(TIdFTPListBaseHeader)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function IsHeader(const AData: String): Boolean; override;
class function IsFooter(const AData : String): Boolean; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override;
public
class function CheckListing(AListing : TIdStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; override;
class function GetIdent : String; override;
end;
implementation
uses IdFTPCommon, IdGlobal, IdSys;
{ TIdFTPLPTSXPlus }
class function TIdFTPLPTSXPlus.CheckListing(AListing: TIdStrings;
const ASysDescript: String; const ADetails: Boolean): boolean;
var i : Integer;
begin
Result := False;
if AListing.Count > 0 then
begin
for i := AListing.Count -1 downto 0 do
begin
if AListing[i]<>'' then
begin
if IsFooter(AListing[i]) then
begin
Result := True;
Break;
end;
end;
end;
end;
end;
class function TIdFTPLPTSXPlus.GetIdent: String;
begin
Result := 'TSX+'; {do not localize}
end;
class function TIdFTPLPTSXPlus.IsFooter(const AData: String): Boolean;
var LBuf, LPart : String;
//The footer is like this:
//Directory [du3:/cug292/pcdsk4/*.*] / 9 Files / 563 Blocks
begin
Result := False;
LBuf := AData;
LPart := Fetch(LBuf,'[');
if LBuf='' then
begin
Exit;
end;
LPart := Sys.TrimRight(LPart);
if LPart = 'Directory' then {do not localize}
begin
Fetch(LBuf,']');
if LBuf='' then
begin
Exit;
end;
LBuf := Sys.TrimLeft(LBuf);
if (Copy(LBuf,1,1)='/') then
begin
IdGlobal.IdDelete(LBuf,1,1);
if IndyPos('Files',LBuf) > 0 then {do not localize}
begin
LPart := Fetch(LPart, '/');
if LBuf='' then
begin
Exit;
end;
Result := (IndyPos('Block', LBuf) > 0); {do not localize}
end;
end;
end;
end;
class function TIdFTPLPTSXPlus.IsHeader(const AData: String): Boolean;
begin
Result := False;
end;
class function TIdFTPLPTSXPlus.MakeNewItem(
AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdTSXPlusFTPListItem.Create(AOwner);
end;
class function TIdFTPLPTSXPlus.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
{
Note that this parser is odd because it will create a new TIdFTPListItem.
I know that is not according to the current conventional design. However, KA9Q
is unusual because a single line can have two items (maybe more)
}
var LBuf, LExt : String;
LNewItem : TIdFTPListItem;
LDir : TIdFTPListItems;
begin
LBuf := Sys.TrimLeft(AItem.Data);
AItem.FileName := Fetch(LBuf,'.');
LExt := Fetch(LBuf);
if LExt = 'dsk' then {do not localize}
begin
AItem.ItemType := ditDirectory;
end
else
begin
AItem.ItemType := ditFile;
AItem.FileName := AItem.FileName + '.'+LExt;
end;
LBuf := Sys.TrimLeft(LBuf);
//block count
(AItem as TIdTSXPlusFTPListItem).NumberBlocks := Sys.StrToInt(Fetch(LBuf),0);
LBuf := Sys.TrimRight(LBuf);
if LBuf<>'' then
begin
LDir := AItem.Collection as TIdFTPListItems;
LNewItem := TIdFTPLPTSXPlus.MakeNewItem( LDir);
LNewItem.Data := LBuf;
TIdFTPLPTSXPlus.ParseLine(LNewItem,APath);
LNewItem.Data := AItem.Data;
Result := True;
end
else
begin
Result := True;
end;
end;
initialization
RegisterFTPListParser(TIdFTPLPTSXPlus);
finalization
UnRegisterFTPListParser(TIdFTPLPTSXPlus);
end.
|
unit kwGetActiveEditorPageName;
{* *Формат:* main_form:GetActivePageName
*Описание:* Помещает в стек номер активной вкладки в окне редактирования документа.
*Примечания:*
Константы с номерами вкладок находятся в файле:
[code]
w:\archi\source\projects\Archi\TestSet\Dictionary\ArchiControls.script"
[code] }
// Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwGetActiveEditorPageName.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "TkwGetActiveEditorPageName" MUID: (4E60CB00004F)
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwRegisterableWord
, tfwScriptingInterfaces
;
type
TkwGetActiveEditorPageName = class(TtfwRegisterableWord)
{* *Формат:* main_form:GetActivePageName
*Описание:* Помещает в стек номер активной вкладки в окне редактирования документа.
*Примечания:*
Константы с номерами вкладок находятся в файле:
[code]
w:\archi\source\projects\Archi\TestSet\Dictionary\ArchiControls.script"
[code] }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
end;//TkwGetActiveEditorPageName
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
{$If Defined(AppClientSide)}
, Editwin
{$IfEnd} // Defined(AppClientSide)
{$If Defined(AppClientSide)}
, Main
{$IfEnd} // Defined(AppClientSide)
//#UC START# *4E60CB00004Fimpl_uses*
//#UC END# *4E60CB00004Fimpl_uses*
;
class function TkwGetActiveEditorPageName.GetWordNameForRegister: AnsiString;
begin
Result := 'main_form:GetActivePageName';
end;//TkwGetActiveEditorPageName.GetWordNameForRegister
procedure TkwGetActiveEditorPageName.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_4E60CB00004F_var*
//#UC END# *4DAEEDE10285_4E60CB00004F_var*
begin
//#UC START# *4DAEEDE10285_4E60CB00004F_impl*
aCtx.rEngine.PushString((MainForm.ActiveMDIChild as TDocEditorWindow).nbkDocPages.ActivePageName);
//#UC END# *4DAEEDE10285_4E60CB00004F_impl*
end;//TkwGetActiveEditorPageName.DoDoIt
initialization
TkwGetActiveEditorPageName.RegisterInEngine;
{* Регистрация TkwGetActiveEditorPageName }
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)
end.
|
program moneyChange(input, output);
const
VALUE_1 = 25;
VALUE_2 = 10;
VALUE_3 = 5;
VALUE_4 = 1;
var
number : integer;
five : integer;
ones : integer;
tens : integer;
tfve : integer;
sum : integer;
flag : integer;
begin
write('Enter amount of money, and hit ENTER: ');
readln(number);
flag := number;
if not (number in [1 .. 99]) then
writeln('You must enter a sum of money up to 99.')
else
begin
tfve := 0; tens := 0; five := 0; ones := 0;
sum := tfve + tens + five + ones;
if (sum <> flag) then
begin
tfve := VALUE_1 * (number div VALUE_1);
number := number - tfve;
sum := sum + tfve;
end;
if (sum <> flag) then
begin
tens := VALUE_2 * (number div VALUE_2);
number := number - tens;
sum := sum + tens;
end;
if (sum <> flag) then
begin
five := VALUE_3 * (number div VALUE_3);
number := number - five;
sum := sum + five;
end;
if (sum <> flag) then
begin
ones := VALUE_4 * (number div VALUE_4);
number := number - ones;
sum := sum + ones;
end;
writeln('You would need: ');
writeln('01c: ', ones div VALUE_4);
writeln('05c: ', five div VALUE_3);
writeln('10c: ', tens div VALUE_2);
writeln('25c: ', tfve div VALUE_1);
end;
end. |
unit dcYrMo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, datacontroller, db, FFSUtils,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDBaseEdit,
LMDCustomEdit, LMDEdit, lmdgraph, FFSTypes, dcEdit;
type
TYrMoStorageFormat = (ysfMMYYYY, ysfYYYYMM);
{ TDateEdit }
TdcYrMo = class(TdcEdit)
private
FInternalDate: TDateTime;
procedure SetAsMY(const Value: string);
procedure SetAsYM(const Value: string);
function GetAsMY: string;
function GetAsYM: string;
procedure SetAsDate(const Value: TDateTime);
function GetAsDate: TDateTime;
procedure SetNewMask(const Value: string);
private
FDefaultToday: boolean;
FRequired: boolean;
FStorageFormat: TYrMoStorageFormat;
procedure CheckValidDate;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
function DateIsBlank(s: string): boolean;
procedure KeyDown(var Key: Word; Shift: TShiftState);override;
procedure KeyPress(var Key: Char);override;
// procedure ReadData(sender: TObject);override;
procedure SetStorageFormat(const Value: TYrMoStorageFormat);
// procedure WriteData(sender: TObject);override;
procedure SetDefaultToday( const Value: boolean);
property NewMask:string write SetNewMask;
protected
procedure Loaded;override;
public
property AsDate:TDateTime read GetAsDate write SetAsDate;
property AsYM:string read GetAsYM write SetAsYM;
property AsMY:string read GetAsMY write SetAsMY;
function IsValidDate:boolean;
published
constructor Create(AOwner: TComponent); override;
property Required : boolean read fRequired write fRequired;
property StorageFormat : TYrMoStorageFormat read FStorageFormat write SetStorageFormat;
property DefaultToday:boolean read FDefaultToday write SetDefaultToday;
end;
procedure Register;
implementation
const
sDateFormat = 'mmyyyy';
DateEditMask = '99/9999';
dsfString : array[TYrMoStorageFormat] of string = ('mm/yyyy', 'yyyymm');
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcYrMo]);
end;
{ TdcYrMo }
constructor TdcYrMo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
width := 89;
fStorageFormat := ysfMMYYYY;
FInternalDate := trunc(now);
end;
procedure TdcYrMo.CheckValidDate;
var okdate : boolean;
dt : TFFSDate;
begin
try
okdate := IsValidDate;
if not okdate then raise exception.create('Invalid Date Entered');
except
okdate := false;
if DateisBlank(Text) then // = ' / / ' then
begin
NewMask := '';
Okdate := true;
end;
if not okdate then
begin
if CanFocus then SetFocus;
raise;
end;
end;
end;
procedure TdcYrMo.CMExit(var Message: TCMExit);
begin
if not (csDesigning in ComponentState) then CheckValidDate;
inherited;
end;
procedure TdcYrMo.KeyDown(var Key: Word; Shift: TShiftState);
var s : string;
n, ok : integer;
begin
if key in [VK_ESCAPE, VK_RETURN] then begin
GetParentForm(Self).Perform(CM_DIALOGKEY, byte(Key), byte(Shift));
if Key = VK_RETURN then begin
inherited KeyDown(key,shift);
Key := 0;
Exit;
end;
end
else begin
if ReadOnly then exit;
// if (Key in [VK_PRIOR, VK_NEXT, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_ADD, VK_SUBTRACT]) {and PopupVisible} then
// begin
// TFFSPopupWindow(FPopup).KeyDown(Key, Shift);
// Key := 0;
// end
// else begin
case Key of
Ord('A') : if (shift = []) then
begin
s := '';
if inputquery('Advance Date by Months','Number of months to advance',s) then
begin
val(s,n,ok);
if ok = 0 then AsDate := IncMonth(FInternalDate, n);
// SelectAll;
end;
Key := 0;
end;
Ord('Q') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(FInternalDate,-3)
else AsDate := IncMonth(FInternalDate,3);
// SelectAll;
key := 0;
end;
Ord('Y') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(FInternalDate,-12)
else AsDate := IncMonth(FInternalDate,12);
// SelectAll;
key := 0;
end;
Ord('M') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(FInternalDate,-1)
else AsDate := IncMonth(FInternalDate,1);
// SelectAll;
key := 0;
end;
VK_PRIOR : if (shift = [ssCtrl]) or (shift = []) then
begin
if shift = [ssCtrl] then AsDate := IncMonth(FInternalDate,-12)
else AsDate := IncMonth(FInternalDate,-1);
// SelectAll;
Key := 0;
end;
VK_NEXT : if (shift = [ssCtrl]) or (shift = []) then
begin
if shift = [ssCtrl] then AsDate := IncMonth(FInternalDate,12)
else AsDate := IncMonth(FInternalDate,1);
Key := 0;
end;
VK_UP,
VK_SUBTRACT : if (shift = []) then
begin
AsDate := IncMonth(FInternalDate,-1);
Key := 0;
end;
VK_DOWN,
VK_ADD : if (shift = []) then
begin
AsDate := IncMonth(FInternalDate,1);
Key := 0;
end;
(* VK_DELETE,
VK_BACK : if (shift = []) then
begin
if masked then begin
if (sellength = 10) and (Mask = DateEditMask) then
begin
NewMask := '';
key := 0;
end;
end
else begin
NewMask := '';
key := 0;
end;
end;
*)
end;
// end;
inherited KeyDown(Key, Shift);
end;
end;
procedure TdcYrMo.KeyPress(var Key: Char);
procedure UpdateValue(var akey:char);
begin
// if PopupVisible then PopupCloseUp(self, false);
NewMask := '';
// SelectAll;
akey := #0;
end;
begin
if key = ' ' then key := 'T'; // default space to TODAY
case upcase(key) of
// 'T',
// '0'..'9' : begin
// if Mask <> DateEditMask then
// begin
// NoMaskText := EmptyStr;
// NewMask := DateEditMask;
// end;
// end;
#13 : CheckValidDate;
// else if not popupvisible then key := #0;
end;
//
// if (Key in ['T', 't', '+', '-']) and PopupVisible then
// begin
// TFFSPopupWindow(FPopup).KeyPress(Key);
// Key := #0;
// end
// else if DirectInput then
// begin
case upcase(key) of
'T' : begin
AsDate := Trunc(Now);
Key := #0;
end;
end;
// end;
inherited KeyPress(key);
end;
function TdcYrMo.DateIsBlank(s:string):boolean;
var x : integer;
nb : boolean;
begin
nb := false;
for x := 1 to length(s) do
begin
if not (s[x] in [' ', '/']) then nb := true;
end;
result := not nb;
end;
(*procedure TdcYrMo.ReadData(sender: TObject);
var s : string;
begin
if not assigned(fdclink.DataController) then exit;
if not assigned(fdclink.datacontroller.databuf) then exit;
s := fdclink.datacontroller.databuf.AsString[DataBufIndex];
if (s > '') then
begin
// if not (Originaldata[1] in ['0'..'9']) then begin end //editmask := ''
// else editmask := dateEditMask;
if (StorageFormat = ysfYYYYMM) then
begin
if s[1] in ['0'..'9'] then s := system.copy(s,5,2) + '/' + system.copy(s,1,4);
end;
end;
// else editmask := '';
text := s;
try
CheckValidDate;
except
end;
end;
*)
procedure TdcYrMo.SetStorageFormat(const Value: TYrMoStorageFormat);
begin
FStorageFormat := Value;
end;
(*
procedure TdcYrMo.WriteData(sender: TObject);
var d : TDateTime;
isadate : boolean;
s : string;
begin
if not assigned(fdclink.DataController) then exit;
if not assigned(fdclink.dataController.DataBuf) then exit;
isadate := IsValidDate;
s := text; // default
if isadate then
begin
d := AsDate;
case StorageFormat of
ysfMMYYYY : s := AsMY;
ysfYYYYMM : s := AsYM;
end;
end;
fdclink.datacontroller.databuf.asString[DataBufIndex] := s;
end;
*)
procedure TdcYrMo.SetDefaultToday(const Value: boolean);
begin
FDefaultToday := Value;
end;
procedure TdcYrMo.SetAsMY(const Value: string);
begin
try
text := AnyDateTommddyyyy(Value);
except
text := '';
end;
end;
procedure TdcYrMo.SetAsYM(const Value: string);
begin
try
text := AnyDateTommddyyyy(Value);
except
text := '';
end;
end;
function TdcYrMo.GetAsMY: string;
var d : TDatetime;
begin
if IsValidDate then begin
d := AsDate;
result := formatdatetime('mm/yyyy',d);
end
else result := '';
end;
function TdcYrMo.GetAsYM: string;
var d : TDatetime;
begin
if IsValidDate then begin
d := AsDate;
result := formatdatetime('yyyymm',d);
end
else result := '';
end;
procedure TdcYrMo.SetAsDate(const Value: TDateTime);
begin
NewMask := DateEditMask;
FInternalDate := Value;
Text := FormatDateTime(sDateFormat, value);
end;
function TdcYrMo.GetAsDate: TDateTime;
var d : TDatetime;
s : string;
begin
s := text;
if length(s) < 3 then s := '00/0000';
system.insert('/01',s,3);
try
d := ffsutils.ConvertToDate(s);
result := d;
except
result := baddate;
end;
end;
procedure TdcYrMo.SetNewMask(const Value: string);
begin
// if Value = Mask then exit;
if Value = '' then FInternalDate := trunc(now);
// Mask := Value;
end;
function TdcYrMo.IsValidDate: boolean;
var s : string;
d : TDateTime;
begin
s := text;
if length(s) < 3 then s := '00/0000';
system.insert('/01',s,3);
result := false;
try
d := strtodate(s);
result := true;
except
end;
end;
procedure TdcYrMo.Loaded;
begin
inherited;
NewMask := DateEditMask;
font.color := FFSColor[fcsDataText];
end;
end.
|
program NPTestD;
type
Emplacement_obj = object
private
Z : Boolean;
public
X, Y : Integer;
procedure No_param; virtual;
constructor Init(InitX, InitY : Integer);
protected
function AkiX : Integer;
function AkiY : Integer;
private
destructor Done;
end;
Emplacement_obj2 = object(Emplacement_obj)
procedure No_param; override;
end;
Ovide1 = object X: Integer; end;
Ovide2 = object(Ovide1) end;
Ovide3 = object(Ovide2) end;
Ovide4 = object(Ovide3) Y: Integer; end;
Emplacement_rec = record
X, Y : Integer;
end;
procedure Emplacement_obj.No_param;
begin
Y:= 1111;
X:= Y
end;
procedure Emplacement_obj2.No_param;
begin
X:= 1234
end;
constructor Emplacement_obj.Init(InitX, InitY : Integer);
begin
X := InitX;
Y := InitY;
end;
function Emplacement_obj.AkiX : Integer;
begin
AkiX := X;
end;
function Emplacement_obj.AkiY : Integer;
begin
AkiY := Y;
end;
destructor Emplacement_obj.Done;
begin
X:= 0;
end;
procedure Affiche;
begin
Writeln('Hello Object Pascal');
end;
var Point_o : Emplacement_obj2;
Point_r : Emplacement_rec;
ov4 : Ovide4;
begin
Affiche;
with point_r do
Y := 3;
with point_o do
Y := 4;
Point_o.X := 2 + Point_o.AkiX;
Point_o.Init(2, 3);
Point_o.No_Param;
WriteLn(Point_o.X); { Must be 1234 }
with ov4 do begin
X:= 8;
Y:= 12
end
end.
|
{Hint: save all files to location: C:\adt32\eclipse\workspace\AppTFPNoGUIGraphicsBridgeDemo1\jni }
unit unit1;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls,
Laz_And_Controls_Events, AndroidWidget, FPNoGUIGraphicsBridge, ViewPort,
GridData, FPColorBridge, GeometryUtilsBridge;
type
{ TAndroidModule1 }
TAndroidModule1 = class(jForm)
FPNoGUIGraphicsBridge1: TFPNoGUIGraphicsBridge;
GridData1: TGridData;
jBitmap1: jBitmap;
jButton1: jButton;
jImageView1: jImageView;
jPanel1: jPanel;
jPanel2: jPanel;
jTextView1: jTextView;
ViewPort1: TViewPort;
procedure jButton1Click(Sender: TObject);
procedure ViewPort1ChangeFontColor(Sender: TObject);
private
{private declarations}
public
{public declarations}
end;
var
AndroidModule1: TAndroidModule1;
PGlobalDirectImagePixel: PJByte;
implementation
{$R *.lfm}
{ TAndroidModule1 }
function GenericFunction1(x: real): real;
begin
Result:= x*x*x;
end;
function GenericFunction2(x: real): real;
begin
Result:= 4*x*x*x*x - 5*x*x*x - x*x + x -1;
end;
procedure TAndroidModule1.ViewPort1ChangeFontColor(Sender: TObject);
begin
FPNoGUIGraphicsBridge1.SetFontColor(ViewPort1.FontColor);
end;
procedure TAndroidModule1.jButton1Click(Sender: TObject);
var
jGraphicsBuffer: jObject;
w, h: integer;
begin
w:= jPanel2.Width;
h:= jPanel2.Height;
FPNoGUIGraphicsBridge1.SetSurfaceSize(w,h);
FPNoGUIGraphicsBridge1.PathToFontFile:= '/system/fonts/Roboto-Regular.ttf'; //DroidSerif-Bold.ttf
FPNoGUIGraphicsBridge1.ActiveViewPort:= ViewPort1; //set in Object inspector!
ViewPort1.SetSize(w,h);
ViewPort1.DrawAxis:= True;
ViewPort1.DrawGrid:= True;
ViewPort1.SetScaleXY(-1.6 {xmin},1.6{xmax}, -2.0{ymin}, 6.0{ymax}); //real world!!
FPNoGUIGraphicsBridge1.AddEntity('blue_layer','Circle',[Point(0.0,1.0){center},
Point(0.0+0.5,1.0){radio=Abs(x2-x1)}],'This is a Circle!','foo');
FPNoGUIGraphicsBridge1.AddEntity('blue_layer','Line',[Point(0.0,1.5),Point(1.0, 3.6)],'','foo');
FPNoGUIGraphicsBridge1.AddEntity('blue_layer','Polyline',[Point(0.0,1.5),Point(0.5,1),
Point(1.0,1.5), Point(0.5,2)],'','');
FPNoGUIGraphicsBridge1.AddEntity('blue_layer','Text',[Point(0.0,0.5)],'Hello World!','');
FPNoGUIGraphicsBridge1.AddFunction(@GenericFunction1,-1.6,1.6);
FPNoGUIGraphicsBridge1.AddFunction(@GenericFunction2,-1.6,1.6);
FPNoGUIGraphicsBridge1.PaintViewPort;
FPNoGUIGraphicsBridge1.PaintGrid(True);
ViewPort1.PenColor:= colbrBlue;
FPNoGUIGraphicsBridge1.DrawEntities('blue_layer');
ViewPort1.PenColor:= colbrRed;
FPNoGUIGraphicsBridge1.DrawFunction(False, 0);
FPNoGUIGraphicsBridge1.DrawFunction(False, 1);
jGraphicsBuffer:= jBitmap1.GetByteBuffer(w,h);
PGlobalDirectImagePixel:= jBitmap1.GetDirectBufferAddress(jGraphicsBuffer);
FPNoGUIGraphicsBridge1.Surface.GetRGBAGraphics(PGlobalDirectImagePixel);
jImageView1.SetImageBitmap(jBitmap1.GetBitmapFromByteBuffer(jGraphicsBuffer, w, h));
end;
{ Android:
system/fonts/Roboto-Regular.ttf
system/fonts/Roboto-Bold.ttf
system/fonts/Roboto-BoldItalic.ttf
system/fonts/Roboto-Italic.ttf
system/fonts/Roboto-BlackItalic.ttf
system/fonts/Roboto-LightItalic.ttf
system/fonts/Roboto-ThinItalic.ttf
system/fonts/Roboto-Light.ttf
system/fonts/DroidSansFallback.ttf
system/fonts/DroidSansGeorgian.ttf
system/fonts/DroidSansHebrew-Bold.ttf
system/fonts/DroidSansHebrew-Regular.ttf
system/fonts/DroidSansMono.ttf
system/fonts/DroidSansThai.ttf
system/fonts/DroidSerif-Bold.ttf
system/fonts/DroidSerif-BoldItalic.ttf
system/fonts/DroidSerif-Italic.ttf
system/fonts/DroidSerif-Regular.ttf
}
end.
|
{@html(<hr>)
@abstract(List classes used in Telemetry library.)
@author(František Milt <fmilt@seznam.cz>)
@created(2013-10-04)
@lastmod(2014-06-07)
@bold(@NoAutoLink(TelemetryLists))
©František Milt, all rights reserved.
Classes in this unit (for details, refer to declaration of individual class):
@preformatted(
TCustomTelemetryList
|- TKnownEventsList
|- TKnownChannelsList
|- TKnownConfigsList
|- TRegisteredEventsList
|- TRegisteredChannelsList
|- TStoredConfigsList
|- TStoredChannelsValuesList
)
Last change: 2014-06-07
Change List:@unorderedList(
@item(2013-10-04 - First stable version.)
@item(2014-04-07 - Type of parameter @code(Item) in function GetItemID
changed to @code(TelemetryString).)
@item(2014-04-07 - Field type changed to @code(TelemetryString) in following
cases:@unorderedList(
@itemSpacing(Compact)
@item(TKnownEvent.Name)
@item(TKnownChannel.Name)
@item(TKnownChannel.IndexConfig)
@item(TKnownConfig.Name)
@item(TChannelInfo.Name)
@item(TStoredConfig.Name)
@item(TStoredChannel.Name)))
@item(2014-04-07 - Type of parameters @code(Name) and @code(IndexConfig)
changed to @code(TelemetryString) in following methods:
@unorderedList(
@itemSpacing(Compact)
@item(TKnownEventsList.IndexOf)
@item(TKnownEventsList.Add)
@item(TKnownEventsList.ReplaceIndex)
@item(TKnownEventsList.Replace)
@item(TKnownEventsList.Insert)
@item(TKnownChannelsList.IndexOf)
@item(TKnownChannelsList.Add)
@item(TKnownChannelsList.ReplaceIndex)
@item(TKnownChannelsList.Replace)
@item(TKnownChannelsList.Insert)
@item(TKnownChannelsList.Remove)
@item(TKnownChannelsList.ChannelIndexConfigID)
@item(TKnownChannelsList.ChannelNameToID)
@item(TKnownConfigsList.IndexOf)
@item(TKnownConfigsList.Add)
@item(TKnownConfigsList.ReplaceIndex)
@item(TKnownConfigsList.Replace)
@item(TKnownConfigsList.Insert)
@item(TKnownConfigsList.Remove)
@item(TKnownConfigsList.IsBinded)
@item(TKnownConfigsList.IsIndexed)
@item(TKnownConfigsList.ConfigNameToID)
@item(TRegisteredChannelsList.IndexOf)
@item(TRegisteredChannelsList.Add)
@item(TRegisteredChannelsList.Remove)
@item(TRegisteredChannelsList.CreateContext)
@item(TStoredConfigsList.IndexOf)
@item(TStoredConfigsList.Add)
@item(TStoredConfigsList.Remove)
@item(TStoredConfigsList.ChangeConfigValue)
@item(TStoredChannelsValuesList.IndexOf)
@item(TStoredChannelsValuesList.StoreChannelValue)))
@item(2014-04-07 - Result type changed to @code(TelemetryString) for
following methods:@unorderedList(
@itemSpacing(Compact)
@item(TKnownChannelsList.ChannelIDToName)
@item(TKnownConfigsList.ConfigIDToName)))
@item(2014-04-11 - Added multicast event TCustomTelemetryList.OnChangeMulti.)
@item(2014-04-13 - Name of the class @code(TStoredChannelValuesList) changed
to @code(@noAutoLink(TStoredChannelsValuesList)).)
@item(2014-04-14 - TKnownConfigsList class now stores fully qualified
configuration value names instead of just attribute
names.)
@item(2014-04-15 - Declarations of following types were moved to unit
TelemetryIDs:@unorderedList(
@itemSpacing(Compact)
@item(TItemID)
@item(PItemID)
@item(TChannelID)
@item(PChannelID)
@item(TConfigID)
@item(PConfigID)))
@item(2014-04-15 - Function GetItemID was moved to unit TelemetryIDs.)
@item(2014-05-04 - Following callback functions were added:@unorderedList(
@itemSpacing(Compact)
@item(GetChannelIDFromName)
@item(GetChannelNameFromID)
@item(GetConfigIDFromName)
@item(GetConfigNameFromID)))
@item(2014-06-07 - Added field @code(MaxIndex) to TKnownChannel record.))
@html(<hr>)}
unit TelemetryLists;
interface
{$INCLUDE '.\Telemetry_defs.inc'}
uses
Classes,
{$IFDEF MulticastEvents}
MulticastEvent,
{$ENDIF}
TelemetryCommon,
TelemetryIDs,
{$IFDEF Documentation}
TelemetryConversions,
TelemetryStrings,
{$ENDIF}
{$IFDEF UseCondensedHeader}
SCS_Telemetry_Condensed;
{$ELSE}
scssdk,
scssdk_value,
scssdk_telemetry_event,
scssdk_telemetry_channel;
{$ENDIF}
{==============================================================================}
{------------------------------------------------------------------------------}
{ TCustomTelemetryList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TCustomTelemetryList // Class declaration }
{==============================================================================}
{ @abstract(Ancestor class for all other list classes in TelemetryLists unit.)
TCustomTelemetryList serves as ancestor for all other list classes declared in
this unit. It wrapps around TList class and adds methods used for easier list
management in descendant classes.
@member(fMainList
Internal list used to hold actual items. It is not publicly visible and is
therefore managed automatically.)
@member(fUpdating
When this variable is set to @true, it indicates that the list is updated
from outside and OnChange event should not be called.@br
It is set by methods BeginUpdate and EndUpdate.)
@member(fOnChange
Holds reference to OnChange event handler.)
@member(fOnChangeMulti
Object handling multicast OnChange event.)
@member(GetCount
Getter for property Count.@br
Returns number of items in list.)
@member(PtrGetItem
Returns item (pointer) from internal list on position given by @code(Index)
parameter.@br
When index falls out of allowed boundary (<0,Count - 1>) an exception is
raised.
@param Index Index of requested item in list.
@returns Item at position given by @code(Index).)
@member(PtrIndexOf
Returns index at which the passed item (pointer) is located in the list.@br
When passed pointer is not found in list, -1 is returned.
@param Item Item (pointer) whose index is requested.
@returns Index of passed item in the list, -1 when not found.)
@member(PtrAdd
Method used to add new item into list. Added item can be @nil.@br
Calls method DoChange when addition is successful.
@param Item New item to be added to the list.
@returns Index at which the new item was put, -1 when the operation failed.)
@member(PtrReplace
Replaces item (change its value) at position given by @code(Index)
parameter. Item can be @nil. When index falls out of allowed boundary
(<0,Count - 1>), an exception is raised.@br
Calls method DoChange when item is successfully replaced.
@param Index Index of item that has to be replaced.
@param Item New walue of the replaced item.)
@member(PtrInsert
Inserts new item at position given by @code(Index). List Count is increased
by one and all existing items from given position (included) up are moved
higher. @code(Item) can be @nil. When index falls out of allowed boundary
(<0,Count> - passed index can be higher than current highest index, if so,
item is added at the end of the list), and exception is raised.@br
Calls method DoChange when item is successfully inserted.
@param Index Index at which the new item should be added.
@param Item Inserted item.)
@member(PtrRemove
Removes item passed in @code(Item) parameter. @code(Item) should not be, but
can be @nil. When given item is not found in list, nothing is removed and
the function fails with no error (-1 is returned). If the list contains more
than one copy of the removed item, only the first occurence is removed.@br
Calls method DoChange when item is successfully removed.
@param Item Item that has to be removed.
@returns(Index at which the removed item was place before removal, -1 whem
given item was not found in the list.))
@member(PtrDelete
Deletes item at position given by @code(Index) parameter. When index falls
out of allowed boundary (<0,Count - 1>), an exception is raised.@br
Calls method DoChange when item is successfully deleted.
@param Index Index of item that has to be deleted.)
@member(Create
Object constructor.)
@member(Destroy
ObjectDestructor.@br
Method Clear is called within destructor, so it is not necessary to
explicitly call it when class instance is freed.
@bold(Note:) OnChange event is not called.)
@member(BeginUpdate
Sets fUpdating to @true.)
@member(EndUpdate
Sets fUpdating to @false and calls DoChange method.)
@member(DoChange
Calls handler of OnChange event (if assigned) - but only if fUpdating is set
to @false, otherwise the handler is not called and method returns
immediately.)
@member(Clear
Deletes all items in the list. It only deletes stored pointers, allocated
memory they are pointing to is not freed. Override this method in
descendants to free memory used by items (put inherited code at the end).@br
Calls method DoChange after all items are deleted.)
@member(Count
Number of items stored in the list.)
@member(OnChange
Event called whenever the list is changed. It can also be called manually by
calling DoChange method. It is NOT called when fUpdating is set to @true
(but can be still called directly if handler is assigned).)
@member(OnChangeMulti
Multicast event called whenever the list is changed. It can also be called
manually by calling DoChange method. It is NOT called when fUpdating is set
to @true (but can be still called directly).@br
Assigning handlers to this event does not interfere with normal OnChange
event.@br
Normal OnChange event is called first, handlers of this event are called
afterwards.)
}
type
TCustomTelemetryList = class(TObject)
private
fMainList: TList;
fUpdating: Boolean;
fOnChange: TNotifyEvent;
{$IFDEF MulticastEvents}
fOnChangeMulti: TMulticastNotifyEvent;
{$ENDIF}
Function GetCount: Integer;
protected
Function PtrGetItem(Index: Integer): Pointer; virtual;
Function PtrIndexOf(Item: Pointer): Integer; virtual;
Function PtrAdd(Item: Pointer): Integer; virtual;
procedure PtrReplace(Index: Integer; Item: Pointer); virtual;
procedure PtrInsert(Index: Integer; Item: Pointer); virtual;
Function PtrRemove(Item: Pointer): Integer; virtual;
procedure PtrDelete(Index: Integer); virtual;
public
constructor Create;
destructor Destroy; override;
procedure BeginUpdate; virtual;
procedure EndUpdate; virtual;
procedure DoChange; virtual;
procedure Clear; virtual;
published
property Count: Integer read GetCount;
property OnChange: TNotifyEvent read fOnChange write fOnChange;
{$IFDEF MulticastEvents}
property OnChangeMulti: TMulticastNotifyEvent read fOnChangeMulti;
{$ENDIF}
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownEventsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Structure used as an item in TKnownEventsList class.
@member(Event @NoAutoLink(Event) identification number.)
@member(Name @NoAutoLink(Name) assigned to @NoAutoLink(event) (this
@NoAutoLink(name) is not defined by Telemetry SDK, do not
assume its value as it can change in the future).)
@member(Valid Denotes whether @NoAutoLink(event) is @NoAutoLink(valid)
(invalid events cannot be successfuly registered).)
@member(Utility Denotes whether @NoAutoLink(event) is marked as
@NoAutoLink(utility) (such events cannot be unregistered
and/or are registered automatically at certain
circumstances).)
}
TKnownEvent = record
Event: scs_event_t;
Name: TelemetryString;
Valid: Boolean;
Utility: Boolean;
end;
// Pointer to TKnownEvent structure.
PKnownEvent = ^TKnownEvent;
const
// Empty TKnownEvent structure.
cEmptyKnownEvent: TKnownEvent =
(Event: SCS_TELEMETRY_EVENT_invalid;
Name: '';
Valid: False;
Utility: False);
{==============================================================================}
{ TKnownEventsList // Class declaration }
{==============================================================================}
{
@abstract(
List used to store informations about known telemetry @noAutoLink(events).)
@member(GetKnownEventPointer
Getter for Pointers[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetKnownEvent
Getter for Events[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Add
Adds new known game event into the list.@br
OnChange event is called after successful addition.
@param Event Event identification number.
@param Name Name of added event.
@param Valid Flag denoting whether added event is marked as valid.
@param Utility Flag denoting whether added event is marked as utility.
@returns Index at which the new event was added, -1 when addition failed.)
@member(ReplaceIndex
Replaces event at position given by @code(Index) parameter. When index falls
out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful replacement.
@param Index Index of item that has to be replaced.
@param Event Replacement event identification number.
@param Name Name of replacement event.
@param Valid Flag denoting whether replacement event is marked as valid.
@param(Utility Flag denoting whether replacement event is marked as
utility.))
@member(Replace
Replaces event given by @code(OldEvent) parameter. When this old event is
not found in the list, nothing happens and the method returns -1.@br
OnChange event is called after successful replacement.
@param OldEvent Identification number of event that has to be replaced.
@param Event Replacement event identification number.
@param Name Name of replacement event.
@param(Valid Flag denoting whether replacement event is marked as
valid.)
@param(Utility Flag denoting whether replacement event is marked as
utility.)
@returns(Index of event that was replaced, -1 when such event was not
found.))
@member(Insert
Inserts new event at position given by @code(Index) parameter. Count is
increased by one and all existing items from given position (included) up
are moved higher. When index falls out of allowed boundary (<0,Count> -
passed index can be higher than current highest index, if so, item is added
at the end of the list), and exception is raised.@br
OnChange event is called after successful insertion.
@param Index Position where the new event should be inserted.
@param Event Event identification number.
@param Name Name of event.
@param Valid Flag denoting whether event is marked as valid.
@param Utility Flag denoting whether event is marked as utility.
@returns Actual position where the new event was inserted.)
@member(Remove
Removes given event from the list. When this event is not found in the list,
method returns -1 and nothing is removed.@br
OnChange event is called after successful removal.
@param(Event Identification number of event that has to be removed from the
list.)
@returns(Index of item that was removed, -1 when requested event was not
found.))
@member(Delete
Deletes event at position given by @code(Index) parameter. When index falls
out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(IsValid
Returns @true when given event is valid, @false when it is not valid or when
that event is not in list.
@param Event Identification number of requested event.
@returns Validity of requested event.)
@member(IsUtility
Returns @true when given event is marked as Utility, @false when it is not
or when not found in the list.
@param Event Identification number of requested event.
@returns Utility state of requested event.)
@member(Pointers
Array property mapped directly to internal list. Use it for direct access to
individual stored items.@br
Unlike Events[] property, you can use returned pointer to change values of
stored items.)
@member(Events
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.)
}
type
TKnownEventsList = class(TCustomTelemetryList)
private
Function GetKnownEventPointer(Index: Integer): PKnownEvent;
Function GetKnownEvent(Index: Integer): TKnownEvent;
public
procedure Clear; override;
{
Searches through list for given event. When the event is not found, -1 is
returned.
@param Event Event whose index is requested.
@returns Index of requested event, -1 when not found.
}
Function IndexOf(Event: scs_event_t): Integer; overload; virtual;
{
Searches through list for event with given name (case-insensitive). When
event with that name is not found, -1 is returned.
@param Name Name of the event whose index is requested.
@returns Index of event with requested name, -1 when not found.
}
Function IndexOf(const Name: TelemetryString): Integer; overload; virtual;
Function Add(Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer; virtual;
procedure ReplaceIndex(Index: Integer; Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False); virtual;
Function Replace(OldEvent, Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer; virtual;
Function Insert(Index: Integer; Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer; virtual;
Function Remove(Event: scs_event_t): Integer; virtual;
procedure Delete(Index: Integer); virtual;
Function IsValid(Event: scs_event_t): Boolean; virtual;
Function IsUtility(Event: scs_event_t): Boolean; virtual;
property Pointers[Index: Integer]: PKnownEvent read GetKnownEventPointer;
property Events[Index: Integer]: TKnownEvent read GetKnownEvent; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownChannelsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Structure used as an item in TKnownChannelsList class.
@member(Name @NoAutoLink(Name) of the channel.)
@member(ID Identifier of the channel (calculated from
@noAutoLink(name)).)
@member(PrimaryType Primary value type of the channel.)
@member(SecondaryType Secondary value type of the channel.)
@member(TertiaryType Tertiary value type of the channel.)
@member(Indexed Flag indicating whether the channel is
@NoAutoLink(indexed).)
@member(IndexConfig Full @NoAutoLink(name) of a config that should store
count (that is, maxindex + 1) for this channel (has
meaning only for @NoAutoLink(indexed) channels).)
@member(IndexConfigID Identifier of config that stores count for this
channel (see IndexConfig field).)
@member(MaxIndex Maximum index for @NoAutoLink(indexed) channels.)
}
TKnownChannel = record
Name: TelemetryString;
ID: TChannelID;
PrimaryType: scs_value_type_t;
SecondaryType: scs_value_type_t;
TertiaryType: scs_value_type_t;
Indexed: Boolean;
IndexConfig: TelemetryString;
IndexConfigID: TConfigID;
MaxIndex: scs_u32_t;
end;
// Pointer to TKnownChannel structure.
PKnownChannel = ^TKnownChannel;
const
// Empty TKnownChannel structure.
cEmptyKnownChannel: TKnownChannel =
(Name: '';
ID: 0;
PrimaryType: SCS_VALUE_TYPE_INVALID;
SecondaryType: SCS_VALUE_TYPE_INVALID;
TertiaryType: SCS_VALUE_TYPE_INVALID;
Indexed: False;
IndexConfig: '';
IndexConfigID: 0;
MaxIndex: SCS_U32_NIL);
{==============================================================================}
{ TKnownChannelsList // Class declaration }
{==============================================================================}
{
@abstract(
List used to store informations about known telemetry @noAutoLink(channels).)
@member(GetKnownChannelPointer
Getter for Pointers[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetKnownChannel
Getter for Events[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Add
Adds new known channel into the list.@br
OnChange event is called after successful addition.
@param Name Name of added channel (ID is calculated from it).
@param PrimaryType Primary type of value for this channel.
@param SecondaryType Secondary type of value for this channel.
@param TertiaryType Tertiary type of value for this channel.
@param Indexed Flag denoting whether added channel is indexed.
@param(IndexConfig Fully qualified name (id + attribute name) of the
configuration containing @noAutoLink(count) for channel
indices. Has no meaning when the channel is not
indexed.)
@returns Index at which the new channel was added, -1 when addition failed.)
@member(ReplaceIndex
Replaces channel at position given by @code(Index) parameter. When index
falls out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful replacement.
@param Index Index of item that has to be replaced.
@param Name Name of replacement channel (ID is calculated from it).
@param PrimaryType Primary type of value for this channel.
@param SecondaryType Secondary type of value for this channel.
@param TertiaryType Tertiary type of value for this channel.
@param Indexed Flag denoting whether channel is indexed.
@param(IndexConfig Fully qualified name (id + attribute name) of the
configuration containing @noAutoLink(count) for channel
indices. Has no meaning when the channel is not
indexed.))
@member(Replace
Replaces channel with name given by @code(OldChannel) parameter. When this
channel is not found in the list, nothing happens and the method returns
-1.@br
OnChange event is called after successful replacement.
@param(OldEvent Identification number of channel that has to be
replaced.)
@param Name Name of replacement channel (ID is calculated from it).
@param PrimaryType Primary type of value for this channel.
@param SecondaryType Secondary type of value for this channel.
@param TertiaryType Tertiary type of value for this channel.
@param Indexed Flag denoting whether channel is indexed.
@param(IndexConfig Fully qualified name (id + attribute name) of the
configuration containing @noAutoLink(count) for channel
indices. Has no meaning when the channel is not
indexed.)
@returns(Index of channel that was replaced, -1 when old channel was not
found.))
@member(Insert
Inserts new channel at position given by @code(Index) parameter. Count is
increased by one and all existing items from given position (included) up
are moved higher. When index falls out of allowed boundary (<0,Count> -
passed index can be higher than current highest index, if so, item is added
at the end of the list), and exception is raised.@br
OnChange event is called after successful insertion.
@param Index Position where the new channel should be inserted.
@param Name Name of inserted channel (ID is calculated from it).
@param PrimaryType Primary type of value for this channel.
@param SecondaryType Secondary type of value for this channel.
@param TertiaryType Tertiary type of value for this channel.
@param Indexed Flag denoting whether channel is indexed.
@param(IndexConfig Fully qualified name (id + attribute name) of the
configuration containing @noAutoLink(count) for channel
indices. Has no meaning when the channel is not
indexed.)
@returns Actual position where the new channel was inserted.)
@member(Remove
Removes channel with given name from the list. When this channel is not
found in the list, method returns -1 and nothing is removed.@br
OnChange event is called after successful removal.
@param Name Name of the channel that has to be removed from the list.
@returns(Index of item that was removed, -1 when requested channel was not
found.))
@member(Delete
Deletes channel at position given by @code(Index) parameter. When index
falls out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(ChannelIndexConfigID
Returns @code(IndexConfigID) for channel with name given in @code(Name)
parameter. When such channel is not found in the list, ID with value
0x00000000 is returned.
@param Name Name of requested channel.
@returns ID of index-configuration for requested channel.)
@member(ChannelNameToID
Returns ID for passed channel name.
@param Name Name of chanel for which you want an ID.
@returns ID of passed channel name.)
@member(ChannelIDToName
Returns name of channel with the same ID as is passed in @code(ID) prameter.
This method actually searches through the list for channel with appropriate
ID. When such channel is not found, an empty string is returned.
@param ID ID of requested channel.
@returns Name of the channel with appropriate ID.)
@member(Pointers
Array property mapped directly to internal list. Use it for direct access to
individual stored items.@br
Unlike Channels[] property, you can use returned pointer to change values of
stored items.)
@member(Channels
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.)
}
type
TKnownChannelsList = class(TCustomTelemetryList)
private
Function GetKnownChannelPointer(Index: Integer): PKnownChannel;
Function GetKnownChannel(Index: Integer): TKnownChannel;
public
procedure Clear; override;
{
Searches through list for channel with given name (case-sensitive). When
the channel is not found, -1 is returned.
@param Name Name of the requested channel.
@returns Index of channel with requested name, -1 when not found.
}
Function IndexOf(const Name: TelemetryString): Integer; overload; virtual;
{
Searches through list for channel with given ID. When channel with that ID
is not found, -1 is returned.
@param ID ID of channel whose index is requested.
@returns Index of channel with requested ID, -1 when not found.
}
Function IndexOf(ID: TChannelID): Integer; overload; virtual;
Function Add(const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer; virtual;
procedure ReplaceIndex(Index: Integer; const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL); virtual;
Function Replace(const OldChannel, Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer; virtual;
Function Insert(Index: Integer; const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer; virtual;
Function Remove(const Name: TelemetryString): Integer; virtual;
procedure Delete(Index: Integer); virtual;
Function ChannelIndexConfigID(const Name: TelemetryString): TItemID; virtual;
Function ChannelNameToID(const Name: TelemetryString): TChannelID; virtual;
Function ChannelIDToName(ID: TChannelID): TelemetryString; virtual;
property Pointers[Index: Integer]: PKnownChannel read GetKnownChannelPointer;
property Channels[Index: Integer]: TKnownChannel read GetKnownChannel; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownConfigsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Structure used as item in TKnownConfigsList class.
@member(Name Full @NoAutoLink(name) of the config.)
@member(ID Identifier of the config (calculated from
@noAutoLink(name)))
@member(ValueType Type of value for current config.)
@member(Indexed Flag indicating whether the config is @NoAutoLink(indexed).)
@member(Binded Flag denoting whether this config is @NoAutoLink(binded) by
a channel (meaning that some @NoAutoLink(indexed) channel
uses this config to obtain maximum index).)
}
TKnownConfig = record
Name: TelemetryString;
ID: TConfigID;
ValueType: scs_value_type_t;
Indexed: Boolean;
Binded: Boolean;
end;
// Pointer to TKnownConfig structure.
PKnownConfig = ^TKnownConfig;
const
// Empty TKnownConfig structure.
cEmptyKnownConfig: TKnownConfig =
(Name: '';
ID: 0;
ValueType: SCS_VALUE_TYPE_INVALID;
Indexed: False;
Binded: False);
{==============================================================================}
{ TKnownConfigsList // Class declaration }
{==============================================================================}
{
@abstract(
List used to store informations about known telemetry configurations values.)
@member(GetKnownConfigPointer
Getter for Pointers[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetKnownConfig
Getter for Configs[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Add
Adds new known config into the list.@br
OnChange event is called after successful addition.
@param Name Full name of added config.
@param ValuetyType Type of this @noAutoLink(configs) value.
@param Indexed Flag denoting whether added config is indexed.
@param(Binded Flag denoting whether added config is binded by some
channel (i.e. some channel has this config as its
IndexConfig property).)
@returns Index at which the new config was added, -1 when addition failed.)
@member(ReplaceIndex
Replaces config at position given by @code(Index) parameter. When index
falls out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful replacement.
@param Index Index of item that has to be replaced.
@param Name Full name of new config.
@param ValuetyType Type of this @noAutoLink(configs) value.
@param Indexed Flag denoting whether added config is indexed.
@param(Binded Flag denoting whether added config is binded by some
channel (i.e. some channel has this config as its
IndexConfig property).))
@member(Replace
Replaces config with name given by @code(OldConfig) parameter. When this
config is not found in the list, nothing happens and the method returns
-1.@br
OnChange event is called after successful replacement.
@param OldConfig Full name of the config that has to be replaced.
@param Name Full name of replacment config.
@param ValuetyType Type of this @noAutoLink(configs) value.
@param Indexed Flag denoting whether config is indexed.
@param(Binded Flag denoting whether config is binded by some channel
(i.e. some channel has this config as its IndexConfig
property).)
@returns(Index of config that was replaced, -1 when old config was not
found.))
@member(Insert
Inserts new config at position given by @code(Index) parameter. Count is
increased by one and all existing items from given position (included) up
are moved higher. When index falls out of allowed boundary (<0,Count> -
passed index can be higher than current highest index, if so, item is added
at the end of the list), and exception is raised.@br
OnChange event is called after successful insertion.
@param Index Position where the new config should be inserted.
@param Name Full name of inserted config.
@param ValuetyType Type of this @noAutoLink(configs) value.
@param Indexed Flag denoting whether config is indexed.
@param(Binded Flag denoting whether config is binded by some channel
(i.e. some channel has this config as its IndexConfig
property).)
@returns Actual position where the new config was inserted.)
@member(Remove
Removes config with given name from the list. When this config is not found
in the list, method returns -1 and nothing is removed.@br
OnChange event is called after successful removal.
@param Name Full name of the config that has to be removed from the list.
@returns(Index of item that was removed, -1 when requested config was not
found.))
@member(Delete
Deletes config at position given by @code(Index) parameter. When index falls
out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(IsBinded
Returns @true when given config is binded, @false when it is not binded or
when not found in list.
@param Name Full name of the requested config.
@returns Binded state of requested config.)
@member(IsIndexed
Returns @true when given config is Indexed, @false when it is not Indexed or
when not found in list.
@param Name Full name of the requested config.
@returns Indexed state of requested config.)
@member(ConfigNameToID
Returns ID for passed Config name.
@param Name Full name of config for which you want an ID.
@returns ID of passed Config name.)
@member(ConfigIDToName
Returns name of Config with the same ID as is passed in "ID" prameter. This
method actually searches through the list for Config with appropriate ID.
When such Config is not found, an empty string is returned.
@param ID ID of requested config.
@returns Full name of the config with appropriate ID.)
@member(Pointers
Array property mapped directly to internal list. Use it for direct access to
individual stored items.@br
Unlike Configs[] property, you can use returned pointer to change values of
stored items.)
@member(Configs
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.)
}
type
TKnownConfigsList = class(TCustomTelemetryList)
private
Function GetKnownConfigPointer(Index: Integer): PKnownConfig;
Function GetKnownConfig(Index: Integer): TKnownConfig;
public
procedure Clear; override;
{
Searches through list for config with given name (case-sensitive). When the
config is not found, -1 is returned.
@param Name Name of the requested config.
@returns Index of config with requested name, -1 when not found.
}
Function IndexOf(const Name: TelemetryString): Integer; overload; virtual;
{
Searches through list for config with given ID. When config with that ID is
not found, -1 is returned.
@param ID ID of config whose index is requested.
@returns Index of config with requested ID, -1 when not found.
}
Function IndexOf(ID: TConfigID): Integer; overload; virtual;
Function Add(const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer; virtual;
procedure ReplaceIndex(Index: Integer; const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False); virtual;
Function Replace(const OldConfig, Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer; virtual;
Function Insert(Index: Integer; const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer; virtual;
Function Remove(const Name: TelemetryString): Integer; virtual;
procedure Delete(Index: Integer); virtual;
Function IsBinded(const Name: TelemetryString): Boolean; virtual;
Function IsIndexed(const Name: TelemetryString): Boolean; virtual;
Function ConfigNameToID(const Name: TelemetryString): TConfigID;
Function ConfigIDToName(ID: TConfigID): TelemetryString; virtual;
property Pointers[Index: Integer]: PKnownConfig read GetKnownConfigPointer;
property Configs[Index: Integer]: TKnownConfig read GetKnownConfig; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredEventsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Structure holding informations about registered @noAutoLink(event).
@member(Event @NoAutoLink(Event) identifier.)
@member(Utility Denotes whether current @NoAutoLink(event) is marked as
@NoAutoLink(utility).)
}
TEventInfo = record
Event: scs_event_t;
Utility: Boolean;
end;
// Pointer to TEventInfo structure.
PEventInfo = ^TEventInfo;
const
// Empty TEventInfo structure.
cEmptyEventInfo: TEventInfo =
(Event: SCS_TELEMETRY_EVENT_invalid;
Utility: False);
{
@abstract(Structure used as item in TRegisteredEventsList.)
Pointer to this structure is passed as @noAutoLink(context) in telemetry API
calls when registering telemetry event.
@member(Recipient Object that should receive event callbacks.)
@member(EventInfo Informations about registered event.)
}
type
TEventContext = record
Recipient: TObject;
EventInfo: TEventInfo;
end;
// Pointer to TEventContext structure.
PEventContext = ^TEventContext;
{==============================================================================}
{ TRegisteredEventsList // Class declaration }
{==============================================================================}
{
@abstract(List used to store @noAutoLink(contexts of registered events).)
When new event is registered in the telemetry API, it is registered with
context which is actually pointer to a variable of TEventContext structure.
This variable is at the same time added as a new item into this list.@br
When event is unregistered, context it is bound to is removed from this list.
@member(GetEventContext
Getter for Contexts[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetEventInfo
Getter for Events[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Delete
Deletes context at position given by @code(Index) parameter. When index
falls out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(CreateContext
This method creates new event context variable, fills it from parameters and
returns pointer to this variable. It is used when registering new telemetry
event, because actual context is needed for this registration, but cannot be
added to this list before the registration is complete.@br
Sequence of actions taken during registration is as follows:
@unorderedlist(
@itemSpacing(Compact)
@item Context is created using this function.
@item Registration in API is attempted.
@item When successful, context is added to this list.
@item When unsuccessful, context is freed using FreeContext method.
)
@param Recipient Telemetry recipient registering created context.
@param Event Identification number of registered event.
@param(Utility Flag indicating whether registered event is marked as
utility.)
@returns Pointer to created event context.)
@member(FreeContext
Frees memory allocated for event context and sets this pointer to @nil.
@param EventContext Pointer to event context to be freed.)
@member(Contexts
Array property mapped directly to internal list. Use it for direct access to
individual stored contexts.@br
Unlike Events[] property, you can use returned pointer to change values of
stored items.)
@member(Events
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.@br
This property does not return whole context structure, only its "EventInfo"
field.)
}
TRegisteredEventsList = class(TCustomTelemetryList)
private
Function GetEventContext(Index: Integer): PEventContext;
Function GetEventInfo(Index: Integer): TEventInfo;
public
procedure Clear; override;
{
Searches through list for context with requested event. When the context is
not found, -1 is returned.
@param Event Identification number of requested event.
@returns Index of context with requested event, -1 when not found.
}
Function IndexOf(Event: scs_event_t): Integer; overload; virtual;
{
Searches through list for given context. When the context is not found,
-1 is returned.
@param EventContext Requested event context.
@returns Index of requested context, -1 when not found.
}
Function IndexOf(EventContext: PEventContext): Integer; overload; virtual;
{
Adds new context into the list. @code(EventContext) parameter must not be
@nil, otherwise an exception is raised.@br
OnChange event is called after successful addition.
@param(EventContext Pointer to event context that has to be added to the
list.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(EventContext: PEventContext): Integer; overload; virtual;
{
Creates and adds new context into the list.@br
OnChange event is called after successful addition.
@param Recipient Telemetry recipient registering this new context.
@param Event Identification number of registered event.
@param(Utility Flag indicating whether registered event is marked as
utility.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(Recipient: TObject; Event: scs_event_t; Utility: Boolean = False): Integer; overload; virtual;
{
Creates and adds new context into the list. Created context has
@code(Recipient) field set to @nil.@br
OnChange event is called after successful addition.
@param Event Identification number of registered event.
@param(Utility Flag indicating whether registered event is marked as
utility.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(Event: scs_event_t; Utility: Boolean = False): Integer; overload; virtual;
{
Removes context with given event from the list.@br
OnChange event is called after successful removal.
@param(Event Identification number of registered event whose context has to
be removed.)
@returns(Index of item that was removed, -1 when context with requested
event was not found.)
}
Function Remove(Event: scs_event_t): Integer; overload; virtual;
{
Removes given context from the list.@br
OnChange event is called after successful removal.
@param EventContext Context to be removed.
@returns(Index of item that was removed, -1 when requested context was not
found.)
}
Function Remove(EventContext: PEventContext): Integer; overload; virtual;
procedure Delete(Index: Integer); virtual;
Function CreateContext(Recipient: TObject; Event: scs_event_t; Utility: Boolean = False): PEventContext; virtual;
procedure FreeContext(var EventContext: PEventContext); virtual;
property Contexts[Index: Integer]: PEventContext read GetEventContext;
property Events[Index: Integer]: TEventInfo read GetEventInfo; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredChannelsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Structure holding informations about registered channel.
@member(Name @NoAutoLink(Name) of the channel.)
@member(ID Identifier of the channel.)
@member(Index @NoAutoLink(Index) of channels value.)
@member(ValueType Type of value for current channel.)
@member(Flags Registration flags.)
@member(IndexConfigID Identifier of config that stores count for this
channel.)
}
TChannelInfo = record
Name: TelemetryString;
ID: TChannelID;
Index: scs_u32_t;
ValueType: scs_value_type_t;
Flags: scs_u32_t;
IndexConfigID: TItemID;
end;
// Pointer to TChannelInfo structure.
PChannelInfo = ^TChannelInfo;
const
// Empty TEventInfo structure.
cEmptyChannelInfo: TChannelInfo =
(Name: '';
ID: 0;
Index: SCS_U32_NIL;
ValueType: SCS_VALUE_TYPE_INVALID;
Flags: 0;
IndexConfigID: 0);
{
@abstract(Structure used as item in TRegisteredEventsList.)
Pointer to this structure is passed as @noAutoLink(context) in telemetry API
calls when registering telemetry channel.
@member(Recipient Object that should receive channel callbacks.)
@member(ChannelInfo Informations about registered channel.)
}
type
TChannelContext = record
Recipient: TObject;
ChannelInfo: TChannelInfo;
end;
// Pointer to TChannelContext structure.
PChannelContext = ^TChannelContext;
{==============================================================================}
{ TRegisteredChannelsList // Class declaration }
{==============================================================================}
{
@abstract(List used to store @noAutoLink(contexts of registered channels).)
When new channel is registered in the telemetry API, it is registered with
context which is actually pointer to a variable of TChannelContext structure.
This variable is at the same time added as a new item into this list.@br
When channel is unregistered, context it is bound to is removed from this
list.
@member(GetChannelContext
Getter for Contexts[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetChannelInfo
Getter for Channels[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Delete
Deletes context at position given by @code(Index) parameter. When index
falls out of allowed boundary (<0,Count - 1>), an exception is raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(CreateContext
This method creates new channel context variable, fills it from parameters
and returns pointer to this variable. It is used when registering new
telemetry channel, because actual context is needed for this registration,
but cannot be added to this list before the registration is complete.@br
Sequence of actions taken during registration is as follows:
@unorderedlist(
@itemSpacing(Compact)
@item Context is created using this function.
@item Registration in API is attempted.
@item When successful, context is added to this list.
@item When unsuccessful, context is freed using FreeContext method.
)
@param Recipient Telemetry recipient registering created context.
@param(Name Name of the registered channel (ID is calculated from
it).)
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@param Flags Registering flags.
@param(IndexConfigID ID of index configuration to which registered channel
is bound.)
@returns Pointer to created channel context.)
@member(FreeContext
Frees memory allocated for channel context and sets this pointer to @nil.
@param ChannelContext Pointer to channel context to be freed.)
@member(Contexts
Array property mapped directly to internal list. Use it for direct access to
individual stored contexts.@br
Unlike Channels[] property, you can use returned pointer to change values of
stored items.)
@member(Channels
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.@br
This property does not return whole context structure, only its
"ChannelInfo" field.)
}
TRegisteredChannelsList = class(TCustomTelemetryList)
private
Function GetChannelContext(Index: Integer): PChannelContext;
Function GetChannelInfo(Index: Integer): TChannelInfo;
public
procedure Clear; override;
{
Searches through list for context created for channel with appropriate name.
When the context is not found, -1 is returned.
@param Name Name of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(const Name: TelemetryString): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate ID.
When the context is not found, -1 is returned.
@param ID ID of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(ID: TChannelID): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate name
and index. When the context is not found, -1 is returned.
@param Name Name of the requested channel.
@param Index Index of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(const Name: TelemetryString; Index: scs_u32_t): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate ID
and index. When the context is not found, -1 is returned.
@param ID ID of the requested channel.
@param Index Index of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(ID: TChannelID; Index: scs_u32_t): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate name,
index and value type. When the context is not found, -1 is returned.
@param Name Name of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate ID,
index and value type. When the context is not found, -1 is returned.
@param ID ID of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate name,
index, value type and flags. When the context is not found, -1 is returned.
@param Name Name of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@param Flags Registering flags of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t): Integer; overload; virtual;
{
Searches through list for context created for channel with appropriate ID,
index, value type and flags. When the context is not found, -1 is returned.
@param ID ID of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@param Flags Registering flags of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t): Integer; overload; virtual;
{
Searches through list given context. When the context is not found, -1 is returned.
@param ChannelContext Requested channel context.
@returns Index of requested context, -1 when not found.
}
Function IndexOf(ChannelContext: PChannelContext): Integer; overload; virtual;
{
Adds new context into the list. @code(ChannelContext) parameter must not be
@nil, otherwise an exception is raised.@br
OnChange event is called after successful addition.
@param(ChannelContext Pointer to channel context that has to be added to the
list.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(ChannelContext: PChannelContext): Integer; overload; virtual;
{
Creates and adds new context into the list.@br
OnChange event is called after successful addition.
@param Recipient Telemetry recipient registering this new context.
@param(Name Name of the registered channel (ID is calculated from
it).)
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@param Flags Registering flags.
@param(IndexConfigID ID of index configuration to which the registered
channel is bound.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(Recipient: TObject; const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): Integer; overload; virtual;
{
Creates and adds new context into the list. Created context has
@code(Recipient) field set to @nil.@br
OnChange event is called after successful addition.
@param(Name Name of the registered channel (ID is calculated from
it).)
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@param Flags Registering flags.
@param(IndexConfigID ID of index configuration to which the registered
channel is bound.)
@returns Index at which the new context was added, -1 when addition failed.
}
Function Add(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): Integer; overload; virtual;
{
Removes context created for given channel from the list.@br
OnChange event is called after successful removal.
@param(Name Name of the registered channel whose context has to be
removed.)
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@returns(Index of item that was removed, -1 when context with requested
channel was not found.)
}
Function Remove(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
{
Removes context created for given channel from the list.@br
OnChange event is called after successful removal.
@param(ID ID of the registered channel whose context has to be
removed.)
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@returns(Index of item that was removed, -1 when context with requested
channel was not found.)
}
Function Remove(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
{
Removes given context from the list.@br
OnChange event is called after successful removal.
@param ChannelContext Context to be removed.
@returns(Index of item that was removed, -1 when requested context was not
found.)
}
Function Remove(ChannelContext: PChannelContext): Integer; overload; virtual;
procedure Delete(Index: Integer); virtual;
Function CreateContext(Recipient: TObject; const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): PChannelContext; virtual;
procedure FreeContext(var ChannelContext: PChannelContext); virtual;
property Contexts[Index: Integer]: PChannelContext read GetChannelContext;
property Channels[Index: Integer]: TChannelInfo read GetChannelInfo; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredConfigsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{
@abstract(Structure used as item in TStoredConfigsList.)
This structure is used to store configuration @noAutoLink(value) obtained from
the API call.
@member(Name Full @NoAutoLink(name) of the config.)
@member(ID Identifier of the config.)
@member(Index Index of configs @NoAutoLink(value).)
@member(Value Actual @NoAutoLink(value) of the config.)
@member(Binded Flag denoting whether this config is @NoAutoLink(binded).)
}
TStoredConfig = record
Name: TelemetryString;
ID: TConfigID;
Index: scs_u32_t;
Value: scs_value_localized_t;
Binded: Boolean;
end;
// Pointer to TStoredConfig structure.
PStoredConfig = ^TStoredConfig;
const
// Empty TStoredConfig structure.
cEmptyStoredConfig: TStoredConfig =
(Name: '';
ID: 0;
Index: SCS_U32_NIL;
Value: (
ValueType: SCS_VALUE_TYPE_INVALID;
BinaryData: (
_type: SCS_VALUE_TYPE_INVALID);
StringData: '');
Binded: True);
{==============================================================================}
{ TStoredConfigsList // Class declaration }
{==============================================================================}
{
@abstract(List used to store configuration values obtained from API calls.)
@member(GetStoredConfigPointer
Getter for Pointers[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Pointer to requested item.)
@member(GetStoredConfig
Getter for Configs[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(Delete
Deletes stored config at position given by @code(Index) parameter. When
index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.@br
OnChange event is called after successful deletion.
@param Index Index of item that has to be deleted.)
@member(Pointers
Array property mapped directly to internal list. Use it for direct access to
individual stored items.@br
Unlike Configs[] property, you can use returned pointer to change values of
stored items.)
@member(Configs
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.)
}
type
TStoredConfigsList = class(TCustomTelemetryList)
private
Function GetStoredConfigPointer(Index: Integer): PStoredConfig;
Function GetStoredConfig(Index: Integer): TStoredConfig;
public
procedure Clear; override;
{
Searches through list for stored config with appropriate name.
When matching config is not found, -1 is returned.
@param Name Name of the requested config.
@returns Index of requested config, -1 when not found.
}
Function IndexOf(const Name: TelemetryString): Integer; overload; virtual;
{
Searches through list for stored config with appropriate ID.
When matching config is not found, -1 is returned.
@param ID ID of the requested config.
@returns Index of requested config, -1 when not found.
}
Function IndexOf(ID: TConfigID): Integer; overload; virtual;
{
Searches through list for stored config with appropriate name and index.
When matching config is not found, -1 is returned.
@param Name Name of the requested config.
@param Index Index of the requested config.
@returns Index of requested config, -1 when not found.
}
Function IndexOf(const Name: TelemetryString; Index: scs_u32_t): Integer; overload; virtual;
{
Searches through list for stored config with appropriate ID and index.
When matching config is not found, -1 is returned.
@param ID ID of the requested config.
@param Index Index of the requested config.
@returns Index of requested config, -1 when not found.
}
Function IndexOf(ID: TConfigID; Index: scs_u32_t): Integer; overload; virtual;
{
Stores new config with its value into the list.@br
OnChange event is called after successful addition.
@param Name Name of stored config (ID is calculated from it).
@param Index Index of stored config.
@param Value Localized value (data) this config contains.
@param(Binded Flag denoting whether this config is binded by some channel
(i.e. some channel has this config as its IndexConfig
property).)
@returns Index at which the new config was stored, -1 when addition failed.
}
Function Add(const Name: TelemetryString; Index: scs_u32_t; Value: scs_value_localized_t; Binded: Boolean = False): Integer; overload; virtual;
{
Stores new config with its value into the list.@br
OnChange event is called after successful addition.
@param Name Name of stored config (ID is calculated from it).
@param Index Index of stored config.
@param Value Value (data) this config contains.
@param(Binded Flag denoting whether this config is binded by some channel
(i.e. some channel has this config as its IndexConfig
property).)
@returns Index at which the new config was stored, -1 when addition failed.
}
Function Add(const Name: TelemetryString; Index: scs_u32_t; Value: p_scs_value_t; Binded: Boolean = False): Integer; overload; virtual;
{
Removes stored config from the list.@br
OnChange event is called after successful removal.
@param Name Name of stored config that has to be removed.
@param Index Index of stored config.
@returns(Index of item that was removed, -1 when requested config was not
found.)
}
Function Remove(const Name: TelemetryString; Index: scs_u32_t = SCS_U32_NIL): Integer; overload; virtual;
{
Removes stored config from the list.@br
OnChange event is called after successful removal.
@param ID ID of stored config that has to be removed.
@param Index Index of stored config.
@returns(Index of item that was removed, -1 when requested config was not
found.)
}
Function Remove(ID: TChannelID; Index: scs_u32_t = SCS_U32_NIL): Integer; overload; virtual;
procedure Delete(Index: Integer); virtual;
{
Changes stored value in config defined by name and index.
OnChange event is called after successful removal.
@param Name Name of stored config whose value should be changed.
@param Index Index of stored config.
@returns(Index of item whose value has been changed, -1 when requested
config was not found.)
}
Function ChangeConfigValue(const Name: TelemetryString; Index: scs_u32_t; Value: scs_value_localized_t): Integer; overload; virtual;
{
Changes stored value in config defined by ID and index.
OnChange event is called after successful removal.
@param ID ID of stored config whose value should be changed.
@param Index Index of stored config.
@returns(Index of item whose value has been changed, -1 when requested
config was not found.)
}
Function ChangeConfigValue(ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t): Integer; overload; virtual;
property Pointers[Index: Integer]: PStoredConfig read GetStoredConfigPointer;
property Configs[Index: Integer]: TStoredConfig read GetStoredConfig; default;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredChannelsValuesList }
{------------------------------------------------------------------------------}
{==============================================================================}
// Identification number used in TStoredChannelsValuesList for faster
// searching.
TMasterID = LongWord;
{
@abstract(Function used to calculate master identification number which is
used in TStoredChannelsValuesList.)@br
This number is used in searching and sorting algorithms and is calculated from
channel ID, Index and ValueType.@br
At the moment, it is calculated by the formula:@br
@longcode( MasterID := (ID xor Index) xor not ValueType; )
@param ID Channel ID.
@param Index Channel index.
@param ValueType Channel ValueType.
@returns Master identification number.
}
Function GetMasterID(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): TMasterID; register;
type
{
@abstract(Structure used to store channel @noAutoLink(value) obtained form
API.)
@member(Name @NoAutoLink(Name) of the channel.)
@member(ID Identifier of the channel.)
@member(Index @NoAutoLink(Index) of channels @NoAutoLink(value).)
@member(Value Actual @NoAutoLink(value) of the channel.)
}
TStoredChannel = record
Name: TelemetryString;
ID: TChannelID;
Index: scs_u32_t;
Value: scs_value_localized_t;
end;
// Pointer to TStoredChannel structure.
PStoredChannel = ^TStoredChannel;
{
@abstract(Structure used as item in TStoredChannelsValuesList.)
This structure is used to store channels @noAutoLink(values) obtained from API
calls in an list sorted by items master ID.
@member(MasterID Identifier of stored channel @NoAutoLink(value).)
@member(StoredChannel Stored channel with its value.)
}
TStoredChannelMasterID = record
MasterID: TMasterID;
StoredChannel: TStoredChannel;
end;
// Pointer to TStoredChannelSorted structure.
PStoredChannelMasterID = ^TStoredChannelMasterID;
{==============================================================================}
{ TStoredChannelsValuesList // Class declaration }
{==============================================================================}
{
@abstract(List used to store channels values obtained from API calls.)
Items in this list are sorted by their master ID.
@member(GetStoredChannelValue
Getter for StoredChannelValues[] property.@br
When index falls out of allowed boundary (<0,Count - 1>), an exception is
raised.
@param Index Index of requested item.
@returns Requested item.)
@member(GetInsertIndex
This function is used to get position at which should the new item with
given master ID be put in order for the list to stay sorted.
@param MasterID Master ID of added item.
@returns Position at which newly added item should be inserted.)
@member(Clear
Deletes all items in the list.@br
OnChange event is called after items deletion.)
@member(StoreChannelValue
Method used to store new value for already present channel. If such channel
is not yet stored in the list, it is added as new item. Function can, in
extreme cases, return -1 (when the channel is not already stored and
addition fails for some reason).@br
OnChange event is called after successful addition or value change.
@param Name Name of requested channel.
@param ID ID of requested channel.
@param Index Index of requested channel.
@param Value Value of the channel.
@returns Index of requested channel, -1 on failure.)
@member(StoredChannelValues
Array property mapped directly to internal list. Use it to obtain values of
individual stored items.)
}
TStoredChannelsValuesList = class(TCustomTelemetryList)
private
Function GetStoredChannelValue(Index: Integer): TStoredChannel;
protected
Function GetInsertIndex(MasterID: TMasterID): Integer; virtual;
public
procedure Clear; override;
{
Searches through list for stored channel with appropriate master index.
When matching config is not found, -1 is returned.
@param MasterID Master ID of requested channel.
@returns Index of requested channel, -1 when not found.
}
Function IndexOf(MasterID: TMasterID): Integer; overload; virtual;
{
Searches through list for stored channel with appropriate ID, index and
value type. When the context is not found, -1 is returned.
@param ID ID of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
{
Searches through list for stored channel with appropriate name, index and
value type. When the context is not found, -1 is returned.
@param Name Name of the requested channel.
@param Index Index of the requested channel.
@param ValueType Type of value of the requested channel.
@returns Index of context with requested channel, -1 when not found.
}
Function IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer; overload; virtual;
Function StoreChannelValue(const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t): Integer; virtual;
property StoredChannelValues[Index: Integer]: TStoredChannel read GetStoredChannelValue; default;
end;
{==============================================================================}
{ Unit Functions and procedures // Declaration }
{==============================================================================}
{
@abstract(Function intended as callback for streaming functions, converting
channel name to ID.)
@code(UserData) passed to streaming function along with this callback must
contain valid TKnownChannelsList object.
@param Name Channel name to be converted to ID.
@param(KnownChannels TKnownChannelsList object that will be used for actual
conversion.)
@returns Channel ID obtained from passed name.
}
Function GetChannelIDFromName(const Name: TelemetryString; KnownChannels: Pointer): TChannelID;
{
@abstract(Function intended as callback for streaming functions, converting
channel ID to name.)
@code(UserData) passed to streaming function along with this callback must
contain valid TKnownChannelsList object.
@param ID Channel ID to be converted to name.
@param(KnownChannels TKnownChannelsList object that will be used for actual
conversion.)
@returns Channel name obtained from passed ID.
}
Function GetChannelNameFromID(ID: TChannelID; KnownChannels: Pointer): TelemetryString;
{
@abstract(Function intended as callback for streaming functions, converting
config name to ID.)
@code(UserData) passed to streaming function along with this callback must
contain valid TKnownConfigsList object.
@param Name Config name to be converted to ID.
@param(KnownChannels TKnownConfigsList object that will be used for actual
conversion.)
@returns Config ID obtained from passed name.
}
Function GetConfigIDFromName(const Name: TelemetryString; KnownConfigs: Pointer): TConfigID;
{
@abstract(Function intended as callback for streaming functions, converting
ID to config name.)
@code(UserData) passed to streaming function along with this callback must
contain valid TKnownConfigsList object.
@param ID Config ID to be converted to name.
@param(KnownChannels TKnownConfigsList object that will be used for actual
conversion.)
@returns Config name obtained from passed ID.
}
Function GetConfigNameFromID(ID: TConfigID; KnownConfigs: Pointer): TelemetryString;
implementation
uses
SysUtils,
TelemetryConversions, TelemetryStrings;
{==============================================================================}
{ Unit Functions and procedures // Implementation }
{==============================================================================}
Function GetMasterID(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): TMasterID; register;
{$IFDEF PurePascal}
begin
Result := (ID xor Index) xor not ValueType;
end;
{$ELSE}
asm
{******************************************************************************}
{ Register Content }
{ EAX ID, Result }
{ EDX Index }
{ ECX ValueType }
{ }
{ Registers used in routine: }
{ EAX (contains result), ECX, EDX }
{******************************************************************************}
XOR EAX, ECX
NOT EDX
XOR EAX, EDX
end;
{$ENDIF}
//------------------------------------------------------------------------------
Function GetChannelIDFromName(const Name: TelemetryString; KnownChannels: Pointer): TChannelID;
begin
Result := TKnownChannelsList(KnownChannels).ChannelNameToID(Name);
end;
//------------------------------------------------------------------------------
Function GetChannelNameFromID(ID: TChannelID; KnownChannels: Pointer): TelemetryString;
begin
Result := TKnownChannelsList(KnownChannels).ChannelIDToName(ID);
end;
//------------------------------------------------------------------------------
Function GetConfigIDFromName(const Name: TelemetryString; KnownConfigs: Pointer): TConfigID;
begin
Result := TKnownConfigsList(KnownConfigs).ConfigNameToID(Name);
end;
//------------------------------------------------------------------------------
Function GetConfigNameFromID(ID: TConfigID; KnownConfigs: Pointer): TelemetryString;
begin
Result := TKnownConfigsList(KnownConfigs).ConfigIDToName(ID);
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TCustomTelemetryList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TCustomTelemetryList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TCustomTelemetryList // Private methods }
{------------------------------------------------------------------------------}
Function TCustomTelemetryList.GetCount: Integer;
begin
Result := fMainList.Count;
end;
{------------------------------------------------------------------------------}
{ TCustomTelemetryList // Protected methods }
{------------------------------------------------------------------------------}
Function TCustomTelemetryList.PtrGetItem(Index: Integer): Pointer;
begin
If (Index >= 0) and (Index < fMainList.Count) then
Result := fMainList[Index]
else
raise Exception.Create('TCustomTelemetryList.PtrGetItem(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TCustomTelemetryList.PtrIndexOf(Item: Pointer): Integer;
begin
Result := fMainList.IndexOf(Item);
end;
//------------------------------------------------------------------------------
Function TCustomTelemetryList.PtrAdd(Item: Pointer): Integer;
begin
Result := -1;
If Assigned(Item) then Result := fMainList.Add(Item);
If Result >= 0 then DoChange;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.PtrReplace(Index: Integer; Item: Pointer);
begin
If (Index >= 0) and (Index < fMainList.Count) then
begin
fMainList[Index] := Item;
DoChange;
end
else
raise Exception.Create('TCustomTelemetryList.PtrReplace(Index,Item): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.PtrInsert(Index: Integer; Item: Pointer);
begin
If (Index >= 0) and (Index <= fMainList.Count) then
begin
fMainList.Insert(Index,Item);
DoChange;
end
else
raise Exception.Create('TCustomTelemetryList.PtrInsert(Index,Item): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TCustomTelemetryList.PtrRemove(Item: Pointer): Integer;
begin
Result := fMainList.Remove(Item);
If Result >= 0 then DoChange;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.PtrDelete(Index: Integer);
begin
If (Index >= 0) and (Index < fMainList.Count) then
begin
fMainList.Delete(Index);
DoChange;
end
else
raise Exception.Create('TCustomTelemetryList.PtrDelete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TCustomTelemetryList // Public methods }
{------------------------------------------------------------------------------}
constructor TCustomTelemetryList.Create;
begin
inherited;
fMainList := TList.Create;
fUpdating := False;
{$IFDEF MulticastEvents}
fOnChangeMulti := TMulticastNotifyEvent.Create(Self);
{$ENDIF}
end;
//------------------------------------------------------------------------------
destructor TCustomTelemetryList.Destroy;
begin
// Prevent OnChange event call.
BeginUpdate;
{$IFDEF MulticastEvents}
fOnChangeMulti.Free;
{$ENDIF}
Clear;
fMainList.Free;
inherited;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.BeginUpdate;
begin
fUpdating := True;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.EndUpdate;
begin
fUpdating := False;
DoChange;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.DoChange;
begin
If not fUpdating then
begin
If Assigned(fOnChange) then fOnChange(Self);
{$IFDEF MulticastEvents}
fOnChangeMulti.Call(Self);
{$ENDIF}
end;
end;
//------------------------------------------------------------------------------
procedure TCustomTelemetryList.Clear;
begin
fMainList.Clear;
DoChange;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownEventsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TKnownEventsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownEventsList // Private methods }
{------------------------------------------------------------------------------}
Function TKnownEventsList.GetKnownEventPointer(Index: Integer): PKnownEvent;
begin
If (Index >= 0) and (Index < Count) then
Result := PKnownEvent(PtrGetItem(Index))
else
raise Exception.Create('TKnownEventsList.GetKnownEventPointer(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.GetKnownEvent(Index: Integer): TKnownEvent;
begin
If (Index >= 0) and (Index < Count) then
Result := GetKnownEventPointer(Index)^
else
raise Exception.Create('TKnownEventsList.GetKnownEvent(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TKnownEventsList // Public methods }
{------------------------------------------------------------------------------}
procedure TKnownEventsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PKnownEvent(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.IndexOf(Event: scs_event_t): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If PKnownEvent(PtrGetItem(i))^.Event = Event then
begin
Result := i;
Break;
end;
end;
Function TKnownEventsList.IndexOf(const Name: TelemetryString): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameTextNoConv(PKnownEvent(PtrGetItem(i))^.Name,Name) then
{$ELSE}
If TelemetrySameText(PKnownEvent(PtrGetItem(i))^.Name,Name) then
{$ENDIF}
begin
Result := i;
Break;
end;
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.Add(Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer;
var
NewEvent: PKnownEvent;
begin
New(NewEvent);
NewEvent^.Event := Event;
NewEvent^.Name := Name;
NewEvent^.Valid := Valid;
NewEvent^.Utility := Utility;
Result := PtrAdd(NewEvent);
If Result < 0 then Dispose(NewEvent);
end;
//------------------------------------------------------------------------------
procedure TKnownEventsList.ReplaceIndex(Index: Integer; Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False);
var
KnownEvent: PKnownEvent;
begin
If (Index >= 0) and (Index < Count) then
begin
KnownEvent := PKnownEvent(PtrGetItem(Index));
KnownEvent^.Event := Event;
KnownEvent^.Name := Name;
KnownEvent^.Valid := Valid;
KnownEvent^.Utility := Utility;
PtrReplace(Index,KnownEvent);
end
else
raise Exception.Create('TKnownEventsList.ReplaceIndex(Index,...): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.Replace(OldEvent, Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer;
begin
Result := IndexOf(OldEvent);
If Result >= 0 then ReplaceIndex(Result,Event,Name,Valid,Utility);
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.Insert(Index: Integer; Event: scs_event_t; const Name: TelemetryString; Valid: Boolean = True; Utility: Boolean = False): Integer;
var
NewEvent: PKnownEvent;
begin
If (Index < 0) or (Index >= Count) then
Result := Add(Event,Name,Valid,Utility)
else
begin
New(NewEvent);
NewEvent^.Event := Event;
NewEvent^.Name := Name;
NewEvent^.Valid := Valid;
NewEvent^.Utility := Utility;
Result := Index;
PtrInsert(Index,NewEvent);
end;
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.Remove(Event: scs_event_t): Integer;
begin
Result := IndexOf(Event);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TKnownEventsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PKnownEvent(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TKnownEventsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.IsValid(Event: scs_event_t): Boolean;
var
Index: Integer;
begin
Result := False;
Index := IndexOf(Event);
If Index >= 0 then
Result := PKnownEvent(PtrGetItem(Index))^.Valid;
end;
//------------------------------------------------------------------------------
Function TKnownEventsList.IsUtility(Event: scs_event_t): Boolean;
var
Index: Integer;
begin
Result := False;
Index := IndexOf(Event);
If Index >= 0 then
Result := PKnownEvent(PtrGetItem(Index))^.Utility;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownChannelsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TKnownChannelsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownChannelsList // Private methods }
{------------------------------------------------------------------------------}
Function TKnownChannelsList.GetKnownChannelPointer(Index: Integer): PKnownChannel;
begin
If (Index >= 0) and (Index < Count) then
Result := PKnownChannel(PtrGetItem(Index))
else
raise Exception.Create('TKnownChannelsList.GetKnownChannelPointer(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.GetKnownChannel(Index: Integer): TKnownChannel;
begin
If (Index >= 0) and (Index < Count) then
Result := GetKnownChannelPointer(Index)^
else
raise Exception.Create('TKnownChannelsList.GetKnownChannel(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TKnownChannelsList // Public methods }
{------------------------------------------------------------------------------}
procedure TKnownChannelsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PKnownChannel(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.IndexOf(const Name: TelemetryString): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(PKnownChannel(PtrGetItem(i))^.Name,Name) then
{$ELSE}
If TelemetrySameStr(PKnownChanneli(PtrGetItem(i))^.Name,Name) then
{$ENDIF}
begin
Result := i;
Break;
end;
end;
Function TKnownChannelsList.IndexOf(ID: TChannelID): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If PKnownChannel(PtrGetItem(i))^.ID = ID then
begin
Result := i;
Break;
end;
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.Add(const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer;
var
NewChannel: PKnownChannel;
begin
New(NewChannel);
NewChannel^.Name := Name;
NewChannel^.ID := ChannelNameToID(Name);
NewChannel^.PrimaryType := PrimaryType;
NewChannel^.SecondaryType := SecondaryType;
NewChannel^.TertiaryType := TertiaryType;
NewChannel^.Indexed := Indexed;
NewChannel^.IndexConfig := IndexConfig;
NewChannel^.IndexConfigID := GetItemID(IndexConfig);
NewChannel^.MaxIndex := MaxIndex;
Result := PtrAdd(NewChannel);
If Result < 0 then Dispose(NewChannel);
end;
//------------------------------------------------------------------------------
procedure TKnownChannelsList.ReplaceIndex(Index: Integer; const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL);
var
KnownChannel: PKnownChannel;
begin
If (Index >= 0) and (Index < Count) then
begin
KnownChannel := PKnownChannel(PtrGetItem(Index));
KnownChannel^.Name := Name;
KnownChannel^.ID := ChannelNameToID(Name);
KnownChannel^.PrimaryType := PrimaryType;
KnownChannel^.SecondaryType := SecondaryType;
KnownChannel^.TertiaryType := TertiaryType;
KnownChannel^.Indexed := Indexed;
KnownChannel^.IndexConfig := IndexConfig;
KnownChannel^.IndexConfigID := GetItemID(IndexConfig);
KnownChannel^.MaxIndex := MaxIndex;
PtrReplace(Index,KnownChannel);
end
else
raise Exception.Create('TKnownChannelsList.ReplaceIndex(Index,...): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.Replace(const OldChannel, Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer;
begin
Result := IndexOf(OldChannel);
If Result >= 0 then
ReplaceIndex(Result,Name,PrimaryType,SecondaryType,TertiaryType,Indexed,Indexconfig,MaxIndex);
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.Insert(Index: Integer; const Name: TelemetryString; PrimaryType, SecondaryType, TertiaryType: scs_value_type_t; Indexed: Boolean; const IndexConfig: TelemetryString = ''; MaxIndex: scs_u32_t = SCS_U32_NIL): Integer;
var
NewChannel: PKnownChannel;
begin
If (Index < 0) or (Index >= Count) then
Result := Add(Name,PrimaryType,SecondaryType,TertiaryType,Indexed,Indexconfig,MaxIndex)
else
begin
New(NewChannel);
NewChannel^.Name := Name;
NewChannel^.ID := ChannelNameToID(Name);
NewChannel^.PrimaryType := PrimaryType;
NewChannel^.SecondaryType := SecondaryType;
NewChannel^.TertiaryType := TertiaryType;
NewChannel^.Indexed := Indexed;
NewChannel^.IndexConfig := IndexConfig;
NewChannel^.IndexConfigID := GetItemID(IndexConfig);
NewChannel^.MaxIndex := MaxIndex;
Result := Index;
PtrInsert(Index,NewChannel);
end;
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.Remove(const Name: TelemetryString): Integer;
begin
Result := IndexOf(Name);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TKnownChannelsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PKnownChannel(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TKnownChannelsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.ChannelIndexConfigID(const Name: TelemetryString): TItemID;
var
Index: Integer;
begin
Result := 0;
Index := IndexOf(Name);
If Index >= 0 then Result := PKnownChannel(PtrGetItem(Index))^.IndexConfigID;
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.ChannelNameToID(const Name: TelemetryString): TChannelID;
begin
Result := GetItemID(Name);
end;
//------------------------------------------------------------------------------
Function TKnownChannelsList.ChannelIDToName(ID: TChannelID): TelemetryString;
var
Index: Integer;
begin
Index := IndexOf(ID);
If Index >= 0 then Result := PKnownChannel(PtrGetItem(Index))^.Name
else Result := '';
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownConfigsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TKnownConfigsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TKnownConfigsList // Private methods }
{------------------------------------------------------------------------------}
Function TKnownConfigsList.GetKnownConfigPointer(Index: Integer): PKnownConfig;
begin
If (Index >= 0) and (Index < Count) then
Result := PKnownConfig(PtrGetItem(Index))
else
raise Exception.Create('TKnownConfigsList.GetKnownConfigPointer(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.GetKnownConfig(Index: Integer): TKnownConfig;
begin
If (Index >= 0) and (Index < Count) then
Result := GetKnownConfigPointer(Index)^
else
raise Exception.Create('TKnownConfigsList.GetKnownConfig(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TKnownConfigsList // Public methods }
{------------------------------------------------------------------------------}
procedure TKnownConfigsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PKnownConfig(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.IndexOf(const Name: TelemetryString): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(PKnownConfig(PtrGetItem(i))^.Name,Name) then
{$ELSE}
If TelemetrySameStr(PKnownConfig(PtrGetItem(i))^.Name,Name) then
{$ENDIF}
begin
Result := i;
Break;
end;
end;
Function TKnownConfigsList.IndexOf(ID: TConfigID): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If PKnownConfig(PtrGetItem(i))^.ID = ID then
begin
Result := i;
Break;
end;
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.Add(const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer;
var
NewConfig: PKnownConfig;
begin
New(NewConfig);
NewConfig^.Name := Name;
NewConfig^.ID := GetItemId(Name);
NewConfig^.ValueType := ValueType;
NewConfig^.Indexed := Indexed;
NewConfig^.Binded := Binded;
Result := PtrAdd(NewConfig);
If Result < 0 then Dispose(NewConfig);
end;
//------------------------------------------------------------------------------
procedure TKnownConfigsList.ReplaceIndex(Index: Integer; const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False);
var
KnownConfig: PKnownConfig;
begin
If (Index >= 0) and (Index < Count) then
begin
KnownConfig := PKnownConfig(PtrGetItem(Index));
KnownConfig^.Name := Name;
KnownConfig^.ID := GetItemId(Name);
KnownConfig^.ValueType := ValueType;
KnownConfig^.Indexed := Indexed;
KnownConfig^.Binded := Binded;
PtrReplace(Index,KnownConfig);
end
else
raise Exception.Create('TKnownConfigsList.ReplaceIndex(Index,...): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.Replace(const OldConfig, Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer;
begin
Result := IndexOf(OldConfig);
If Result >= 0 then
ReplaceIndex(Result,Name,ValueType,Indexed,Binded);
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.Insert(Index: Integer; const Name: TelemetryString; ValueType: scs_value_type_t; Indexed: Boolean; Binded: Boolean = False): Integer;
var
NewConfig: PKnownConfig;
begin
If (Index < 0) or (Index >= Count) then
Result := Add(Name,ValueType,Indexed,Binded)
else
begin
New(NewConfig);
NewConfig^.Name := Name;
NewConfig^.ID := GetItemId(Name);
NewConfig^.ValueType := ValueType;
NewConfig^.Indexed := Indexed;
NewConfig^.Binded := Binded;
Result := Index;
PtrInsert(Index,NewConfig);
end;
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.Remove(const Name: TelemetryString): Integer;
begin
Result := IndexOf(Name);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TKnownConfigsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PKnownConfig(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TKnownConfigsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.IsBinded(const Name: TelemetryString): Boolean;
var
Index: Integer;
begin
Result := False;
Index := IndexOf(Name);
If Index >= 0 then Result := PKnownConfig(PtrGetItem(Index))^.Binded;
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.IsIndexed(const Name: TelemetryString): Boolean;
var
Index: Integer;
begin
Result := False;
Index := IndexOf(Name);
If Index >= 0 then Result := PKnownConfig(PtrGetItem(Index))^.Indexed;
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.ConfigNameToID(const Name: TelemetryString): TConfigID;
begin
Result := GetItemID(Name);
end;
//------------------------------------------------------------------------------
Function TKnownConfigsList.ConfigIDToName(ID: TConfigID): TelemetryString;
var
Index: Integer;
begin
Index := IndexOf(ID);
If Index >= 0 then Result := PKnownConfig(PtrGetItem(Index))^.Name
else Result := '';
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredEventsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TRegisteredEventsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredEventsList // Private methods }
{------------------------------------------------------------------------------}
Function TRegisteredEventsList.GetEventContext(Index: Integer): PEventContext;
begin
If (Index >= 0) and (Index < Count) then
Result := PEventContext(PtrGetItem(Index))
else
raise Exception.Create('TRegisteredEventsList.GetEventContext(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TRegisteredEventsList.GetEventInfo(Index: Integer): TEventInfo;
begin
If (Index >= 0) and (Index < Count) then
Result := GetEventContext(Index)^.EventInfo
else
raise Exception.Create('TRegisteredEventsList.GetEventInfo(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TRegisteredEventsList // Public methods }
{------------------------------------------------------------------------------}
procedure TRegisteredEventsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PEventContext(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TRegisteredEventsList.IndexOf(Event: scs_event_t): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If PEventContext(PtrGetItem(i))^.EventInfo.Event = Event then
begin
Result := i;
Break;
end;
end;
Function TRegisteredEventsList.IndexOf(EventContext: PEventContext): Integer;
begin
Result := PtrIndexOf(EventContext);
end;
//------------------------------------------------------------------------------
Function TRegisteredEventsList.Add(EventContext: PEventContext): Integer;
begin
If Assigned(EventContext) then Result := PtrAdd(EventContext)
else
raise Exception.Create('TRegisteredEventsList.Add(EventContext): Context must not be nil.');
end;
Function TRegisteredEventsList.Add(Recipient: TObject; Event: scs_event_t; Utility: Boolean = False): Integer;
var
NewEvent: PEventContext;
begin
NewEvent := CreateContext(Recipient,Event,Utility);
Result := Add(NewEvent);
If Result < 0 then FreeContext(NewEvent);
end;
Function TRegisteredEventsList.Add(Event: scs_event_t; Utility: Boolean = False): Integer;
begin
Result := Add(nil,Event,Utility);
end;
//------------------------------------------------------------------------------
Function TRegisteredEventsList.Remove(Event: scs_event_t): Integer;
begin
Result := IndexOf(Event);
If Result >= 0 then Delete(Result);
end;
Function TRegisteredEventsList.Remove(EventContext: PEventContext): Integer;
begin
Result := IndexOf(EventContext);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TRegisteredEventsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PEventContext(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TRegisteredEventsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TRegisteredEventsList.CreateContext(Recipient: TObject; Event: scs_event_t; Utility: Boolean = False): PEventContext;
begin
New(Result);
Result^.Recipient := Recipient;
Result^.EventInfo.Event := Event;
Result^.EventInfo.Utility := Utility;
end;
//------------------------------------------------------------------------------
procedure TRegisteredEventsList.FreeContext(var EventContext: PEventContext);
begin
Dispose(EventContext);
EventContext := nil;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredChannelsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TRegisteredChannelsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TRegisteredChannelsList // Private methods }
{------------------------------------------------------------------------------}
Function TRegisteredChannelsList.GetChannelContext(Index: Integer): PChannelContext;
begin
If (Index >= 0) and (Index < Count) then
Result := PChannelContext(PtrGetItem(Index))
else
raise Exception.Create('TRegisteredChannelsList.GetChannelContext(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TRegisteredChannelsList.GetChannelInfo(Index: Integer): TChannelInfo;
begin
If (Index >= 0) and (Index < Count) then
Result := GetChannelContext(Index)^.ChannelInfo
else
raise Exception.Create('TRegisteredChannelsList.GetChannelInfo(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TRegisteredChannelsList // Public methods }
{------------------------------------------------------------------------------}
procedure TRegisteredChannelsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PChannelContext(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TRegisteredChannelsList.IndexOf(const Name: TelemetryString): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(PChannelContext(PtrGetItem(i))^.ChannelInfo.Name,Name) then
{$ELSE}
If TelemetrySameStr(PChannelContext(PtrGetItem(i))^.ChannelInfo.Name,Name) then
{$ENDIF}
begin
Result := i;
Break;
end;
end;
Function TRegisteredChannelsList.IndexOf(ID: TChannelID): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If (PChannelContext(PtrGetItem(i))^.ChannelInfo.ID = ID) then
begin
Result := i;
Break;
end;
end;
Function TRegisteredChannelsList.IndexOf(const Name: TelemetryString; Index: scs_u32_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(TempItem^.ChannelInfo.Name,Name)
{$ELSE}
If TelemetrySameStr(TempItem^.ChannelInfo.Name,Name)
{$ENDIF}
and (TempItem^.ChannelInfo.Index = Index) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(ID: TChannelID; Index: scs_u32_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
If (TempItem^.ChannelInfo.ID = ID) and (TempItem^.ChannelInfo.Index = Index) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(TempItem^.ChannelInfo.Name,Name)
{$ELSE}
If TelemetrySameStr(TempItem^.ChannelInfo.Name,Name)
{$ENDIF}
and (TempItem^.ChannelInfo.Index = Index) and (TempItem^.ChannelInfo.ValueType = ValueType) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
If (TempItem^.ChannelInfo.ID = ID) and (TempItem^.ChannelInfo.Index = Index) and
(TempItem^.ChannelInfo.ValueType = ValueType) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(TempItem^.ChannelInfo.Name,Name)
{$ELSE}
If TelemetrySameStr(TempItem^.ChannelInfo.Name,Name)
{$ENDIF}
and (TempItem^.ChannelInfo.Index = Index) and (TempItem^.ChannelInfo.ValueType = ValueType)
and (TempItem^.ChannelInfo.Flags = Flags) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t): Integer;
var
i: Integer;
TempItem: PChannelContext;
begin
Result := -1;
For i := 0 to (Count - 1) do
begin
TempItem := PChannelContext(PtrGetItem(i));
If (TempItem^.ChannelInfo.ID = ID) and (TempItem^.ChannelInfo.Index = Index) and
(TempItem^.ChannelInfo.ValueType = ValueType) and (TempItem^.ChannelInfo.Flags = Flags) then
begin
Result := i;
Break;
end;
end;
end;
Function TRegisteredChannelsList.IndexOf(ChannelContext: PChannelContext): Integer;
begin
Result := PtrIndexOf(ChannelContext);
end;
//------------------------------------------------------------------------------
Function TRegisteredChannelsList.Add(ChannelContext: PChannelContext): Integer;
begin
If Assigned(ChannelContext) then Result := PtrAdd(ChannelContext)
else
raise Exception.Create('TRegisteredChannelsList.Add(ChannelContext): Context must not be nil.');
end;
Function TRegisteredChannelsList.Add(Recipient: TObject; const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): Integer;
var
NewChannel: PChannelContext;
begin
NewChannel := CreateContext(Recipient,Name,Index,ValueType,Flags,IndexConfigID);
Result := Add(NewChannel);
If Result < 0 then FreeContext(NewChannel);
end;
Function TRegisteredChannelsList.Add(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): Integer;
begin
Result := Add(nil,Name,Index,ValueType,Flags,IndexConfigID);
end;
//------------------------------------------------------------------------------
Function TRegisteredChannelsList.Remove(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
begin
Result := IndexOf(Name,Index,ValueType);
If Result >= 0 then Delete(Result);
end;
Function TRegisteredChannelsList.Remove(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
begin
Result := IndexOf(ID,Index,ValueType);
If Result >= 0 then Delete(Result);
end;
Function TRegisteredChannelsList.Remove(ChannelContext: PChannelContext): Integer;
begin
Result := IndexOf(ChannelContext);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TRegisteredChannelsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PChannelContext(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TRegisteredChannelsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TRegisteredChannelsList.CreateContext(Recipient: TObject; const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none; IndexConfigID: TItemID = 0): PChannelContext;
begin
New(Result);
Result^.Recipient := Recipient;
Result^.ChannelInfo.Name := Name;
Result^.ChannelInfo.ID := GetItemID(Name);
Result^.ChannelInfo.Index := Index;
Result^.ChannelInfo.ValueType := ValueType;
Result^.ChannelInfo.Flags := Flags;
Result^.ChannelInfo.IndexConfigID := IndexConfigID;
end;
//------------------------------------------------------------------------------
procedure TRegisteredChannelsList.FreeContext(var ChannelContext: PChannelContext);
begin
Dispose(ChannelContext);
ChannelContext := nil;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredConfigsList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TStoredConfigsList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredConfigsList // Private methods }
{------------------------------------------------------------------------------}
Function TStoredConfigsList.GetStoredConfigPointer(Index: Integer): PStoredConfig;
begin
If (Index >= 0) and (Index < Count) then
Result := PStoredConfig(PtrGetItem(Index))
else
raise Exception.Create('TStoredConfigsList.GetStoredConfigPointer(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TStoredConfigsList.GetStoredConfig(Index: Integer): TStoredConfig;
begin
If (Index >= 0) and (Index < Count) then
Result := GetStoredConfigPointer(Index)^
else
raise Exception.Create('TStoredConfigsList.GetStoredConfig(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TStoredConfigsList // Public methods }
{------------------------------------------------------------------------------}
procedure TStoredConfigsList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PStoredConfig(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TStoredConfigsList.IndexOf(const Name: TelemetryString): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(PStoredConfig(PtrGetItem(i))^.Name,Name) then
{$ELSE}
If TelemetrySameStr(PStoredConfig(PtrGetItem(i))^.Name,Name) then
{$ENDIF}
begin
Result := i;
Break;
end;
end;
Function TStoredConfigsList.IndexOf(ID: TConfigID): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If (PStoredConfig(PtrGetItem(i))^.ID = ID) then
begin
Result := i;
Break;
end;
end;
Function TStoredConfigsList.IndexOf(const Name: TelemetryString; Index: scs_u32_t): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(PStoredConfig(PtrGetItem(i))^.Name,Name)
{$ELSE}
If TelemetrySameStr(PStoredConfig(PtrGetItem(i))^.Name,Name)
{$ENDIF}
and (PStoredConfig(PtrGetItem(i))^.Index = Index) then
begin
Result := i;
Break;
end;
end;
Function TStoredConfigsList.IndexOf(ID: TConfigID; Index: scs_u32_t): Integer;
var
i: Integer;
begin
Result := -1;
For i := 0 to (Count - 1) do
If (PStoredConfig(PtrGetItem(i))^.ID = ID) and
(PStoredConfig(PtrGetItem(i))^.Index = Index) then
begin
Result := i;
Break;
end;
end;
//------------------------------------------------------------------------------
Function TStoredConfigsList.Add(const Name: TelemetryString; Index: scs_u32_t; Value: scs_value_localized_t; Binded: Boolean = False): Integer;
var
NewConfig: PStoredConfig;
begin
New(NewConfig);
NewConfig^.Name := Name;
NewConfig^.ID := GetItemID(Name);
NewConfig^.Index := Index;
NewConfig^.Value := Value;
NewConfig^.Binded := Binded;
Result := PtrAdd(NewConfig);
If Result < 0 then Dispose(NewConfig);
end;
Function TStoredConfigsList.Add(const Name: TelemetryString; Index: scs_u32_t; Value: p_scs_value_t; Binded: Boolean = False): Integer;
var
EmptyValue: scs_value_localized_t;
begin
EmptyValue.ValueType := SCS_VALUE_TYPE_INVALID;
If Assigned(Value) then Result := Add(Name,Index,scs_value_localized(Value^),Binded)
else Result := Add(Name,Index,EmptyValue,Binded);
end;
//------------------------------------------------------------------------------
Function TStoredConfigsList.Remove(const Name: TelemetryString; Index: scs_u32_t = SCS_U32_NIL): Integer;
begin
Result := IndexOf(Name,Index);
If Result >= 0 then Delete(Result);
end;
Function TStoredConfigsList.Remove(ID: TChannelID; Index: scs_u32_t = SCS_U32_NIL): Integer;
begin
Result := IndexOf(ID,Index);
If Result >= 0 then Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TStoredConfigsList.Delete(Index: Integer);
begin
If (Index >= 0) and (Index < Count) then
begin
Dispose(PStoredConfig(PtrGetItem(Index)));
PtrDelete(Index);
end
else
raise Exception.Create('TStoredConfigsList.Delete(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
//------------------------------------------------------------------------------
Function TStoredConfigsList.ChangeConfigValue(const Name: TelemetryString; Index: scs_u32_t; Value: scs_value_localized_t): Integer;
begin
Result := IndexOf(Name,Index);
If Result >= 0 then
begin
PStoredConfig(PtrGetItem(Result))^.Value := Value;
DoChange;
end;
end;
Function TStoredConfigsList.ChangeConfigValue(ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t): Integer;
begin
Result := IndexOf(ID,Index);
If Result >= 0 then
begin
PStoredConfig(PtrGetItem(Result))^.Value := Value;
DoChange;
end;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredChannelsValuesList }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TStoredChannelsValuesList // Implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TStoredChannelsValuesList // Private methods }
{------------------------------------------------------------------------------}
Function TStoredChannelsValuesList.GetStoredChannelValue(Index: Integer): TStoredChannel;
begin
If (Index >= 0) and (Index < Count) then
Result := PStoredChannelMasterID(PtrGetItem(Index))^.StoredChannel
else
raise Exception.Create('TStoredChannelsValuesList.GetStoredChannelValue(Index): Index (' +
IntToStr(Index) + ') out of bounds.');
end;
{------------------------------------------------------------------------------}
{ TStoredChannelsValuesList // Protected methods }
{------------------------------------------------------------------------------}
Function TStoredChannelsValuesList.GetInsertIndex(MasterID: TMasterID): Integer;
var
Index: Integer;
MinIndex: Integer;
MaxIndex: Integer;
begin
Result := -1;
If Count > 0 then
begin
Index := -1;
MinIndex := 0;
MaxIndex := Count - 1;
while MaxIndex >= MinIndex do
begin
Index := ((MaxIndex - MinIndex) shr 1) + MinIndex;
If PStoredChannelMasterID(PtrGetItem(Index))^.MasterID < MasterID then MinIndex := Index + 1
else If PStoredChannelMasterID(PtrGetItem(Index))^.MasterID > MasterID then MaxIndex := Index - 1;
end;
If Index >= 0 then
If PStoredChannelMasterID(PtrGetItem(Index))^.MasterID > MasterID then Result := Index
else Result := Index + 1;
end;
end;
{------------------------------------------------------------------------------}
{ TStoredChannelsValuesList // Public methods }
{------------------------------------------------------------------------------}
procedure TStoredChannelsValuesList.Clear;
var
i: Integer;
begin
For i := (Count - 1) downto 0 do
Dispose(PStoredChannelMasterID(PtrGetItem(i)));
inherited;
end;
//------------------------------------------------------------------------------
Function TStoredChannelsValuesList.IndexOf(MasterID: TMasterID): Integer;
var
Index: Integer;
MinIndex: Integer;
MaxIndex: Integer;
begin
Result := -1;
MinIndex := 0;
MaxIndex := Count - 1;
while MaxIndex >= MinIndex do
begin
Index := ((MaxIndex - MinIndex) shr 1) + MinIndex;
If PStoredChannelMasterID(PtrGetItem(Index))^.MasterID < MasterID then MinIndex := Index + 1
else If PStoredChannelMasterID(PtrGetItem(Index))^.MasterID > MasterID then MaxIndex := Index - 1
else
begin
Result := Index;
Break;
end;
end;
end;
Function TStoredChannelsValuesList.IndexOf(ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
begin
Result := IndexOf(GetMasterID(ID,Index,ValueType));
end;
Function TStoredChannelsValuesList.IndexOf(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Integer;
begin
Result := IndexOf(GetItemID(Name),Index,ValueType);
end;
//------------------------------------------------------------------------------
Function TStoredChannelsValuesList.StoreChannelValue(const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t): Integer;
var
MasterID: TMasterID;
StoredChannel: PStoredChannelMasterID;
begin
Result := -1;
If Assigned(Value) then
begin
MasterID := GetMasterID(ID,Index,Value^._type);
Result := IndexOf(MasterID);
If Result >= 0 then
begin
StoredChannel := PStoredChannelMasterID(PtrGetItem(Result));
StoredChannel^.MasterID := MasterID;
StoredChannel^.StoredChannel.Name := Name;
StoredChannel^.StoredChannel.ID := ID;
StoredChannel^.StoredChannel.Index := Index;
StoredChannel^.StoredChannel.Value := scs_value_localized(Value^);
DoChange;
end
else
begin
New(StoredChannel);
StoredChannel^.MasterID := MasterID;
StoredChannel^.StoredChannel.Name := Name;
StoredChannel^.StoredChannel.ID := ID;
StoredChannel^.StoredChannel.Index := Index;
StoredChannel^.StoredChannel.Value := scs_value_localized(Value^);
Result := GetInsertIndex(MasterID);
If Result >= 0 then
PtrInsert(Result,StoredChannel)
else
Result := PtrAdd(StoredChannel);
If Result < 0 then Dispose(StoredChannel);
end;
end;
end;
end.
|
unit ADC.UCMAEvents;
interface
uses
ActiveX, windows, ComObj, SysUtils;
type
IUCMAEvents = interface(IDispatch)
['{7F0A6F02-8FA2-46DB-A444-6962635218D5}']
procedure OnClientSignIn; safecall;
procedure OnClientSignOut; safecall;
procedure OnClientDisconnected; safecall;
procedure OnSettingChanged; safecall;
procedure OnContactInformationChanged; safecall;
procedure OnUriChanged(const oldURI: WideString; const newURI: WideString); safecall;
end;
type
TUCMAEventClientSignIn = procedure(Sender: TObject) of object;
TUCMAEventClientSignOut = procedure(Sender: TObject) of object;
TUCMAEventClientDisconnected = procedure(Sender: TObject) of object;
TUCMAEventSettingChanged = procedure(Sender: TObject) of object;
TUCMAEventContactInformationChanged = procedure(Sender: TObject) of object;
TUCMAEventUriChanged = procedure(Sender: TObject; oldURI, newURI: WideString) of object;
type
TUCMAEventSink = class(TInterfacedObject, IUnknown, IDispatch)
private
FConnection: Integer;
FIID: TGUID;
FOnClientSignIn: TUCMAEventClientSignIn;
FOnClientSignOut: TUCMAEventClientSignOut;
FOnClientDisconnected: TUCMAEventClientDisconnected;
FOnSettingChanged: TUCMAEventSettingChanged;
FOnContactInformationChanged: TUCMAEventContactInformationChanged;
FOnUriChanged: TUCMAEventUriChanged;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
protected
FSource: IUnknown;
procedure DoClientSignIn; stdcall;
procedure DoClientSignOut; stdcall;
procedure DoClientDisconnected; stdcall;
procedure DoSettingChanged; stdcall;
procedure DoContactInformationChanged; stdcall;
procedure DoUriChanged(const oldURI, newURI: string); stdcall;
public
constructor Create;
procedure Connect(Source: IUnknown);
procedure Disconnect;
property OnClientSignIn: TUCMAEventClientSignIn read FOnClientSignIn write FOnClientSignIn;
property OnClientSignOut: TUCMAEventClientSignOut read FOnClientSignOut write FOnClientSignOut;
property OnClientDisconnected: TUCMAEventClientDisconnected read FOnClientDisconnected write FOnClientDisconnected;
property OnSettingChanged: TUCMAEventSettingChanged read FOnSettingChanged write FOnSettingChanged;
property OnContactInformationChanged: TUCMAEventContactInformationChanged read FOnContactInformationChanged write FOnContactInformationChanged;
property OnUriChanged: TUCMAEventUriChanged read FOnUriChanged write FOnUriChanged;
end;
implementation
{ TUCMAEventSink }
procedure TUCMAEventSink.Connect(Source: IInterface);
begin
Assert(Source <> nil);
Disconnect;
try
InterfaceConnect(Source, FIID, Self, FConnection);
FSource := Source;
except
raise Exception.Create (Format ('Unable to connect %s.'#13'%s',
['UCMA Application', Exception(ExceptObject).Message]
));
end;
end;
constructor TUCMAEventSink.Create;
begin
FIID := IUCMAEvents;
inherited Create;
end;
procedure TUCMAEventSink.Disconnect;
begin
if (FSource = nil)
then Exit;
try
InterfaceDisconnect(FSource, FIID, FConnection);
FSource := nil;
except
Pointer(FSource) := nil;
end;
end;
procedure TUCMAEventSink.DoClientDisconnected;
begin
if Assigned(OnClientDisconnected )
then OnClientDisconnected(Self);
end;
procedure TUCMAEventSink.DoClientSignIn;
begin
if Assigned(OnClientSignIn)
then OnClientSignIn(Self);
end;
procedure TUCMAEventSink.DoClientSignOut;
begin
if Assigned(OnClientSignOut)
then OnClientSignOut(Self);
end;
procedure TUCMAEventSink.DoContactInformationChanged;
begin
if Assigned(OnContactInformationChanged)
then OnContactInformationChanged(Self);
end;
procedure TUCMAEventSink.DoSettingChanged;
begin
if Assigned(OnSettingChanged)
then OnSettingChanged(Self);
end;
procedure TUCMAEventSink.DoUriChanged(const oldURI, newURI: string);
begin
if Assigned(OnUriChanged)
then OnUriChanged(Self, oldURI, newURI);
end;
function TUCMAEventSink.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
Result := E_NOTIMPL;
end;
function TUCMAEventSink.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HResult;
begin
Pointer(TypeInfo) := nil;
Result := E_NOTIMPL;
end;
function TUCMAEventSink.GetTypeInfoCount(out Count: Integer): HResult;
begin
Count := 0;
Result := E_NOTIMPL;
end;
function TUCMAEventSink.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
begin
{ Params: PDispParams }
{ VarResult: Variant }
{ ExcepInfo: TExcepInfo }
{ ArgErr: DWORD }
Result := DISP_E_MEMBERNOTFOUND;
case DispID of
1000: begin
DoClientSignIn;
Result:= S_OK;
end;
1001: begin
DoClientSignOut;
Result:= S_OK;
end;
1002: begin
DoClientDisconnected;
Result:= S_OK;
end;
1003: begin
DoSettingChanged;
Result:= S_OK;
end;
1004: begin
DoContactInformationChanged;
Result:= S_OK;
end;
1005: begin
{ The arguments are passed in the array rgvarg[ ], with the number of }
{ arguments passed in cArgs. The arguments in the array should be placed }
{ from last to first, so rgvarg[0] has the last argument and }
{ rgvarg[cArgs -1] has the first argument. }
{ https://msdn.microsoft.com/en-us/library/windows/desktop/ms221653(v=vs.85).aspx }
DoUriChanged(
TDispParams(Params).rgvarg^[1].bstrval,
TDispParams(Params).rgvarg^[0].bstrval
);
Result:= S_OK;
end;
end;
end;
function TUCMAEventSink.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result:= S_OK
else if IsEqualIID(IID, FIID) then
Result:= QueryInterface(IDispatch, Obj)
else
Result:= E_NOINTERFACE;
end;
function TUCMAEventSink._AddRef: Integer;
begin
Result := 2;
end;
function TUCMAEventSink._Release: Integer;
begin
Result := 1;
end;
end.
|
unit GeneralFunctions;
interface
uses
Winapi.Windows,
vcl.dialogs,
Winapi.Messages,
System.SysUtils,
System.Win.Crtl,
System.Classes,
System.SyncObjs,
System.TypInfo,
FilterAPI,
GlobalConfig;
function FilterAPIMessageCallback(pSendMessage: PMESSAGE_SEND_DATA; pReplyMessage: PMESSAGE_REPLY_DATA): Bool; stdcall;
procedure FilterAPIDisconnectCallback(); stdcall;
function DriverManagement(Install: Boolean = False): String;
function DisplayFilterMessage(pSendMessage: PMESSAGE_SEND_DATA): Bool;
//function FormatIOName(pSendMessage: PMESSAGE_SEND_DATA): String;
function StartFilterService(MsgCallback: TMessageCallback; GlobalConfig:TGlobalConfig): String;
function StopService(): String;
const
fnHasNoPrefix = 0;
fnUNCPrefix = 1;
fnNonUNCPrefix = 2;
UNCPrefix = '\\?\UNC';
NonUNCPrefix = '\\?\';
var
DLLFilterAPIHandle: NativeInt = 0;
DriverInstalled: Boolean = False;
ResultMsgCallback: TMessageCallback;
ListOfOpenFileIDs: TStringList;
Lock_OpenFileIDsList: TCriticalSection;
CloseAppInProgress: Boolean;
implementation
{
function FormatIOName(pSendMessage: PMESSAGE_SEND_DATA): String;
var
ioType: TEVENT_TYPE;
messageType: ULONG;
begin
Result := 'UnKnown IO Type:' + UIntToStr(pSendMessage.MessageType);
messageType := pSendMessage.MessageType;
if (messageType = ULONG(FILTER_SEND_FILE_CHANGED_EVENT)) then
begin
for ioType := Low(TEVENT_TYPE) to High(TEVENT_TYPE) do
if( messageType And ULONG(ioType) > 0) then Result := Result + Ord(ioType)) + ';';
end
else
begin
if ((messageType = ULONG(PRE_QUERY_INFORMATION)) and pSendMessage.FsContext = nil )
then Result := 'PRE_FASTIO_NETWORK_QUERY_OPEN'
else
if ((messageType = ULONG(POST_QUERY_INFORMATION)) and pSendMessage.FsContext = nil)
then Result := 'POST_FASTIO_NETWORK_QUERY_OPEN'
else Result := GetEnumName(TypeInfo(FilterAPI.MessageType),messageType);
end;
end;
}
function DisplayFilterMessage(pSendMessage: PMESSAGE_SEND_DATA): Bool;
var
userName: Array [0 .. 55] of char;
domainName: Array [0 .. 55] of char;
userNameSize: ULONG;
domainNameSize: ULONG;
snu: SID_NAME_USE;
ret: Boolean;
DataString: String;
FileName: String;
User: String;
Domain: String;
FileInfoStr: String;
ErrMsg: PChar;
ErrMsgLen: ULONG;
ioName: String;
begin
Result := False;
if CloseAppInProgress then
exit;
Result := False;
userNameSize := MAX_PATH;
domainNameSize := MAX_PATH;
try
ret := LookupAccountSid(nil, @pSendMessage.Sid, @userName, userNameSize, @domainName, domainNameSize, snu);
SetLength(User, userNameSize);
Move(userName[0], User[1], userNameSize * SizeOf(char));
SetLength(Domain, domainNameSize);
Move(domainName[0], Domain[1], domainNameSize * SizeOf(char));
SetLength(DataString, pSendMessage.DataBufferLength div 2);
Move(pSendMessage.DataBuffer[0], DataString[1], pSendMessage.DataBufferLength);
SetLength(FileName, pSendMessage.FileNameLength div 2);
Move(pSendMessage.FileName[0], FileName[1], pSendMessage.FileNameLength);
//ioName := FormatIOName( pSendMessage);
FileInfoStr := format('ioType:%x - FILE: %s - DOMAIN: %s - USER: %s' +
' - PROCESSID: %d - THREADID: %d - FileSize: %d' +
' - ATTRIB: %d - ACCESS: %d' +
' - DISP: %d - SHARE: %d' +
' - CREATEOPTIONS: %d - CREATESTATUS: %d' +
' - IOStatus: %x',// +
[pSendMessage.MessageType,
ExtractFileName(FileName),
Domain, User, pSendMessage.ProcessId,
pSendMessage.ThreadId, pSendMessage.FileSize,
pSendMessage.FileAttributes,
pSendMessage.DesiredAccess,
pSendMessage.Disposition,
pSendMessage.ShareAccess,
pSendMessage.CreateOptions,
pSendMessage.CreateStatus,
pSendMessage.Status]);
ResultMsgCallback(FileInfoStr);
except
end;
end;
function FilterAPIMessageCallback(pSendMessage: PMESSAGE_SEND_DATA; pReplyMessage: PMESSAGE_REPLY_DATA): Bool;
begin
Result := False;
if CloseAppInProgress then
exit;
DisplayFilterMessage(pSendMessage);
if( pReplyMessage <> nil) then
begin
//for control filter, you can deny the pre-IO access as below.
//pReplyMessage.ReturnStatus := ULONG(STATUS_ACCESS_DENIED);
//pReplyMessage.FilterStatus = ULONG(FILTER_COMPLETE_PRE_OPERATION);
//by default allow the IO access as below:
pReplyMessage.ReturnStatus := ULONG(STATUS_SUCCESS);
end;
Result := True;
end;
procedure FilterAPIDisconnectCallback();
begin
//ShowMessage('FilterAPIDisconnectCallback');
end;
function StartFilterService(MsgCallback: TMessageCallback; GlobalConfig:TGlobalConfig): String;
var
ErrMsg: String;
RetVal: ULONG;
ret: Boolean;
PIDValue: ULONG;
AppName: String;
FileCount: ULONG;
AppPID: ULONG;
begin
ResultMsgCallback := MsgCallback;
ErrMsg := DriverManagement(TRUE);
if (Pos('FILTERAPI', UpperCase(ErrMsg)) > 0) then
begin
Result := ErrMsg;
exit;
end;
//Purchase a license key with the link: http://www.easefilter.com/Order.htm
//Email us to request a trial key: info@easefilter.com //free email is not accepted.
RetVal := SetRegistrationKey('BA110-3DD98-88593-C186E-C3F3F-68096');
if (not IsDriverServiceRunning) then
begin
ret := UnInstallDriver = 1;
if (not ret) then
begin
Result := 'UnInstallDriver Failed' + GetLastFilterAPIErrorMsg;
//exit;
end
else
Result := 'UnInstall filter driver succeeded!';
ret := InstallDriver = 1;
if (not ret) then
begin
Result := 'InstallDriver Failed' + GetLastFilterAPIErrorMsg;
exit;
end;
Result := 'Install filter driver succeeded!';
end;
if RetVal <> 1 then
begin
Result := 'SetRegistrationKey Failed' + GetLastFilterAPIErrorMsg;
exit;
end
else
begin
Result := 'SetRegistrationKey - Passed';
ret := RegisterMessageCallback(GlobalConfig.ThreadCount, @FilterAPIMessageCallback, @FilterAPIDisconnectCallback);
if not ret then
Result := 'RegisterMessageCallback Failed' + GetLastFilterAPIErrorMsg;
end;
GlobalConfig.SendConfigSettingsToFilter(MsgCallback);
end;
function StopService(): String;
var
ErrMsg: String;
begin
Result := '';
if (DLLFilterAPIHandle > 0) then
begin
try
Disconnect();
Result := 'Filter Service Stoped!';
except
end;
end;
end;
function DriverManagement(Install: Boolean = False): String;
var
fName: String;
ErrMsg: String;
RetVal: Integer;
begin
Result := '';
if (DLLFilterAPIHandle > 0) then
begin
if (Not Install) then
begin
// -----------------
if DriverInstalled then
begin
if DLLFilterAPIHandle > 0 then
try
FreeLibrary(DLLFilterAPIHandle);
finally
DLLFilterAPIHandle := 0;
Result := 'FilterAPI Unloaded';
end;
try
if UnInstallDriver = 0 then
Result := 'Uninstalled Driver!';
DriverInstalled := False;
except
end;
end;
end;
exit;
end;
fName := 'FilterAPI.dll';
// -----------------
RetVal := LoadFilterAPI(fName, DLLFilterAPIHandle, ErrMsg);
if Length(ErrMsg) > 0 then
begin
Result := 'Failed To Load DLL: ' + ErrMsg + ' (' + fName + ')';
exit;
end
else
begin
Result := 'Success - Loading DLL (' + fName + ')';
end;
if (Not DriverInstalled) and Install then
begin
// -----------------
if InstallDriver < 2 then
begin
DriverInstalled := TRUE;
Result := 'Driver Installed ' + GetLastFilterAPIErrorMsg;
end
else
Result := 'InstallDriver Return Value' + GetLastFilterAPIErrorMsg;
end
else if (Not Install) then
begin
// -----------------
// if DriverInstalled then
begin
if UnInstallDriver = 0 then
Result := 'Uninstalled Driver!';
DriverInstalled := False;
end;
if DLLFilterAPIHandle > 0 then
begin
FreeLibrary(DLLFilterAPIHandle);
DLLFilterAPIHandle := 0;
Result := 'FilterAPI Unloaded';
end;
end;
end;
Initialization
ListOfOpenFileIDs := TStringList.Create;
Lock_OpenFileIDsList := TCriticalSection.Create;
Finalization
ListOfOpenFileIDs.Free;
Lock_OpenFileIDsList.Free;
end.
|
PROGRAM Stat(INPUT, OUTPUT);
CONST
NegOne = -1;
NegTwo = -2;
VAR
Overflow, InvalidData: BOOLEAN;
Average, Num, NumMax, NumMin, Counter: INTEGER;
PROCEDURE ReadDigit(VAR InF: TEXT; VAR D: INTEGER);
VAR
Ch: CHAR;
BEGIN {ReadDigit}
D := NegOne;
IF NOT(EOLN(InF))
THEN
BEGIN
READ(InF, Ch);
IF (Ch = '0') THEN D := 0 ELSE
IF (Ch = '1') THEN D := 1 ELSE
IF (Ch = '2') THEN D := 2 ELSE
IF (Ch = '3') THEN D := 3 ELSE
IF (Ch = '4') THEN D := 4 ELSE
IF (Ch = '5') THEN D := 5 ELSE
IF (Ch = '6') THEN D := 6 ELSE
IF (Ch = '7') THEN D := 7 ELSE
IF (Ch = '8') THEN D := 8 ELSE
IF (Ch = '9') THEN D := 9 ELSE
IF (Ch = ' ') THEN D := NegTwo
END
END; {ReadDigit}
PROCEDURE ReadNumber(VAR InF: TEXT; VAR N: INTEGER);
VAR
D: INTEGER;
BEGIN {ReadNumber}
N := 0;
D := 0;
WHILE (NOT(EOLN(InF))) AND (D <> NegOne) AND (D <> NegTwo) AND (N <> NegOne)
DO
BEGIN
ReadDigit(InF, D);
IF (D <> NegOne) AND (D <> NegTwo)
THEN
IF ((N * 10) + D) <= MAXINT
THEN
N := N * 10 + D
ELSE
N := NegOne
ELSE
IF D <> NegTwo
THEN
N := NegTwo
END
END; {ReadNumber}
BEGIN {Stat}
Num := 0;
NumMax := NegOne;
NumMin := NegOne;
Counter := 0;
Average := 0;
Overflow := FALSE;
InvalidData := FALSE;
WHILE (NOT(EOLN(INPUT))) AND NOT(Overflow) AND NOT(InvalidData) AND (Num <> NegTwo)
DO
BEGIN
ReadNumber(INPUT, Num);
IF (Num <> NegOne) AND (Num <> NegTwo) AND ((MAXINT - Average) >= Num)
THEN
BEGIN
Counter := Counter + 1;
Average := Average + Num;
IF (NumMax <= Num) OR (NumMax = NegOne)
THEN
NumMax := Num;
IF (NumMin >= Num) OR (NumMin = NegOne)
THEN
NumMin := Num
END
ELSE
IF (Num = NegTwo)
THEN
InvalidData := TRUE
ELSE
Overflow := TRUE
END;
IF (Counter <> 0) AND NOT(Overflow) AND NOT(InvalidData)
THEN
BEGIN
WRITELN(OUTPUT, 'Maximum number = ', NumMax);
WRITELN(OUTPUT, 'Minimum number = ', NumMin);
WRITELN(OUTPUT, 'Average score = ', Average DIV Counter, '.', (Average MOD Counter) * 100 DIV Counter)
END
ELSE
IF Overflow
THEN
WRITELN(OUTPUT, 'Overflow')
ELSE
WRITELN(OUTPUT, 'Invalid data')
END. {Stat}
|
unit WPCTRStyleScroller;
{ -----------------------------------------------------------------------------
Copyright (C) 2002-2015 by wpcubed GmbH - Author: Julian Ziersch
info: http://www.wptools.de mailto:support@wptools.de
__ __ ___ _____ _ _____
/ / /\ \ \/ _ \/__ \___ ___ | |___ |___ |
\ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / /
\ /\ / ___/ / / | (_) | (_) | \__ \ / /
\/ \/\/ \/ \___/ \___/|_|___/ /_/
*****************************************************************************
WPCTRMemo - WPTools 7 main editor control
-----------------------------------------------------------------------------
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------- }
{$I WPINC.INC}
interface
uses {$IFDEF DELPHIXE}WinAPI.Windows, WinAPI.Messages, Vcl.Themes,
{$ELSE} Windows, Messages, {$ENDIF}
Graphics, Forms, Menus, StdCtrls, Dialogs, ExtCtrls, Controls, SysUtils,
Classes, WPRTEDefs, WPRTEEdit, WPRTEPaint, WPRTEDefsConsts, WPRTEPlatform,
WPCTRMemo;
{$I WPMSG.INC}
type
{:: The component TWPStyleScroller has been designed to scroll horizontal or vertical.
For other configurations please don't change the property ScrollDirection and
change the public (but not published) properties EditOptions, Scrollbars, AutoZoom, Zooming and LayoutMode }
TWPScrollerDirection = (wpScrollHorizontal, wpScrollVertical);
{:: This is a scrollable viewer for paragraph styles.<br>
To let this component view and change the styles in an editor, this editor and the style scroller must use the
same TWPRTFProps component. It must be assigned to property WPRTFPropsComponent.<br>
To attached an editor to the style scroller it is possible to use the property EditBox. This editor will
be updated, when the uder clicks on one of the styles.<br>
<b>Alternatively</b>, esspecially to attach multiple editors, create a TActionList and inside of it a
TWPToolsCustomEditContolAction. As AttachedControl specify the scroller and attach the action list to the
TWPRichText using the property ActionList. Now it is possible to also show the currently active style
automatically.
<br>
<br>
<b>Note:</b><br>
This class inherits from the TWPCustomRtfEdit class which is also
used to build an editor for text. This makes this class very powerfull, yet the
implementation very small. The implementation is a good example for the development of
a specialized paged viewer and to highlight the power of the WPTools' concept. }
TWPStyleScroller = class(TWPCustomRtfEdit)
private
FCurrStyleName, FAspect: String;
FEditbox, FRTFEdit: TWPCustomRtfEdit;
FScrollDirection: TWPScrollerDirection;
FHasDefaultItem: Boolean;
function GetShaded: Boolean;
procedure SetShaded(x: Boolean);
procedure SetHasDefaultItem(x: Boolean);
protected
procedure SetCurrStyleName(x: String); virtual;
procedure SetScrollDirection(x: TWPScrollerDirection); virtual;
procedure SetAspect(x: String);
procedure DoClickEvent(PageNo, x, Y: Integer; var Ignore: Boolean);
override;
procedure DoMeasureTextPage(Sender: TObject;
PageInfo: TWPMeasurePageParam); override;
procedure DoPaintWatermarkEvent(Sender: TObject;
RTFEngine: TWPRTFEnginePaint; toCanvas: TCanvas; PageRect: TRect;
PaintPageNr, RTFPageNr: Integer; WaterMarkRef: TObject;
XRes, YRes: Integer; CurrentZoom: Single;
PaintMode: TWPPaintModes); override;
procedure SetWPRTFPropsComponent(X: TWPRTFProps); override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure WMWPTOOLSUPDATE(var Message: TMessage); message WM_WPTOOLSUPDATE;
procedure WPRTFEDITCHANGED(var Message: TMessage);
message WP_RTFEDIT_CHANGED;
procedure DoGetPageIsSelected(Sender: TObject; PageNr: Integer;
var IsSelected: Boolean);
public
constructor Create(aOwner: TComponent); Override;
procedure UpdateStyleList; virtual;
{:: This is a reference to the style which is currently active }
function CurrentStyle : TWPTextStyle;
published
{:: This is the name of the style which is currently selected }
property CurrStyleName: String read FCurrStyleName write SetCurrStyleName;
{:: This is the attached editor. It is better to use a TWPToolsCustomEditControlAction linked to
this control, since then the scroller is automatically synchronized }
property Editbox: TWPCustomRtfEdit read FEditbox write FEditbox;
{:: This propertzy must be set to the TWPRTFProps instance which is also sued be the TWPRichText. }
property WPRTFPropsComponent;
{:: The scroller supports horizontal and vertical scrolling }
property ScrollDirection: TWPScrollerDirection read FScrollDirection
write SetScrollDirection default wpScrollHorizontal;
{:: This is the aspect, w / h of the pages which show the styles }
property Aspect: String read FAspect write SetAspect;
{:: "Shaded" changes the design of the scroller }
property Shaded: Boolean read GetShaded write SetShaded default true;
{:: If this property is true, the firtst item can to delete the style selection }
property HasDefaultItem: Boolean read FHasDefaultItem
write SetHasDefaultItem default true;
property ColorDesktop;
property ColorDesktopTo;
property PaperColor;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnClick;
property OnClickPage;
property OnMeasureTextPage;
// ------------ Standard Properties ----------------------------
property Anchors;
property Align;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnPaint;
property Constraints;
end;
implementation
const
MarginsTwips = 200;
PageWidthTwips = 2000;
procedure TWPStyleScroller.DoClickEvent(PageNo, x, Y: Integer;
var Ignore: Boolean);
var
par: TParagraph;
s: String;
begin
inherited DoClickEvent(PageNo, X, Y, Ignore);
if not Ignore then
begin
par := Memo.PaintPageStartPar[PageNo];
if (par <> nil) then
begin
s := par.ABaseStyleName;
CurrStyleName := s;
if FEditbox <> nil then
FEditbox.ActiveStyleName := s
else if FRTFEdit <> nil then
FRTFEdit.ActiveStyleName := s;
end;
Ignore := true;
end;
end;
procedure TWPStyleScroller.DoMeasureTextPage(Sender: TObject;
PageInfo: TWPMeasurePageParam);
begin
inherited;
if FHasDefaultItem and not PageInfo.changed and (PageInfo.PageNr = 1) then
begin
PageInfo.WidthTW := PageInfo.HeightTW; // square
PageInfo.changed := true;
end;
end;
procedure TWPStyleScroller.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if (FEditbox <> nil) and (AComponent = WPRTFPropsComponent) then
Clear;
end;
inherited Notification(AComponent, Operation);
if (Operation = opRemove) then
begin
if (FEditbox <> nil) and (AComponent = FEditbox) then
FEditbox := nil;
end;
end;
procedure TWPStyleScroller.SetWPRTFPropsComponent(X: TWPRTFProps);
begin
inherited SetWPRTFPropsComponent(x);
UpdateStyleList;
end;
procedure TWPStyleScroller.WMWPTOOLSUPDATE(var Message: TMessage);
begin
if Message.WParam = WPUPD_STYLESHEET then
UpdateStyleList
else if Message.WParam = WPUPD_STYLESHEET_DEF then
ReformatAll(true, true)
else
inherited WMWPTOOLSUPDATE(Message);
end;
procedure TWPStyleScroller.WPRTFEDITCHANGED(var Message: TMessage);
begin
if Message.LParam = 0 then
FRTFEdit := nil
else
begin
FRTFEdit := TObject(Message.LParam) as TWPCustomRtfEdit;
if FRTFEdit.ParStyles.Count <> PageCount then
UpdateStyleList;
if FRTFEdit.ActiveStyleName <> FCurrStyleName then
CurrStyleName := FRTFEdit.ActiveStyleName;
end;
end;
procedure TWPStyleScroller.SetCurrStyleName(x: String);
begin
if FCurrStyleName <> x then
begin
FCurrStyleName := x;
Repaint;
end;
end;
function TWPStyleScroller.CurrentStyle : TWPTextStyle;
begin
if (FCurrStyleName='') or (WPRTFPropsComponent=nil) then Result := nil else
Result := WPRTFPropsComponent.ParStyles.FindTextStyle(FCurrStyleName);
end;
function TWPStyleScroller.GetShaded: Boolean;
begin
Result := wpPaintPageShade in ViewOptionsEx;
end;
procedure TWPStyleScroller.SetShaded(x: Boolean);
begin
if x then
begin
ViewOptionsEx := ViewOptionsEx + [wpPaintPageShade];
XBetween := 160;
YBetween := 160;
XOffset := 80;
YOffset := 20;
end
else
begin
ViewOptionsEx := ViewOptionsEx - [wpPaintPageShade];
XBetween := 80;
YBetween := 80;
XOffset := 80;
YOffset := 20;
end;
end;
procedure TWPStyleScroller.SetHasDefaultItem(x: Boolean);
begin
if x <> FHasDefaultItem then
begin
FHasDefaultItem := x;
UpdateStyleList;
end;
end;
procedure TWPStyleScroller.SetAspect(x: String);
var
d: Single;
begin
if (x <> '') and (FAspect <> x) then
begin
d := WPStrToFloat(x);
if d > 0 then
begin
Header.PageWidth := PageWidthTwips;
Header.PageHeight := Round(PageWidthTwips * d);
ReformatAll(false, true);
end;
FAspect := x;
end;
end;
constructor TWPStyleScroller.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
LayoutMode := wplayFullLayout;
FHasDefaultItem := true;
AutoZoom := wpAutoZoomHorizontalTiles;
ScrollBars := {$IFDEF DELPHIXE3}System.UITypes.TScrollStyle.{$ENDIF}ssHorizontal;
FScrollDirection := wpScrollHorizontal;
Header.SetPageWH(PageWidthTwips, Round(PageWidthTwips * 0.33), MarginsTwips,
MarginsTwips, MarginsTwips, MarginsTwips);
Aspect := '0.33';
FormatOptions := [wpfAlwaysFormatWithScreenRes];
FormatOptionsEx2 := FormatOptionsEx2 + [wpfIgnoreSoftPagebreaks];
EditOptions := [wpNoVertScrolling];
EditOptionsEx := [wpDontClearStylesInNew, wpDisableSelection, wpDisableCaret,
wpDisableGetFocus];
EditOptionsEx2 := EditOptionsEx2 + [wpShowPageHoverframe];
ViewOptions := [wpDontDisplayScrollPageHint, wpDontPaintPageFrame];
ViewOptionsEx := ViewOptionsEx + [wpDontClearPageBackground,
wpPaintPageShade];
XBetween := 160;
YBetween := 160;
XOffset := 80;
YOffset := 20;
Width := 200;
Height := 50;
Memo.OnGetPageIsSelected := DoGetPageIsSelected;
end;
procedure TWPStyleScroller.SetScrollDirection(x: TWPScrollerDirection);
begin
// if FScrollDirection<>x then - no, we want to use this to restet the properties
FScrollDirection := x;
if FScrollDirection = wpScrollHorizontal then
begin
EditOptions := [wpNoVertScrolling];
AutoZoom := wpAutoZoomHorizontalTiles;
ViewOptions := ViewOptions - [wpCenterPaintPages];
ReformatAll(false, true);
ScrollBars := {$IFDEF DELPHIXE3}System.UITypes.TScrollStyle.{$ENDIF}ssHorizontal;
end
else
begin
EditOptions := [wpNoHorzScrolling];
AutoZoom := wpAutoZoomFullPage;
ViewOptions := ViewOptions + [wpCenterPaintPages];
ReformatAll(false, true);
ScrollBars := {$IFDEF DELPHIXE3}System.UITypes.TScrollStyle.{$ENDIF}ssVertical;
end;
end;
procedure TWPStyleScroller.UpdateStyleList;
var
i: Integer;
d: Single;
begin
ClearEx(true, true, true);
d := WPStrToFloat(FAspect);
Header.SetPageWH(PageWidthTwips, Round(PageWidthTwips * d), MarginsTwips,
MarginsTwips, MarginsTwips, MarginsTwips);
CheckActiveText(true);
WritingAttr.SetFontName('Tahoma');
if FHasDefaultItem then
ActiveText.AppendNewPar;
for i := 0 to ParStyles.Count - 1 do
begin
with ActiveText.AppendNewPar do
begin
SetText(ParStyles[i].Name);
ABaseStyleName := ParStyles[i].Name;
if FHasDefaultItem or (i > 0) then
IncludeProp(paprNewPage);
end;
if ParStyles[i].Description <> '' then
with ActiveText.AppendNewPar do
begin
SetText(ParStyles[i].Description);
ASet(WPAT_CharFontSize, 600);
end;
end;
ReformatAll(true, true);
end;
procedure TWPStyleScroller.DoGetPageIsSelected(Sender: TObject; PageNr: Integer;
var IsSelected: Boolean);
var
par: TParagraph;
begin
par := Memo.PaintPageStartPar[PageNr];
IsSelected := (par <> nil) and (par.ABaseStyleName = CurrStyleName);
end;
procedure TWPStyleScroller.DoPaintWatermarkEvent(Sender: TObject;
RTFEngine: TWPRTFEnginePaint; toCanvas: TCanvas; PageRect: TRect;
PaintPageNr, RTFPageNr: Integer; WaterMarkRef: TObject; XRes, YRes: Integer;
CurrentZoom: Single; PaintMode: TWPPaintModes);
var
IsSelected: Boolean;
begin
IsSelected := false;
DoGetPageIsSelected(nil, PaintPageNr, IsSelected);
inc(PageRect.Right, 2);
// Draw Background
WPDrawShadedBackground(toCanvas.Handle, PageRect, $FAFAFA, $DFDFDF);
// Draw the orange border
if IsSelected then
WPDrawFocusRect(toCanvas.Handle, PageRect, XRes);
// Draw the X on page 0
if FHasDefaultItem and (PaintPageNr = 0) then
begin
InflateRect(PageRect, -XRes div 20, -XRes div 20);
toCanvas.Pen.Width := XRes div 20;
toCanvas.Pen.Color := WPDrawRectWithBitmap_pen;
toCanvas.Pen.Style := psSolid;
toCanvas.Polyline([PageRect.TopLeft, PageRect.BottomRight]);
toCanvas.MoveTo(PageRect.Right, PageRect.Top);
toCanvas.LineTo(PageRect.Left, PageRect.Bottom);
end;
end;
end.
|
unit FileWriter;
interface
procedure initOutFile(outFileExt : string);
procedure closeOutFile;
procedure writeToFile(line : string; indent : integer); (* write and restructure*)
implementation
const
INDENT_STR = ' ';
var
outFile : text;
currentIndent : integer;
procedure addToIndent(indent : integer);
begin
currentIndent := currentIndent + indent;
if(currentIndent < 0) then begin
writeln('Cannot set indent to something smaller than 0');
currentIndent := 0;
end;
end;
procedure initOutFile(outFileExt : string);
begin
currentIndent := 0;
assign(outFile, outFileExt);
rewrite(outFile);
end;
procedure closeOutFile;
begin
close(outFile);
end;
procedure writeToFile(line : string; indent : integer); (* write and restructure*)
var
tIdentStr : string;
i : integer;
begin
i := 0;
tIdentStr := '';
if(indent < 0) then (* BESCHREIB DEN SCHAAS *)
addToIndent(indent);
while(i < currentIndent) do begin
tIdentStr := tIdentStr + INDENT_STR;
inc(i);
end;
writeLn(outFile, tIdentStr, line);
if(indent > 0) then
addToIndent(indent);
end;
begin
end.
|
{ Interface to the SYN symbol table. This table holds the symbols that are
* defined in the syntax definition file being read.
}
module sst_r_syn_sym;
define sst_r_syn_sym_init;
define sst_r_syn_sym_delete;
define sst_r_syn_sym_add;
define sst_r_syn_sym_lookup;
define sst_r_syn_sym_called;
define sst_r_syn_sym_loop_init;
define sst_r_syn_sym_loop_next;
%include 'sst_r_syn.ins.pas';
var
pos: string_hash_pos_t; {table position when looping over entries}
notend: boolean; {not yet hit end of table when looping}
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_INIT
*
* Initialize the symbol table. The memory for the symbol table will be
* subordinate to the memory for the root SST scope.
}
procedure sst_r_syn_sym_init; {create and initialize the SYN symbol table}
val_param;
begin
string_hash_create ( {create hash table for SYN file symbols}
table_sym, {hash table to initialize}
sst_r_syn_nbuck_k, {number of buckets in hash table}
syn_name_maxlen_k, {max length of any entry name}
sizeof(symbol_data_t), {amount of user data per entry}
[string_hashcre_nodel_k], {won't need to deallocate individual entries}
sst_scope_root_p^.mem_p^); {parent memory context for hash table}
end;
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_DELETE
*
* Delete the symbol table and release its resources.
}
procedure sst_r_syn_sym_delete; {delete the symbol table, dealloc resources}
val_param;
begin
string_hash_delete (table_sym);
end;
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_ADD (NAME, DATA_P)
*
* Add the symbol of name NAME to the symbol table. DATA_P is returned
* pointing to the data in the symbol table for the new symbol.
*
* The program is bombed with an appropriate error message if NAME is already
* in the symbol table.
}
procedure sst_r_syn_sym_add ( {add new symbol to table, bomb if already exist}
in name: univ string_var_arg_t; {name of symbol to add, case-insensitive}
out data_p: symbol_data_p_t); {pointer to data for new symbol in the table}
val_param;
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
uname: string_var80_t; {upper case symbol name}
pos: string_hash_pos_t; {position into symbol table}
found: boolean; {name found in symbol table}
name_p: string_var_p_t; {pointer to symbol name in table}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
uname.max := size_char(uname.str); {init local var string}
string_copy (name, uname); {make upper case symbol name in UNAME}
string_upcase (uname);
string_hash_pos_lookup ( {get position handle for this name}
table_sym, {the table to find position in}
uname, {name to get position for}
pos, {returned position for this name}
found); {TRUE iff name already exists}
if found then begin {trying to create duplicate symbol ?}
sys_msg_parm_vstr (msg_parm[1], uname);
syn_msg_pos_bomb (syn_p^, 'sst_syn_read', 'symbol_already_used', msg_parm, 1);
end;
string_hash_ent_add (pos, name_p, data_p); {create new entry, get pointer to data}
data_p^.name_p := name_p; {point to table entry name string}
data_p^.sym_p := nil; {no SST symbol created for this name yet}
data_p^.call_p := nil; {init to this symbol doesn't call any others}
end;
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_LOOKUP (NAME, DATA_P)
*
* Look up the name NAME in the SYN symbol table. DATA_P is returned pointing
* to the data for the symbol in the symbol table.
*
* The program is bombed with an appropriate error message if NAME is not in
* the symbol table.
}
procedure sst_r_syn_sym_lookup ( {look up name in table, bomb if not found}
in name: univ string_var_arg_t; {name of symbol to look up, case-insensitive}
out data_p: symbol_data_p_t); {pointer to symbol data}
val_param;
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
uname: string_var80_t; {upper case symbol name}
name_p: string_var_p_t; {pointer to name string in symbol table}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
uname.max := size_char(uname.str); {init local var string}
string_copy (name, uname); {make upper case symbol name in UNAME}
string_upcase (uname);
string_hash_ent_lookup ( {look up name in the symbol table}
table_sym, {the symbol table to look in}
uname, {name to look up}
name_p, {returned pointer to name string in table}
data_p); {returned pointer to data for this entry}
if data_p = nil then begin {no such entry in the symbol table ?}
sys_msg_parm_vstr (msg_parm[1], uname);
syn_msg_pos_bomb (syn_p^, 'sst_syn_read', 'symbol_not_declared', msg_parm, 1);
end;
end;
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_CALLED (NAME)
*
* Indicate that the syntax construction NAME is called from the current syntax
* parsing function being built. The named symbol is added to the list of
* syntaxes called by the current syntax, if not already in the list.
}
procedure sst_r_syn_sym_called ( {symbol is called from curr syn parsing function}
in name: univ string_var_arg_t); {name of called symbol, case-insensitive}
val_param;
var
data_p: symbol_data_p_t; {pointer to data for the called symbol}
call_p: call_p_t; {points to current called chain entry}
begin
sst_r_syn_sym_lookup (name, data_p); {get pointer to data for the called symbol}
call_p := def_syn_p^.call_p; {init to first entry in caller's list}
while call_p <> nil do begin {scan the list of called syntaxes}
if string_equal ( {called routine is already in the list ?}
call_p^.data_p^.name_p^, data_p^.name_p^)
then return;
call_p := call_p^.next_p; {advance to next called syntax list entry}
end; {back to check this new entry}
{
* The syntax NAME is not already in the list of syntaxes called by the current
* syntax.
}
string_hash_mem_alloc_ndel ( {allocate memory for new called list entry}
table_sym, sizeof(call_p^), call_p);
call_p^.data_p := data_p; {point to data of called syntax}
call_p^.next_p := def_syn_p^.call_p; {link new entry to start of list}
def_syn_p^.call_p := call_p;
end;
{
********************************************************************************
*
* Subroutine SST_R_SYN_SYM_LOOP_INIT
*
* Initialize for looping over all symbol table entries. Only one thread can
* use this looping feature at a time.
}
procedure sst_r_syn_sym_loop_init; {init loop over sym table entries, one thread only}
val_param;
begin
string_hash_pos_first (table_sym, pos, notend);
end;
{
********************************************************************************
*
* Function SST_R_SYN_SYM_LOOP_NEXT (DATA_P)
*
* Get the next table entry in the current loop. Looping must have been
* previously initialized with SST_R_SYN_SYM_LOOP_INIT.
*
* When there is a next entry, DATA_P is returned pointing to the data for that
* entry, and the function returns TRUE. When the end of table is reached,
* DATA_P is returned NIL and the function returns FALSE.
*
* Only one thread can use this looping mechanism at a time.
}
function sst_r_syn_sym_loop_next ( {get next symbol table entry, one thread only}
out data_p: symbol_data_p_t) {pointer to next entry, NIL at end}
:boolean; {returning with entry, not hit end of table}
val_param;
var
name_p: string_var_p_t; {pointer to entry name string in the table}
begin
if not notend then begin {at end of table ?}
data_p := nil;
sst_r_syn_sym_loop_next := false;
return;
end;
string_hash_ent_atpos (pos, name_p, data_p); {get info about this entry}
sst_r_syn_sym_loop_next := true; {indicate returning with an entry}
string_hash_pos_next (pos, notend); {advance saved state to next entry}
end;
|
unit uParamTransicao;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, contnrs;
type
{ TParamTransicao }
TParamTransicao = class(TObject)
private
FInput: string;
FSimboloPilhaCompara: string;
FSimboloPilhaInsere: string;
FDestino: TObject;
public
constructor Create(const pInput: string;
const pSimboloPilhaCompara, pSimboloPilhaInsere: string;
const pDestino: TObject);
destructor destroy;override;
property Imput: string read FInput;
property SimboloPilhaCompara: string read FSimboloPilhaCompara;
property SimboloPilhaInsere: string read FSimboloPilhaInsere;
property Destino: TObject read FDestino;
end;
{ TListaParamTransicao }
TListaParamTransicao = class(TObjectList)
private
function GetItem(const pIndex: integer): TParamTransicao;
procedure SetItem(const pIndex: integer; pValue: TParamTransicao);
public
property Items[Idx: Integer]: TParamTransicao read GetItem write SetItem;
end;
implementation
{ TListaParamTransicao }
function TListaParamTransicao.GetItem(const pIndex: integer): TParamTransicao;
begin
result := TParamTransicao(inherited Items[pIndex]);
end;
procedure TListaParamTransicao.SetItem(const pIndex: integer;
pValue: TParamTransicao);
begin
Items[pIndex] := pValue;
end;
{ TParamTransicao }
constructor TParamTransicao.Create(const pInput: string;
const pSimboloPilhaCompara, pSimboloPilhaInsere: string;
const pDestino: TObject);
begin
FInput := pInput;
FSimboloPilhaCompara := pSimboloPilhaCompara;
FSimboloPilhaInsere := pSimboloPilhaInsere;;
FDestino := pDestino;
end;
destructor TParamTransicao.destroy;
begin
inherited destroy;
end;
end.
|
unit ChargeService;
interface
uses
JunoApi4Delphi.Interfaces, RESTRequest4D, REST.Types, Charge,
System.JSON, REST.Json;
type
TChargeService = class(TInterfacedObject, iChargeService)
private
FParent : iJunoApi4DelphiConig;
FAuth : iAuthorizationService;
FJSONCharge : TJSONObject;
FJSONBilling : TJSONObject;
FJSONMain : TJSONObject;
public
constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
destructor Destroy; override;
class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iChargeService;
function CreateCharge : iChargeService;
function ChargeDescription(Value : String) : iChargeService;
function ChargeReferences(Value : String) : iChargeService;
function ChargeAmount(Value : Double) : iChargeService;
function ChargeDueDate(Value : String) : iChargeService;
function ChargeInstallments(Value : Integer) : iChargeService;
function ChargeMaxOverdueDays(Value : Integer) : iChargeService;
function ChargeFine(Value : Integer) : iChargeService;
function ChargeInterest(Value : String) : iChargeService;
function ChargeDiscountAmount(Value : String) : iChargeService;
function ChargeDiscountDays(Value : Integer) : iChargeService;
function ChargePaymentTypes(Value : String) : iChargeService;
function ChargePaymentAdvance(Value : Boolean) : iChargeService;
function BillingName(Value : String) : iChargeService;
function BillingDocument(Value : String) : iChargeService;
function BillingEmail(Value : String) : iChargeService;
function BillingSecondaryEmail(Value : String) : iChargeService;
function BillingPhone(Value : String) : iChargeService;
function BillingBirthDate(Value : String) : iChargeService;
function BillingNotify(Value : Boolean) : iChargeService;
function &End : String;
function ListCharge : iChargeService; overload;
function GetCharge : String;
function createdOnStart(Value : String) : iChargeService; overload;
function createdOnStart : String;overload;
function createdOnEnd(Value : String) : iChargeService; overload;
function createdOnEnd : String; overload;
function dueDateStart(Value : String) : iChargeService; overload;
function dueDateStart : String; overload;
function paymentDateStart(Value : String) : iChargeService; overload;
function paymentDateStart : String; overload;
function paymentDateEnd(Value : String) : iChargeService; overload;
function paymentDateEnd : String; overload;
function showUnarchived(Value : Boolean) : iChargeService; overload;
function showUnarchived : Boolean; overload;
function showArchived(Value : Boolean) : iChargeService; overload;
function showArchived : Boolean; overload;
function showDue(Value : Boolean) : iChargeService; overload;
function showDue : Boolean; overload;
function showNotDue(Value : Boolean) : iChargeService; overload;
function showNotDue : Boolean; overload;
function showPaid(Value : Boolean) : iChargeService; overload;
function showPaid : Boolean; overload;
function showNotPaid(Value : Boolean) : iChargeService; overload;
function showNotPaid : Boolean; overload;
function showCancelled(Value : Boolean) : iChargeService; overload;
function showCancelled : Boolean; overload;
function showNotCancelled(Value : Boolean) : iChargeService; overload;
function showNotCancelled : Boolean; overload;
function showManualReconciliation(Value : Boolean) : iChargeService; overload;
function showManualReconciliation : Boolean; overload;
function showNotManualReconciliation(Value : Boolean) : iChargeService; overload;
function showNotManualReconciliation : Boolean; overload;
function showNotFailed(Value : Boolean) : iChargeService; overload;
function showNotFailed : Boolean; overload;
function orderBy(Value : String) : iChargeService; overload;
function orderBy : String; overload;
function orderAsc(Value : Boolean) : iChargeService; overload;
function orderAsc : Boolean; overload;
function pageSize(Value : Integer) : iChargeService; overload;
function pageSize : Integer; overload;
function page(Value : Integer) : iChargeService; overload;
function page : Integer; overload;
function firstObjectId(Value : String) : iChargeService; overload;
function firstObjectId : String; overload;
function firstValue(Value : String) : iChargeService; overload;
function firstValue : String; overload;
function lastObjectId(Value : String) : iChargeService; overload;
function lastObjectId : String; overload;
function lastValue(Value : String) : iChargeService; overload;
function lastValue : String; overload;
function &ListEnd : String;
function GetFirstCharge(Value : String) : String;
function CancelCharge(Value : String) : String;
function UpdateSplit(Value : String) : String;
end;
implementation
uses
System.SysUtils;
CONST
CHARGES_ENDPOINT = '/charges';
{ TChargeService }
function TChargeService.BillingBirthDate(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('birthDate', Value);
end;
function TChargeService.BillingDocument(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('document', Value);
end;
function TChargeService.BillingEmail(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('email', Value);
end;
function TChargeService.BillingName(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('name', Value);
end;
function TChargeService.BillingNotify(Value: Boolean): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('notify', TJSONBool.Create(Value));
end;
function TChargeService.BillingPhone(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('phone', Value);
end;
function TChargeService.BillingSecondaryEmail(Value: String): iChargeService;
begin
Result := Self;
FJSONBilling.AddPair('secondaryEmail', Value);
end;
function TChargeService.CancelCharge(Value: String): String;
begin
Result :=
TRequest.New
.BaseURL(FParent.ResourceEndpoint + CHARGES_ENDPOINT +'/'+ Value +'/cancelation')
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER)
.Put.Content;
end;
function TChargeService.ChargeAmount(Value: Double): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('amount',TJSONNumber.Create(Value));
end;
function TChargeService.ChargeDescription(Value: String): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('description',Value);
end;
function TChargeService.ChargeDiscountAmount(Value: String): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('discountAmount',Value);
end;
function TChargeService.ChargeDiscountDays(Value: Integer): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('discountDays',TJSONNumber.Create(Value));
end;
function TChargeService.ChargeDueDate(Value: String): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('dueDate',Value);
end;
function TChargeService.ChargeFine(Value: Integer): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('fine', TJSONNumber.Create(Value));
end;
function TChargeService.ChargeInstallments(Value: Integer): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('installments',TJSONNumber.Create(Value));
end;
function TChargeService.ChargeInterest(Value: String): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('interest',Value);
end;
function TChargeService.ChargeMaxOverdueDays(Value: Integer): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('maxOverdueDays',TJSONNumber.Create(Value));
end;
function TChargeService.ChargePaymentAdvance(Value: Boolean): iChargeService;
begin
Result := Self;
FJSONCharge.AddPair('paymentAdvance',TJSONBool.Create(Value));
end;
function TChargeService.ChargePaymentTypes(Value: String): iChargeService;
var
JSONArray : TJSONArray;
begin
Result := Self;
JSONArray := TJSONArray.Create;
JSONArray.Add(Value);
FJSONCharge.AddPair('paymentTypes',JSONArray);
end;
function TChargeService.ChargeReferences(Value: String): iChargeService;
var
JSONArray : TJSONArray;
begin
Result := Self;
JSONArray := TJSONArray.Create;
JSONArray.Add(Value);
FJSONCharge.AddPair('references',JSONArray);
end;
function TChargeService.&End: String;
begin
FJSONMain.AddPair('charge',FJSONCharge);
FJSONMain.AddPair('billing',FJSONBilling);
Result :=
TRequest.New
.BaseURL(FParent.ResourceEndpoint + CHARGES_ENDPOINT)
.Accept('application/json')
.Token(FAuth.Token)
.AddBody('application/json',ctAPPLICATION_JSON)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER)
.AddParam('body', FJSONMain.ToString, pkREQUESTBODY)
.Post.Content;
end;
function TChargeService.firstObjectId(Value: String): iChargeService;
begin
end;
function TChargeService.firstObjectId: String;
begin
end;
function TChargeService.firstValue: String;
begin
end;
function TChargeService.firstValue(Value: String): iChargeService;
begin
end;
function TChargeService.GetCharge: String;
begin
Result :=
TRequest.New
.BaseURL(FParent.ResourceEndpoint + CHARGES_ENDPOINT)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER)
.Get.Content;
end;
function TChargeService.GetFirstCharge(Value : String) : String;
begin
Result :=
TRequest.New
.BaseURL(FParent.ResourceEndpoint + CHARGES_ENDPOINT +'/'+ Value)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER)
.Get.Content;
end;
function TChargeService.lastObjectId: String;
begin
end;
function TChargeService.lastObjectId(Value: String): iChargeService;
begin
end;
function TChargeService.lastValue(Value: String): iChargeService;
begin
end;
function TChargeService.lastValue: String;
begin
end;
function TChargeService.ListCharge: iChargeService;
begin
end;
function TChargeService.ListEnd: String;
begin
end;
constructor TChargeService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
begin
FParent := Parent;
FAuth := AuthService;
FJSONCharge := TJSONObject.Create;
FJSONBilling := TJSONObject.Create;
FJSONMain := TJSONObject.Create;
end;
function TChargeService.CreateCharge: iChargeService;
begin
Result := Self;
end;
function TChargeService.createdOnEnd(Value: String): iChargeService;
begin
end;
function TChargeService.createdOnEnd: String;
begin
end;
function TChargeService.createdOnStart: String;
begin
end;
function TChargeService.createdOnStart(Value: String): iChargeService;
begin
end;
destructor TChargeService.Destroy;
begin
inherited;
FJSONCharge.DisposeOf;
FJSONBilling.DisposeOf;
end;
function TChargeService.dueDateStart: String;
begin
end;
function TChargeService.dueDateStart(Value: String): iChargeService;
begin
end;
class function TChargeService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iChargeService;
begin
Result := Self.Create(Parent, AuthService);
end;
function TChargeService.orderAsc(Value: Boolean): iChargeService;
begin
end;
function TChargeService.orderAsc: Boolean;
begin
end;
function TChargeService.orderBy: String;
begin
end;
function TChargeService.orderBy(Value: String): iChargeService;
begin
end;
function TChargeService.page: Integer;
begin
end;
function TChargeService.page(Value: Integer): iChargeService;
begin
end;
function TChargeService.pageSize: Integer;
begin
end;
function TChargeService.pageSize(Value: Integer): iChargeService;
begin
end;
function TChargeService.paymentDateEnd(Value: String): iChargeService;
begin
end;
function TChargeService.paymentDateEnd: String;
begin
end;
function TChargeService.paymentDateStart(Value: String): iChargeService;
begin
end;
function TChargeService.paymentDateStart: String;
begin
end;
function TChargeService.showArchived: Boolean;
begin
end;
function TChargeService.showArchived(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showCancelled: Boolean;
begin
end;
function TChargeService.showCancelled(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showDue(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showDue: Boolean;
begin
end;
function TChargeService.showManualReconciliation: Boolean;
begin
end;
function TChargeService.showManualReconciliation(
Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotCancelled(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotCancelled: Boolean;
begin
end;
function TChargeService.showNotDue(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotDue: Boolean;
begin
end;
function TChargeService.showNotFailed(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotFailed: Boolean;
begin
end;
function TChargeService.showNotManualReconciliation: Boolean;
begin
end;
function TChargeService.showNotManualReconciliation(
Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotPaid(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showNotPaid: Boolean;
begin
end;
function TChargeService.showPaid(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showPaid: Boolean;
begin
end;
function TChargeService.showUnarchived(Value: Boolean): iChargeService;
begin
end;
function TChargeService.showUnarchived: Boolean;
begin
end;
function TChargeService.UpdateSplit(Value: String): String;
begin
Result := 'Falta implementar';
end;
end.
|
unit Model.ListagemAssinantesJornal;
interface
uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, Generics.Collections, Controller.PlanilhaListagemJornal,
Model.PlanilhaListagemJornal,FireDAC.Comp.DataSet, Data.DB, System.SysUtils;
type
TListagemAssinantesJornal = class
private
FProduto: String;
FBairro: String;
FCodigo: String;
FCEP: String;
FID: Integer;
FNumero: String;
FAgente: Integer;
FEdicao: TDateTime;
FQuantidade: Integer;
FComplemento: String;
FModalidade: Integer;
FREferencia: String;
FNome: String;
FEndereco: String;
FAcao: TAcao;
FDescricaoModalidade: String;
FConexao : TConexao;
function Insert(): Boolean;
function Update(): Boolean;
function Delete(): Boolean;
function Search(aParam: Array of variant): TFDQuery;
public
property ID: Integer read FID write FID;
property Agente: Integer read FAgente write FAgente;
property Edicao: TDateTime read FEdicao write FEdicao;
property Codigo: String read FCodigo write FCodigo;
property Nome: String read FNome write FNome;
property Endereco: String read FEndereco write FEndereco;
property Numero: String read FNumero write FNumero;
property Complemento: String read FComplemento write FComplemento;
property Bairro: String read FBairro write FBairro;
property CEP: String read FCEP write FCEP;
property Referencia: String read FREferencia write FReferencia;
property Produto: String read FProduto write FProduto;
property Modalidade: Integer read FModalidade write FModalidade;
property DescricaoModalidade: String read FDescricaoModalidade write FDescricaoModalidade;
property Quantidade: Integer read FQuantidade write FQuantidade;
property Acao: TAcao read FAcao write FAcao;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
function SaveData(mtbLista: TFDMemTable): Boolean;
function DeleteEdicao(): Boolean;
function DeleteAll(): Boolean;
function QueryInsertMode(): TFDQuery;
end;
const
TABLENAME = 'listagem_jornal';
SQLINSERT = 'insert into ' + TABLENAME + '('+
'cod_agente, dat_edicao, cod_assinatura, nom_assinante, des_endereco, num_endereco, des_complemento, ' +
'des_bairro, num_cep, des_referencia, des_produto, cod_modalidade, des_modalidade, qtd_exemplares) '+
'VALUES ' +
'(:pcod_agente, :pdat_edicao, :pcod_assinatura, :pnom_assinante, :pdes_endereco, :pnum_endereco, ' +
':pdes_complemento, :pdes_bairro, :pnum_cep, :pdes_referencia, :pdes_produto, :pcod_modalidade, ' +
':pdes_modalidade, :pqtd_exemplares);';
SQLUPDATE = 'update ' + TABLENAME + 'set ' +
'cod_agente = :pcod_agente, dat_edicao = :pdat_edicao, cod_assinatura = :pcod_assinatura, ' +
'nom_assinante = :pnom_assinante, des_endereco = :pdes_endereco, num_endereco = :pnum_endereco, ' +
'des_complemento = :pdes_complemento, des_bairro = :pdes_bairro, num_cep = :pnum_cep, ' +
'des_referencia = :pdes_referencia, des_produto = :pdes_produto, cod_modalidade = :pcod_modalidade, ' +
'des_modalidade = :pdes_modalidade, qtd_exemplares = :pqtd_exemplares ' +
'WHERE id_registro = :pid_registro;';
implementation
{ TListagemAssinantesJornal }
uses dataModule;
function TListagemAssinantesJornal.Delete: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE id_registro = p:id_registro', [Self.ID]);
Result := True;
finally
FDquery.Free;
FConexao.Free;
end;
end;
function TListagemAssinantesJornal.DeleteAll: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME);
Result := True;
finally
FConexao.Free;
FDquery.Free;
end;
end;
function TListagemAssinantesJornal.DeleteEdicao: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE dat_edicao = :pdat_edicao', [Self.Edicao]);
Result := True;
finally
FConexao.Free;
FDquery.Free;
end;
end;
function TListagemAssinantesJornal.Gravar: Boolean;
begin
case FAcao of
tacIncluir: Result := Self.Insert();
tacAlterar: Result := Self.Update();
tacExcluir: Result := Self.Delete();
tacDeleteData: Result := Self.DeleteEdicao();
tacDeleteAll: Result := Self.DeleteAll();
end;
end;
function TListagemAssinantesJornal.SaveData(mtbLista: TFDMemTable): Boolean;
var
fdQuery : TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
fdQuery := FConexao.ReturnQuery();
fdQuery.SQL.Add('select * from ' + TABLENAME);
fdQuery.Open();
fdQuery.CopyDataSet(mtbLista, [coAppend]);
fdQuery.Close;
Result := True;
finally
fdQuery.Free;
FConexao.Free;
end;
end;
function TListagemAssinantesJornal.Insert: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL(SQLINSERT,[Self.Agente, Self.Edicao, Self.Codigo, Self.Nome, Self.Endereco,
Self.Numero, Self.Complemento, Self.Bairro, Self.CEP, Self.Referencia,
Self.Produto, Self.Modalidade, Self.DescricaoModalidade, Self.Quantidade]);
Result := True;
finally
FDQuery.Free;
FConexao.Free;
end;
end;
function TListagemAssinantesJornal.Localizar(aParam: array of variant): TFDQuery;
begin
Result := Self.Search(aParam);
end;
function TListagemAssinantesJornal.QueryInsertMode: TFDQuery;
var
FDQuery: TFDQuery;
begin
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Text := SQLINSERT;
Result := FDQuery;
end;
function TListagemAssinantesJornal.Search(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
try
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('WHERE id_registro = :pid_registro');
FDQuery.ParamByName('pid_registro').AsInteger := aParam[1];
end;
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE cod_agente = :pcod_agente');
FDQuery.ParamByName('pcod_agente').AsString := aParam[1];
end;
if aParam[0] = 'EDICAO' then
begin
FDQuery.SQL.Add('WHERE dat_edicao = :pdat_edicao');
FDQuery.ParamByName('pdat_edicao').AsDate := aParam[1];
end;
if aParam[0] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE cod_assinatura = :pcod_assinatura');
FDQuery.ParamByName('pcod_assinatura').AsString := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('WHERE nom_assinante like :pnom_assinante');
FDQuery.ParamByName('pnom_assinante').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
finally
FConexao.Free;
end;
end;
function TListagemAssinantesJornal.Update: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL(SQLUPDATE,[Self.Agente, Self.Edicao, Self.Codigo, Self.Nome, Self.Endereco,
Self.Numero, Self.Complemento, Self.Bairro, Self.CEP, Self.Referencia,
Self.Produto, Self.Modalidade, Self.DescricaoModalidade, Self.Quantidade, Self.ID]);
Result := True;
finally
FDQuery.Free;
FConexao.Free;
end;
end;
end.
|
unit midi.output.form;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TOutputMIDIDevicesForm = class(TForm)
Label1: TLabel;
DevicesList: TListBox;
SelectBtn: TButton;
CloseBtn: TButton;
procedure SelectBtnClick(Sender: TObject);
private
_selected: integer;
function GetSelected: integer;
{ Private declarations }
public
{ Public declarations }
procedure Init(devices: TStrings; selected: integer);
property Selected: integer read GetSelected;
end;
implementation
{$R *.dfm}
{ TOutputMIDIDevicesForm }
function TOutputMIDIDevicesForm.GetSelected: integer;
begin
result := _selected;
end;
procedure TOutputMIDIDevicesForm.Init(devices: TStrings; selected: integer);
begin
selected := -1;
DevicesList.Items.AddStrings(devices);
if selected <> -1 then
DevicesList.Selected[selected] := true;
end;
procedure TOutputMIDIDevicesForm.SelectBtnClick(Sender: TObject);
var
i: integer;
begin
_selected := -1;
if DevicesList.SelCount <> 0 then
for i := 0 to DevicesList.Count - 1 do
begin
if DevicesList.Selected[i] then
begin
_selected := i;
break;
end;
end;
end;
end.
|
{6. Realizar un programa que lea información de 200 productos de un
supermercado. De cada producto se lee código y precio (cada código es un
número entre 1 y 200). Informar en pantalla:
- Los códigos de los dos productos más baratos.
- La cantidad de productos de más de 16 pesos con código par.
}
program ejercicio6;
const
Df = 200;
type
rangoCodigo = 1..200;
var
codigo: rangoCodigo;
i, dig,codmin1, codmin2, cantProductos: Integer;
precio, min1, min2: Real;
ok: Boolean;
begin
cantProductos:=0;
min1:= 9999;
min2:= 9999;
for i := 1 to Df do
begin
write('Ingrese el CODIGO DEL PRODUCTO: ');
readln(codigo);
write('Ingrese el PRECIO DEL PRODUCTO: ');
readln(precio);
writeln('------------------------------');
if precio <= min1 then
begin
min2:=min1;
codmin2:= codmin1;
min1:= precio;
codmin1:= codigo;
end
else
if precio <= min2 then
begin
min2:= precio;
codmin2:= codigo;
end;
if ((codigo mod 2)= 0) and (precio > 16) then
begin
cantProductos:= cantProductos + 1;
end;
end;
writeln('Los codigo de los productos mas baratos son: ', min1, ' y ', min2);
writeln('La cntidad de productos de mas de 16 pesos y con codigo par es: ', cantProductos);
readln();
end. |
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is : Turbopower Abbrevia
*
* The Initial Developer of the Original Code is
* Robert J. Love
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Robert J. Love
*
* ***** END LICENSE BLOCK ***** *)
unit AbTempFileStream;
interface
uses SysUtils,Classes;
type
TAbTempFileStream = class (TFileStream)
private
FFileName: string;
FDeleteFile : Boolean;
public
constructor Create(aDeleteFile : Boolean);
destructor Destroy; override;
property FileName: string read FFileName;
end;
implementation
uses AbUtils;
{ TAbTempFileStream }
constructor TAbTempFileStream.Create(aDeleteFile : Boolean);
begin
FDeleteFile := aDeleteFile;
FFileName := AbGetTempFile('',True);
inherited Create(FFileName,fmOpenReadWrite + fmShareExclusive);
end;
destructor TAbTempFileStream.Destroy;
var
ScopeFileName : String;
ScopeDel : Boolean;
begin
ScopeFileName := FFileName;
ScopeDel := FDeleteFile;
if Not FDeleteFile then // This file will not be deleted here
AbFlushOsBuffers(Handle); // Flush Buffers to make sure commited to disk.
inherited;
if ScopeDel then
DeleteFile(ScopeFileName);
end;
end.
|
unit FindUnit.FileCache;
interface
uses
Generics.Collections, Classes, FindUnit.PasParser;
type
TUnitsController = class(TObject)
private
FSearchHistory: TDictionary<string,string>;
FNeedGenerateFindInfo: Boolean;
FUnits: TObjectList<TPasFile>;
FContent: TStringList;
FReady: Boolean;
function SearchOnHistory(const SearchString: string): TStringList;
procedure AddToHistory(const SearchString, Content: string);
procedure SetUnits(const Value: TObjectList<TPasFile>);
public
constructor Create;
destructor Destroy; override;
function GetFindInfo(const SearchString: string): TStringList;
property Units: TObjectList<TPasFile> read FUnits write SetUnits;
property Ready: Boolean read FReady write FReady;
end;
implementation
uses
FindUnit.SearchString, SysUtils;
{ TUnitUpdateController }
procedure TUnitsController.AddToHistory(const SearchString, Content: string);
begin
if FSearchHistory = nil then
Exit;
FSearchHistory.AddOrSetValue(UpperCase(SearchString), Content);
end;
constructor TUnitsController.Create;
begin
inherited;
end;
destructor TUnitsController.Destroy;
begin
FSearchHistory.Free;
FUnits.Free;
inherited;
end;
function TUnitsController.GetFindInfo(const SearchString: string): TStringList;
var
Search: TSearchString;
begin
Result := SearchOnHistory(SearchString);
if Result <> nil then
Exit;
Search := TSearchString.Create(FUnits);
try
Result := Search.GetMatch(SearchString);
AddToHistory(SearchString, Result.Text);
finally
Search.Free;
end;
end;
function TUnitsController.SearchOnHistory(const SearchString: string): TStringList;
var
Local: string;
Content: string;
begin
Result := nil;
if FSearchHistory = nil then
Exit;
Local := UpperCase(SearchString);
if FSearchHistory.TryGetValue(Local, Content) then
begin
Result := TStringList.Create;
Result.Text := Content;
end;
end;
procedure TUnitsController.SetUnits(const Value: TObjectList<TPasFile>);
begin
FUnits := Value;
FSearchHistory.Free;
FSearchHistory := TDictionary<string,string>.Create;
end;
end.
|
{ *******************************************************************************
Copyright (c) 2004-2010 by Edyard Tolmachev
IMadering project
http://imadering.com
ICQ: 118648
E-mail: imadering@mail.ru
******************************************************************************* }
unit ContactInfoUnit;
interface
{$REGION 'Uses'}
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Buttons,
ExtCtrls,
Htmlview,
ShellApi,
StrUtils,
VarsUnit,
Menus,
JvSimpleXml,
GIFImg;
type
TContactInfoForm = class(TForm)
ReqInfoBitBtn: TBitBtn;
OKBitBtn: TBitBtn;
BottomHTMLViewer: THTMLViewer;
InfoLabel: TLabel;
AvatarImage: TImage;
TopHTMLViewer: THTMLViewer;
HoroImage: TImage;
Bevel1: TBevel;
TopPopupMenu: TPopupMenu;
BottomPopupMenu: TPopupMenu;
TopCopyHTML: TMenuItem;
BottomCopyHTML: TMenuItem;
TopAllCopyHTML: TMenuItem;
BottomAllCopyHTML: TMenuItem;
Bevel2: TBevel;
procedure OKBitBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ReqInfoBitBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TopHTMLViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BottomHTMLViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BottomHTMLViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure TopHTMLViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure TopCopyHTMLClick(Sender: TObject);
procedure BottomCopyHTMLClick(Sender: TObject);
procedure TopPopupMenuPopup(Sender: TObject);
procedure BottomPopupMenuPopup(Sender: TObject);
procedure TopAllCopyHTMLClick(Sender: TObject);
procedure BottomAllCopyHTMLClick(Sender: TObject);
procedure FormDblClick(Sender: TObject);
procedure BottomHTMLViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean);
private
{ Private declarations }
HTMLStyle: string;
procedure AddHTML(const ToWhere: THTMLViewer; Text: string; TextClass: string = 'cdef'; InsertBR: Boolean = False; StupidInsert: Boolean = False; ClearIt: Boolean = False);
procedure CreateSummery(Info_Node: TJvSimpleXmlElem);
public
{ Public declarations }
ReqUIN: string;
ReqProto: string;
procedure TranslateForm;
procedure LoadUserUnfo;
end;
{$ENDREGION}
var
ContactInfoForm: TContactInfoForm;
implementation
{$R *.dfm}
{$REGION 'MyUses'}
uses
MainUnit,
IcqProtoUnit,
UtilsUnit,
IcqOptionsUnit,
OverbyteIcsUrl,
JabberProtoUnit,
MraProtoUnit;
{$ENDREGION}
{$REGION 'MyConst'}
const
C_ContForm = 'contact_info_form';
{$ENDREGION}
{$REGION 'Other'}
procedure TContactInfoForm.TopAllCopyHTMLClick(Sender: TObject);
begin
// Выделяем всё и копируем в буфер обмена
TopHTMLViewer.SelectAll;
TopHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.TopCopyHTMLClick(Sender: TObject);
begin
// Копируем выделенный текст в буфер обмена
TopHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.TopHTMLViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
// При нажатии комбинации клавиш Ctrl + C в истории чата
// копируем выделенный текст в буфер обмена
if (GetKeyState(VK_CONTROL) < 0) and (Key = 67) then
TopHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.TopHTMLViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
// Сбрасываем выделение текста в чате по клику левой клавишей мыши
if Button = MbLeft then
TopHTMLViewer.SelLength := 0;
end;
procedure TContactInfoForm.TopPopupMenuPopup(Sender: TObject);
begin
// Проверяем есть ли выделенный текст в истории чата
if TopHTMLViewer.SelLength = 0 then
TopCopyHTML.Enabled := False
else
TopCopyHTML.Enabled := True;
end;
{$ENDREGION}
{$REGION 'TranslateForm'}
procedure TContactInfoForm.TranslateForm;
begin
// Создаём шаблон для перевода
// CreateLang(Self);
// Применяем язык
SetLang(Self);
// Другое
BottomCopyHTML.Caption := TopCopyHTML.Caption;
BottomAllCopyHTML.Caption := TopAllCopyHTML.Caption;
end;
{$ENDREGION}
{$REGION 'AddHTML'}
procedure TContactInfoForm.AddHTML(const ToWhere: THTMLViewer; Text: string; TextClass: string = 'cdef'; InsertBR: Boolean = False; StupidInsert: Boolean = False; ClearIt: Boolean = False);
var
Doc: string;
begin
Doc := UTF8ToString(ToWhere.DocumentSource);
if StupidInsert then
Doc := Doc + Text
else
Doc := Doc + '<span class="' + TextClass + '">' + Text + '</span>';
if InsertBR then
Doc := Doc + '<br>';
if ClearIt then
Doc := Text;
LoadHTMLStrings(ToWhere, Doc);
end;
{$ENDREGION}
{$REGION 'LoadUserUnfo'}
procedure TContactInfoForm.LoadUserUnfo;
var
AvatarFile: string;
JvXML: TJvSimpleXml;
XML_Node: TJvSimpleXmlElem;
begin
// Устанавливаем заголовок окна
Caption := Lang_Vars[57].L_S;
// Стираем отображение предыдущей инфы
TopHTMLViewer.Clear;
BottomHTMLViewer.Clear;
// Добавляем стили для верхнего уровня
AddHTML(TopHTMLViewer, HTMLStyle, EmptyStr, False, False, True);
// Отображаем учётную запись контакта
AddHTML(TopHTMLViewer, Lang_Vars[20].L_S + C_BN + ReqProto + C_TN + C_BN, C_cbold);
AddHTML(TopHTMLViewer, ReqUIN, C_cdef, True);
// Очищаем картинку гороскопа
HoroImage.Picture.Assign(nil);
// Загружаем аватар
AvatarImage.Picture.Assign(nil);
AvatarFile := V_MyPath + C_IconsFolder + V_CurrentIcons + C_NoAvatarFileName;
if FileExists(AvatarFile) then
AvatarImage.Picture.LoadFromFile(AvatarFile);
// Ищем локально файл с информацией
if FileExists(V_ProfilePath + C_AnketaFolder + ReqProto + C_BN + ReqUIN + C_XML_Ext) then
begin
// Инициализируем XML
JvXML_Create(JvXML);
try
with JvXML do
begin
// Загружаем настройки
LoadFromFile(V_ProfilePath + C_AnketaFolder + ReqProto + C_BN + ReqUIN + C_XML_Ext);
if Root <> nil then
begin
// Открываем раздел с информацией
XML_Node := Root.Items.ItemNamed[C_Infos];
if XML_Node <> nil then
begin
// Отображаем, что информация найдена
InfoLabel.Caption := Lang_Vars[55].L_S;
// Запускаем создание суммарного инфо из распакованного файла
CreateSummery(XML_Node);
end
else
ReqInfoBitBtnClick(nil);
end;
end;
finally
JvXML.Free;
end;
end
else // Если файл с инфой не нашли, то запрашиваем её и ожидаем получения
ReqInfoBitBtnClick(nil);
end;
{$ENDREGION}
{$REGION 'Other'}
procedure TContactInfoForm.BottomAllCopyHTMLClick(Sender: TObject);
begin
// Выделяем всё и копируем в буфер обмена
BottomHTMLViewer.SelectAll;
BottomHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.BottomCopyHTMLClick(Sender: TObject);
begin
// Копируем выделенный текст в буфер обмена
BottomHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.BottomHTMLViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean);
begin
// Отключаем реакции
Handled := True;
// Открываем ссылку из чата во внешнем браузере
OpenURL(SRC);
end;
procedure TContactInfoForm.BottomHTMLViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
// При нажатии комбинации клавиш Ctrl + C в истории чата
// копируем выделенный текст в буфер обмена
if (GetKeyState(VK_CONTROL) < 0) and (Key = 67) then
BottomHTMLViewer.CopyToClipboard;
end;
procedure TContactInfoForm.BottomHTMLViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
// Сбрасываем выделение текста в чате по клику левой клавишей мыши
if Button = MbLeft then
BottomHTMLViewer.SelLength := 0;
end;
procedure TContactInfoForm.BottomPopupMenuPopup(Sender: TObject);
begin
// Проверяем есть ли выделенный текст в истории чата
if BottomHTMLViewer.SelLength = 0 then
BottomCopyHTML.Enabled := False
else
BottomCopyHTML.Enabled := True;
end;
{$ENDREGION}
{$REGION 'CreateSummery'}
procedure TContactInfoForm.CreateSummery(Info_Node: TJvSimpleXmlElem);
const
C_cmargin = 'cmargin';
var
Nick, First, Last, Age, IDay, IMonth, IYear, FullName: string;
Email0, Email1, Email2, Email3, OCity, OState, Gender: string;
Address, City, State, Zip, Country, OCountry, CountryFlag: string;
// WebAware, Auth: boolean;
WCity, WState, WZip, WAddress, Company, Department, Position, WSite, WCountry, Occupation: string;
Phone, Fax, Cellular, WPhone, WFax, HomePage, LastUpdateInfo: string;
Int1, Int2, Int3, Int4, I1, I2, I3, I4, About, HoroImg: string;
Lang1, Lang2, Lang3, Marital, Sexual, XHeight, Relig, Smok, Hair, Children: string;
XML_Node: TJvSimpleXmlElem;
begin
IDay := '00';
IMonth := '00';
Gender := '0';
// Добавляем стили для нижнего уровня
AddHTML(BottomHTMLViewer, HTMLStyle, EmptyStr, False, False, True);
// Загружаем информацию из распакованного xml файла с инфой
if Info_Node <> nil then
begin
// Ник, Имя и фамилию
XML_Node := Info_Node.Items.ItemNamed[C_NameInfo];
if XML_Node <> nil then
begin
Nick := URLDecode(XML_Node.Properties.Value(C_Nick));
First := URLDecode(XML_Node.Properties.Value(C_First));
Last := URLDecode(XML_Node.Properties.Value(C_Last));
FullName := URLDecode(XML_Node.Properties.Value(C_Name));
if IsNotNull([Nick, First, Last, FullName]) then
begin
// Вставляем разделитель
AddHTML(TopHTMLViewer, C_HR, EmptyStr, False, True);
// Вставляем ник и имена
if Nick <> EmptyStr then
begin
AddHTML(TopHTMLViewer, Lang_Vars[128].L_S + C_TN + C_BN, C_cbold);
AddHTML(TopHTMLViewer, Nick, C_cdef, True);
end;
if (First <> EmptyStr) or (Last <> EmptyStr) or (FullName <> EmptyStr) then
begin
AddHTML(TopHTMLViewer, Lang_Vars[129].L_S + C_TN + C_BN, C_cbold);
if Trim(FullName) <> EmptyStr then
AddHTML(TopHTMLViewer, FullName, C_cdef)
else
begin
if Trim(First) <> EmptyStr then
AddHTML(TopHTMLViewer, First + C_BN);
AddHTML(TopHTMLViewer, Last, C_cdef);
end;
end;
end;
end;
// Email адреса
XML_Node := Info_Node.Items.ItemNamed[C_EmailsInfo];
if XML_Node <> nil then
begin
Email0 := URLDecode(XML_Node.Properties.Value(C_Email + '0'));
Email1 := URLDecode(XML_Node.Properties.Value(C_Email + '1'));
Email2 := URLDecode(XML_Node.Properties.Value(C_Email + '2'));
Email3 := URLDecode(XML_Node.Properties.Value(C_Email + '3'));
if IsNotNull([Email0, Email1, Email2, Email3]) then
begin
if Trim(Email0) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, C_Email + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Format(C_HTML_Email, [Email0, Email0]), C_cmargin, True);
end;
if Trim(Email1) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, C_Email + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Format(C_HTML_Email, [Email1, Email1]), C_cmargin, True);
end;
if Trim(Email2) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, C_Email + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Format(C_HTML_Email, [Email2, Email2]), C_cmargin, True);
end;
if Trim(Email3) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, C_Email + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Format(C_HTML_Email, [Email3, Email3]), C_cmargin, True);
end;
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// Место жительства
XML_Node := Info_Node.Items.ItemNamed[C_HomeInfo];
if XML_Node <> nil then
begin
CountryFlag := EmptyStr;
Address := URLDecode(XML_Node.Properties.Value(C_Address));
City := URLDecode(XML_Node.Properties.Value(C_City));
State := URLDecode(XML_Node.Properties.Value(C_State));
Zip := URLDecode(XML_Node.Properties.Value(C_Zip));
Country := URLDecode(XML_Node.Properties.Value(C_Country));
// Получаем текст страны из кода
if ReqProto = C_Icq then
begin
if Assigned(IcqOptionsForm) then
Country := IcqOptionsForm.CountryInfoComboBox.Items.Values[C_QN + Country + C_EN];
CountryFlag := GetFlagFile(V_MyPath + C_FlagsFolder, XML_Node.Properties.Value(C_Country), EmptyStr);
end
else if ReqProto = C_Jabber then
begin
end
else if ReqProto = C_Mra then
begin
end;
if IsNotNull([Country, City]) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[132].L_S + C_TN + C_BN, C_cbold);
if (Country <> EmptyStr) and (CountryFlag <> EmptyStr) then
AddHTML(BottomHTMLViewer, Format(C_HTML_Flags + C_BN, [CountryFlag]) + StrArrayToStr([Country, City]), C_cdef, True)
else
AddHTML(BottomHTMLViewer, StrArrayToStr([Country, City]), C_cdef, True);
end;
if IsNotNull([Address, State, Zip]) then
begin
if Trim(Address) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[134].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Address, C_cdef, True);
end;
if Trim(State) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[135].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, State, C_cdef, True);
end;
if Trim(Zip) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[136].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Zip, C_cdef, True);
end;
end;
// Вставляем разделитель
if (IsNotNull([Country, City])) or (IsNotNull([Address, State, Zip])) then
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
// Пол, последнее обновление, домашняя страничка, авторизация и вебаваре
XML_Node := Info_Node.Items.ItemNamed[C_PerInfo];
if XML_Node <> nil then
begin
// WebAware := XML_Node.Properties.Value(C_WebAware);
// Auth := XML_Node.Properties.Value(C_Auth);
HomePage := URLDecode(XML_Node.Properties.Value(C_HomePage));
LastUpdateInfo := XML_Node.Properties.Value(C_LastChange);
Gender := XML_Node.Properties.Value(C_Gender);
if Gender = '1' then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[130].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Lang_Vars[51].L_S + C_BN + Format(C_HTML_Female, [V_CurrentIcons]), C_cdef, True);
end
else if Gender = '2' then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[130].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Lang_Vars[50].L_S + C_BN + Format(C_HTML_Male, [V_CurrentIcons]), C_cdef, True);
end;
end;
// Дата рождения
XML_Node := Info_Node.Items.ItemNamed[C_AgeInfo];
if XML_Node <> nil then
begin
Age := XML_Node.Properties.Value(C_Age);
IDay := XML_Node.Properties.Value(C_Day);
if Length(IDay) = 1 then
IDay := '0' + IDay;
IMonth := XML_Node.Properties.Value(C_Month);
if Length(IMonth) = 1 then
IMonth := '0' + IMonth;
IYear := XML_Node.Properties.Value(C_Year);
if (Age <> '0') and (Age <> EmptyStr) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[131].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Age, C_cdef, True);
end;
if (IDay <> '0') and (IMonth <> '0') and (IYear <> '0') then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[133].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, IDay + '.' + IMonth + '.' + IYear, C_cdef, True);
end;
// Вставляем разделитель
if (Gender <> '0') or ((IDay <> '0') and (IMonth <> '0') and (IYear <> '0')) then
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
// Место рождения
XML_Node := Info_Node.Items.ItemNamed[C_OHomeInfo];
if XML_Node <> nil then
begin
CountryFlag := EmptyStr;
OCountry := XML_Node.Properties.Value(C_Country);
// Получаем текст страны из кода
if ReqProto = C_Icq then
begin
if Assigned(IcqOptionsForm) then
OCountry := IcqOptionsForm.CountryInfoComboBox.Items.Values[C_QN + OCountry + C_EN];
CountryFlag := GetFlagFile(V_MyPath + C_FlagsFolder, XML_Node.Properties.Value(C_Country), EmptyStr);
end
else if ReqProto = C_Jabber then
begin
end
else if ReqProto = C_Mra then
begin
end;
OCity := URLDecode(XML_Node.Properties.Value(C_City));
OState := URLDecode(XML_Node.Properties.Value(C_State));
if IsNotNull([OCountry, OCity]) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[137].L_S + C_TN + C_BN, C_cbold);
if (OCountry <> EmptyStr) and (CountryFlag <> EmptyStr) then
AddHTML(BottomHTMLViewer, Format(C_HTML_Flags + C_BN, [CountryFlag]) + StrArrayToStr([OCountry, OCity]), C_cdef, True)
else
AddHTML(BottomHTMLViewer, StrArrayToStr([OCountry, OCity]), C_cdef, True);
end;
if Trim(OState) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[135].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, OState, C_cdef, True);
end;
// Вставляем разделитель
if (IsNotNull([OCountry, OCity])) or (Trim(OState) <> EmptyStr) then
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
// Работа
XML_Node := Info_Node.Items.ItemNamed[C_WorkInfo];
if XML_Node <> nil then
begin
CountryFlag := EmptyStr;
WCity := URLDecode(XML_Node.Properties.Value(C_City));
WState := URLDecode(XML_Node.Properties.Value(C_State));
WZip := URLDecode(XML_Node.Properties.Value(C_Zip));
WAddress := URLDecode(XML_Node.Properties.Value(C_Address));
Company := URLDecode(XML_Node.Properties.Value(C_Corp));
Department := URLDecode(XML_Node.Properties.Value(C_Dep));
Position := URLDecode(XML_Node.Properties.Value(C_Prof));
WSite := URLDecode(XML_Node.Properties.Value(C_Site));
WCountry := URLDecode(XML_Node.Properties.Value(C_Country));
Occupation := URLDecode(XML_Node.Properties.Value(C_Occup));
// Получаем текст страны из кода
if ReqProto = C_Icq then
begin
if Assigned(IcqOptionsForm) then
WCountry := IcqOptionsForm.CountryInfoComboBox.Items.Values[C_QN + WCountry + C_EN];
CountryFlag := GetFlagFile(V_MyPath + C_FlagsFolder, XML_Node.Properties.Value(C_Country), EmptyStr);
end
else if ReqProto = C_Jabber then
begin
end
else if ReqProto = C_Mra then
begin
end;
// Получаем текст занятия из кода
if Assigned(IcqOptionsForm) then
Occupation := IcqOptionsForm.CompanyProfInfoComboBox.Items.Values[C_QN + Occupation + C_EN];
if IsNotNull([WCountry, WCity]) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[138].L_S + C_TN + C_BN, C_cbold);
if (WCountry <> EmptyStr) and (CountryFlag <> EmptyStr) then
AddHTML(BottomHTMLViewer, Format(C_HTML_Flags + C_BN, [CountryFlag]) + StrArrayToStr([WCountry, WCity]), C_cdef, True)
else
AddHTML(BottomHTMLViewer, StrArrayToStr([WCountry, WCity]), C_cdef, True);
end;
if IsNotNull([WAddress, WState, WZip]) then
begin
if Trim(WAddress) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[134].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WAddress, C_cdef, True);
end;
if Trim(WState) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[135].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WState, C_cdef, True);
end;
if Trim(WZip) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[136].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WZip, C_cdef, True);
end;
end;
if IsNotNull([Company, Department, Position, Occupation, WSite]) then
begin
if Trim(Company) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[139].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Company, C_cdef, True);
end;
if Trim(Department) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[140].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Department, C_cdef, True);
end;
if Trim(Position) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[141].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Position, C_cdef, True);
end;
if Trim(Occupation) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[142].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Occupation, C_cdef, True);
end;
if Trim(WSite) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[143].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WSite, C_cdef, True);
end;
end;
// Вставляем разделитель
if (IsNotNull([WCountry, WCity])) or (IsNotNull([WAddress, WState, WZip])) or (IsNotNull([Company, Department, Position, Occupation, WSite])) then
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
// Телефоны
XML_Node := Info_Node.Items.ItemNamed[C_PhoneInfo];
if XML_Node <> nil then
begin
Phone := URLDecode(XML_Node.Properties.Value(C_Phone + '1'));
Fax := URLDecode(XML_Node.Properties.Value(C_Phone + '2'));
Cellular := URLDecode(XML_Node.Properties.Value(C_Phone + '3'));
WPhone := URLDecode(XML_Node.Properties.Value(C_Phone + '4'));
WFax := URLDecode(XML_Node.Properties.Value(C_Phone + '5'));
if IsNotNull([Phone, Fax, Cellular, WPhone, WFax]) then
begin
if Trim(Phone) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[144].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Phone, C_cdef, True);
end;
if Trim(Fax) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[145].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Fax, C_cdef, True);
end;
if Trim(Cellular) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[146].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Cellular, C_cdef, True);
end;
if Trim(WPhone) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[147].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WPhone, C_cdef, True);
end;
if Trim(WFax) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[148].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, WFax, C_cdef, True);
end;
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// Интересы
XML_Node := Info_Node.Items.ItemNamed[C_IntInfo];
if XML_Node <> nil then
begin
Int1 := URLDecode(XML_Node.Properties.Value(C_CS + '1'));
Int2 := URLDecode(XML_Node.Properties.Value(C_CS + '2'));
Int3 := URLDecode(XML_Node.Properties.Value(C_CS + '3'));
Int4 := URLDecode(XML_Node.Properties.Value(C_CS + '4'));
end;
XML_Node := Info_Node.Items.ItemNamed[C_IntIdInfo];
if XML_Node <> nil then
begin
I1 := XML_Node.Properties.Value(C_Id + '1');
I2 := XML_Node.Properties.Value(C_Id + '2');
I3 := XML_Node.Properties.Value(C_Id + '3');
I4 := XML_Node.Properties.Value(C_Id + '4');
// Получаем название интереса из кода интереса
if Assigned(IcqOptionsForm) then
begin
with IcqOptionsForm do
begin
I1 := Interest1InfoComboBox.Items.Values[C_QN + I1 + C_EN];
I2 := Interest1InfoComboBox.Items.Values[C_QN + I2 + C_EN];
I3 := Interest1InfoComboBox.Items.Values[C_QN + I3 + C_EN];
I4 := Interest1InfoComboBox.Items.Values[C_QN + I4 + C_EN];
end;
end;
// Формируем отображение интересов
if IsNotNull([I1, I2, I3, I4, Int1, Int2, Int3, Int4]) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[149].L_S + C_TN + C_BN, C_cbold, True);
if (Trim(I1) <> EmptyStr) or (Trim(Int1) <> EmptyStr) then
begin
AddHTML(BottomHTMLViewer, C_nbsp + C_nbsp);
AddHTML(BottomHTMLViewer, I1 + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Int1, C_cdef, True);
end;
if (Trim(I2) <> EmptyStr) or (Trim(Int2) <> EmptyStr) then
begin
AddHTML(BottomHTMLViewer, C_nbsp + C_nbsp);
AddHTML(BottomHTMLViewer, I2 + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Int2, C_cdef, True);
end;
if (Trim(I3) <> EmptyStr) or (Trim(Int3) <> EmptyStr) then
begin
AddHTML(BottomHTMLViewer, C_nbsp + C_nbsp);
AddHTML(BottomHTMLViewer, I3 + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Int3, C_cdef, True);
end;
if (Trim(I4) <> EmptyStr) or (Trim(Int4) <> EmptyStr) then
begin
AddHTML(BottomHTMLViewer, C_nbsp + C_nbsp);
AddHTML(BottomHTMLViewer, I4 + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Int4, C_cdef, True);
end;
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// Личное
XML_Node := Info_Node.Items.ItemNamed[C_PersInfo];
if XML_Node <> nil then
begin
Marital := XML_Node.Properties.Value(C_Marital);
Sexual := XML_Node.Properties.Value(C_Sexual);
XHeight := XML_Node.Properties.Value(C_Height);
Relig := XML_Node.Properties.Value(C_Relig);
Smok := XML_Node.Properties.Value(C_Smok);
Hair := XML_Node.Properties.Value(C_Hair);
Children := XML_Node.Properties.Value(C_Children);
// Получаем название из кода
if Assigned(IcqOptionsForm) then
begin
with IcqOptionsForm do
begin
Marital := PersonalMaritalInfoComboBox.Items.Values[C_QN + Marital + C_EN];
Sexual := PersonalSexInfoComboBox.Items.Values[C_QN + Sexual + C_EN];
Relig := PersonalReligionInfoComboBox.Items.Values[C_QN + Relig + C_EN];
Smok := PersonalSmokInfoComboBox.Items.Values[C_QN + Smok + C_EN];
Hair := PersonalHairColourInfoComboBox.Items.Values[C_QN + Hair + C_EN];
XHeight := PersonalHeightInfoComboBox.Items.Values[C_QN + XHeight + C_EN];
Children := PersonalChildrenInfoComboBox.Items.Values[C_QN + Children + C_EN];
end;
end;
// Формируем отображение
if IsNotNull([Marital, Sexual, XHeight, Relig, Smok, Hair, Children]) then
begin
if Trim(Marital) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[153].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Marital, C_cdef, True);
end;
if Trim(Sexual) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[154].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Sexual, C_cdef, True);
end;
if Trim(XHeight) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[155].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, XHeight, C_cdef, True);
end;
if Trim(Relig) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[156].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Relig, C_cdef, True);
end;
if Trim(Smok) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[157].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Smok, C_cdef, True);
end;
if Trim(Hair) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[158].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Hair, C_cdef, True);
end;
if Trim(Children) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[159].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, Children, C_cdef, True);
end;
// Вставляем разделитель
if IsNotNull([Marital, Sexual, Relig, Smok, Hair, XHeight, Children]) then
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// Языки
XML_Node := Info_Node.Items.ItemNamed[C_LangInfo];
if XML_Node <> nil then
begin
Lang1 := XML_Node.Properties.Value(C_Lang + '1');
Lang2 := XML_Node.Properties.Value(C_Lang + '2');
Lang3 := XML_Node.Properties.Value(C_Lang + '3');
// Получаем название языка из кода языка
if Assigned(IcqOptionsForm) then
begin
with IcqOptionsForm do
begin
Lang1 := Lang1InfoComboBox.Items.Values[C_QN + Lang1 + C_EN];
Lang2 := Lang1InfoComboBox.Items.Values[C_QN + Lang2 + C_EN];
Lang3 := Lang1InfoComboBox.Items.Values[C_QN + Lang3 + C_EN];
end;
end;
// Формируем отображение языков
if IsNotNull([Lang1, Lang2, Lang3]) then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[152].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, StrArrayToStr([Lang1, Lang2, Lang3]), C_cdef, True);
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// О себе
XML_Node := Info_Node.Items.ItemNamed[C_AboutInfo];
if XML_Node <> nil then
begin
About := URLDecode(XML_Node.Value);
if Trim(About) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[150].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, About, C_cdef, True);
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
end;
// Домашняя страница
if Trim(HomePage) <> EmptyStr then
begin
DecorateURL(HomePage);
AddHTML(BottomHTMLViewer, Lang_Vars[151].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, HomePage, C_cmargin, True);
// Вставляем разделитель
AddHTML(BottomHTMLViewer, C_HR, EmptyStr, False, True);
end;
// Дата последнего обновления, дополнительные данные
if Trim(LastUpdateInfo) <> EmptyStr then
begin
AddHTML(BottomHTMLViewer, Lang_Vars[160].L_S + C_TN + C_BN, C_cbold);
AddHTML(BottomHTMLViewer, LastUpdateInfo, C_cdef, True);
end;
// Вычисляем знак гороскопа
if ((IDay <> '00') and (IMonth <> '00')) and ((IDay <> '0') and (IMonth <> '0')) and ((IDay <> EmptyStr) and (IMonth <> EmptyStr)) then
begin
// Загружаем картинку гороскопа
HoroImg := V_MyPath + C_IconsFolder + V_CurrentIcons + C_SN + 'horoscope1' + C_BMP_Ext;
if FileExists(HoroImg) then
HoroImage.Picture.LoadFromFile(HoroImg);
// Прокручиваем на картинку этого знака
HoroImage.Canvas.CopyRect(Rect(0, 0, 32, 32), HoroImage.Canvas, Bounds(Horospope(StrToInt(IDay), StrToInt(IMonth)), 0, 32, 32));
end;
end;
// Загружаем аватар
try
// JPG
if FileExists(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_JPG_Ext) then
AvatarImage.Picture.LoadFromFile(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_JPG_Ext)
// GIF
else if FileExists(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_GIF_Ext) then
AvatarImage.Picture.LoadFromFile(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_GIF_Ext)
// BMP
else if FileExists(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_BMP_Ext) then
AvatarImage.Picture.LoadFromFile(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_BMP_Ext)
// PNG
else if FileExists(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_PNG_Ext) then
AvatarImage.Picture.LoadFromFile(V_ProfilePath + C_AvatarFolder + ReqProto + C_BN + ReqUIN + C_PNG_Ext);
except
end;
{else
begin
if (Length(UserAvatarHash) = 32) and (ICQ_Avatar_Work_Phaze) then
begin
ICQ_GetAvatarImage(UIN, UserAvatarHash);
end;
if (Length(UserAvatarHash) = 32) and (not AvatarServiceDisable) and (not ICQ_Avatar_Connect_Phaze) and
(not ICQ_Avatar_Work_Phaze) and (ICQ_Work_Phaze) then
begin
ICQ_Avatar_Connect_Phaze := true;
ICQ_Avatar_Work_Phaze := false;
ICQ_GetAvatar_UIN := UIN;
ICQ_GetAvatar_Hash := UserAvatarHash;
ICQ_GetAvatarBosServer;
end;
//SearchAvatarTimer.Enabled := true;
end;}
end;
{$ENDREGION}
{$REGION 'ReqInfoBitBtnClick'}
procedure TContactInfoForm.ReqInfoBitBtnClick(Sender: TObject);
begin
// Запрашиваем информацию о контакте
InfoLabel.Caption := EmptyStr;
if ReqProto = C_Icq then
begin
if (ReqUIN > EmptyStr) and (ICQ_Work_Phaze) then
begin
InfoLabel.Caption := Lang_Vars[56].L_S;
ICQ_ReqInfo_New_Pkt(ReqUIN);
end;
end
else if ReqProto = C_Jabber then
begin
if (ReqUIN > EmptyStr) and (Jabber_Work_Phaze) then
begin
InfoLabel.Caption := Lang_Vars[56].L_S;
Jab_GetUserInfo(ReqUIN);
end;
end
else if ReqProto = C_Mra then
begin
end;
end;
{$ENDREGION}
{$REGION 'Other'}
procedure TContactInfoForm.OKBitBtnClick(Sender: TObject);
begin
// Закрываем окно
Close;
end;
procedure TContactInfoForm.FormDblClick(Sender: TObject);
begin
// Устанавливаем перевод
TranslateForm;
end;
{$ENDREGION}
{$REGION 'FormCreate'}
procedure TContactInfoForm.FormCreate(Sender: TObject);
var
JvXML: TJvSimpleXml;
XML_Node: TJvSimpleXmlElem;
begin
// Инициализируем XML
JvXML_Create(JvXML);
try
with JvXML do
begin
// Загружаем настройки
if FileExists(V_ProfilePath + C_SettingsFileName) then
begin
LoadFromFile(V_ProfilePath + C_SettingsFileName);
if Root <> nil then
begin
// Загружаем позицию окна
XML_Node := Root.Items.ItemNamed[C_ContForm];
if XML_Node <> nil then
begin
Top := XML_Node.Properties.IntValue('t');
Left := XML_Node.Properties.IntValue('l');
end;
end;
end;
end;
finally
JvXML.Free;
end;
// Переводим форму на другие языки
TranslateForm;
HTMLStyle := '<html><head>' + V_DetailsCSS + '<title>Details</title></head><body>';
// Ставим иконки окна и кнопок
MainForm.AllImageList.GetIcon(178, Icon);
MainForm.AllImageList.GetBitmap(140, OKBitBtn.Glyph);
MainForm.AllImageList.GetBitmap(6, ReqInfoBitBtn.Glyph);
// Помещаем кнопку формы в таскбар и делаем независимой
SetWindowLong(Handle, GWL_HWNDPARENT, 0);
SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW);
end;
{$ENDREGION}
{$REGION 'FormDestroy'}
procedure TContactInfoForm.FormDestroy(Sender: TObject);
var
JvXML: TJvSimpleXml;
XML_Node: TJvSimpleXmlElem;
begin
// Создаём необходимые папки
ForceDirectories(V_ProfilePath);
// Сохраняем настройки положения окна в xml
// Инициализируем XML
JvXML_Create(JvXML);
try
with JvXML do
begin
if FileExists(V_ProfilePath + C_SettingsFileName) then
LoadFromFile(V_ProfilePath + C_SettingsFileName);
if Root <> nil then
begin
// Очищаем раздел формы если он есть
XML_Node := Root.Items.ItemNamed[C_ContForm];
if XML_Node <> nil then
XML_Node.Clear
else
XML_Node := Root.Items.Add(C_ContForm);
XML_Node.Properties.Add('t', Top);
XML_Node.Properties.Add('l', Left);
// Записываем сам файл
SaveToFile(V_ProfilePath + C_SettingsFileName);
end;
end;
finally
JvXML.Free;
end;
end;
{$ENDREGION}
end.
|
{
texteditor.pas
This example shows how to create a simple text editor with PasCocoa
This example project is released under public domain
AUTHORS: Felipe Monteiro de Carvalho
}
program texteditor;
{$mode delphi}
{$linkframework Cocoa}
{$linklib objc}
uses
Math,
objc, ctypes, MacOSAll, AppKit, Foundation,
{$ifndef WITHOUT_PKG}cocoa_pkg,{$endif}
controller, model, view, mytoolbar;
var
pool: NSAutoreleasePool;
begin
{ Avoids arithmetic exceptions in Objective-C code }
SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
{ Creates the AutoreleasePool }
pool := NSAutoreleasePool.Create;
{ Creates the application NSApp object }
NSApp := NSApplication.sharedApplication;
// NSBundleNib.loadNibNamed_owner(CFStringCreateWithPascalString(nil, 'applemenu', kCFStringEncodingUTF8), NSApp.Handle);
{ Initializes the controller and the model. Must be before the view to
attach the events (controller) and guarantee that resources are loaded (model) }
myController := TMyController.Create();
myModel := TMyModel.Create();
{ Initializes the view object }
myView := TMyView.Create;
myView.CreateUserInterface;
{ Enters main message loop }
myView.MainWindow.orderFrontRegardless;
NSApp.setDelegate(myController.Handle);
NSApp.run;
{ Releases all objects }
myController.Free;
myModel.Free;
myView.Free;
{ Releases the AutoreleasePool }
pool.Free;
end.
|
unit kwPopEditorSelectPara;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Костицын М.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSelectPara.pas"
// Начат: 16.12.2011
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SelectPara
//
// pop:editor:SelectPara. Выделяет текущий параграф в редакторе
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
evCustomEditorWindow,
tfwScriptingInterfaces,
Controls,
Classes
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
TkwPopEditorSelectPara = class(_kwEditorFromStackWord_)
{* pop:editor:SelectPara. Выделяет текущий параграф в редакторе }
protected
// realized methods
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorSelectPara
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
evTypes,
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade,
Forms
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopEditorSelectPara;
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
// start class TkwPopEditorSelectPara
procedure TkwPopEditorSelectPara.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_4EEB668D000C_var*
//#UC END# *4F4CB81200CA_4EEB668D000C_var*
begin
//#UC START# *4F4CB81200CA_4EEB668D000C_impl*
anEditor.Select(ev_stPara);
//#UC END# *4F4CB81200CA_4EEB668D000C_impl*
end;//TkwPopEditorSelectPara.DoWithEditor
class function TkwPopEditorSelectPara.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:editor:SelectPara';
end;//TkwPopEditorSelectPara.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit UNumPad;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls,UDialog, FMX.Objects, FMX.Edit;
type
TNumPadDialog = class(TDialogFrame)
ok: TButton;
Number0: TButton;
Dot: TButton;
Cancel: TButton;
Number3: TButton;
Number2: TButton;
Number1: TButton;
Number4: TButton;
Number5: TButton;
Number6: TButton;
Clear: TButton;
Number9: TButton;
Number8: TButton;
Number7: TButton;
lbTitle: TLabel;
resultBox: TEdit;
Line1: TLine;
procedure Number1Click(Sender: TObject);
procedure Number2Click(Sender: TObject);
procedure Number3Click(Sender: TObject);
procedure Number4Click(Sender: TObject);
procedure Number5Click(Sender: TObject);
procedure Number6Click(Sender: TObject);
procedure Number7Click(Sender: TObject);
procedure Number8Click(Sender: TObject);
procedure Number9Click(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure Number0Click(Sender: TObject);
procedure DotClick(Sender: TObject);
procedure okClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.fmx}
procedure TNumPadDialog.CancelClick(Sender: TObject);
begin
resultBox.Text := '';
self.DialogResult := mrCancel;
FProcessDialogResult.ProcessDialogResult;
end;
procedure TNumPadDialog.ClearClick(Sender: TObject);
begin
resultBox.Text := '';
end;
procedure TNumPadDialog.DotClick(Sender: TObject);
var
I: Integer;
isdot: Integer;
begin
for I := 0 to resultBox.Text.Length - 1 do
begin
if resultBox.Text[I] = '.' then
isdot := 1;
end;
if isdot <> 1 then
resultBox.Text := resultBox.Text + '.';
end;
procedure TNumPadDialog.Number0Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(0);
end;
procedure TNumPadDialog.Number1Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(1);
end;
procedure TNumPadDialog.Number2Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(2);
end;
procedure TNumPadDialog.Number3Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(3);
end;
procedure TNumPadDialog.Number4Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(4);
end;
procedure TNumPadDialog.Number5Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(5);
end;
procedure TNumPadDialog.Number6Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(6);
end;
procedure TNumPadDialog.Number7Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(7);
end;
procedure TNumPadDialog.Number8Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(8);
end;
procedure TNumPadDialog.Number9Click(Sender: TObject);
begin
resultBox.Text := resultBox.Text + IntToStr(9);
end;
procedure TNumPadDialog.okClick(Sender: TObject);
begin
ReturnString := resultBox.Text;
DialogResult := mrOK;
FProcessDialogResult.ProcessDialogResult;
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品退货调整
*******************************************************************************}
unit UFormProductReturnAdjust;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, UGridPainter, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, ExtCtrls, UImageButton, Grids, UGridExPainter;
type
TfFormProductReturnAdjust = class(TSkinFormBase)
GridList: TDrawGridEx;
Panel1: TPanel;
BtnOK: TImageButton;
BtnExit: TImageButton;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
EditID: TcxTextEdit;
EditMan: TcxTextEdit;
EditTime: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Panel1Resize(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
private
{ Private declarations }
FReturnID: string;
//退单号
FPainter: TGridPainter;
//绘制对象
procedure LoadReturnDetail(const nReturn: string);
//商品信息
procedure OnEditExit(Sender: TObject);
//数据生效
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowProductReturnAdjust(const nReturn: string): Boolean;
//调整退货单
implementation
{$R *.dfm}
uses
ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule, FZSale_Intf;
function ShowProductReturnAdjust(const nReturn: string): Boolean;
begin
with TfFormProductReturnAdjust.Create(Application) do
begin
FReturnID := nReturn;
LoadReturnDetail(nReturn);
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormProductReturnAdjust.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormProductReturnAdjust.FormCreate(Sender: TObject);
var nIdx: Integer;
begin
for nIdx:=ComponentCount-1 downto 0 do
if Components[nIdx] is TImageButton then
LoadFixImageButton(TImageButton(Components[nIdx]));
//xxxxx
FPainter := TGridPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('品牌', 50);
AddHeader('商品名称', 50);
AddHeader('现有库存', 50);
AddHeader('原退货量', 50);
AddHeader('现调整为', 50);
end;
LoadFormConfig(Self);
LoadDrawGridConfig(Name, GridList);
end;
procedure TfFormProductReturnAdjust.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveFormConfig(Self);
SaveDrawGridConfig(Name, GridList);
FPainter.Free;
end;
procedure TfFormProductReturnAdjust.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 调整按钮位置
procedure TfFormProductReturnAdjust.Panel1Resize(Sender: TObject);
var nW,nL: Integer;
begin
nW := BtnOK.Width + 65 + BtnExit.Width;
nL := Trunc((Panel1.Width - nW) / 2);
BtnOk.Left := nL;
BtnExit.Left := nL + BtnOK.Width + 65;
end;
//------------------------------------------------------------------------------
//Desc: 载入退货明细
procedure TfFormProductReturnAdjust.LoadReturnDetail(const nReturn: string);
var nStr,nHint: string;
nIdx,nInt: Integer;
nDS: TDataSet;
nEdit: TcxTextEdit;
nLabel: TLabel;
nData: TGridDataArray;
begin
nStr := 'Select rd.*,BrandName,StyleName,ColorName,SizeName,D_Number,' +
'P_Number,T_Man,T_Date From $RD rd ' +
' Left Join $PT pt On pt.ProductID=rd.D_Product ' +
' Left Join $ST st On st.StyleID=pt.StyleID ' +
' Left Join $SZ sz On sz.SizeID=pt.SizeID ' +
' Left Join $CR cr On cr.ColorID=pt.ColorID ' +
' Left Join $RT rt On rt.T_ID=rd.D_Return ' +
' Left Join $BR br On br.BrandID=pt.BrandID ' +
' Left Join $DP dp on dp.P_ID=rd.D_Product ' +
'Where D_Return=''$ID'' Order By StyleName,ColorName,SizeName';
//xxxxx
nStr := MacroValue(nStr, [MI('$RD', sTable_ReturnDtl), MI('$ID', nReturn),
MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size),
MI('$CR', sTable_DL_Color), MI('$RT', sTable_Return),
MI('$BR', sTable_DL_Brand), MI('$PT', sTable_DL_Product),
MI('$DP', sTable_Product)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
First;
nInt := 1;
EditID.Text := FReturnID;
EditMan.Text := FieldByName('T_Man').AsString;
EditTime.Text := DateTime2Str(FieldByName('T_Date').AsDateTime);
while not Eof do
begin
SetLength(nData, 8);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := FieldByName('BrandName').AsString;
nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString,
FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]);
nData[2].FText := nStr;
nData[3].FText := FieldByName('P_Number').AsString;
nData[4].FText := FieldByName('D_Number').AsString;
with nData[5] do
begin
FText := '';
FCtrls := TList.Create;
nEdit := TcxTextEdit.Create(Self);
FCtrls.Add(nEdit);
with nEdit do
begin
Width := 42;
Height := 18;
Text := nData[4].FText;
OnExit := OnEditExit;
Tag := FPainter.DataCount;
end;
nLabel := TLabel.Create(Self);
nLabel.Transparent := True;
nLabel.Caption := '件';
FCtrls.Add(nLabel);
end;
nData[6].FText := FieldByName('D_Product').AsString;
nData[7].FText := FieldByName('R_ID').AsString;
FPainter.AddData(nData);
Next;
end;
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 内容生效
procedure TfFormProductReturnAdjust.OnEditExit(Sender: TObject);
var nTag: Integer;
begin
with TcxTextEdit(Sender) do
begin
if (not IsNumber(Text, False)) or (StrToInt(Text) < 0) then
begin
SetFocus;
ShowMsg('请填写有效件数', sHint); Exit;
end;
nTag := TComponent(Sender).Tag;
if StrToInt(Text) > StrToInt(FPainter.Data[nTag][3].FText) then
begin
if not QueryDlg('退货件数已经超出库存,要继续吗?', sAsk) then SetFocus;
end;
end;
end;
//Desc: 保存
procedure TfFormProductReturnAdjust.BtnOKClick(Sender: TObject);
var nStr,nHint: string;
nIdx,nNum: Integer;
nSQLList: SQLItems;
begin
ActiveControl := nil;
if Assigned(ActiveControl) then Exit;
nSQLList := SQLItems.Create;
try
nNum := 0;
for nIdx:=0 to FPainter.DataCount - 1 do
begin
nStr := TcxTextEdit(FPainter.Data[nIdx][5].FCtrls[0]).Text;
if IsNumber(nStr, False) and (StrToInt(nStr) > 0) then
nNum := nNum + StrToInt(nStr);
//xxxxx
end;
if nNum < 1 then
begin
nSQLList.Free;
ShowMsg('退货件数为零', sHint); Exit;
end;
nStr := 'Update %s Set T_Number=%d Where T_ID=''%s''';
nStr := Format(nStr, [sTable_Return, nNum, FReturnID]);
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
for nIdx:=0 to FPainter.DataCount - 1 do
begin
nStr := TcxTextEdit(FPainter.Data[nIdx][5].FCtrls[0]).Text;
if (not IsNumber(nStr, False)) or (StrToInt(nStr) < 0) then Continue;
nNum := StrToInt(nStr);
if nNum = StrToInt(FPainter.Data[nIdx][4].FText) then Continue;
//退货量不变
nStr := 'Update %s Set D_Number=%d Where R_ID=%s';
nStr := Format(nStr, [sTable_ReturnDtl, nNum, FPainter.Data[nIdx][7].FText]);
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
end;
if FDM.SQLUpdates(nSQLList, True, nHint) > -1 then
begin
ModalResult := mrOk;
end else ShowDlg(nHint, sWarn);
finally
//nSQLList.Free;
end;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clHttpAuth;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, Contnrs, SysUtils, Windows, SyncObjs,
{$ELSE}
System.Classes, System.Contnrs, System.SysUtils, Winapi.Windows, System.SyncObjs,
{$ENDIF}
clUriUtils, clSspiAuth;
type
//TODO test for multithreading, probably add accessor to all authentication methods
TclHttpAuthorization = class
private
FStartNewConnection: Boolean;
FAuthValue: string;
protected
function GetSupportedAuthMethod(AuthChallenge: TStrings; const AMethod: string): string;
procedure SetStartNewConnection(Value: Boolean);
procedure SetAuthValue(const AValue: string);
procedure DoAuthorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject); virtual; abstract;
public
class function Authorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject): TclHttpAuthorization;
class procedure RegisterAuthorization(Authorization: TclHttpAuthorization);
class function RegisteredAuthorizations: TObjectList;
property StartNewConnection: Boolean read FStartNewConnection;
property AuthValue: string read FAuthValue;
end;
TclHttpBasicAuthorization = class(TclHttpAuthorization)
private
function BuildAuthorizationString(const AUser, APassword: string): string;
protected
procedure DoAuthorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject); override;
end;
TclDigestChallenge = class
private
FStale: Boolean;
FRealm: string;
FAlgorithm: string;
FQopOptions: string;
FNonce: string;
FDomain: string;
FOpaque: string;
FNonceCount: Integer;
FUserName: string;
FClientNonce: string;
FResponse: string;
FUri: string;
FMethod: string;
FCharSet: string;
public
procedure Parse(const AChallenge: string);
function BuildAuthorization: string;
property Realm: string read FRealm write FRealm;
property Domain: string read FDomain write FDomain;
property Nonce: string read FNonce write FNonce;
property Opaque: string read FOpaque write FOpaque;
property Stale: Boolean read FStale write FStale;
property Algorithm: string read FAlgorithm write FAlgorithm;
property QopOptions: string read FQopOptions write FQopOptions;
property UserName: string read FUserName write FUserName;
property Uri: string read FUri write FUri;
property ClientNonce: string read FClientNonce write FClientNonce;
property NonceCount: Integer read FNonceCount write FNonceCount;
property Response: string read FResponse write FResponse;
property Method: string read FMethod write FMethod;
property CharSet: string read FCharSet write FCharSet;
end;
TclHttpDigestAuthorization = class(TclHttpAuthorization)
private
function BuildAuthorizationString(AUrl: TclUrlParser; const AMethod, AChallenge,
AUserName, APassword: string): string;
function CreateNonce: string;
function CreateResponse(AChallenge: TclDigestChallenge; const AUserName, APassword: string): string;
function ComputeData(AChallenge: TclDigestChallenge): string;
function ComputeSectret(AChallenge: TclDigestChallenge;
const AUserName, APassword: string): string;
protected
procedure DoAuthorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject); override;
end;
TclHttpNtlmAuthorization = class(TclHttpAuthorization)
private
FSessions: TStrings;
FAccessor: TCriticalSection;
function BuildAuthorizationString(ASession: TclNtAuthClientSspi;
AUrl: TclUrlParser; const APackage, AChallenge, AUserName, APassword: string;
var ACompleted: Boolean): string;
protected
procedure DoAuthorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject); override;
public
constructor Create;
destructor Destroy; override;
procedure CloseSessions;
end;
implementation
uses
clEncoder, clHeaderFieldList, clCryptHash, clHttpHeader;
var
RegAuthorizations: TObjectList = nil;
{ TclHttpAuthorization }
class function TclHttpAuthorization.Authorize(AUrl: TclUrlParser; const AMethod, AUserName, APassword: string;
AuthChallenge: TStrings; AContext: TObject): TclHttpAuthorization;
var
i: Integer;
begin
for i := RegisteredAuthorizations().Count - 1 downto 0 do
begin
Result := TclHttpAuthorization(RegisteredAuthorizations()[i]);
Result.DoAuthorize(AUrl, AMethod, AUserName, APassword, AuthChallenge, AContext);
if (Result.AuthValue <> '') then
begin
Exit;
end;
end;
Result := nil;
end;
class procedure TclHttpAuthorization.RegisterAuthorization(Authorization: TclHttpAuthorization);
begin
RegisteredAuthorizations().Add(Authorization);
end;
class function TclHttpAuthorization.RegisteredAuthorizations: TObjectList;
begin
if (RegAuthorizations = nil) then
begin
RegAuthorizations := TObjectList.Create();
end;
Result := RegAuthorizations;
end;
function TclHttpAuthorization.GetSupportedAuthMethod(AuthChallenge: TStrings;
const AMethod: string): string;
var
i: Integer;
s: string;
begin
s := LowerCase(AMethod);
for i := 0 to AuthChallenge.Count - 1 do
begin
if (system.Pos(s, LowerCase(AuthChallenge[i])) > 0) then
begin
Result := AuthChallenge[i];
Exit;
end;
end;
Result := '';
end;
procedure TclHttpAuthorization.SetAuthValue(const AValue: string);
begin
FAuthValue := AValue;
end;
procedure TclHttpAuthorization.SetStartNewConnection(Value: Boolean);
begin
FStartNewConnection := Value;
end;
{ TclHttpBasicAuthorization }
procedure TclHttpBasicAuthorization.DoAuthorize(AUrl: TclUrlParser;
const AMethod, AUserName, APassword: string; AuthChallenge: TStrings; AContext: TObject);
var
res: string;
begin
res := GetSupportedAuthMethod(AuthChallenge, 'basic');
if (res <> '') then
begin
res := BuildAuthorizationString(AUserName, APassword);
end;
SetAuthValue(res);
end;
function TclHttpBasicAuthorization.BuildAuthorizationString(const AUser, APassword: string): string;
var
s: string;
begin
SetStartNewConnection(True);
Result := '';
if (AUser = '') and (APassword = '') then Exit;
s := AUser;
if (s <> '') then
begin
s := s + ':';
end;
s := s + APassword;
Result := TclEncoder.EncodeToString(s, cmBase64);
Result := 'Basic ' + Result;
end;
{ TclHttpDigestAuthorization }
procedure TclHttpDigestAuthorization.DoAuthorize(AUrl: TclUrlParser;
const AMethod, AUserName, APassword: string; AuthChallenge: TStrings; AContext: TObject);
var
res: string;
begin
res := GetSupportedAuthMethod(AuthChallenge, 'digest');
if (res <> '') then
begin
res := BuildAuthorizationString(AUrl, AMethod, res, AUserName, APassword);
end;
SetAuthValue(res);
end;
function TclHttpDigestAuthorization.CreateNonce: string;
var
y, mm, d, h, m, s, ms: Word;
begin
DecodeTime(Now(), h, m, s, ms);
DecodeDate(Date(), y, mm, d);
Result := IntToHex(mm, 2) + IntToHex(d, 2) + IntToHex(h, 2) + IntToHex(m, 2);
Result := Result + IntToHex(s, 2) + IntToHex(ms, 4);
Result := Result + IntToHex(Integer(GetTickCount()), 8) + IntToHex(Integer(GetTickCount()) + 1, 8);
Result := 'ab' + LowerCase(Result);
end;
function TclHttpDigestAuthorization.ComputeSectret(AChallenge: TclDigestChallenge;
const AUserName, APassword: string): string;
begin
Result := '';
if (AUserName = '') then Exit;
if (AChallenge.Algorithm = '') or SameText('md5', AChallenge.Algorithm) then
begin
Result := AUserName + ':' + AChallenge.Realm + ':' + APassword;
end else
if SameText('md5-sess', AChallenge.Algorithm) then
begin
Result := AUserName + ':' + AChallenge.Realm + ':' + APassword;
Result := MD5(Result) + ':' + AChallenge.Nonce + ':' + AChallenge.ClientNonce;
end;
end;
function TclHttpDigestAuthorization.ComputeData(AChallenge: TclDigestChallenge): string;
var
options: TStrings;
begin
Result := AChallenge.Method + ':' + AChallenge.Uri;
options := TStringList.Create();
try
options.Text := StringReplace(LowerCase(AChallenge.QopOptions), ',', #13#10, [rfReplaceAll]);
if (options.IndexOf('auth') > -1) then
begin
AChallenge.QopOptions := 'auth';
end;
finally
options.Free();
end;
end;
function TclHttpDigestAuthorization.CreateResponse(AChallenge: TclDigestChallenge;
const AUserName, APassword: string): string;
var
secret, data: string;
begin
secret := ComputeSectret(AChallenge, AUserName, APassword);
data := ComputeData(AChallenge);
if (secret = '') or (data = '') then
begin
Result := '';
Exit;
end;
secret := MD5(secret);
data := MD5(data);
Result := AChallenge.Nonce + ':';
if (AChallenge.QopOptions <> '') then
begin
Result := Result + IntToHex(AChallenge.NonceCount, 8) + ':'
+ AChallenge.ClientNonce + ':' + AChallenge.QopOptions + ':';
end;
Result := Result + data;
Result := MD5(secret + ':' + Result);
end;
function TclHttpDigestAuthorization.BuildAuthorizationString(AUrl: TclUrlParser;
const AMethod, AChallenge, AUserName, APassword: string): string;
var
challenge: TclDigestChallenge;
begin
Result := '';
if (AUserName = '') then Exit;
challenge := TclDigestChallenge.Create();
try
challenge.Parse(AChallenge);
if (challenge.QopOptions <> '') then
begin
if (challenge.ClientNonce = '') or challenge.Stale then
begin
challenge.ClientNonce := CreateNonce();
challenge.NonceCount := 1;
end else
begin
challenge.NonceCount := challenge.NonceCount + 1;
end;
end;
challenge.Method := AMethod;
challenge.UserName := AUserName;
challenge.Uri := AUrl.AbsolutePath;
//TODO utf-8 support
challenge.Response := CreateResponse(challenge, AUserName, APassword);
if (challenge.Response <> '') then
begin
Result := challenge.BuildAuthorization();
end;
finally
challenge.Free();
end;
end;
{ TclDigestChallenge }
function TclDigestChallenge.BuildAuthorization: string;
const
authField = 'authfield';
var
fieldList: TclHeaderFieldList;
src: TStrings;
begin
fieldList := nil;
src := nil;
try
fieldList := TclHeaderFieldList.Create();
fieldList.CharsPerLine := 0;
fieldList.ItemDelimiter := ',';
src := TStringList.Create();
fieldList.Parse(0, src);
fieldList.AddEmptyField(authField);
fieldList.AddQuotedFieldItem(authField, 'username', UserName);
fieldList.AddQuotedFieldItem(authField, 'realm', Realm);
if (QopOptions <> '') then
begin
fieldList.AddQuotedFieldItem(authField, 'qop', QopOptions);
fieldList.AddQuotedFieldItem(authField, 'algorithm', Algorithm);
end;
fieldList.AddQuotedFieldItem(authField, 'uri', Uri);
fieldList.AddQuotedFieldItem(authField, 'nonce', Nonce);
if (QopOptions <> '') then
begin
fieldList.AddFieldItem(authField, 'nc', IntToHex(NonceCount, 8));
fieldList.AddQuotedFieldItem(authField, 'cnonce', ClientNonce);
end;
fieldList.AddQuotedFieldItem(authField, 'opaque', Opaque);
fieldList.AddQuotedFieldItem(authField, 'response', Response);
Result := 'Digest ' + fieldList.GetFieldValue(authField);
finally
src.Free();
fieldList.Free();
end;
end;
procedure TclDigestChallenge.Parse(const AChallenge: string);
var
s: string;
fieldList: TclHeaderFieldList;
begin
fieldList := TclHeaderFieldList.Create();
try
FCharSet := fieldList.GetFieldValueItem(AChallenge, 'charset');
//TODO utf-8 support
FRealm := fieldList.GetFieldValueItem(AChallenge, 'realm');
FDomain := fieldList.GetFieldValueItem(AChallenge, 'domain');
FNonce := fieldList.GetFieldValueItem(AChallenge, 'nonce');
FOpaque := fieldList.GetFieldValueItem(AChallenge, 'opaque');
FStale := SameText('true', fieldList.GetFieldValueItem(AChallenge, 'stale'));
FAlgorithm := fieldList.GetFieldValueItem(AChallenge, 'algorithm');
FQopOptions := fieldList.GetFieldValueItem(AChallenge, 'qop');
FUserName := fieldList.GetFieldValueItem(AChallenge, 'username');
FUri := fieldList.GetFieldValueItem(AChallenge, 'uri');
FClientNonce := fieldList.GetFieldValueItem(AChallenge, 'cnonce');
s := fieldList.GetFieldValueItem(AChallenge, 'nc');
if (s <> '') then
begin
s := '$' + s;
end;
FNonceCount := StrToIntDef(s, 0);
FResponse := fieldList.GetFieldValueItem(AChallenge, 'response');
finally
fieldList.Free();
end;
end;
{ TclHttpNtlmAuthorization }
procedure TclHttpNtlmAuthorization.DoAuthorize(AUrl: TclUrlParser;
const AMethod, AUserName, APassword: string; AuthChallenge: TStrings; AContext: TObject);
var
ind: Integer;
sspiSession: TclNtAuthClientSspi;
completed: Boolean;
res, package: string;
begin
package := 'Negotiate';
res := GetSupportedAuthMethod(AuthChallenge, package);
if (res = '') then
begin
package := 'NTLM';
res := GetSupportedAuthMethod(AuthChallenge, package);
end;
if (res = '') then
begin
SetAuthValue('');
Exit;
end;
FAccessor.Enter();
try
ind := FSessions.IndexOf(IntToStr(Integer(AContext)));
if (ind < 0) then
begin
sspiSession := TclNtAuthClientSspi.Create();
FSessions.AddObject(IntToStr(Integer(AContext)), sspiSession);
end else
begin
sspiSession := TclNtAuthClientSspi(FSessions.Objects[ind]);
end;
completed := False;
res := BuildAuthorizationString(sspiSession, AUrl, package, res, AUserName, APassword, completed);
if completed then
begin
sspiSession.Free();
if (ind < 0) then
begin
ind := FSessions.Count - 1;
end;
FSessions.Delete(ind);
end;
finally
SetAuthValue(res);
FAccessor.Leave();
end;
end;
function TclHttpNtlmAuthorization.BuildAuthorizationString(ASession: TclNtAuthClientSspi;
AUrl: TclUrlParser; const APackage, AChallenge, AUserName, APassword: string;
var ACompleted: Boolean): string;
var
ind: Integer;
inputChallenge: string;
encoder: TclEncoder;
buf: TStream;
authIdentity: TclAuthIdentity;
begin
ACompleted := True;
Result := '';
inputChallenge := Trim(AChallenge);
ind := system.Pos(UpperCase(APackage), UpperCase(inputChallenge));
if (ind <> 1) then Exit;
inputChallenge := Trim(system.Copy(inputChallenge, Length(APackage) + 1, Length(inputChallenge)));
SetStartNewConnection(inputChallenge = '');
encoder := nil;
buf := nil;
authIdentity := nil;
try
encoder := TclEncoder.Create(nil);
encoder.SuppressCrlf := True;
encoder.EncodeMethod := cmBase64;
buf := TMemoryStream.Create();
encoder.Decode(inputChallenge, buf);
buf.Position := 0;
if (AUserName <> '') then
begin
authIdentity := TclAuthIdentity.Create(AUserName, APassword);
end;
ACompleted := ASession.GenChallenge(APackage, buf, 'HTTP/' + AUrl.Host, authIdentity);
buf.Position := 0;
Result := encoder.Encode(buf);
Result := APackage + ' ' + Result;
finally
authIdentity.Free();
buf.Free();
encoder.Free();
end;
end;
constructor TclHttpNtlmAuthorization.Create;
begin
inherited Create();
FAccessor := TCriticalSection.Create();
FSessions := TStringList.Create();
end;
destructor TclHttpNtlmAuthorization.Destroy;
begin
CloseSessions();
FSessions.Free();
FAccessor.Free();
inherited Destroy();
end;
procedure TclHttpNtlmAuthorization.CloseSessions;
var
i: Integer;
begin
FAccessor.Enter();
try
for i := FSessions.Count - 1 downto 0 do
begin
FSessions.Objects[i].Free();
end;
FSessions.Clear();
finally
FAccessor.Leave();
end;
end;
initialization
TclHttpAuthorization.RegisterAuthorization(TclHttpBasicAuthorization.Create());
TclHttpAuthorization.RegisterAuthorization(TclHttpDigestAuthorization.Create());
TclHttpAuthorization.RegisterAuthorization(TclHttpNtlmAuthorization.Create());
finalization
RegAuthorizations.Free();
end.
|
unit PrimShutDown_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/PrimCommon/Forms/PrimShutDown_Form.pas"
// Начат: 21.08.2009 21:18
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMForm::Class>> F1 Базовые определения предметной области::F1 Application Template::View::PrimCommon::PrimShutDown
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
ExtCtrls
{$If not defined(NoVCM)}
,
vcmUserControls
{$IfEnd} //not NoVCM
,
F1_Application_Template_InternalOperations_Controls,
vtLabel,
l3StringIDEx
{$If not defined(NoScripts)}
,
tfwInteger
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
kwBynameControlPush
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
PrimShutDown_sftNone_UserType,
vcmExternalInterfaces {a},
vcmInterfaces {a},
vcmEntityForm {a}
;
type
TPrimShutDownForm = {form} class(TvcmEntityForm)
private
// private fields
f_WarningText : TvtLabel;
{* Поле для свойства WarningText}
f_ShutdownTimer : TTimer;
{* Поле для свойства ShutdownTimer}
protected
procedure InitEntities; override;
procedure MakeControls; override;
protected
// property methods
function pm_GetWarningText: TvtLabel;
function pm_GetShutdownTimer: TTimer;
protected
// realized methods
procedure System_InitShutdown_Execute(aShotdown: Boolean;
aCloseInterval: Integer);
{* Начать процесс завершения работы }
procedure System_InitShutdown(const aParams: IvcmExecuteParams);
{* Начать процесс завершения работы }
protected
// protected fields
f_InShutdown : Boolean;
f_CloseInterval : Integer;
f_CloseCaption : AnsiString;
protected
// protected methods
procedure UpdateCloseButton; virtual; abstract;
procedure UpdateSize; virtual; abstract;
public
// public properties
property WarningText: TvtLabel
read pm_GetWarningText;
property ShutdownTimer: TTimer
read pm_GetShutdownTimer;
end;//TPrimShutDownForm
TvcmEntityFormRef = TPrimShutDownForm;
implementation
uses
Classes
{$If not defined(NoVCM)}
,
vcmBase
{$IfEnd} //not NoVCM
{$If not defined(NoScripts)}
,
tfwScriptingInterfaces
{$IfEnd} //not NoScripts
,
l3MessageID,
StdRes {a}
;
var
{ Локализуемые строки sftNoneLocalConstants }
str_sftNoneCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'sftNoneCaption'; rValue : 'Предупреждение о закрытии приложения');
{ Заголовок пользовательского типа "Предупреждение о закрытии приложения" }
type
Tkw_PrimShutDown_Control_WarningText = class(TtfwControlString)
{* Слово словаря для идентификатора контрола WarningText
----
*Пример использования*:
[code]
контрол::WarningText TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimShutDown_Control_WarningText
// start class Tkw_PrimShutDown_Control_WarningText
{$If not defined(NoScripts)}
function Tkw_PrimShutDown_Control_WarningText.GetString: AnsiString;
{-}
begin
Result := 'WarningText';
end;//Tkw_PrimShutDown_Control_WarningText.GetString
{$IfEnd} //not NoScripts
type
Tkw_PrimShutDown_Control_WarningText_Push = class(TkwBynameControlPush)
{* Слово словаря для контрола WarningText
----
*Пример использования*:
[code]
контрол::WarningText:push pop:control:SetFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimShutDown_Control_WarningText_Push
// start class Tkw_PrimShutDown_Control_WarningText_Push
{$If not defined(NoScripts)}
procedure Tkw_PrimShutDown_Control_WarningText_Push.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushString('WarningText');
inherited;
end;//Tkw_PrimShutDown_Control_WarningText_Push.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_PrimShutDown_Component_ShutdownTimer = class(TtfwControlString)
{* Слово словаря для идентификатора компонента ShutdownTimer
----
*Пример использования*:
[code]
компонент::ShutdownTimer TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimShutDown_Component_ShutdownTimer
// start class Tkw_PrimShutDown_Component_ShutdownTimer
{$If not defined(NoScripts)}
function Tkw_PrimShutDown_Component_ShutdownTimer.GetString: AnsiString;
{-}
begin
Result := 'ShutdownTimer';
end;//Tkw_PrimShutDown_Component_ShutdownTimer.GetString
{$IfEnd} //not NoScripts
function TPrimShutDownForm.pm_GetWarningText: TvtLabel;
begin
if (f_WarningText = nil) then
f_WarningText := FindComponent('WarningText') As TvtLabel;
Result := f_WarningText;
end;
function TPrimShutDownForm.pm_GetShutdownTimer: TTimer;
begin
if (f_ShutdownTimer = nil) then
f_ShutdownTimer := FindComponent('ShutdownTimer') As TTimer;
Result := f_ShutdownTimer;
end;
procedure TPrimShutDownForm.System_InitShutdown_Execute(aShotdown: Boolean;
aCloseInterval: Integer);
//#UC START# *4A8EC9E902CD_4A8EC8AC02EEexec_var*
//#UC END# *4A8EC9E902CD_4A8EC8AC02EEexec_var*
begin
//#UC START# *4A8EC9E902CD_4A8EC8AC02EEexec_impl*
f_InShutdown := True;
f_CloseInterval := aCloseInterval;
if aShotdown then
WarningText.CCaption := vcmFmt(str_ShotdownWarning, [f_CloseInterval])
else
WarningText.CCaption := vcmFmt(str_LogoutWarning, [f_CloseInterval]);
UpdateSize;
UpdateCloseButton;
ShutDownTimer.Enabled := True;
//#UC END# *4A8EC9E902CD_4A8EC8AC02EEexec_impl*
end;//TPrimShutDownForm.System_InitShutdown_Execute
procedure TPrimShutDownForm.System_InitShutdown(const aParams: IvcmExecuteParams);
begin
with (aParams.Data As ISystem_InitShutdown_Params) do
System_InitShutdown_Execute(Shotdown, CloseInterval);
end;
procedure TPrimShutDownForm.InitEntities;
begin
inherited;
with Entities.Entities do
begin
PublishFormEntity(en_System, nil);
PublishOpWithResult(en_System, op_InitShutdown, System_InitShutdown, nil, nil);
end;//with Entities.Entities
end;
procedure TPrimShutDownForm.MakeControls;
begin
inherited;
with AddUsertype(sftNoneName,
str_sftNoneCaption,
str_sftNoneCaption,
true,
-1,
-1,
'',
nil,
nil,
nil,
vcm_ccNone) do
begin
end;//with AddUsertype(sftNoneName
end;
initialization
// Регистрация Tkw_PrimShutDown_Control_WarningText
Tkw_PrimShutDown_Control_WarningText.Register('контрол::WarningText', TvtLabel);
// Регистрация Tkw_PrimShutDown_Control_WarningText_Push
Tkw_PrimShutDown_Control_WarningText_Push.Register('контрол::WarningText:push');
// Регистрация Tkw_PrimShutDown_Component_ShutdownTimer
Tkw_PrimShutDown_Component_ShutdownTimer.Register('компонент::ShutdownTimer', TTimer);
// Инициализация str_sftNoneCaption
str_sftNoneCaption.Init;
end. |
unit tcItem;
interface
uses
l3Interfaces,
l3CacheableBase,
tcInterfaces;
type
TtcItem = class(Tl3CacheableBase,
ItcItem)
private
f_ID: Il3CString;
f_Caption: Il3CString;
protected
// ItcItem
function pm_GetID: Il3CString;
function pm_GetCaption: Il3CString;
procedure pm_SetCaption(const aValue: Il3CString);
protected
procedure Cleanup; override;
public
constructor Create(const anID: Il3CString); reintroduce;
end;
implementation
{ TtcItem }
procedure TtcItem.Cleanup;
begin
f_ID := nil;
f_Caption := nil;
inherited Cleanup;
end;
constructor TtcItem.Create(const anID: Il3CString);
begin
inherited Create;
f_ID := anID;
end;
function TtcItem.pm_GetCaption: Il3CString;
begin
Result := f_Caption;
end;
function TtcItem.pm_GetID: Il3CString;
begin
Result := f_ID;
end;
procedure TtcItem.pm_SetCaption(const aValue: Il3CString);
begin
f_Caption := aValue;
end;
end.
|
unit TTSPENDTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSPENDRecord = record
PLenderNum: String[4];
PCifFlag: String[1];
PLoanNum: String[20];
PCollNum: Integer;
End;
TTTSPENDBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSPENDRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSPEND = (TTSPENDPrimaryKey);
TTTSPENDTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCifFlag: TStringField;
FDFLoanNum: TStringField;
FDFCollNum: TIntegerField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanNum(const Value: String);
function GetPLoanNum:String;
procedure SetPCollNum(const Value: Integer);
function GetPCollNum:Integer;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSPEND);
function GetEnumIndex: TEITTSPEND;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSPENDRecord;
procedure StoreDataBuffer(ABuffer:TTTSPENDRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanNum: TStringField read FDFLoanNum;
property DFCollNum: TIntegerField read FDFCollNum;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanNum: String read GetPLoanNum write SetPLoanNum;
property PCollNum: Integer read GetPCollNum write SetPCollNum;
published
property Active write SetActive;
property EnumIndex: TEITTSPEND read GetEnumIndex write SetEnumIndex;
end; { TTTSPENDTable }
procedure Register;
implementation
function TTTSPENDTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSPENDTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSPENDTable.GenerateNewFieldName }
function TTTSPENDTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSPENDTable.CreateField }
procedure TTTSPENDTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanNum := CreateField( 'LoanNum' ) as TStringField;
FDFCollNum := CreateField( 'CollNum' ) as TIntegerField;
end; { TTTSPENDTable.CreateFields }
procedure TTTSPENDTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSPENDTable.SetActive }
procedure TTTSPENDTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSPENDTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSPENDTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSPENDTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSPENDTable.SetPLoanNum(const Value: String);
begin
DFLoanNum.Value := Value;
end;
function TTTSPENDTable.GetPLoanNum:String;
begin
result := DFLoanNum.Value;
end;
procedure TTTSPENDTable.SetPCollNum(const Value: Integer);
begin
DFCollNum.Value := Value;
end;
function TTTSPENDTable.GetPCollNum:Integer;
begin
result := DFCollNum.Value;
end;
procedure TTTSPENDTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CifFlag, String, 1, N');
Add('LoanNum, String, 20, N');
Add('CollNum, Integer, 0, N');
end;
end;
procedure TTTSPENDTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CifFlag;LoanNum;CollNum, Y, Y, N, N');
end;
end;
procedure TTTSPENDTable.SetEnumIndex(Value: TEITTSPEND);
begin
case Value of
TTSPENDPrimaryKey : IndexName := '';
end;
end;
function TTTSPENDTable.GetDataBuffer:TTTSPENDRecord;
var buf: TTTSPENDRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanNum := DFLoanNum.Value;
buf.PCollNum := DFCollNum.Value;
result := buf;
end;
procedure TTTSPENDTable.StoreDataBuffer(ABuffer:TTTSPENDRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanNum.Value := ABuffer.PLoanNum;
DFCollNum.Value := ABuffer.PCollNum;
end;
function TTTSPENDTable.GetEnumIndex: TEITTSPEND;
var iname : string;
begin
result := TTSPENDPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSPENDPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSPENDTable, TTTSPENDBuffer ] );
end; { Register }
function TTTSPENDBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..4] of string = ('LENDERNUM','CIFFLAG','LOANNUM','COLLNUM' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 4) and (flist[x] <> s) do inc(x);
if x <= 4 then result := x else result := 0;
end;
function TTTSPENDBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
end;
end;
function TTTSPENDBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCifFlag;
3 : result := @Data.PLoanNum;
4 : result := @Data.PCollNum;
end;
end;
end.
|
unit VideoUtils;
interface
uses
Windows, Dibs, VideoICM, VideoDraw;
// DIBs compression I/O hooks
procedure DibUnpackVideo( SourcePixels : pointer; DibHeader : PDib; DibPixels : pointer; ForceTopDown : boolean );
procedure RegisterVideoDibIoHooks;
procedure UnregisterVideoDibIoHooks;
// Compression/Decompression
const
COMP_USERCHOSEN = $52455355; // 'USER': Ask user which compressor and settings to use..
COMP_DEFAULT = $00000000; // Use default compressor codec
function CompressImage( DibHeader : PDib; DibPixels : pointer; RealTime : boolean;
Codec : dword; lQuality : longint ) : PDib;
function DecompressImage( DibHeader : PDib; DibPixels : pointer; RealTime : boolean ) : PDib;
// Compressed Drawing
function DrawCompBegin( dc : HDC; DibHeader : PDib; Flags : dword ) : HDRAWDIB;
procedure DrawCompEnd( hdd : HDRAWDIB );
procedure DrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer;
x, y : integer; Flags : dword );
procedure StretchDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer;
x, y : integer; dx, dy : integer; Flags : dword );
procedure ClipDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer;
x, y : integer; const ClippingRect : TRect; Flags : dword );
procedure ClipStretchDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer;
const Rect, ClippingRect : TRect; Flags : dword );
// Helpers
const
fccTypeVIDEO = ICTYPE_VIDEO;
function GetCompressor( fccHandler : dword; RealTime : boolean ) : HIC;
function GetDecompressor( fccHandler : dword; RealTime : boolean ) : HIC;
function LocateCompressor( DibHeader : PBitmapInfoHeader; RealTime : boolean ) : HIC;
function LocateDecompressor( DibHeader : PBitmapInfoHeader; RealTime : boolean ) : HIC;
function GetUserChosenCompressor( DibHeader : PBitmapInfoHeader; var lQuality : longint;
WinHandle : HWND; const Title : string ) : HIC;
// Codec enumeration: ----------------------------------------------------------------
type
TVideoCodecEnumProc = procedure ( const Info : TICInfo; UserData : dword );
procedure EnumerateCompressors( DibHeader : PBitmapInfoHeader; UserData : dword;
CodecFound, CodecCanHandleThis : TVideoCodecEnumProc );
procedure EnumerateDecompressors( DibHeader : PBitmapInfoHeader; UserData : dword;
CodecFound, CodecCanHandleThis : TVideoCodecEnumProc );
type
TLogProc = procedure ( Message : string );
var
LogProc : TLogProc = nil;
// Quick hack: Output codecs
// You need to set LogProc in order to use these procedures
procedure DebugEnumerateCompressors( DibHeader : PBitmapInfoHeader );
procedure DebugEnumerateDecompressors( DibHeader : PBitmapInfoHeader );
implementation
uses
Rects;
// DIBs compression I/O hooks
procedure DibUnpackVideo( SourcePixels : pointer; DibHeader : PDib; DibPixels : pointer; ForceTopDown : boolean );
var
UnpackedDib : PDib;
UnpackedPixels : pointer;
begin
UnpackedDib := DecompressImage( DibHeader, SourcePixels, false );
UnpackedPixels := DibPtr( UnpackedDib );
with DibHeader^ do
try
if ( biHeight > 0 ) and ForceTopDown
then biHeight := -abs( biHeight );
if UnpackedDib.biHeight * biHeight > 0 // Same orientation?
then Move( UnpackedPixels^, DibPixels^, DibSizeImage( UnpackedDib ) )
else DibCopyFlippedVert( UnpackedDib, UnpackedPixels, DibPixels );
finally
DibFree( UnpackedDib );
end;
end;
procedure RegisterVideoDibIoHooks;
begin
//RegisterDibIOHooks( , DibUnpackVideo );
end;
procedure UnregisterVideoDibIoHooks;
begin
//UnregisterDibIOHooks( );
end;
// Compression/Decompression
function CompressImage( DibHeader : PDib; DibPixels : pointer; RealTime : boolean;
Codec : dword; lQuality : longint ) : PDib;
var
ic : HIC;
tmpHeader : PDib;
icOk : boolean;
begin
if Codec = COMP_USERCHOSEN
then
begin
getmem( tmpHeader, sizeof( tmpHeader^ ) ); // This stuff is to handle top-down DIBs,
move( DibHeader^, tmpHeader^, sizeof( tmpHeader^ ) ); // they are made bottom-up in ICCompressImage
if tmpHeader.biHeight < 0
then tmpHeader.biHeight := -tmpHeader.biHeight;
ic := GetUserChosenCompressor( tmpHeader, lQuality, 0, '' );
icOk := ( ic <> 0 );
end
else
if Codec = COMP_DEFAULT
then
begin
ic := 0;
icOk := true;
end
else
begin
ic := GetCompressor( Codec, RealTime );
icOk := ( ic <> 0 );
end;
if icOk
then
begin
Result := ICCompressImage( ic, 0, DibHeader, DibPixels, nil, lQuality );
if ic <> 0
then ICClose( ic );
end
else Result := nil;
end;
function DecompressImage( DibHeader : PDib; DibPixels : pointer; RealTime : boolean ) : PDib;
var
ic : HIC;
begin
if ( ( DibHeader.biCompression <> BI_RGB ) and ( DibHeader.biCompression <> BI_BITFIELDS ) ) or
( DibPixels <> DibPtr( DibHeader ) )
then
begin
ic := LocateDecompressor( DibHeader, RealTime );
Result := ICDecompressImage( ic, 0, DibHeader, DibPixels, nil );
ICClose( ic );
end
else Result := DibHeader; // Image is already unpacked and OK
end;
// Compressed Drawing
function DrawCompBegin( dc : HDC; DibHeader : PDib; Flags : dword ) : HDRAWDIB;
begin
Result := DrawDibOpen;
with DibHeader^ do
DrawDibBegin( Result, dc, biWidth, biHeight, DibHeader, biWidth, biHeight, Flags );
end;
procedure DrawCompEnd( hdd : HDRAWDIB );
begin
DrawDibEnd( hdd );
end;
procedure DrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer; x, y : integer; Flags : dword );
begin
with DibHeader^ do
DrawDibDraw( hdd, dc, x, y, biWidth, biHeight, DibHeader, DibPixels, 0, 0, biWidth, biHeight, Flags );
end;
procedure StretchDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer; x, y : integer; dx, dy : integer; Flags : dword );
begin
with DibHeader^ do
DrawDibDraw( hdd, dc, x, y, dx, dy, DibHeader, DibPixels, 0, 0, biWidth, biHeight, Flags );
end;
procedure ClipDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer; x, y : integer; const ClippingRect : TRect; Flags : dword );
var
SrcOfs : TPoint;
Rect : TRect;
DstRect : TRect;
DstSize : TPoint;
begin
with DibHeader^ do
begin
Rect := RectFromBounds( x, y, biWidth, biHeight );
if IntersectRect( DstRect, Rect, ClippingRect )
then
begin
DstSize := RectSize( DstRect );
if Rect.Left < DstRect.Left
then SrcOfs.x := DstRect.Left - Rect.Left
else SrcOfs.x := 0;
if Rect.Top < DstRect.Top
then SrcOfs.y := DstRect.Top - Rect.Top
else SrcOfs.y := 0;
DrawDibDraw( hdd, dc, DstRect.Left, DstRect.Top, DstSize.x, DstSize.y, DibHeader, DibPixels, SrcOfs.x, SrcOfs.y, DstSize.x, DstSize.y, Flags );
end;
end;
end;
procedure ClipStretchDrawCompImage( hdd : HDRAWDIB; dc : HDC; DibHeader : PDib; DibPixels : pointer; const Rect, ClippingRect : TRect; Flags : dword );
var
SrcOfs : TPoint;
SrcSize : TPoint;
DstRect : TRect;
DstSize : TPoint;
begin
with DibHeader^ do
if IntersectRect( DstRect, ClippingRect, Rect )
then
begin
DstSize := RectSize( DstRect );
if Rect.Left < DstRect.Left
then SrcOfs.x := (DstRect.Left - Rect.Left) * biWidth div (Rect.Right - Rect.Left)
else SrcOfs.x := 0;
SrcSize.x := DstSize.x * biWidth div (Rect.Right - Rect.Left);
if Rect.Top < DstRect.Top
then SrcOfs.y := (DstRect.Top - Rect.Top) * biHeight div (Rect.Bottom - Rect.Top)
else SrcOfs.y := 0;
SrcSize.y := DstSize.y * biHeight div (Rect.Bottom - Rect.Top);
DrawDibDraw( hdd, dc, DstRect.Left, DstRect.Top, DstSize.x, DstSize.y, DibHeader, DibPixels, SrcOfs.x, SrcOfs.y, SrcSize.x, SrcSize.y, Flags );
end;
end;
// Helpers
function GetUserChosenCompressor( DibHeader : PBitmapInfoHeader; var lQuality : longint;
WinHandle : HWND; const Title : string ) : HIC;
var
Info : TCompVars;
begin
Info.cbSize := sizeof( TCompVars );
Info.dwFlags := 0;
if ICCompressorChoose( WinHandle, 0, DibHeader, nil, Info, pchar( Title ) )
then
begin
lQuality := Info.lQ;
Result := Info.ic;
end
else Result := 0;
end;
function GetCompressor( fccHandler : dword; RealTime : boolean ) : HIC;
var
wMode : word;
begin
if RealTime
then wMode := ICMODE_FASTCOMPRESS
else wMode := ICMODE_COMPRESS;
Result := ICOpen( fccTypeVIDEO, fccHandler, wMode );
end;
function GetDecompressor( fccHandler : dword; RealTime : boolean ) : HIC;
var
wMode : word;
begin
if RealTime
then wMode := ICMODE_FASTDECOMPRESS
else wMode := ICMODE_DECOMPRESS;
Result := ICOpen( fccTypeVIDEO, fccHandler, wMode );
end;
function LocateCompressor( DibHeader : PBitmapInfoHeader; RealTime : boolean ) : HIC;
var
wMode : word;
begin
if RealTime
then wMode := ICMODE_FASTCOMPRESS
else wMode := ICMODE_COMPRESS;
Result := ICLocate( fccTypeVIDEO, 0, DibHeader, nil, wMode );
end;
function LocateDecompressor( DibHeader : PBitmapInfoHeader; RealTime : boolean ) : HIC;
var
wMode : word;
begin
if RealTime
then wMode := ICMODE_FASTDECOMPRESS
else wMode := ICMODE_DECOMPRESS;
Result := ICLocate( fccTypeVIDEO, 0, DibHeader, nil, wMode );
end;
// Codec enumeration: ----------------------------------------------------------------
procedure EnumerateCompressors( DibHeader : PBitmapInfoHeader; UserData : dword;
CodecFound, CodecCanHandleThis : TVideoCodecEnumProc );
var
Info : TICInfo;
ic : HIC;
i : integer;
begin
i := 0;
with Info do
while ICInfo( fccTypeVIDEO, i, Info ) do
begin
inc( i );
CodecFound( Info, UserData );
ic := ICOpen( Info.fccType, Info.fccHandler, ICMODE_QUERY );
if ic <> 0
then
begin
// Skip this compressor if it can't handle the specified format.
if ICCompressQuery( ic, DibHeader, nil) = ICERR_OK
then
begin
// Find out the compressor name.
ICGetInfo( ic, Info, sizeof( Info ) );
CodecCanHandleThis( Info, UserData );
end
else ICClose( ic );
end;
end;
end;
procedure EnumerateDecompressors( DibHeader : PBitmapInfoHeader; UserData : dword;
CodecFound, CodecCanHandleThis : TVideoCodecEnumProc );
var
Info : TICInfo;
ic : HIC;
i : integer;
begin
i := 0;
with Info do
while ICInfo( fccTypeVIDEO, i, Info ) do
begin
inc( i );
CodecFound( Info, UserData );
ic := ICOpen( Info.fccType, Info.fccHandler, ICMODE_QUERY );
if ic <> 0
then
begin
// Skip this compressor if it can't handle the specified format.
if ICDecompressQuery( ic, DibHeader, nil) = ICERR_OK
then
begin
// Find out the compressor name.
ICGetInfo( ic, Info, sizeof( Info ) );
CodecCanHandleThis( Info, UserData );
end
else ICClose( ic );
end;
end;
end;
procedure DebugCodecFound( const Info : TICInfo; UserData : dword );
begin
assert( Assigned( LogProc ), 'Unassigned LogProc in VideoUtils.DebugCodecFound' );
with Info do
if boolean(UserData)
then LogProc( '>>> Found a compressor (' + FourCCToStr( Info.fccHandler ) + ')' )
else LogProc( '>>> Found a decompressor (' + FourCCToStr( Info.fccHandler ) + ')' );
end;
procedure DebugCodecCanHandleThis( const Info : TICInfo; UserData : dword );
begin
assert( Assigned( LogProc ), 'Unassigned LogProc in VideoUtils.DebugCodecCanHandleThis' );
with Info do
LogProc( 'Named ''' + WideCharToString( Info.szName ) +
''', description ''' + WideCharToString( Info.szDescription ) +
''', found in driver ''' + WideCharToString( Info.szDriver ) + '''...' );
end;
procedure DebugEnumerateCompressors( DibHeader : PBitmapInfoHeader );
begin
EnumerateCompressors( DibHeader, dword(true), DebugCodecFound, DebugCodecCanHandleThis );
end;
procedure DebugEnumerateDecompressors( DibHeader : PBitmapInfoHeader );
begin
EnumerateDecompressors( DibHeader, dword(false), DebugCodecFound, DebugCodecCanHandleThis );
end;
end.
|
unit FloatEdit;
interface
uses classes,Cautious_edit;
type
TFloatEdit = class(TCautiousEdit)
private
function get_value: Real;
procedure set_value(value: Real);
public
constructor Create(owner: TComponent); override;
procedure Change; override;
function isValid: boolean;
published
property value: Real Read get_value Write set_value;
end;
TIntegerEdit=class(TCautiousEdit)
private
function get_value: Integer;
procedure set_value(value: Integer);
public
procedure Change; override;
function isValid: boolean;
constructor Create(owner: TComponent); override;
published
property value: Integer Read get_value Write set_value stored false;
end;
procedure Register;
implementation
uses sysUtils,float_expression_lib;
(*
TFloatEdit
*)
function TFloatEdit.get_value: Real;
var res: Extended;
expr: TFloatExpression;
E: Exception;
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
if expr.isCorrect then Result:=expr.getValue
else begin
Result:=0;
if not (csDesigning in self.ComponentState) then begin
E:=Exception.CreateFMT('TFloatLabel: %s',[expr.errorMsg]);
expr.Free; //не хотим терять память
Raise E;
end;
end;
expr.Free;
end
else
if TryStrToFloat(text,res) then begin
Result:=res;
end
else begin
Result:=0;
if not (csDesigning in self.ComponentState) then
Raise Exception.Create('TFloatLabel: Not a number');
end;
end;
procedure TFloatEdit.Change;
var res: Extended;
expr: TFloatExpression;
resourcestring
FloatEditNotARealNumberMsg = 'Не является действительным числом';
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
if expr.isCorrect then ReturnToNormal
else TurnRed(expr.errorMsg);
expr.Free;
end
else
if TryStrToFloat(text,res) then ReturnToNormal
else TurnRed(FloatEditNotARealNumberMsg);
inherited Change;
end;
procedure TFloatEdit.set_value(value: Real);
begin
text:=FloatToStr(value);
end;
constructor TFloatEdit.Create(owner: TComponent);
begin
inherited Create(owner);
if (csDesigning in ComponentState) then value:=0;
end;
function TFloatEdit.isValid: Boolean;
var t: Extended;
expr: TFloatExpression;
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
Result:=expr.isCorrect;
expr.Free;
end
else
Result:=TryStrToFloat(text,t);
end;
(*
TIntegerEdit
*)
function TIntegerEdit.get_value: Integer;
var res: Integer;
expr: TFloatExpression;
E: Exception;
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
if expr.isCorrect then Result:=expr.getIntegerValue
else begin
Result:=0;
if not (csDesigning in ComponentState) then begin
E:=Exception.CreateFmt('TIntegerEdit: %s',[expr.errorMsg]);
expr.Free;
raise E;
end;
end;
expr.Free;
end
else
if TryStrToInt(text,res) then begin
Result:=res;
end
else begin
Result:=0;
if not (csDesigning in self.ComponentState) then
Raise Exception.Create('TIntegerEdit: Not a number');
end;
end;
function TIntegerEdit.isValid: boolean;
var t: Integer;
expr: TFloatExpression;
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
Result:=expr.isCorrect;
expr.Free;
end
else
Result:=TryStrToInt(text,t);
end;
procedure TIntegerEdit.Change;
var res: Integer;
expr: TFloatExpression;
resourcestring
IntegerEditNotAnIntegerNumberMsg = 'Не является целым числом';
begin
if AllowExpressions then begin
expr:=TFloatExpression.Create(nil);
expr.SetRootComponent(ExpressionRootComponent);
expr.SetString(text);
if expr.isCorrect then ReturnToNormal
else TurnRed(expr.errorMsg);
expr.Free;
end
else
if TryStrToInt(text,res) then ReturnToNormal
else TurnRed(IntegerEditNotAnIntegerNumberMsg);
inherited Change;
end;
procedure TIntegerEdit.set_value(value: Integer);
begin
text:=IntToStr(value);
end;
constructor TIntegerEdit.Create(owner: TComponent);
begin
inherited Create(owner);
if (csDesigning in ComponentState) then value:=0;
end;
procedure Register;
begin
RegisterComponents('CautiousEdit', [TFloatEdit,TIntegerEdit]);
end;
end.
|
object ExportDlg: TExportDlg
Left = 245
Top = 108
BorderStyle = bsDialog
Caption = 'Exportar Datos'
ClientHeight = 246
ClientWidth = 347
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Verdana'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
ShowHint = True
PixelsPerInch = 96
TextHeight = 13
object Bevel1: TBevel
Left = 24
Top = 192
Width = 307
Height = 4
Shape = bsBottomLine
end
object Label1: TLabel
Left = 24
Top = 20
Width = 119
Height = 13
Caption = 'Nombre de Archivo: '
end
object Label2: TLabel
Left = 24
Top = 168
Width = 40
Height = 13
Caption = 'Titulo: '
end
object OKBtn: TButton
Left = 96
Top = 204
Width = 75
Height = 25
Hint = 'exporte la informacion'
Caption = 'Exportar'
Default = True
ModalResult = 1
TabOrder = 5
end
object CancelBtn: TButton
Left = 176
Top = 204
Width = 75
Height = 25
Hint = 'anular proceso'
Cancel = True
Caption = 'Anular'
ModalResult = 2
TabOrder = 4
end
object rgFormato: TRadioGroup
Left = 24
Top = 48
Width = 307
Height = 57
Hint = 'seleccione formato de archivo de exportacion'
Caption = '[ Formato de exportacion ]'
Columns = 2
ItemIndex = 0
Items.Strings = (
'Texto'
'Excell'
'HTML ( Paginas Web )'
'XML ')
TabOrder = 1
OnClick = rgFormatoClick
end
object rgReg: TRadioGroup
Left = 24
Top = 112
Width = 307
Height = 41
Hint = 'registros a exportar'
Caption = '[ Registros a exportar ]'
Columns = 2
ItemIndex = 0
Items.Strings = (
'Todos'
'Los seleccionados')
TabOrder = 2
end
object edTitulo: TEdit
Left = 64
Top = 164
Width = 267
Height = 21
Hint = 'coloque titulo del listado'
Color = 16777088
TabOrder = 3
Text = 'Listado'
end
object cbArchivo: TJvComboEdit
Left = 150
Top = 16
Width = 179
Height = 21
Hint = 'seleccione nombre de archivo '
Color = 16777088
Glyph.Data = {
DE000000424DDE0000000000000076000000280000000D0000000D0000000100
0400000000006800000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7000777777777777700077777707777770007777706077777000777706660777
7000777066666077700077066666660770007000066600007000777706660777
7000777706660777700077770666077770007777000007777000777777777777
7000}
TabOrder = 0
OnButtonClick = cbArchivoButtonClick
end
object OpenDlg: TOpenDialog
Filter = 'Archivos de texto|*.txt|Todos los archivos|*.*'
Title = 'Seleccione Archivo'
Left = 8
end
object CdsXMLConvert: TClientDataSet
Aggregates = <>
Params = <>
Left = 232
Top = 96
end
end
|
unit EditUser_Frm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Forms,
System.Classes, Vcl.Graphics, System.ImageList, Vcl.ImgList, Vcl.Menus,
Vcl.StdCtrls, Vcl.Controls, Vcl.Dialogs, System.Actions, Vcl.ActnList,
Data.DB,
BaseLayout_Frm, CommonValues, VBCommonValues,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore,
dxSkinsDefaultPainters, cxImageList, dxLayoutLookAndFeels, cxClasses, cxStyles,
dxLayoutContainer, dxLayoutControl, dxLayoutcxEditAdapters, cxEdit, cxButtons,
dxLayoutControlAdapters, cxContainer, cxCheckBox, cxDBEdit, cxTextEdit;
type
TEditUserFrm = class(TBaseLayoutFrm)
litFirstName: TdxLayoutItem;
litLastName: TdxLayoutItem;
litLoginName: TdxLayoutItem;
litEmailAddress: TdxLayoutItem;
litAccountEnabled: TdxLayoutItem;
grpName: TdxLayoutGroup;
grpLogin: TdxLayoutGroup;
edtFirstName: TcxDBTextEdit;
edtLastName: TcxDBTextEdit;
edtLoginName: TcxDBTextEdit;
edtEmailAddress: TcxDBTextEdit;
grpEmailAddress: TdxLayoutGroup;
cbxAccountEnabled: TcxDBCheckBox;
grpPW: TdxLayoutGroup;
litPW: TdxLayoutItem;
litConfirmPW: TdxLayoutItem;
grpButtons: TdxLayoutGroup;
btnOK: TcxButton;
btnCancel: TcxButton;
litOK: TdxLayoutItem;
litCancel: TdxLayoutItem;
sep1: TdxLayoutSeparatorItem;
litLegend: TdxLayoutLabeledItem;
litMatch: TdxLayoutImageItem;
litNoMatch: TdxLayoutImageItem;
edtConfirmPassword: TcxTextEdit;
edtPassword: TcxTextEdit;
spc1: TdxLayoutEmptySpaceItem;
grpPasswordControl: TdxLayoutGroup;
litShowPaassword: TdxLayoutItem;
litChangePassword: TdxLayoutItem;
cbxShowPassword: TcxCheckBox;
spc2: TdxLayoutEmptySpaceItem;
spc3: TdxLayoutEmptySpaceItem;
cbxChangePassword: TcxDBCheckBox;
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure edtPasswordPropertiesChange(Sender: TObject);
procedure cbxShowPasswordPropertiesEditValueChanged(Sender: TObject);
private
{ Private declarations }
FPasswordModified: Boolean;
function GetPassword(PW: string): string;
procedure SetPassword(PW: string);
public
{ Public declarations }
end;
var
EditUserFrm: TEditUserFrm;
implementation
{$R *.dfm}
uses VBBase_DM, User_DM, ED;
procedure TEditUserFrm.FormCreate(Sender: TObject);
begin
inherited;
Caption := 'User Account Data';
Self.Width := 535;
Self.Height := 220; // 160
edtFirstName.DataBinding.DataSource := UserDM.dtsSystemUser;
edtLastName.DataBinding.DataSource := UserDM.dtsSystemUser;
edtLoginName.DataBinding.DataSource := UserDM.dtsSystemUser;
edtEmailAddress.DataBinding.DataSource := UserDM.dtsSystemUser;
cbxAccountEnabled.DataBinding.DataSource := UserDM.dtsSystemUser;
cbxChangePassword.DataBinding.DataSource := UserDM.dtsSystemUser;
edtPassword.Text := GetPassword(UserDM.cdsSystemUser.FieldByName('PASSWORD').AsString);
litMatch.Visible := False;
litNoMatch.Visible := False;
FPasswordModified := False;
end;
function TEditUserFrm.GetPassword(PW: string): string;
var
ED: TED;
begin
Result := '';
ED := TED.Create(EKEY1, EKEY2);
try
Result := ED.DCString(PW);
finally
ED.Free;
end;
end;
procedure TEditUserFrm.SetPassword(PW: string);
begin
end;
procedure TEditUserFrm.btnOKClick(Sender: TObject);
var
NextID: Integer;
begin
inherited;
if VarIsNull(edtFirstName.EditValue) or SameText(Trim(edtFirstName.Text), '') then
begin
edtFirstName.SetFocus;
raise EValidateException.Create('First name must have a value.');
end;
if VarIsNull(edtLastName.EditValue) or SameText(Trim(edtLastName.Text), '') then
begin
edtLastName.SetFocus;
raise EValidateException.Create('Last name must have a value.');
end;
if VarIsNull(edtLoginName.EditValue) or SameText(Trim(edtLoginName.Text), '') then
begin
edtLoginName.SetFocus;
raise EValidateException.Create('Login name must have a value.');
end;
if VarIsNull(edtPassword.EditValue) or SameText(Trim(edtPassword.Text), '') then
begin
edtPassword.SetFocus;
raise EValidateException.Create('Password must have a value.');
end;
if FPasswordModified then
begin
// if VarIsNull(edtConfirmPassword.EditValue) or SameText(Trim(edtConfirmPassword.Text), '') then
// begin
// edtConfirmPassword.SetFocus;
// raise EValidateException.Create('Confirm password must have a value.');
// end;
if not SameStr(Trim(edtPassword.Text), Trim(edtConfirmPassword.Text)) then
begin
edtConfirmPassword.SetFocus;
raise EValidateException.Create('Password confirmation does not match the password.');
end;
end;
if VBBaseDM.DBAction = acInsert then
begin
NextID := VBBaseDM.GetNextID(UserDM.cdsSystemUser.UpdateOptions.GeneratorName);
UserDM.cdsSystemUser.FieldByName('ID').AsInteger := NextID;
end;
// UserDM.cdsSystemUser.Post;
// UserDM.PostData(UserDM.cdsSystemUser);
UserDM.cdsSystemUser.Post;
VBBaseDM.PostData(UserDM.cdsSystemUser);
Self.ModalResult := mrOK;
end;
procedure TEditUserFrm.cbxShowPasswordPropertiesEditValueChanged(Sender: TObject);
begin
inherited;
if cbxShowPassword.Checked then
begin
edtPassword.Style.Font.nAME := 'Verdana';
edtPassword.Style.Font.Charset := ANSI_CHARSET;
edtPassword.Style.Font.nAME := 'Verdana';
edtConfirmPassword.Style.Font.Charset := ANSI_CHARSET;
edtConfirmPassword.Properties.PasswordChar := #0;
edtPassword.Properties.EchoMode := eemNormal;
edtConfirmPassword.Properties.EchoMode := eemNormal;
end
else
begin
edtPassword.Style.Font.nAME := 'Wingdings';
edtPassword.Style.Font.Charset := SYMBOL_CHARSET;
edtPassword.Style.Font.nAME := 'Wingdings';
edtConfirmPassword.Style.Font.Charset := SYMBOL_CHARSET;
edtConfirmPassword.Properties.PasswordChar := 'l';
edtPassword.Properties.EchoMode := eemPassword;
edtConfirmPassword.Properties.EchoMode := eemPassword;
end;
end;
procedure TEditUserFrm.edtPasswordPropertiesChange(Sender: TObject);
begin
inherited;
litMatch.Visible := SameStr(Trim(edtPassword.Text), Trim(edtConfirmPassword.Text));
litNoMatch.Visible := not litMatch.Visible;
FPasswordModified := True;
end;
end.
;
|
unit trackandfield_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,nz80,main_engine,controls_engine,sn_76496,vlm_5030,gfx_engine,
dac,rom_engine,pal_engine,konami_decrypt,sound_engine,qsnapshot,file_engine;
function iniciar_trackfield:boolean;
implementation
const
trackfield_rom:array[0..4] of tipo_roms=(
(n:'a01_e01.bin';l:$2000;p:$6000;crc:$2882f6d4),(n:'a02_e02.bin';l:$2000;p:$8000;crc:$1743b5ee),
(n:'a03_k03.bin';l:$2000;p:$a000;crc:$6c0d1ee9),(n:'a04_e04.bin';l:$2000;p:$c000;crc:$21d6c448),
(n:'a05_e05.bin';l:$2000;p:$e000;crc:$f08c7b7e));
trackfield_char:array[0..2] of tipo_roms=(
(n:'h16_e12.bin';l:$2000;p:0;crc:$50075768),(n:'h15_e11.bin';l:$2000;p:$2000;crc:$dda9e29f),
(n:'h14_e10.bin';l:$2000;p:$4000;crc:$c2166a5c));
trackfield_sprites:array[0..3] of tipo_roms=(
(n:'c11_d06.bin';l:$2000;p:0;crc:$82e2185a),(n:'c12_d07.bin';l:$2000;p:$2000;crc:$800ff1f1),
(n:'c13_d08.bin';l:$2000;p:$4000;crc:$d9faf183),(n:'c14_d09.bin';l:$2000;p:$6000;crc:$5886c802));
trackfield_pal:array[0..2] of tipo_roms=(
(n:'361b16.f1';l:$20;p:$0;crc:$d55f30b5),(n:'361b17.b16';l:$100;p:$20;crc:$d2ba4d32),
(n:'361b18.e15';l:$100;p:$120;crc:$053e5861));
trackfield_vlm:tipo_roms=(n:'c9_d15.bin';l:$2000;p:$0;crc:$f546a56b);
trackfield_snd:tipo_roms=(n:'c2_d13.bin';l:$2000;p:$0;crc:$95bf79b6);
trackfield_dip_a:array [0..1] of def_dip=(
(mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),());
trackfield_dip_b:array [0..7] of def_dip=(
(mask:$1;name:'Lives';number:2;dip:((dip_val:$1;dip_name:'1'),(dip_val:$0;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'After Last Event';number:2;dip:((dip_val:$2;dip_name:'Game Over'),(dip_val:$0;dip_name:'Game Continues'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Bonus Life';number:2;dip:((dip_val:$8;dip_name:'None'),(dip_val:$0;dip_name:'100000'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'World Records';number:2;dip:((dip_val:$10;dip_name:'Don''t Erase'),(dip_val:$0;dip_name:'Erase on Reset'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Hard'),(dip_val:$0;dip_name:'Difficult'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
irq_ena:boolean;
sound_latch,chip_latch:byte;
mem_opcodes:array[0..$9fff] of byte;
last_addr:word;
procedure update_video_trackfield;
var
x,y,atrib:byte;
f,nchar,color:word;
scroll_x:array[0..$1f] of word;
begin
for f:=0 to $7ff do begin
if gfx[0].buffer[f] then begin
x:=f mod 64;
y:=f div 64;
atrib:=memoria[$3800+f];
nchar:=memoria[$3000+f]+((atrib and $c0) shl 2);
color:=(atrib and $f) shl 4;
put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $10)<>0,(atrib and $20)<>0);
gfx[0].buffer[f]:=false;
end;
end;
for f:=0 to $1f do scroll_x[f]:=memoria[$1840+f]+((memoria[$1c40+f] and 1) shl 8);
scroll__x_part2(1,2,8,@scroll_x);
for f:=$1f downto 0 do begin
atrib:=memoria[$1800+(f*2)];
nchar:=memoria[$1c01+(f*2)]+((atrib and $20) shl 3);
y:=241-memoria[$1801+(f*2)];
x:=memoria[$1c00+(f*2)]-1;
color:=(atrib and $0f) shl 4;
put_gfx_sprite(nchar,color,(atrib and $40)=0,(atrib and $80)<>0,1);
actualiza_gfx_sprite(x,y,2,1);
end;
actualiza_trozo_final(0,16,256,224,2);
end;
procedure eventos_trackfield;
begin
if event.arcade then begin
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
//System
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
end;
end;
procedure trackfield_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=239 then begin
if irq_ena then m6809_0.change_irq(HOLD_LINE);
update_video_trackfield;
end;
end;
//General
eventos_trackfield;
video_sync;
end;
end;
function trackfield_getbyte(direccion:word):byte;
begin
case direccion of
$1200..$127f:trackfield_getbyte:=marcade.dswb; //DSW2
$1280..$128f:case (direccion and 3) of
0:trackfield_getbyte:=marcade.in2; //SYSTEM
1:trackfield_getbyte:=marcade.in0;
2:trackfield_getbyte:=marcade.in1;
3:trackfield_getbyte:=marcade.dswa; //DSW1
end;
$1800..$1fff,$2800..$3fff:trackfield_getbyte:=memoria[direccion];
$6000..$ffff:if m6809_0.opcode then trackfield_getbyte:=mem_opcodes[direccion-$6000]
else trackfield_getbyte:=memoria[direccion];
end;
end;
procedure trackfield_putbyte(direccion:word;valor:byte);
begin
case direccion of
$1080..$10ff:case (direccion and 7) of
0:main_screen.flip_main_screen:=(valor and $1)<>0;
1:z80_0.change_irq(HOLD_LINE);
7:irq_ena:=(valor<>0);
end;
$1100..$117f:sound_latch:=valor;
$1800..$1fff,$2800..$2fff:memoria[direccion]:=valor;
$3000..$3fff:begin
gfx[0].buffer[direccion and $7ff]:=true;
memoria[direccion]:=valor;
end;
$6000..$ffff:; //ROM
end;
end;
function trackfield_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$1fff:trackfield_snd_getbyte:=mem_snd[direccion];
$4000..$5fff:trackfield_snd_getbyte:=mem_snd[(direccion and $3ff)+$4000];
$6000..$7fff:trackfield_snd_getbyte:=sound_latch;
$8000..$9fff:trackfield_snd_getbyte:=(z80_0.totalt shr 10) and $f;
$e000..$ffff:if ((direccion and 7)=2) then trackfield_snd_getbyte:=vlm5030_0.get_bsy shl 4;
end;
end;
procedure trackfield_snd_putbyte(direccion:word;valor:byte);
var
changes,offset:integer;
begin
case direccion of
0..$1fff:; //ROM
$4000..$4fff:mem_snd[$4000+(direccion and $3ff)]:=valor;
$a000..$bfff:chip_latch:=valor;
$c000..$dfff:sn_76496_0.Write(chip_latch);
$e000..$ffff:case (direccion and $7) of
0:dac_0.data8_w(valor);
1,2:;
3:begin
offset:=direccion and $3ff;
changes:=offset xor last_addr;
// A4 VLM5030 ST pin */
if (changes and $100)<>0 then vlm5030_0.set_st((offset and $100) shr 8);
// A5 VLM5030 RST pin */
if (changes and $200)<>0 then vlm5030_0.set_rst((offset and $200) shr 9);
last_addr:=offset;
end;
4:vlm5030_0.data_w(valor);
end;
end;
end;
procedure trackfield_sound_update;
begin
sn_76496_0.Update;
dac_0.update;
vlm5030_0.update;
end;
procedure trackfield_qsave(nombre:string);
var
data:pbyte;
buffer:array[0..4] of byte;
size:word;
begin
open_qsnapshot_save('trackfield'+nombre);
getmem(data,250);
//CPU
size:=m6809_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=z80_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//SND
size:=sn_76496_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=vlm5030_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=dac_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//MEM
savedata_com_qsnapshot(@memoria,$6000);
savedata_com_qsnapshot(@mem_snd[$2000],$e000);
//MISC
buffer[0]:=byte(irq_ena);
buffer[1]:=sound_latch;
buffer[2]:=chip_latch;
buffer[3]:=last_addr and $ff;
buffer[4]:=last_addr shr 8;
savedata_qsnapshot(@buffer,5);
freemem(data);
close_qsnapshot;
end;
procedure trackfield_qload(nombre:string);
var
data:pbyte;
buffer:array[0..4] of byte;
begin
if not(open_qsnapshot_load('trackfield'+nombre)) then exit;
getmem(data,250);
//CPU
loaddata_qsnapshot(data);
m6809_0.load_snapshot(data);
loaddata_qsnapshot(data);
z80_0.load_snapshot(data);
//SND
loaddata_qsnapshot(data);
sn_76496_0.load_snapshot(data);
loaddata_qsnapshot(data);
vlm5030_0.load_snapshot(data);
loaddata_qsnapshot(data);
dac_0.load_snapshot(data);
//MEM
loaddata_qsnapshot(@memoria);
loaddata_qsnapshot(@mem_snd[$2000]);
//MISC
loaddata_qsnapshot(@buffer);
irq_ena:=buffer[0]<>0;
sound_latch:=buffer[1];
chip_latch:=buffer[2];
last_addr:=buffer[3] or (buffer[4] shl 8);
freemem(data);
close_qsnapshot;
//end
fillchar(gfx[0].buffer,$800,1);
end;
//Main
procedure close_trackfield;
begin
write_file(Directory.Arcade_nvram+'trackfield.nv',@memoria[$2800],$800);
end;
procedure reset_trackfield;
begin
m6809_0.reset;
z80_0.reset;
vlm5030_0.reset;
dac_0.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
irq_ena:=false;
sound_latch:=0;
chip_latch:=0;
last_addr:=0;
end;
function iniciar_trackfield:boolean;
var
colores:tpaleta;
f:word;
longitud:integer;
bit0,bit1,bit2:byte;
memoria_temp:array[0..$bfff] of byte;
rweights,gweights:array[0..3] of single;
bweights:array[0..2] of single;
const
pc_x:array[0..7] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4);
pc_y:array[0..7] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32);
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8);
resistances_rg:array[0..2] of integer=(1000,470,220);
resistances_b:array[0..1] of integer=(470,220);
begin
iniciar_trackfield:=false;
llamadas_maquina.bucle_general:=trackfield_principal;
llamadas_maquina.reset:=reset_trackfield;
llamadas_maquina.close:=close_trackfield;
llamadas_maquina.save_qsnap:=trackfield_qsave;
llamadas_maquina.load_qsnap:=trackfield_qload;
iniciar_audio(false);
screen_init(1,512,256);
screen_mod_scroll(1,512,256,511,256,256,255);
screen_init(2,256,256,false,true);
iniciar_video(256,224);
//Main CPU
m6809_0:=cpu_m6809.Create(18432000 div 12,$100,TCPU_M6809);
m6809_0.change_ram_calls(trackfield_getbyte,trackfield_putbyte);
//Sound CPU
z80_0:=cpu_z80.create(14318180 div 4,$100);
z80_0.change_ram_calls(trackfield_snd_getbyte,trackfield_snd_putbyte);
z80_0.init_sound(trackfield_sound_update);
//Sound Chip
sn_76496_0:=sn76496_chip.Create(14318180 div 8);
vlm5030_0:=vlm5030_chip.Create(3579545,$2000,4);
if not(roms_load(vlm5030_0.get_rom_addr,trackfield_vlm)) then exit;
dac_0:=dac_chip.Create(0.80);
if not(roms_load(@memoria,trackfield_rom)) then exit;
konami1_decode(@memoria[$6000],@mem_opcodes,$a000);
//NV ram
if read_file_size(Directory.Arcade_nvram+'trackfield.nv',longitud) then read_file(Directory.Arcade_nvram+'trackfield.nv',@memoria[$2800],longitud);
if not(roms_load(@mem_snd,trackfield_snd)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,trackfield_char)) then exit;
init_gfx(0,8,8,$300);
gfx_set_desc_data(4,0,32*8,0,1,2,3);
convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false);
//sprites
if not(roms_load(@memoria_temp,trackfield_sprites)) then exit;
init_gfx(1,16,16,$100);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,($100*64*8)+4,$100*64*8,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//paleta
if not(roms_load(@memoria_temp,trackfield_pal)) then exit;
compute_resistor_weights(0, 255, -1.0,
3,@resistances_rg,@rweights,1000,0,
3,@resistances_rg,@gweights,1000,0,
2,@resistances_b,@bweights,1000,0);
for f:=0 to $1f do begin
// red component */
bit0:=(memoria_temp[f] shr 0) and $01;
bit1:=(memoria_temp[f] shr 1) and $01;
bit2:=(memoria_temp[f] shr 2) and $01;
colores[f].r:=combine_3_weights(@rweights, bit0, bit1, bit2);
// green component */
bit0:=(memoria_temp[f] shr 3) and $01;
bit1:=(memoria_temp[f] shr 4) and $01;
bit2:=(memoria_temp[f] shr 5) and $01;
colores[f].g:=combine_3_weights(@gweights, bit0, bit1, bit2);
// blue component */
bit0:=(memoria_temp[f] shr 6) and $01;
bit1:=(memoria_temp[f] shr 7) and $01;
colores[f].b:=combine_2_weights(@bweights, bit0, bit1);
end;
set_pal(colores,$20);
for f:=0 to $ff do begin
gfx[0].colores[f]:=(memoria_temp[$120+f] and $f) or $10;
gfx[1].colores[f]:=memoria_temp[$20+f] and $f;
end;
//DIP
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$59;
marcade.dswa_val:=@trackfield_dip_a;
marcade.dswb_val:=@trackfield_dip_b;
//final
reset_trackfield;
iniciar_trackfield:=true;
end;
end.
|
namespace Sugar;
interface
type
SugarException = public class({$IF TOFFEE}Foundation.NSException{$ELSE}Exception{$ENDIF})
public
constructor;
constructor(aMessage: String);
constructor(aFormat: String; params aParams: array of Object);
{$IF TOFFEE}
constructor withError(aError: NSError);
property Message: String read reason;
{$ENDIF}
end;
SugarNotImplementedException = public class(SugarException);
SugarNotSupportedException = public class (SugarException);
SugarArgumentException = public class (SugarException);
SugarArgumentNullException = public class(SugarArgumentException)
public
constructor(aMessage: String);
class method RaiseIfNil(Value: Object; Name: String);
end;
SugarArgumentOutOfRangeException = public class (SugarArgumentException);
SugarFormatException = public class(SugarException);
SugarIOException = public class(SugarException);
HttpException = public class(SugarException)
assembly
constructor(aMessage: String; aResponse: nullable HttpResponse := nil);
begin
inherited constructor(aMessage);
Response := aResponse;
end;
public
property Response: nullable HttpResponse; readonly;
end;
SugarFileNotFoundException = public class (SugarException)
public
property FileName: String read write; readonly;
constructor (aFileName: String);
end;
SugarStackEmptyException = public class (SugarException);
SugarInvalidOperationException = public class (SugarException);
SugarKeyNotFoundException = public class (SugarException)
public
constructor;
end;
SugarAppContextMissingException = public class (SugarException)
public
class method RaiseIfMissing;
end;
{$IF TOFFEE}
SugarNSErrorException = public class(SugarException)
public
constructor(Error: Foundation.NSError);
end;
{$ENDIF}
ErrorMessage = public static class
public
class const FORMAT_ERROR = "Input string was not in a correct format";
class const OUT_OF_RANGE_ERROR = "Range ({0},{1}) exceeds data length {2}";
class const NEGATIVE_VALUE_ERROR = "{0} can not be negative";
class const ARG_OUT_OF_RANGE_ERROR = "{0} argument was out of range of valid values.";
class const ARG_NULL_ERROR = "Argument {0} can not be nil";
class const TYPE_RANGE_ERROR = "Specified value exceeds range of {0}";
class const COLLECTION_EMPTY = "Collection is empty";
class const KEY_NOTFOUND = "Entry with specified key does not exist";
class const KEY_EXISTS = "An element with the same key already exists in the dictionary";
class const FILE_EXISTS = "File {0} already exists";
class const FILE_NOTFOUND = "File {0} not found";
class const FILE_WRITE_ERROR = "File {0} can not be written";
class const FILE_READ_ERROR = "File {0} can not be read";
class const FOLDER_EXISTS = "Folder {0} already exists";
class const FOLDER_NOTFOUND = "Folder {0} not found";
class const FOLDER_CREATE_ERROR = "Unable to create folder {0}";
class const FOLDER_DELETE_ERROR = "Unable to delete folder {0}";
class const IO_RENAME_ERROR = "Unable to reanme {0} to {1}";
class const APP_CONTEXT_MISSING = "Environment.ApplicationContext is not set.";
class const NOTSUPPORTED_ERROR = "{0} is not supported on current platform";
end;
implementation
{$IF TOFFEE}
constructor SugarNSErrorException(Error: Foundation.NSError);
begin
inherited constructor(Error.localizedDescription);
end;
{$ENDIF}
constructor SugarException;
begin
constructor("SugarException");
end;
constructor SugarException(aMessage: String);
begin
{$IF TOFFEE}
inherited initWithName('SugarException') reason(aMessage) userInfo(nil);
{$ELSE}
inherited constructor(aMessage);
{$ENDIF}
end;
{$IF TOFFEE}
constructor SugarException withError(aError: NSError);
begin
inherited initWithName('SugarException') reason(aError.description) userInfo(nil);
end;
{$ENDIF}
constructor SugarException(aFormat: String; params aParams: array of Object);
begin
constructor(String.Format(aFormat, aParams));
end;
constructor SugarArgumentNullException(aMessage: String);
begin
inherited constructor(ErrorMessage.ARG_NULL_ERROR, aMessage)
end;
class method SugarArgumentNullException.RaiseIfNil(Value: Object; Name: String);
begin
if Value = nil then
raise new SugarArgumentNullException(Name);
end;
class method SugarAppContextMissingException.RaiseIfMissing;
begin
if Environment.ApplicationContext = nil then
raise new SugarAppContextMissingException(ErrorMessage.APP_CONTEXT_MISSING);
end;
constructor SugarFileNotFoundException(aFileName: String);
begin
inherited constructor (ErrorMessage.FILE_NOTFOUND, aFileName);
FileName := aFileName;
end;
constructor SugarKeyNotFoundException;
begin
inherited constructor(ErrorMessage.KEY_NOTFOUND);
end;
end. |
unit ssGraphUtil;
interface
uses Types, Graphics;
type
TGradientDirection=(gdHorizontal, gdVertical);
TTriVertex = packed record
x : Longint;
y : Longint;
Red : SmallInt;
Green: SmallInt;
Blue : SmallInt;
Alpha: SmallInt;
end;
function PointInRect(APoint: TPoint; ARect: TRect): Boolean;
function DrawGradient(Canvas: TCanvas; Rect: TRect; Color1, Color2: TColor; Direction: TGradientDirection): boolean;
implementation
uses Windows;
var
GradProc: function (DC: HDC; var p2: TTriVertex; p3: ULONG; p4: Pointer; p5, p6: ULONG): BOOL; stdcall;
Img32DLLHandle: Integer;
function PointInRect(APoint: TPoint; ARect: TRect): Boolean;
begin
Result := (APoint.X > ARect.Left) and (APoint.X < ARect.Right) and
(APoint.Y > ARect.Top) and (APoint.Y < ARect.Bottom);
end;
function DrawGradient(Canvas: TCanvas; Rect: TRect; Color1, Color2: TColor; Direction: TGradientDirection): boolean;
function InitTriVertex(XPos: Integer; YPos: Integer; Color: TColor): TTriVertex;
begin
Result.x:=XPos;
Result.y:=YPos;
Result.Alpha:=2;
Result.Red:=(GetRValue(ColorToRGB(Color)) shl 8);
Result.Green:=(GetGValue(ColorToRGB(Color)) shl 8);
Result.Blue:=(GetBValue(ColorToRGB(Color)) shl 8);
end;
var
GRect : TGradientRect;
Vertex: array[0..2] of TTriVertex;
begin
Result:=False;
if not Assigned(GradProc) then Exit;
GRect.UpperLeft:=0;
GRect.LowerRight:=1;
Vertex[0]:=InitTriVertex(Rect.Left,Rect.Top,Color1);
Vertex[1]:=InitTriVertex(Rect.Right,Rect.Bottom,Color2);
case Direction of
gdHorizontal: GradProc(Canvas.Handle, Vertex[0], 2, @GRect, 1, GRADIENT_FILL_RECT_H);
gdVertical: GradProc(Canvas.Handle, Vertex[0], 2, @GRect, 1, GRADIENT_FILL_RECT_V);
end;
Result:=True;
end;
initialization
Img32DLLHandle:=0;
Img32DLLHandle:=LoadLibrary('MSIMG32.DLL');
if Img32DLLHandle<>0
then GradProc:=GetProcAddress(Img32DLLHandle,'GradientFill');
finalization
if Img32DLLHandle<>0 then FreeLibrary(Img32DLLHandle);
end.
|
unit ExportSeparatedByMainTest;
{* Экспорт в NSRC, разделённые по мейну, с помощью свойства DivideBy }
// Модуль: "w:\archi\source\projects\ImportExportTest\ExportSeparatedByMainTest.pas"
// Стереотип: "TestCase"
// Элемент модели: "ExportSeparatedByMainTest" MUID: (55FFA0290014)
// Имя типа: "TExportSeparatedByMainTest"
{$Include w:\archi\source\projects\ImportExportTest.inc}
interface
{$If Defined(nsTest)}
uses
l3IntfUses
, ExportPipeTestPrim
;
type
TExportSeparatedByMainTest = class(TExportPipeTestPrim)
{* Экспорт в NSRC, разделённые по мейну, с помощью свойства DivideBy }
protected
procedure TuneExportPipe; override;
{* Процедура настройки трубы. Метод для перекрытия в потомках. }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TExportSeparatedByMainTest
{$IfEnd} // Defined(nsTest)
implementation
{$If Defined(nsTest)}
uses
l3ImplUses
, TestFrameWork
, ddPipeOutInterfaces
, l3Base
//#UC START# *55FFA0290014impl_uses*
//#UC END# *55FFA0290014impl_uses*
;
procedure TExportSeparatedByMainTest.TuneExportPipe;
{* Процедура настройки трубы. Метод для перекрытия в потомках. }
//#UC START# *55EEA16603AE_55FFA0290014_var*
//#UC END# *55EEA16603AE_55FFA0290014_var*
begin
//#UC START# *55EEA16603AE_55FFA0290014_impl*
Pipe.AllPartsDivideBy([edbAccGroup]);
//#UC END# *55EEA16603AE_55FFA0290014_impl*
end;//TExportSeparatedByMainTest.TuneExportPipe
function TExportSeparatedByMainTest.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'ExportPipeTests';
end;//TExportSeparatedByMainTest.GetFolder
function TExportSeparatedByMainTest.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55FFA0290014';
end;//TExportSeparatedByMainTest.GetModelElementGUID
initialization
TestFramework.RegisterTest(TExportSeparatedByMainTest.Suite);
{$IfEnd} // Defined(nsTest)
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.